106f32e7eSjoerg //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This contains code to emit Expr nodes as LLVM code.
1006f32e7eSjoerg //
1106f32e7eSjoerg //===----------------------------------------------------------------------===//
1206f32e7eSjoerg
13*13fbcb42Sjoerg #include "CGCUDARuntime.h"
1406f32e7eSjoerg #include "CGCXXABI.h"
1506f32e7eSjoerg #include "CGCall.h"
1606f32e7eSjoerg #include "CGCleanup.h"
1706f32e7eSjoerg #include "CGDebugInfo.h"
1806f32e7eSjoerg #include "CGObjCRuntime.h"
1906f32e7eSjoerg #include "CGOpenMPRuntime.h"
2006f32e7eSjoerg #include "CGRecordLayout.h"
2106f32e7eSjoerg #include "CodeGenFunction.h"
2206f32e7eSjoerg #include "CodeGenModule.h"
2306f32e7eSjoerg #include "ConstantEmitter.h"
2406f32e7eSjoerg #include "TargetInfo.h"
2506f32e7eSjoerg #include "clang/AST/ASTContext.h"
2606f32e7eSjoerg #include "clang/AST/Attr.h"
2706f32e7eSjoerg #include "clang/AST/DeclObjC.h"
2806f32e7eSjoerg #include "clang/AST/NSAPI.h"
2906f32e7eSjoerg #include "clang/Basic/Builtins.h"
3006f32e7eSjoerg #include "clang/Basic/CodeGenOptions.h"
31*13fbcb42Sjoerg #include "clang/Basic/SourceManager.h"
3206f32e7eSjoerg #include "llvm/ADT/Hashing.h"
3306f32e7eSjoerg #include "llvm/ADT/StringExtras.h"
3406f32e7eSjoerg #include "llvm/IR/DataLayout.h"
3506f32e7eSjoerg #include "llvm/IR/Intrinsics.h"
3606f32e7eSjoerg #include "llvm/IR/LLVMContext.h"
3706f32e7eSjoerg #include "llvm/IR/MDBuilder.h"
3806f32e7eSjoerg #include "llvm/Support/ConvertUTF.h"
3906f32e7eSjoerg #include "llvm/Support/MathExtras.h"
4006f32e7eSjoerg #include "llvm/Support/Path.h"
41*13fbcb42Sjoerg #include "llvm/Support/SaveAndRestore.h"
4206f32e7eSjoerg #include "llvm/Transforms/Utils/SanitizerStats.h"
4306f32e7eSjoerg
4406f32e7eSjoerg #include <string>
4506f32e7eSjoerg
4606f32e7eSjoerg using namespace clang;
4706f32e7eSjoerg using namespace CodeGen;
4806f32e7eSjoerg
4906f32e7eSjoerg //===--------------------------------------------------------------------===//
5006f32e7eSjoerg // Miscellaneous Helper Methods
5106f32e7eSjoerg //===--------------------------------------------------------------------===//
5206f32e7eSjoerg
EmitCastToVoidPtr(llvm::Value * value)5306f32e7eSjoerg llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
5406f32e7eSjoerg unsigned addressSpace =
5506f32e7eSjoerg cast<llvm::PointerType>(value->getType())->getAddressSpace();
5606f32e7eSjoerg
5706f32e7eSjoerg llvm::PointerType *destType = Int8PtrTy;
5806f32e7eSjoerg if (addressSpace)
5906f32e7eSjoerg destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
6006f32e7eSjoerg
6106f32e7eSjoerg if (value->getType() == destType) return value;
6206f32e7eSjoerg return Builder.CreateBitCast(value, destType);
6306f32e7eSjoerg }
6406f32e7eSjoerg
6506f32e7eSjoerg /// CreateTempAlloca - This creates a alloca and inserts it into the entry
6606f32e7eSjoerg /// block.
CreateTempAllocaWithoutCast(llvm::Type * Ty,CharUnits Align,const Twine & Name,llvm::Value * ArraySize)6706f32e7eSjoerg Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
6806f32e7eSjoerg CharUnits Align,
6906f32e7eSjoerg const Twine &Name,
7006f32e7eSjoerg llvm::Value *ArraySize) {
7106f32e7eSjoerg auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
7206f32e7eSjoerg Alloca->setAlignment(Align.getAsAlign());
7306f32e7eSjoerg return Address(Alloca, Align);
7406f32e7eSjoerg }
7506f32e7eSjoerg
7606f32e7eSjoerg /// CreateTempAlloca - This creates a alloca and inserts it into the entry
7706f32e7eSjoerg /// block. The alloca is casted to default address space if necessary.
CreateTempAlloca(llvm::Type * Ty,CharUnits Align,const Twine & Name,llvm::Value * ArraySize,Address * AllocaAddr)7806f32e7eSjoerg Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
7906f32e7eSjoerg const Twine &Name,
8006f32e7eSjoerg llvm::Value *ArraySize,
8106f32e7eSjoerg Address *AllocaAddr) {
8206f32e7eSjoerg auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
8306f32e7eSjoerg if (AllocaAddr)
8406f32e7eSjoerg *AllocaAddr = Alloca;
8506f32e7eSjoerg llvm::Value *V = Alloca.getPointer();
8606f32e7eSjoerg // Alloca always returns a pointer in alloca address space, which may
8706f32e7eSjoerg // be different from the type defined by the language. For example,
8806f32e7eSjoerg // in C++ the auto variables are in the default address space. Therefore
8906f32e7eSjoerg // cast alloca to the default address space when necessary.
9006f32e7eSjoerg if (getASTAllocaAddressSpace() != LangAS::Default) {
9106f32e7eSjoerg auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
9206f32e7eSjoerg llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
9306f32e7eSjoerg // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
9406f32e7eSjoerg // otherwise alloca is inserted at the current insertion point of the
9506f32e7eSjoerg // builder.
9606f32e7eSjoerg if (!ArraySize)
9706f32e7eSjoerg Builder.SetInsertPoint(AllocaInsertPt);
9806f32e7eSjoerg V = getTargetHooks().performAddrSpaceCast(
9906f32e7eSjoerg *this, V, getASTAllocaAddressSpace(), LangAS::Default,
10006f32e7eSjoerg Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
10106f32e7eSjoerg }
10206f32e7eSjoerg
10306f32e7eSjoerg return Address(V, Align);
10406f32e7eSjoerg }
10506f32e7eSjoerg
10606f32e7eSjoerg /// CreateTempAlloca - This creates an alloca and inserts it into the entry
10706f32e7eSjoerg /// block if \p ArraySize is nullptr, otherwise inserts it at the current
10806f32e7eSjoerg /// insertion point of the builder.
CreateTempAlloca(llvm::Type * Ty,const Twine & Name,llvm::Value * ArraySize)10906f32e7eSjoerg llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
11006f32e7eSjoerg const Twine &Name,
11106f32e7eSjoerg llvm::Value *ArraySize) {
11206f32e7eSjoerg if (ArraySize)
11306f32e7eSjoerg return Builder.CreateAlloca(Ty, ArraySize, Name);
11406f32e7eSjoerg return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
11506f32e7eSjoerg ArraySize, Name, AllocaInsertPt);
11606f32e7eSjoerg }
11706f32e7eSjoerg
11806f32e7eSjoerg /// CreateDefaultAlignTempAlloca - This creates an alloca with the
11906f32e7eSjoerg /// default alignment of the corresponding LLVM type, which is *not*
12006f32e7eSjoerg /// guaranteed to be related in any way to the expected alignment of
12106f32e7eSjoerg /// an AST type that might have been lowered to Ty.
CreateDefaultAlignTempAlloca(llvm::Type * Ty,const Twine & Name)12206f32e7eSjoerg Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
12306f32e7eSjoerg const Twine &Name) {
12406f32e7eSjoerg CharUnits Align =
12506f32e7eSjoerg CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
12606f32e7eSjoerg return CreateTempAlloca(Ty, Align, Name);
12706f32e7eSjoerg }
12806f32e7eSjoerg
InitTempAlloca(Address Var,llvm::Value * Init)12906f32e7eSjoerg void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
130*13fbcb42Sjoerg auto *Alloca = Var.getPointer();
131*13fbcb42Sjoerg assert(isa<llvm::AllocaInst>(Alloca) ||
132*13fbcb42Sjoerg (isa<llvm::AddrSpaceCastInst>(Alloca) &&
133*13fbcb42Sjoerg isa<llvm::AllocaInst>(
134*13fbcb42Sjoerg cast<llvm::AddrSpaceCastInst>(Alloca)->getPointerOperand())));
135*13fbcb42Sjoerg
136*13fbcb42Sjoerg auto *Store = new llvm::StoreInst(Init, Alloca, /*volatile*/ false,
137*13fbcb42Sjoerg Var.getAlignment().getAsAlign());
13806f32e7eSjoerg llvm::BasicBlock *Block = AllocaInsertPt->getParent();
13906f32e7eSjoerg Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
14006f32e7eSjoerg }
14106f32e7eSjoerg
CreateIRTemp(QualType Ty,const Twine & Name)14206f32e7eSjoerg Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
14306f32e7eSjoerg CharUnits Align = getContext().getTypeAlignInChars(Ty);
14406f32e7eSjoerg return CreateTempAlloca(ConvertType(Ty), Align, Name);
14506f32e7eSjoerg }
14606f32e7eSjoerg
CreateMemTemp(QualType Ty,const Twine & Name,Address * Alloca)14706f32e7eSjoerg Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
14806f32e7eSjoerg Address *Alloca) {
14906f32e7eSjoerg // FIXME: Should we prefer the preferred type alignment here?
15006f32e7eSjoerg return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
15106f32e7eSjoerg }
15206f32e7eSjoerg
CreateMemTemp(QualType Ty,CharUnits Align,const Twine & Name,Address * Alloca)15306f32e7eSjoerg Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
15406f32e7eSjoerg const Twine &Name, Address *Alloca) {
155*13fbcb42Sjoerg Address Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
15606f32e7eSjoerg /*ArraySize=*/nullptr, Alloca);
157*13fbcb42Sjoerg
158*13fbcb42Sjoerg if (Ty->isConstantMatrixType()) {
159*13fbcb42Sjoerg auto *ArrayTy = cast<llvm::ArrayType>(Result.getType()->getElementType());
160*13fbcb42Sjoerg auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
161*13fbcb42Sjoerg ArrayTy->getNumElements());
162*13fbcb42Sjoerg
163*13fbcb42Sjoerg Result = Address(
164*13fbcb42Sjoerg Builder.CreateBitCast(Result.getPointer(), VectorTy->getPointerTo()),
165*13fbcb42Sjoerg Result.getAlignment());
166*13fbcb42Sjoerg }
167*13fbcb42Sjoerg return Result;
16806f32e7eSjoerg }
16906f32e7eSjoerg
CreateMemTempWithoutCast(QualType Ty,CharUnits Align,const Twine & Name)17006f32e7eSjoerg Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
17106f32e7eSjoerg const Twine &Name) {
17206f32e7eSjoerg return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
17306f32e7eSjoerg }
17406f32e7eSjoerg
CreateMemTempWithoutCast(QualType Ty,const Twine & Name)17506f32e7eSjoerg Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
17606f32e7eSjoerg const Twine &Name) {
17706f32e7eSjoerg return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
17806f32e7eSjoerg Name);
17906f32e7eSjoerg }
18006f32e7eSjoerg
18106f32e7eSjoerg /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
18206f32e7eSjoerg /// expression and compare the result against zero, returning an Int1Ty value.
EvaluateExprAsBool(const Expr * E)18306f32e7eSjoerg llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
18406f32e7eSjoerg PGO.setCurrentStmt(E);
18506f32e7eSjoerg if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
18606f32e7eSjoerg llvm::Value *MemPtr = EmitScalarExpr(E);
18706f32e7eSjoerg return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
18806f32e7eSjoerg }
18906f32e7eSjoerg
19006f32e7eSjoerg QualType BoolTy = getContext().BoolTy;
19106f32e7eSjoerg SourceLocation Loc = E->getExprLoc();
192*13fbcb42Sjoerg CGFPOptionsRAII FPOptsRAII(*this, E);
19306f32e7eSjoerg if (!E->getType()->isAnyComplexType())
19406f32e7eSjoerg return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
19506f32e7eSjoerg
19606f32e7eSjoerg return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
19706f32e7eSjoerg Loc);
19806f32e7eSjoerg }
19906f32e7eSjoerg
20006f32e7eSjoerg /// EmitIgnoredExpr - Emit code to compute the specified expression,
20106f32e7eSjoerg /// ignoring the result.
EmitIgnoredExpr(const Expr * E)20206f32e7eSjoerg void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
20306f32e7eSjoerg if (E->isRValue())
20406f32e7eSjoerg return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
20506f32e7eSjoerg
20606f32e7eSjoerg // Just emit it as an l-value and drop the result.
20706f32e7eSjoerg EmitLValue(E);
20806f32e7eSjoerg }
20906f32e7eSjoerg
21006f32e7eSjoerg /// EmitAnyExpr - Emit code to compute the specified expression which
21106f32e7eSjoerg /// can have any type. The result is returned as an RValue struct.
21206f32e7eSjoerg /// If this is an aggregate expression, AggSlot indicates where the
21306f32e7eSjoerg /// result should be returned.
EmitAnyExpr(const Expr * E,AggValueSlot aggSlot,bool ignoreResult)21406f32e7eSjoerg RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
21506f32e7eSjoerg AggValueSlot aggSlot,
21606f32e7eSjoerg bool ignoreResult) {
21706f32e7eSjoerg switch (getEvaluationKind(E->getType())) {
21806f32e7eSjoerg case TEK_Scalar:
21906f32e7eSjoerg return RValue::get(EmitScalarExpr(E, ignoreResult));
22006f32e7eSjoerg case TEK_Complex:
22106f32e7eSjoerg return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
22206f32e7eSjoerg case TEK_Aggregate:
22306f32e7eSjoerg if (!ignoreResult && aggSlot.isIgnored())
22406f32e7eSjoerg aggSlot = CreateAggTemp(E->getType(), "agg-temp");
22506f32e7eSjoerg EmitAggExpr(E, aggSlot);
22606f32e7eSjoerg return aggSlot.asRValue();
22706f32e7eSjoerg }
22806f32e7eSjoerg llvm_unreachable("bad evaluation kind");
22906f32e7eSjoerg }
23006f32e7eSjoerg
23106f32e7eSjoerg /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
23206f32e7eSjoerg /// always be accessible even if no aggregate location is provided.
EmitAnyExprToTemp(const Expr * E)23306f32e7eSjoerg RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
23406f32e7eSjoerg AggValueSlot AggSlot = AggValueSlot::ignored();
23506f32e7eSjoerg
23606f32e7eSjoerg if (hasAggregateEvaluationKind(E->getType()))
23706f32e7eSjoerg AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
23806f32e7eSjoerg return EmitAnyExpr(E, AggSlot);
23906f32e7eSjoerg }
24006f32e7eSjoerg
24106f32e7eSjoerg /// EmitAnyExprToMem - Evaluate an expression into a given memory
24206f32e7eSjoerg /// location.
EmitAnyExprToMem(const Expr * E,Address Location,Qualifiers Quals,bool IsInit)24306f32e7eSjoerg void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
24406f32e7eSjoerg Address Location,
24506f32e7eSjoerg Qualifiers Quals,
24606f32e7eSjoerg bool IsInit) {
24706f32e7eSjoerg // FIXME: This function should take an LValue as an argument.
24806f32e7eSjoerg switch (getEvaluationKind(E->getType())) {
24906f32e7eSjoerg case TEK_Complex:
25006f32e7eSjoerg EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
25106f32e7eSjoerg /*isInit*/ false);
25206f32e7eSjoerg return;
25306f32e7eSjoerg
25406f32e7eSjoerg case TEK_Aggregate: {
25506f32e7eSjoerg EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
25606f32e7eSjoerg AggValueSlot::IsDestructed_t(IsInit),
25706f32e7eSjoerg AggValueSlot::DoesNotNeedGCBarriers,
25806f32e7eSjoerg AggValueSlot::IsAliased_t(!IsInit),
25906f32e7eSjoerg AggValueSlot::MayOverlap));
26006f32e7eSjoerg return;
26106f32e7eSjoerg }
26206f32e7eSjoerg
26306f32e7eSjoerg case TEK_Scalar: {
26406f32e7eSjoerg RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
26506f32e7eSjoerg LValue LV = MakeAddrLValue(Location, E->getType());
26606f32e7eSjoerg EmitStoreThroughLValue(RV, LV);
26706f32e7eSjoerg return;
26806f32e7eSjoerg }
26906f32e7eSjoerg }
27006f32e7eSjoerg llvm_unreachable("bad evaluation kind");
27106f32e7eSjoerg }
27206f32e7eSjoerg
27306f32e7eSjoerg static void
pushTemporaryCleanup(CodeGenFunction & CGF,const MaterializeTemporaryExpr * M,const Expr * E,Address ReferenceTemporary)27406f32e7eSjoerg pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
27506f32e7eSjoerg const Expr *E, Address ReferenceTemporary) {
27606f32e7eSjoerg // Objective-C++ ARC:
27706f32e7eSjoerg // If we are binding a reference to a temporary that has ownership, we
27806f32e7eSjoerg // need to perform retain/release operations on the temporary.
27906f32e7eSjoerg //
28006f32e7eSjoerg // FIXME: This should be looking at E, not M.
28106f32e7eSjoerg if (auto Lifetime = M->getType().getObjCLifetime()) {
28206f32e7eSjoerg switch (Lifetime) {
28306f32e7eSjoerg case Qualifiers::OCL_None:
28406f32e7eSjoerg case Qualifiers::OCL_ExplicitNone:
28506f32e7eSjoerg // Carry on to normal cleanup handling.
28606f32e7eSjoerg break;
28706f32e7eSjoerg
28806f32e7eSjoerg case Qualifiers::OCL_Autoreleasing:
28906f32e7eSjoerg // Nothing to do; cleaned up by an autorelease pool.
29006f32e7eSjoerg return;
29106f32e7eSjoerg
29206f32e7eSjoerg case Qualifiers::OCL_Strong:
29306f32e7eSjoerg case Qualifiers::OCL_Weak:
29406f32e7eSjoerg switch (StorageDuration Duration = M->getStorageDuration()) {
29506f32e7eSjoerg case SD_Static:
29606f32e7eSjoerg // Note: we intentionally do not register a cleanup to release
29706f32e7eSjoerg // the object on program termination.
29806f32e7eSjoerg return;
29906f32e7eSjoerg
30006f32e7eSjoerg case SD_Thread:
30106f32e7eSjoerg // FIXME: We should probably register a cleanup in this case.
30206f32e7eSjoerg return;
30306f32e7eSjoerg
30406f32e7eSjoerg case SD_Automatic:
30506f32e7eSjoerg case SD_FullExpression:
30606f32e7eSjoerg CodeGenFunction::Destroyer *Destroy;
30706f32e7eSjoerg CleanupKind CleanupKind;
30806f32e7eSjoerg if (Lifetime == Qualifiers::OCL_Strong) {
30906f32e7eSjoerg const ValueDecl *VD = M->getExtendingDecl();
31006f32e7eSjoerg bool Precise =
31106f32e7eSjoerg VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
31206f32e7eSjoerg CleanupKind = CGF.getARCCleanupKind();
31306f32e7eSjoerg Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
31406f32e7eSjoerg : &CodeGenFunction::destroyARCStrongImprecise;
31506f32e7eSjoerg } else {
31606f32e7eSjoerg // __weak objects always get EH cleanups; otherwise, exceptions
31706f32e7eSjoerg // could cause really nasty crashes instead of mere leaks.
31806f32e7eSjoerg CleanupKind = NormalAndEHCleanup;
31906f32e7eSjoerg Destroy = &CodeGenFunction::destroyARCWeak;
32006f32e7eSjoerg }
32106f32e7eSjoerg if (Duration == SD_FullExpression)
32206f32e7eSjoerg CGF.pushDestroy(CleanupKind, ReferenceTemporary,
32306f32e7eSjoerg M->getType(), *Destroy,
32406f32e7eSjoerg CleanupKind & EHCleanup);
32506f32e7eSjoerg else
32606f32e7eSjoerg CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
32706f32e7eSjoerg M->getType(),
32806f32e7eSjoerg *Destroy, CleanupKind & EHCleanup);
32906f32e7eSjoerg return;
33006f32e7eSjoerg
33106f32e7eSjoerg case SD_Dynamic:
33206f32e7eSjoerg llvm_unreachable("temporary cannot have dynamic storage duration");
33306f32e7eSjoerg }
33406f32e7eSjoerg llvm_unreachable("unknown storage duration");
33506f32e7eSjoerg }
33606f32e7eSjoerg }
33706f32e7eSjoerg
33806f32e7eSjoerg CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
33906f32e7eSjoerg if (const RecordType *RT =
34006f32e7eSjoerg E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
34106f32e7eSjoerg // Get the destructor for the reference temporary.
34206f32e7eSjoerg auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
34306f32e7eSjoerg if (!ClassDecl->hasTrivialDestructor())
34406f32e7eSjoerg ReferenceTemporaryDtor = ClassDecl->getDestructor();
34506f32e7eSjoerg }
34606f32e7eSjoerg
34706f32e7eSjoerg if (!ReferenceTemporaryDtor)
34806f32e7eSjoerg return;
34906f32e7eSjoerg
35006f32e7eSjoerg // Call the destructor for the temporary.
35106f32e7eSjoerg switch (M->getStorageDuration()) {
35206f32e7eSjoerg case SD_Static:
35306f32e7eSjoerg case SD_Thread: {
35406f32e7eSjoerg llvm::FunctionCallee CleanupFn;
35506f32e7eSjoerg llvm::Constant *CleanupArg;
35606f32e7eSjoerg if (E->getType()->isArrayType()) {
35706f32e7eSjoerg CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
35806f32e7eSjoerg ReferenceTemporary, E->getType(),
35906f32e7eSjoerg CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
36006f32e7eSjoerg dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
36106f32e7eSjoerg CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
36206f32e7eSjoerg } else {
36306f32e7eSjoerg CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
36406f32e7eSjoerg GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
36506f32e7eSjoerg CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
36606f32e7eSjoerg }
36706f32e7eSjoerg CGF.CGM.getCXXABI().registerGlobalDtor(
36806f32e7eSjoerg CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
36906f32e7eSjoerg break;
37006f32e7eSjoerg }
37106f32e7eSjoerg
37206f32e7eSjoerg case SD_FullExpression:
37306f32e7eSjoerg CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
37406f32e7eSjoerg CodeGenFunction::destroyCXXObject,
37506f32e7eSjoerg CGF.getLangOpts().Exceptions);
37606f32e7eSjoerg break;
37706f32e7eSjoerg
37806f32e7eSjoerg case SD_Automatic:
37906f32e7eSjoerg CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
38006f32e7eSjoerg ReferenceTemporary, E->getType(),
38106f32e7eSjoerg CodeGenFunction::destroyCXXObject,
38206f32e7eSjoerg CGF.getLangOpts().Exceptions);
38306f32e7eSjoerg break;
38406f32e7eSjoerg
38506f32e7eSjoerg case SD_Dynamic:
38606f32e7eSjoerg llvm_unreachable("temporary cannot have dynamic storage duration");
38706f32e7eSjoerg }
38806f32e7eSjoerg }
38906f32e7eSjoerg
createReferenceTemporary(CodeGenFunction & CGF,const MaterializeTemporaryExpr * M,const Expr * Inner,Address * Alloca=nullptr)39006f32e7eSjoerg static Address createReferenceTemporary(CodeGenFunction &CGF,
39106f32e7eSjoerg const MaterializeTemporaryExpr *M,
39206f32e7eSjoerg const Expr *Inner,
39306f32e7eSjoerg Address *Alloca = nullptr) {
39406f32e7eSjoerg auto &TCG = CGF.getTargetHooks();
39506f32e7eSjoerg switch (M->getStorageDuration()) {
39606f32e7eSjoerg case SD_FullExpression:
39706f32e7eSjoerg case SD_Automatic: {
39806f32e7eSjoerg // If we have a constant temporary array or record try to promote it into a
39906f32e7eSjoerg // constant global under the same rules a normal constant would've been
40006f32e7eSjoerg // promoted. This is easier on the optimizer and generally emits fewer
40106f32e7eSjoerg // instructions.
40206f32e7eSjoerg QualType Ty = Inner->getType();
40306f32e7eSjoerg if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
40406f32e7eSjoerg (Ty->isArrayType() || Ty->isRecordType()) &&
40506f32e7eSjoerg CGF.CGM.isTypeConstant(Ty, true))
40606f32e7eSjoerg if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
407*13fbcb42Sjoerg auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
40806f32e7eSjoerg auto *GV = new llvm::GlobalVariable(
40906f32e7eSjoerg CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
41006f32e7eSjoerg llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
41106f32e7eSjoerg llvm::GlobalValue::NotThreadLocal,
41206f32e7eSjoerg CGF.getContext().getTargetAddressSpace(AS));
41306f32e7eSjoerg CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
41406f32e7eSjoerg GV->setAlignment(alignment.getAsAlign());
41506f32e7eSjoerg llvm::Constant *C = GV;
41606f32e7eSjoerg if (AS != LangAS::Default)
41706f32e7eSjoerg C = TCG.performAddrSpaceCast(
41806f32e7eSjoerg CGF.CGM, GV, AS, LangAS::Default,
41906f32e7eSjoerg GV->getValueType()->getPointerTo(
42006f32e7eSjoerg CGF.getContext().getTargetAddressSpace(LangAS::Default)));
42106f32e7eSjoerg // FIXME: Should we put the new global into a COMDAT?
42206f32e7eSjoerg return Address(C, alignment);
42306f32e7eSjoerg }
42406f32e7eSjoerg return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
42506f32e7eSjoerg }
42606f32e7eSjoerg case SD_Thread:
42706f32e7eSjoerg case SD_Static:
42806f32e7eSjoerg return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
42906f32e7eSjoerg
43006f32e7eSjoerg case SD_Dynamic:
43106f32e7eSjoerg llvm_unreachable("temporary can't have dynamic storage duration");
43206f32e7eSjoerg }
43306f32e7eSjoerg llvm_unreachable("unknown storage duration");
43406f32e7eSjoerg }
43506f32e7eSjoerg
436*13fbcb42Sjoerg /// Helper method to check if the underlying ABI is AAPCS
isAAPCS(const TargetInfo & TargetInfo)437*13fbcb42Sjoerg static bool isAAPCS(const TargetInfo &TargetInfo) {
438*13fbcb42Sjoerg return TargetInfo.getABI().startswith("aapcs");
439*13fbcb42Sjoerg }
440*13fbcb42Sjoerg
44106f32e7eSjoerg LValue CodeGenFunction::
EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * M)44206f32e7eSjoerg EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
443*13fbcb42Sjoerg const Expr *E = M->getSubExpr();
44406f32e7eSjoerg
44506f32e7eSjoerg assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
44606f32e7eSjoerg !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
44706f32e7eSjoerg "Reference should never be pseudo-strong!");
44806f32e7eSjoerg
44906f32e7eSjoerg // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
45006f32e7eSjoerg // as that will cause the lifetime adjustment to be lost for ARC
45106f32e7eSjoerg auto ownership = M->getType().getObjCLifetime();
45206f32e7eSjoerg if (ownership != Qualifiers::OCL_None &&
45306f32e7eSjoerg ownership != Qualifiers::OCL_ExplicitNone) {
45406f32e7eSjoerg Address Object = createReferenceTemporary(*this, M, E);
45506f32e7eSjoerg if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
45606f32e7eSjoerg Object = Address(llvm::ConstantExpr::getBitCast(Var,
45706f32e7eSjoerg ConvertTypeForMem(E->getType())
45806f32e7eSjoerg ->getPointerTo(Object.getAddressSpace())),
45906f32e7eSjoerg Object.getAlignment());
46006f32e7eSjoerg
46106f32e7eSjoerg // createReferenceTemporary will promote the temporary to a global with a
46206f32e7eSjoerg // constant initializer if it can. It can only do this to a value of
46306f32e7eSjoerg // ARC-manageable type if the value is global and therefore "immune" to
46406f32e7eSjoerg // ref-counting operations. Therefore we have no need to emit either a
46506f32e7eSjoerg // dynamic initialization or a cleanup and we can just return the address
46606f32e7eSjoerg // of the temporary.
46706f32e7eSjoerg if (Var->hasInitializer())
46806f32e7eSjoerg return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
46906f32e7eSjoerg
47006f32e7eSjoerg Var->setInitializer(CGM.EmitNullConstant(E->getType()));
47106f32e7eSjoerg }
47206f32e7eSjoerg LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
47306f32e7eSjoerg AlignmentSource::Decl);
47406f32e7eSjoerg
47506f32e7eSjoerg switch (getEvaluationKind(E->getType())) {
47606f32e7eSjoerg default: llvm_unreachable("expected scalar or aggregate expression");
47706f32e7eSjoerg case TEK_Scalar:
47806f32e7eSjoerg EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
47906f32e7eSjoerg break;
48006f32e7eSjoerg case TEK_Aggregate: {
48106f32e7eSjoerg EmitAggExpr(E, AggValueSlot::forAddr(Object,
48206f32e7eSjoerg E->getType().getQualifiers(),
48306f32e7eSjoerg AggValueSlot::IsDestructed,
48406f32e7eSjoerg AggValueSlot::DoesNotNeedGCBarriers,
48506f32e7eSjoerg AggValueSlot::IsNotAliased,
48606f32e7eSjoerg AggValueSlot::DoesNotOverlap));
48706f32e7eSjoerg break;
48806f32e7eSjoerg }
48906f32e7eSjoerg }
49006f32e7eSjoerg
49106f32e7eSjoerg pushTemporaryCleanup(*this, M, E, Object);
49206f32e7eSjoerg return RefTempDst;
49306f32e7eSjoerg }
49406f32e7eSjoerg
49506f32e7eSjoerg SmallVector<const Expr *, 2> CommaLHSs;
49606f32e7eSjoerg SmallVector<SubobjectAdjustment, 2> Adjustments;
49706f32e7eSjoerg E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
49806f32e7eSjoerg
49906f32e7eSjoerg for (const auto &Ignored : CommaLHSs)
50006f32e7eSjoerg EmitIgnoredExpr(Ignored);
50106f32e7eSjoerg
50206f32e7eSjoerg if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
50306f32e7eSjoerg if (opaque->getType()->isRecordType()) {
50406f32e7eSjoerg assert(Adjustments.empty());
50506f32e7eSjoerg return EmitOpaqueValueLValue(opaque);
50606f32e7eSjoerg }
50706f32e7eSjoerg }
50806f32e7eSjoerg
50906f32e7eSjoerg // Create and initialize the reference temporary.
51006f32e7eSjoerg Address Alloca = Address::invalid();
51106f32e7eSjoerg Address Object = createReferenceTemporary(*this, M, E, &Alloca);
51206f32e7eSjoerg if (auto *Var = dyn_cast<llvm::GlobalVariable>(
51306f32e7eSjoerg Object.getPointer()->stripPointerCasts())) {
51406f32e7eSjoerg Object = Address(llvm::ConstantExpr::getBitCast(
51506f32e7eSjoerg cast<llvm::Constant>(Object.getPointer()),
51606f32e7eSjoerg ConvertTypeForMem(E->getType())->getPointerTo()),
51706f32e7eSjoerg Object.getAlignment());
51806f32e7eSjoerg // If the temporary is a global and has a constant initializer or is a
51906f32e7eSjoerg // constant temporary that we promoted to a global, we may have already
52006f32e7eSjoerg // initialized it.
52106f32e7eSjoerg if (!Var->hasInitializer()) {
52206f32e7eSjoerg Var->setInitializer(CGM.EmitNullConstant(E->getType()));
52306f32e7eSjoerg EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
52406f32e7eSjoerg }
52506f32e7eSjoerg } else {
52606f32e7eSjoerg switch (M->getStorageDuration()) {
52706f32e7eSjoerg case SD_Automatic:
52806f32e7eSjoerg if (auto *Size = EmitLifetimeStart(
52906f32e7eSjoerg CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
53006f32e7eSjoerg Alloca.getPointer())) {
53106f32e7eSjoerg pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
53206f32e7eSjoerg Alloca, Size);
53306f32e7eSjoerg }
53406f32e7eSjoerg break;
53506f32e7eSjoerg
53606f32e7eSjoerg case SD_FullExpression: {
53706f32e7eSjoerg if (!ShouldEmitLifetimeMarkers)
53806f32e7eSjoerg break;
53906f32e7eSjoerg
54006f32e7eSjoerg // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
54106f32e7eSjoerg // marker. Instead, start the lifetime of a conditional temporary earlier
54206f32e7eSjoerg // so that it's unconditional. Don't do this with sanitizers which need
54306f32e7eSjoerg // more precise lifetime marks.
54406f32e7eSjoerg ConditionalEvaluation *OldConditional = nullptr;
54506f32e7eSjoerg CGBuilderTy::InsertPoint OldIP;
54606f32e7eSjoerg if (isInConditionalBranch() && !E->getType().isDestructedType() &&
54706f32e7eSjoerg !SanOpts.has(SanitizerKind::HWAddress) &&
54806f32e7eSjoerg !SanOpts.has(SanitizerKind::Memory) &&
54906f32e7eSjoerg !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) {
55006f32e7eSjoerg OldConditional = OutermostConditional;
55106f32e7eSjoerg OutermostConditional = nullptr;
55206f32e7eSjoerg
55306f32e7eSjoerg OldIP = Builder.saveIP();
55406f32e7eSjoerg llvm::BasicBlock *Block = OldConditional->getStartingBlock();
55506f32e7eSjoerg Builder.restoreIP(CGBuilderTy::InsertPoint(
55606f32e7eSjoerg Block, llvm::BasicBlock::iterator(Block->back())));
55706f32e7eSjoerg }
55806f32e7eSjoerg
55906f32e7eSjoerg if (auto *Size = EmitLifetimeStart(
56006f32e7eSjoerg CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
56106f32e7eSjoerg Alloca.getPointer())) {
56206f32e7eSjoerg pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
56306f32e7eSjoerg Size);
56406f32e7eSjoerg }
56506f32e7eSjoerg
56606f32e7eSjoerg if (OldConditional) {
56706f32e7eSjoerg OutermostConditional = OldConditional;
56806f32e7eSjoerg Builder.restoreIP(OldIP);
56906f32e7eSjoerg }
57006f32e7eSjoerg break;
57106f32e7eSjoerg }
57206f32e7eSjoerg
57306f32e7eSjoerg default:
57406f32e7eSjoerg break;
57506f32e7eSjoerg }
57606f32e7eSjoerg EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
57706f32e7eSjoerg }
57806f32e7eSjoerg pushTemporaryCleanup(*this, M, E, Object);
57906f32e7eSjoerg
58006f32e7eSjoerg // Perform derived-to-base casts and/or field accesses, to get from the
58106f32e7eSjoerg // temporary object we created (and, potentially, for which we extended
58206f32e7eSjoerg // the lifetime) to the subobject we're binding the reference to.
58306f32e7eSjoerg for (unsigned I = Adjustments.size(); I != 0; --I) {
58406f32e7eSjoerg SubobjectAdjustment &Adjustment = Adjustments[I-1];
58506f32e7eSjoerg switch (Adjustment.Kind) {
58606f32e7eSjoerg case SubobjectAdjustment::DerivedToBaseAdjustment:
58706f32e7eSjoerg Object =
58806f32e7eSjoerg GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
58906f32e7eSjoerg Adjustment.DerivedToBase.BasePath->path_begin(),
59006f32e7eSjoerg Adjustment.DerivedToBase.BasePath->path_end(),
59106f32e7eSjoerg /*NullCheckValue=*/ false, E->getExprLoc());
59206f32e7eSjoerg break;
59306f32e7eSjoerg
59406f32e7eSjoerg case SubobjectAdjustment::FieldAdjustment: {
59506f32e7eSjoerg LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
59606f32e7eSjoerg LV = EmitLValueForField(LV, Adjustment.Field);
59706f32e7eSjoerg assert(LV.isSimple() &&
59806f32e7eSjoerg "materialized temporary field is not a simple lvalue");
599*13fbcb42Sjoerg Object = LV.getAddress(*this);
60006f32e7eSjoerg break;
60106f32e7eSjoerg }
60206f32e7eSjoerg
60306f32e7eSjoerg case SubobjectAdjustment::MemberPointerAdjustment: {
60406f32e7eSjoerg llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
60506f32e7eSjoerg Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
60606f32e7eSjoerg Adjustment.Ptr.MPT);
60706f32e7eSjoerg break;
60806f32e7eSjoerg }
60906f32e7eSjoerg }
61006f32e7eSjoerg }
61106f32e7eSjoerg
61206f32e7eSjoerg return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
61306f32e7eSjoerg }
61406f32e7eSjoerg
61506f32e7eSjoerg RValue
EmitReferenceBindingToExpr(const Expr * E)61606f32e7eSjoerg CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
61706f32e7eSjoerg // Emit the expression as an lvalue.
61806f32e7eSjoerg LValue LV = EmitLValue(E);
61906f32e7eSjoerg assert(LV.isSimple());
620*13fbcb42Sjoerg llvm::Value *Value = LV.getPointer(*this);
62106f32e7eSjoerg
62206f32e7eSjoerg if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
62306f32e7eSjoerg // C++11 [dcl.ref]p5 (as amended by core issue 453):
62406f32e7eSjoerg // If a glvalue to which a reference is directly bound designates neither
62506f32e7eSjoerg // an existing object or function of an appropriate type nor a region of
62606f32e7eSjoerg // storage of suitable size and alignment to contain an object of the
62706f32e7eSjoerg // reference's type, the behavior is undefined.
62806f32e7eSjoerg QualType Ty = E->getType();
62906f32e7eSjoerg EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
63006f32e7eSjoerg }
63106f32e7eSjoerg
63206f32e7eSjoerg return RValue::get(Value);
63306f32e7eSjoerg }
63406f32e7eSjoerg
63506f32e7eSjoerg
63606f32e7eSjoerg /// getAccessedFieldNo - Given an encoded value and a result number, return the
63706f32e7eSjoerg /// input field number being accessed.
getAccessedFieldNo(unsigned Idx,const llvm::Constant * Elts)63806f32e7eSjoerg unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
63906f32e7eSjoerg const llvm::Constant *Elts) {
64006f32e7eSjoerg return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
64106f32e7eSjoerg ->getZExtValue();
64206f32e7eSjoerg }
64306f32e7eSjoerg
64406f32e7eSjoerg /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
emitHash16Bytes(CGBuilderTy & Builder,llvm::Value * Low,llvm::Value * High)64506f32e7eSjoerg static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
64606f32e7eSjoerg llvm::Value *High) {
64706f32e7eSjoerg llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
64806f32e7eSjoerg llvm::Value *K47 = Builder.getInt64(47);
64906f32e7eSjoerg llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
65006f32e7eSjoerg llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
65106f32e7eSjoerg llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
65206f32e7eSjoerg llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
65306f32e7eSjoerg return Builder.CreateMul(B1, KMul);
65406f32e7eSjoerg }
65506f32e7eSjoerg
isNullPointerAllowed(TypeCheckKind TCK)65606f32e7eSjoerg bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
65706f32e7eSjoerg return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
65806f32e7eSjoerg TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
65906f32e7eSjoerg }
66006f32e7eSjoerg
isVptrCheckRequired(TypeCheckKind TCK,QualType Ty)66106f32e7eSjoerg bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
66206f32e7eSjoerg CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
66306f32e7eSjoerg return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
66406f32e7eSjoerg (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
66506f32e7eSjoerg TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
66606f32e7eSjoerg TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
66706f32e7eSjoerg }
66806f32e7eSjoerg
sanitizePerformTypeCheck() const66906f32e7eSjoerg bool CodeGenFunction::sanitizePerformTypeCheck() const {
67006f32e7eSjoerg return SanOpts.has(SanitizerKind::Null) |
67106f32e7eSjoerg SanOpts.has(SanitizerKind::Alignment) |
67206f32e7eSjoerg SanOpts.has(SanitizerKind::ObjectSize) |
67306f32e7eSjoerg SanOpts.has(SanitizerKind::Vptr);
67406f32e7eSjoerg }
67506f32e7eSjoerg
EmitTypeCheck(TypeCheckKind TCK,SourceLocation Loc,llvm::Value * Ptr,QualType Ty,CharUnits Alignment,SanitizerSet SkippedChecks,llvm::Value * ArraySize)67606f32e7eSjoerg void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
67706f32e7eSjoerg llvm::Value *Ptr, QualType Ty,
67806f32e7eSjoerg CharUnits Alignment,
67906f32e7eSjoerg SanitizerSet SkippedChecks,
68006f32e7eSjoerg llvm::Value *ArraySize) {
68106f32e7eSjoerg if (!sanitizePerformTypeCheck())
68206f32e7eSjoerg return;
68306f32e7eSjoerg
68406f32e7eSjoerg // Don't check pointers outside the default address space. The null check
68506f32e7eSjoerg // isn't correct, the object-size check isn't supported by LLVM, and we can't
68606f32e7eSjoerg // communicate the addresses to the runtime handler for the vptr check.
68706f32e7eSjoerg if (Ptr->getType()->getPointerAddressSpace())
68806f32e7eSjoerg return;
68906f32e7eSjoerg
69006f32e7eSjoerg // Don't check pointers to volatile data. The behavior here is implementation-
69106f32e7eSjoerg // defined.
69206f32e7eSjoerg if (Ty.isVolatileQualified())
69306f32e7eSjoerg return;
69406f32e7eSjoerg
69506f32e7eSjoerg SanitizerScope SanScope(this);
69606f32e7eSjoerg
69706f32e7eSjoerg SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
69806f32e7eSjoerg llvm::BasicBlock *Done = nullptr;
69906f32e7eSjoerg
70006f32e7eSjoerg // Quickly determine whether we have a pointer to an alloca. It's possible
70106f32e7eSjoerg // to skip null checks, and some alignment checks, for these pointers. This
70206f32e7eSjoerg // can reduce compile-time significantly.
70306f32e7eSjoerg auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
70406f32e7eSjoerg
70506f32e7eSjoerg llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
70606f32e7eSjoerg llvm::Value *IsNonNull = nullptr;
70706f32e7eSjoerg bool IsGuaranteedNonNull =
70806f32e7eSjoerg SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
70906f32e7eSjoerg bool AllowNullPointers = isNullPointerAllowed(TCK);
71006f32e7eSjoerg if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
71106f32e7eSjoerg !IsGuaranteedNonNull) {
71206f32e7eSjoerg // The glvalue must not be an empty glvalue.
71306f32e7eSjoerg IsNonNull = Builder.CreateIsNotNull(Ptr);
71406f32e7eSjoerg
71506f32e7eSjoerg // The IR builder can constant-fold the null check if the pointer points to
71606f32e7eSjoerg // a constant.
71706f32e7eSjoerg IsGuaranteedNonNull = IsNonNull == True;
71806f32e7eSjoerg
71906f32e7eSjoerg // Skip the null check if the pointer is known to be non-null.
72006f32e7eSjoerg if (!IsGuaranteedNonNull) {
72106f32e7eSjoerg if (AllowNullPointers) {
72206f32e7eSjoerg // When performing pointer casts, it's OK if the value is null.
72306f32e7eSjoerg // Skip the remaining checks in that case.
72406f32e7eSjoerg Done = createBasicBlock("null");
72506f32e7eSjoerg llvm::BasicBlock *Rest = createBasicBlock("not.null");
72606f32e7eSjoerg Builder.CreateCondBr(IsNonNull, Rest, Done);
72706f32e7eSjoerg EmitBlock(Rest);
72806f32e7eSjoerg } else {
72906f32e7eSjoerg Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
73006f32e7eSjoerg }
73106f32e7eSjoerg }
73206f32e7eSjoerg }
73306f32e7eSjoerg
73406f32e7eSjoerg if (SanOpts.has(SanitizerKind::ObjectSize) &&
73506f32e7eSjoerg !SkippedChecks.has(SanitizerKind::ObjectSize) &&
73606f32e7eSjoerg !Ty->isIncompleteType()) {
737*13fbcb42Sjoerg uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
73806f32e7eSjoerg llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
73906f32e7eSjoerg if (ArraySize)
74006f32e7eSjoerg Size = Builder.CreateMul(Size, ArraySize);
74106f32e7eSjoerg
74206f32e7eSjoerg // Degenerate case: new X[0] does not need an objectsize check.
74306f32e7eSjoerg llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
74406f32e7eSjoerg if (!ConstantSize || !ConstantSize->isNullValue()) {
74506f32e7eSjoerg // The glvalue must refer to a large enough storage region.
74606f32e7eSjoerg // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
74706f32e7eSjoerg // to check this.
74806f32e7eSjoerg // FIXME: Get object address space
74906f32e7eSjoerg llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
75006f32e7eSjoerg llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
75106f32e7eSjoerg llvm::Value *Min = Builder.getFalse();
75206f32e7eSjoerg llvm::Value *NullIsUnknown = Builder.getFalse();
75306f32e7eSjoerg llvm::Value *Dynamic = Builder.getFalse();
75406f32e7eSjoerg llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
75506f32e7eSjoerg llvm::Value *LargeEnough = Builder.CreateICmpUGE(
75606f32e7eSjoerg Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
75706f32e7eSjoerg Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
75806f32e7eSjoerg }
75906f32e7eSjoerg }
76006f32e7eSjoerg
76106f32e7eSjoerg uint64_t AlignVal = 0;
76206f32e7eSjoerg llvm::Value *PtrAsInt = nullptr;
76306f32e7eSjoerg
76406f32e7eSjoerg if (SanOpts.has(SanitizerKind::Alignment) &&
76506f32e7eSjoerg !SkippedChecks.has(SanitizerKind::Alignment)) {
76606f32e7eSjoerg AlignVal = Alignment.getQuantity();
76706f32e7eSjoerg if (!Ty->isIncompleteType() && !AlignVal)
768*13fbcb42Sjoerg AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
769*13fbcb42Sjoerg /*ForPointeeType=*/true)
770*13fbcb42Sjoerg .getQuantity();
77106f32e7eSjoerg
77206f32e7eSjoerg // The glvalue must be suitably aligned.
77306f32e7eSjoerg if (AlignVal > 1 &&
77406f32e7eSjoerg (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
77506f32e7eSjoerg PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
77606f32e7eSjoerg llvm::Value *Align = Builder.CreateAnd(
77706f32e7eSjoerg PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
77806f32e7eSjoerg llvm::Value *Aligned =
77906f32e7eSjoerg Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
78006f32e7eSjoerg if (Aligned != True)
78106f32e7eSjoerg Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
78206f32e7eSjoerg }
78306f32e7eSjoerg }
78406f32e7eSjoerg
78506f32e7eSjoerg if (Checks.size() > 0) {
78606f32e7eSjoerg // Make sure we're not losing information. Alignment needs to be a power of
78706f32e7eSjoerg // 2
78806f32e7eSjoerg assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
78906f32e7eSjoerg llvm::Constant *StaticData[] = {
79006f32e7eSjoerg EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
79106f32e7eSjoerg llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
79206f32e7eSjoerg llvm::ConstantInt::get(Int8Ty, TCK)};
79306f32e7eSjoerg EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
79406f32e7eSjoerg PtrAsInt ? PtrAsInt : Ptr);
79506f32e7eSjoerg }
79606f32e7eSjoerg
79706f32e7eSjoerg // If possible, check that the vptr indicates that there is a subobject of
79806f32e7eSjoerg // type Ty at offset zero within this object.
79906f32e7eSjoerg //
80006f32e7eSjoerg // C++11 [basic.life]p5,6:
80106f32e7eSjoerg // [For storage which does not refer to an object within its lifetime]
80206f32e7eSjoerg // The program has undefined behavior if:
80306f32e7eSjoerg // -- the [pointer or glvalue] is used to access a non-static data member
80406f32e7eSjoerg // or call a non-static member function
80506f32e7eSjoerg if (SanOpts.has(SanitizerKind::Vptr) &&
80606f32e7eSjoerg !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
80706f32e7eSjoerg // Ensure that the pointer is non-null before loading it. If there is no
80806f32e7eSjoerg // compile-time guarantee, reuse the run-time null check or emit a new one.
80906f32e7eSjoerg if (!IsGuaranteedNonNull) {
81006f32e7eSjoerg if (!IsNonNull)
81106f32e7eSjoerg IsNonNull = Builder.CreateIsNotNull(Ptr);
81206f32e7eSjoerg if (!Done)
81306f32e7eSjoerg Done = createBasicBlock("vptr.null");
81406f32e7eSjoerg llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
81506f32e7eSjoerg Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
81606f32e7eSjoerg EmitBlock(VptrNotNull);
81706f32e7eSjoerg }
81806f32e7eSjoerg
81906f32e7eSjoerg // Compute a hash of the mangled name of the type.
82006f32e7eSjoerg //
82106f32e7eSjoerg // FIXME: This is not guaranteed to be deterministic! Move to a
82206f32e7eSjoerg // fingerprinting mechanism once LLVM provides one. For the time
82306f32e7eSjoerg // being the implementation happens to be deterministic.
82406f32e7eSjoerg SmallString<64> MangledName;
82506f32e7eSjoerg llvm::raw_svector_ostream Out(MangledName);
82606f32e7eSjoerg CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
82706f32e7eSjoerg Out);
82806f32e7eSjoerg
829*13fbcb42Sjoerg // Contained in NoSanitizeList based on the mangled type.
830*13fbcb42Sjoerg if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
831*13fbcb42Sjoerg Out.str())) {
83206f32e7eSjoerg llvm::hash_code TypeHash = hash_value(Out.str());
83306f32e7eSjoerg
83406f32e7eSjoerg // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
83506f32e7eSjoerg llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
83606f32e7eSjoerg llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
83706f32e7eSjoerg Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
83806f32e7eSjoerg llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
83906f32e7eSjoerg llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
84006f32e7eSjoerg
84106f32e7eSjoerg llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
84206f32e7eSjoerg Hash = Builder.CreateTrunc(Hash, IntPtrTy);
84306f32e7eSjoerg
84406f32e7eSjoerg // Look the hash up in our cache.
84506f32e7eSjoerg const int CacheSize = 128;
84606f32e7eSjoerg llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
84706f32e7eSjoerg llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
84806f32e7eSjoerg "__ubsan_vptr_type_cache");
84906f32e7eSjoerg llvm::Value *Slot = Builder.CreateAnd(Hash,
85006f32e7eSjoerg llvm::ConstantInt::get(IntPtrTy,
85106f32e7eSjoerg CacheSize-1));
85206f32e7eSjoerg llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
853*13fbcb42Sjoerg llvm::Value *CacheVal = Builder.CreateAlignedLoad(
854*13fbcb42Sjoerg IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
85506f32e7eSjoerg getPointerAlign());
85606f32e7eSjoerg
85706f32e7eSjoerg // If the hash isn't in the cache, call a runtime handler to perform the
85806f32e7eSjoerg // hard work of checking whether the vptr is for an object of the right
85906f32e7eSjoerg // type. This will either fill in the cache and return, or produce a
86006f32e7eSjoerg // diagnostic.
86106f32e7eSjoerg llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
86206f32e7eSjoerg llvm::Constant *StaticData[] = {
86306f32e7eSjoerg EmitCheckSourceLocation(Loc),
86406f32e7eSjoerg EmitCheckTypeDescriptor(Ty),
86506f32e7eSjoerg CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
86606f32e7eSjoerg llvm::ConstantInt::get(Int8Ty, TCK)
86706f32e7eSjoerg };
86806f32e7eSjoerg llvm::Value *DynamicData[] = { Ptr, Hash };
86906f32e7eSjoerg EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
87006f32e7eSjoerg SanitizerHandler::DynamicTypeCacheMiss, StaticData,
87106f32e7eSjoerg DynamicData);
87206f32e7eSjoerg }
87306f32e7eSjoerg }
87406f32e7eSjoerg
87506f32e7eSjoerg if (Done) {
87606f32e7eSjoerg Builder.CreateBr(Done);
87706f32e7eSjoerg EmitBlock(Done);
87806f32e7eSjoerg }
87906f32e7eSjoerg }
88006f32e7eSjoerg
88106f32e7eSjoerg /// Determine whether this expression refers to a flexible array member in a
88206f32e7eSjoerg /// struct. We disable array bounds checks for such members.
isFlexibleArrayMemberExpr(const Expr * E)88306f32e7eSjoerg static bool isFlexibleArrayMemberExpr(const Expr *E) {
88406f32e7eSjoerg // For compatibility with existing code, we treat arrays of length 0 or
88506f32e7eSjoerg // 1 as flexible array members.
886*13fbcb42Sjoerg // FIXME: This is inconsistent with the warning code in SemaChecking. Unify
887*13fbcb42Sjoerg // the two mechanisms.
88806f32e7eSjoerg const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
88906f32e7eSjoerg if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
890*13fbcb42Sjoerg // FIXME: Sema doesn't treat [1] as a flexible array member if the bound
891*13fbcb42Sjoerg // was produced by macro expansion.
89206f32e7eSjoerg if (CAT->getSize().ugt(1))
89306f32e7eSjoerg return false;
89406f32e7eSjoerg } else if (!isa<IncompleteArrayType>(AT))
89506f32e7eSjoerg return false;
89606f32e7eSjoerg
89706f32e7eSjoerg E = E->IgnoreParens();
89806f32e7eSjoerg
89906f32e7eSjoerg // A flexible array member must be the last member in the class.
90006f32e7eSjoerg if (const auto *ME = dyn_cast<MemberExpr>(E)) {
90106f32e7eSjoerg // FIXME: If the base type of the member expr is not FD->getParent(),
90206f32e7eSjoerg // this should not be treated as a flexible array member access.
90306f32e7eSjoerg if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
904*13fbcb42Sjoerg // FIXME: Sema doesn't treat a T[1] union member as a flexible array
905*13fbcb42Sjoerg // member, only a T[0] or T[] member gets that treatment.
906*13fbcb42Sjoerg if (FD->getParent()->isUnion())
907*13fbcb42Sjoerg return true;
90806f32e7eSjoerg RecordDecl::field_iterator FI(
90906f32e7eSjoerg DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
91006f32e7eSjoerg return ++FI == FD->getParent()->field_end();
91106f32e7eSjoerg }
91206f32e7eSjoerg } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
91306f32e7eSjoerg return IRE->getDecl()->getNextIvar() == nullptr;
91406f32e7eSjoerg }
91506f32e7eSjoerg
91606f32e7eSjoerg return false;
91706f32e7eSjoerg }
91806f32e7eSjoerg
LoadPassedObjectSize(const Expr * E,QualType EltTy)91906f32e7eSjoerg llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
92006f32e7eSjoerg QualType EltTy) {
92106f32e7eSjoerg ASTContext &C = getContext();
92206f32e7eSjoerg uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
92306f32e7eSjoerg if (!EltSize)
92406f32e7eSjoerg return nullptr;
92506f32e7eSjoerg
92606f32e7eSjoerg auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
92706f32e7eSjoerg if (!ArrayDeclRef)
92806f32e7eSjoerg return nullptr;
92906f32e7eSjoerg
93006f32e7eSjoerg auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
93106f32e7eSjoerg if (!ParamDecl)
93206f32e7eSjoerg return nullptr;
93306f32e7eSjoerg
93406f32e7eSjoerg auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
93506f32e7eSjoerg if (!POSAttr)
93606f32e7eSjoerg return nullptr;
93706f32e7eSjoerg
93806f32e7eSjoerg // Don't load the size if it's a lower bound.
93906f32e7eSjoerg int POSType = POSAttr->getType();
94006f32e7eSjoerg if (POSType != 0 && POSType != 1)
94106f32e7eSjoerg return nullptr;
94206f32e7eSjoerg
94306f32e7eSjoerg // Find the implicit size parameter.
94406f32e7eSjoerg auto PassedSizeIt = SizeArguments.find(ParamDecl);
94506f32e7eSjoerg if (PassedSizeIt == SizeArguments.end())
94606f32e7eSjoerg return nullptr;
94706f32e7eSjoerg
94806f32e7eSjoerg const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
94906f32e7eSjoerg assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
95006f32e7eSjoerg Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
95106f32e7eSjoerg llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
95206f32e7eSjoerg C.getSizeType(), E->getExprLoc());
95306f32e7eSjoerg llvm::Value *SizeOfElement =
95406f32e7eSjoerg llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
95506f32e7eSjoerg return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
95606f32e7eSjoerg }
95706f32e7eSjoerg
95806f32e7eSjoerg /// If Base is known to point to the start of an array, return the length of
95906f32e7eSjoerg /// that array. Return 0 if the length cannot be determined.
getArrayIndexingBound(CodeGenFunction & CGF,const Expr * Base,QualType & IndexedType)96006f32e7eSjoerg static llvm::Value *getArrayIndexingBound(
96106f32e7eSjoerg CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
96206f32e7eSjoerg // For the vector indexing extension, the bound is the number of elements.
96306f32e7eSjoerg if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
96406f32e7eSjoerg IndexedType = Base->getType();
96506f32e7eSjoerg return CGF.Builder.getInt32(VT->getNumElements());
96606f32e7eSjoerg }
96706f32e7eSjoerg
96806f32e7eSjoerg Base = Base->IgnoreParens();
96906f32e7eSjoerg
97006f32e7eSjoerg if (const auto *CE = dyn_cast<CastExpr>(Base)) {
97106f32e7eSjoerg if (CE->getCastKind() == CK_ArrayToPointerDecay &&
97206f32e7eSjoerg !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
97306f32e7eSjoerg IndexedType = CE->getSubExpr()->getType();
97406f32e7eSjoerg const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
97506f32e7eSjoerg if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
97606f32e7eSjoerg return CGF.Builder.getInt(CAT->getSize());
97706f32e7eSjoerg else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
97806f32e7eSjoerg return CGF.getVLASize(VAT).NumElts;
97906f32e7eSjoerg // Ignore pass_object_size here. It's not applicable on decayed pointers.
98006f32e7eSjoerg }
98106f32e7eSjoerg }
98206f32e7eSjoerg
98306f32e7eSjoerg QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
98406f32e7eSjoerg if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
98506f32e7eSjoerg IndexedType = Base->getType();
98606f32e7eSjoerg return POS;
98706f32e7eSjoerg }
98806f32e7eSjoerg
98906f32e7eSjoerg return nullptr;
99006f32e7eSjoerg }
99106f32e7eSjoerg
EmitBoundsCheck(const Expr * E,const Expr * Base,llvm::Value * Index,QualType IndexType,bool Accessed)99206f32e7eSjoerg void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
99306f32e7eSjoerg llvm::Value *Index, QualType IndexType,
99406f32e7eSjoerg bool Accessed) {
99506f32e7eSjoerg assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
99606f32e7eSjoerg "should not be called unless adding bounds checks");
99706f32e7eSjoerg SanitizerScope SanScope(this);
99806f32e7eSjoerg
99906f32e7eSjoerg QualType IndexedType;
100006f32e7eSjoerg llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
100106f32e7eSjoerg if (!Bound)
100206f32e7eSjoerg return;
100306f32e7eSjoerg
100406f32e7eSjoerg bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
100506f32e7eSjoerg llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
100606f32e7eSjoerg llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
100706f32e7eSjoerg
100806f32e7eSjoerg llvm::Constant *StaticData[] = {
100906f32e7eSjoerg EmitCheckSourceLocation(E->getExprLoc()),
101006f32e7eSjoerg EmitCheckTypeDescriptor(IndexedType),
101106f32e7eSjoerg EmitCheckTypeDescriptor(IndexType)
101206f32e7eSjoerg };
101306f32e7eSjoerg llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
101406f32e7eSjoerg : Builder.CreateICmpULE(IndexVal, BoundVal);
101506f32e7eSjoerg EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
101606f32e7eSjoerg SanitizerHandler::OutOfBounds, StaticData, Index);
101706f32e7eSjoerg }
101806f32e7eSjoerg
101906f32e7eSjoerg
102006f32e7eSjoerg CodeGenFunction::ComplexPairTy CodeGenFunction::
EmitComplexPrePostIncDec(const UnaryOperator * E,LValue LV,bool isInc,bool isPre)102106f32e7eSjoerg EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
102206f32e7eSjoerg bool isInc, bool isPre) {
102306f32e7eSjoerg ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
102406f32e7eSjoerg
102506f32e7eSjoerg llvm::Value *NextVal;
102606f32e7eSjoerg if (isa<llvm::IntegerType>(InVal.first->getType())) {
102706f32e7eSjoerg uint64_t AmountVal = isInc ? 1 : -1;
102806f32e7eSjoerg NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
102906f32e7eSjoerg
103006f32e7eSjoerg // Add the inc/dec to the real part.
103106f32e7eSjoerg NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
103206f32e7eSjoerg } else {
103306f32e7eSjoerg QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
103406f32e7eSjoerg llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
103506f32e7eSjoerg if (!isInc)
103606f32e7eSjoerg FVal.changeSign();
103706f32e7eSjoerg NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
103806f32e7eSjoerg
103906f32e7eSjoerg // Add the inc/dec to the real part.
104006f32e7eSjoerg NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
104106f32e7eSjoerg }
104206f32e7eSjoerg
104306f32e7eSjoerg ComplexPairTy IncVal(NextVal, InVal.second);
104406f32e7eSjoerg
104506f32e7eSjoerg // Store the updated result through the lvalue.
104606f32e7eSjoerg EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1047*13fbcb42Sjoerg if (getLangOpts().OpenMP)
1048*13fbcb42Sjoerg CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1049*13fbcb42Sjoerg E->getSubExpr());
105006f32e7eSjoerg
105106f32e7eSjoerg // If this is a postinc, return the value read from memory, otherwise use the
105206f32e7eSjoerg // updated value.
105306f32e7eSjoerg return isPre ? IncVal : InVal;
105406f32e7eSjoerg }
105506f32e7eSjoerg
EmitExplicitCastExprType(const ExplicitCastExpr * E,CodeGenFunction * CGF)105606f32e7eSjoerg void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
105706f32e7eSjoerg CodeGenFunction *CGF) {
105806f32e7eSjoerg // Bind VLAs in the cast type.
105906f32e7eSjoerg if (CGF && E->getType()->isVariablyModifiedType())
106006f32e7eSjoerg CGF->EmitVariablyModifiedType(E->getType());
106106f32e7eSjoerg
106206f32e7eSjoerg if (CGDebugInfo *DI = getModuleDebugInfo())
106306f32e7eSjoerg DI->EmitExplicitCastType(E->getType());
106406f32e7eSjoerg }
106506f32e7eSjoerg
106606f32e7eSjoerg //===----------------------------------------------------------------------===//
106706f32e7eSjoerg // LValue Expression Emission
106806f32e7eSjoerg //===----------------------------------------------------------------------===//
106906f32e7eSjoerg
107006f32e7eSjoerg /// EmitPointerWithAlignment - Given an expression of pointer type, try to
107106f32e7eSjoerg /// derive a more accurate bound on the alignment of the pointer.
EmitPointerWithAlignment(const Expr * E,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)107206f32e7eSjoerg Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
107306f32e7eSjoerg LValueBaseInfo *BaseInfo,
107406f32e7eSjoerg TBAAAccessInfo *TBAAInfo) {
107506f32e7eSjoerg // We allow this with ObjC object pointers because of fragile ABIs.
107606f32e7eSjoerg assert(E->getType()->isPointerType() ||
107706f32e7eSjoerg E->getType()->isObjCObjectPointerType());
107806f32e7eSjoerg E = E->IgnoreParens();
107906f32e7eSjoerg
108006f32e7eSjoerg // Casts:
108106f32e7eSjoerg if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
108206f32e7eSjoerg if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
108306f32e7eSjoerg CGM.EmitExplicitCastExprType(ECE, this);
108406f32e7eSjoerg
108506f32e7eSjoerg switch (CE->getCastKind()) {
108606f32e7eSjoerg // Non-converting casts (but not C's implicit conversion from void*).
108706f32e7eSjoerg case CK_BitCast:
108806f32e7eSjoerg case CK_NoOp:
108906f32e7eSjoerg case CK_AddressSpaceConversion:
109006f32e7eSjoerg if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
109106f32e7eSjoerg if (PtrTy->getPointeeType()->isVoidType())
109206f32e7eSjoerg break;
109306f32e7eSjoerg
109406f32e7eSjoerg LValueBaseInfo InnerBaseInfo;
109506f32e7eSjoerg TBAAAccessInfo InnerTBAAInfo;
109606f32e7eSjoerg Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
109706f32e7eSjoerg &InnerBaseInfo,
109806f32e7eSjoerg &InnerTBAAInfo);
109906f32e7eSjoerg if (BaseInfo) *BaseInfo = InnerBaseInfo;
110006f32e7eSjoerg if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
110106f32e7eSjoerg
110206f32e7eSjoerg if (isa<ExplicitCastExpr>(CE)) {
110306f32e7eSjoerg LValueBaseInfo TargetTypeBaseInfo;
110406f32e7eSjoerg TBAAAccessInfo TargetTypeTBAAInfo;
1105*13fbcb42Sjoerg CharUnits Align = CGM.getNaturalPointeeTypeAlignment(
1106*13fbcb42Sjoerg E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
110706f32e7eSjoerg if (TBAAInfo)
110806f32e7eSjoerg *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
110906f32e7eSjoerg TargetTypeTBAAInfo);
111006f32e7eSjoerg // If the source l-value is opaque, honor the alignment of the
111106f32e7eSjoerg // casted-to type.
111206f32e7eSjoerg if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
111306f32e7eSjoerg if (BaseInfo)
111406f32e7eSjoerg BaseInfo->mergeForCast(TargetTypeBaseInfo);
111506f32e7eSjoerg Addr = Address(Addr.getPointer(), Align);
111606f32e7eSjoerg }
111706f32e7eSjoerg }
111806f32e7eSjoerg
111906f32e7eSjoerg if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
112006f32e7eSjoerg CE->getCastKind() == CK_BitCast) {
112106f32e7eSjoerg if (auto PT = E->getType()->getAs<PointerType>())
112206f32e7eSjoerg EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
112306f32e7eSjoerg /*MayBeNull=*/true,
112406f32e7eSjoerg CodeGenFunction::CFITCK_UnrelatedCast,
112506f32e7eSjoerg CE->getBeginLoc());
112606f32e7eSjoerg }
112706f32e7eSjoerg return CE->getCastKind() != CK_AddressSpaceConversion
112806f32e7eSjoerg ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
112906f32e7eSjoerg : Builder.CreateAddrSpaceCast(Addr,
113006f32e7eSjoerg ConvertType(E->getType()));
113106f32e7eSjoerg }
113206f32e7eSjoerg break;
113306f32e7eSjoerg
113406f32e7eSjoerg // Array-to-pointer decay.
113506f32e7eSjoerg case CK_ArrayToPointerDecay:
113606f32e7eSjoerg return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
113706f32e7eSjoerg
113806f32e7eSjoerg // Derived-to-base conversions.
113906f32e7eSjoerg case CK_UncheckedDerivedToBase:
114006f32e7eSjoerg case CK_DerivedToBase: {
114106f32e7eSjoerg // TODO: Support accesses to members of base classes in TBAA. For now, we
114206f32e7eSjoerg // conservatively pretend that the complete object is of the base class
114306f32e7eSjoerg // type.
114406f32e7eSjoerg if (TBAAInfo)
114506f32e7eSjoerg *TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
114606f32e7eSjoerg Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
114706f32e7eSjoerg auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
114806f32e7eSjoerg return GetAddressOfBaseClass(Addr, Derived,
114906f32e7eSjoerg CE->path_begin(), CE->path_end(),
115006f32e7eSjoerg ShouldNullCheckClassCastValue(CE),
115106f32e7eSjoerg CE->getExprLoc());
115206f32e7eSjoerg }
115306f32e7eSjoerg
115406f32e7eSjoerg // TODO: Is there any reason to treat base-to-derived conversions
115506f32e7eSjoerg // specially?
115606f32e7eSjoerg default:
115706f32e7eSjoerg break;
115806f32e7eSjoerg }
115906f32e7eSjoerg }
116006f32e7eSjoerg
116106f32e7eSjoerg // Unary &.
116206f32e7eSjoerg if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
116306f32e7eSjoerg if (UO->getOpcode() == UO_AddrOf) {
116406f32e7eSjoerg LValue LV = EmitLValue(UO->getSubExpr());
116506f32e7eSjoerg if (BaseInfo) *BaseInfo = LV.getBaseInfo();
116606f32e7eSjoerg if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1167*13fbcb42Sjoerg return LV.getAddress(*this);
116806f32e7eSjoerg }
116906f32e7eSjoerg }
117006f32e7eSjoerg
117106f32e7eSjoerg // TODO: conditional operators, comma.
117206f32e7eSjoerg
117306f32e7eSjoerg // Otherwise, use the alignment of the type.
1174*13fbcb42Sjoerg CharUnits Align =
1175*13fbcb42Sjoerg CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo, TBAAInfo);
117606f32e7eSjoerg return Address(EmitScalarExpr(E), Align);
117706f32e7eSjoerg }
117806f32e7eSjoerg
EmitNonNullRValueCheck(RValue RV,QualType T)1179*13fbcb42Sjoerg llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
1180*13fbcb42Sjoerg llvm::Value *V = RV.getScalarVal();
1181*13fbcb42Sjoerg if (auto MPT = T->getAs<MemberPointerType>())
1182*13fbcb42Sjoerg return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1183*13fbcb42Sjoerg return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1184*13fbcb42Sjoerg }
1185*13fbcb42Sjoerg
GetUndefRValue(QualType Ty)118606f32e7eSjoerg RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
118706f32e7eSjoerg if (Ty->isVoidType())
118806f32e7eSjoerg return RValue::get(nullptr);
118906f32e7eSjoerg
119006f32e7eSjoerg switch (getEvaluationKind(Ty)) {
119106f32e7eSjoerg case TEK_Complex: {
119206f32e7eSjoerg llvm::Type *EltTy =
119306f32e7eSjoerg ConvertType(Ty->castAs<ComplexType>()->getElementType());
119406f32e7eSjoerg llvm::Value *U = llvm::UndefValue::get(EltTy);
119506f32e7eSjoerg return RValue::getComplex(std::make_pair(U, U));
119606f32e7eSjoerg }
119706f32e7eSjoerg
119806f32e7eSjoerg // If this is a use of an undefined aggregate type, the aggregate must have an
119906f32e7eSjoerg // identifiable address. Just because the contents of the value are undefined
120006f32e7eSjoerg // doesn't mean that the address can't be taken and compared.
120106f32e7eSjoerg case TEK_Aggregate: {
120206f32e7eSjoerg Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
120306f32e7eSjoerg return RValue::getAggregate(DestPtr);
120406f32e7eSjoerg }
120506f32e7eSjoerg
120606f32e7eSjoerg case TEK_Scalar:
120706f32e7eSjoerg return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
120806f32e7eSjoerg }
120906f32e7eSjoerg llvm_unreachable("bad evaluation kind");
121006f32e7eSjoerg }
121106f32e7eSjoerg
EmitUnsupportedRValue(const Expr * E,const char * Name)121206f32e7eSjoerg RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
121306f32e7eSjoerg const char *Name) {
121406f32e7eSjoerg ErrorUnsupported(E, Name);
121506f32e7eSjoerg return GetUndefRValue(E->getType());
121606f32e7eSjoerg }
121706f32e7eSjoerg
EmitUnsupportedLValue(const Expr * E,const char * Name)121806f32e7eSjoerg LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
121906f32e7eSjoerg const char *Name) {
122006f32e7eSjoerg ErrorUnsupported(E, Name);
122106f32e7eSjoerg llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
122206f32e7eSjoerg return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
122306f32e7eSjoerg E->getType());
122406f32e7eSjoerg }
122506f32e7eSjoerg
IsWrappedCXXThis(const Expr * Obj)122606f32e7eSjoerg bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
122706f32e7eSjoerg const Expr *Base = Obj;
122806f32e7eSjoerg while (!isa<CXXThisExpr>(Base)) {
122906f32e7eSjoerg // The result of a dynamic_cast can be null.
123006f32e7eSjoerg if (isa<CXXDynamicCastExpr>(Base))
123106f32e7eSjoerg return false;
123206f32e7eSjoerg
123306f32e7eSjoerg if (const auto *CE = dyn_cast<CastExpr>(Base)) {
123406f32e7eSjoerg Base = CE->getSubExpr();
123506f32e7eSjoerg } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
123606f32e7eSjoerg Base = PE->getSubExpr();
123706f32e7eSjoerg } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
123806f32e7eSjoerg if (UO->getOpcode() == UO_Extension)
123906f32e7eSjoerg Base = UO->getSubExpr();
124006f32e7eSjoerg else
124106f32e7eSjoerg return false;
124206f32e7eSjoerg } else {
124306f32e7eSjoerg return false;
124406f32e7eSjoerg }
124506f32e7eSjoerg }
124606f32e7eSjoerg return true;
124706f32e7eSjoerg }
124806f32e7eSjoerg
EmitCheckedLValue(const Expr * E,TypeCheckKind TCK)124906f32e7eSjoerg LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
125006f32e7eSjoerg LValue LV;
125106f32e7eSjoerg if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
125206f32e7eSjoerg LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
125306f32e7eSjoerg else
125406f32e7eSjoerg LV = EmitLValue(E);
125506f32e7eSjoerg if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
125606f32e7eSjoerg SanitizerSet SkippedChecks;
125706f32e7eSjoerg if (const auto *ME = dyn_cast<MemberExpr>(E)) {
125806f32e7eSjoerg bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
125906f32e7eSjoerg if (IsBaseCXXThis)
126006f32e7eSjoerg SkippedChecks.set(SanitizerKind::Alignment, true);
126106f32e7eSjoerg if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
126206f32e7eSjoerg SkippedChecks.set(SanitizerKind::Null, true);
126306f32e7eSjoerg }
1264*13fbcb42Sjoerg EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
1265*13fbcb42Sjoerg LV.getAlignment(), SkippedChecks);
126606f32e7eSjoerg }
126706f32e7eSjoerg return LV;
126806f32e7eSjoerg }
126906f32e7eSjoerg
127006f32e7eSjoerg /// EmitLValue - Emit code to compute a designator that specifies the location
127106f32e7eSjoerg /// of the expression.
127206f32e7eSjoerg ///
127306f32e7eSjoerg /// This can return one of two things: a simple address or a bitfield reference.
127406f32e7eSjoerg /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
127506f32e7eSjoerg /// an LLVM pointer type.
127606f32e7eSjoerg ///
127706f32e7eSjoerg /// If this returns a bitfield reference, nothing about the pointee type of the
127806f32e7eSjoerg /// LLVM value is known: For example, it may not be a pointer to an integer.
127906f32e7eSjoerg ///
128006f32e7eSjoerg /// If this returns a normal address, and if the lvalue's C type is fixed size,
128106f32e7eSjoerg /// this method guarantees that the returned pointer type will point to an LLVM
128206f32e7eSjoerg /// type of the same size of the lvalue's type. If the lvalue has a variable
128306f32e7eSjoerg /// length type, this is not possible.
128406f32e7eSjoerg ///
EmitLValue(const Expr * E)128506f32e7eSjoerg LValue CodeGenFunction::EmitLValue(const Expr *E) {
128606f32e7eSjoerg ApplyDebugLocation DL(*this, E);
128706f32e7eSjoerg switch (E->getStmtClass()) {
128806f32e7eSjoerg default: return EmitUnsupportedLValue(E, "l-value expression");
128906f32e7eSjoerg
129006f32e7eSjoerg case Expr::ObjCPropertyRefExprClass:
129106f32e7eSjoerg llvm_unreachable("cannot emit a property reference directly");
129206f32e7eSjoerg
129306f32e7eSjoerg case Expr::ObjCSelectorExprClass:
129406f32e7eSjoerg return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
129506f32e7eSjoerg case Expr::ObjCIsaExprClass:
129606f32e7eSjoerg return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
129706f32e7eSjoerg case Expr::BinaryOperatorClass:
129806f32e7eSjoerg return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
129906f32e7eSjoerg case Expr::CompoundAssignOperatorClass: {
130006f32e7eSjoerg QualType Ty = E->getType();
130106f32e7eSjoerg if (const AtomicType *AT = Ty->getAs<AtomicType>())
130206f32e7eSjoerg Ty = AT->getValueType();
130306f32e7eSjoerg if (!Ty->isAnyComplexType())
130406f32e7eSjoerg return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
130506f32e7eSjoerg return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
130606f32e7eSjoerg }
130706f32e7eSjoerg case Expr::CallExprClass:
130806f32e7eSjoerg case Expr::CXXMemberCallExprClass:
130906f32e7eSjoerg case Expr::CXXOperatorCallExprClass:
131006f32e7eSjoerg case Expr::UserDefinedLiteralClass:
131106f32e7eSjoerg return EmitCallExprLValue(cast<CallExpr>(E));
131206f32e7eSjoerg case Expr::CXXRewrittenBinaryOperatorClass:
131306f32e7eSjoerg return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm());
131406f32e7eSjoerg case Expr::VAArgExprClass:
131506f32e7eSjoerg return EmitVAArgExprLValue(cast<VAArgExpr>(E));
131606f32e7eSjoerg case Expr::DeclRefExprClass:
131706f32e7eSjoerg return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1318*13fbcb42Sjoerg case Expr::ConstantExprClass: {
1319*13fbcb42Sjoerg const ConstantExpr *CE = cast<ConstantExpr>(E);
1320*13fbcb42Sjoerg if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
1321*13fbcb42Sjoerg QualType RetType = cast<CallExpr>(CE->getSubExpr()->IgnoreImplicit())
1322*13fbcb42Sjoerg ->getCallReturnType(getContext());
1323*13fbcb42Sjoerg return MakeNaturalAlignAddrLValue(Result, RetType);
1324*13fbcb42Sjoerg }
132506f32e7eSjoerg return EmitLValue(cast<ConstantExpr>(E)->getSubExpr());
1326*13fbcb42Sjoerg }
132706f32e7eSjoerg case Expr::ParenExprClass:
132806f32e7eSjoerg return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
132906f32e7eSjoerg case Expr::GenericSelectionExprClass:
133006f32e7eSjoerg return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
133106f32e7eSjoerg case Expr::PredefinedExprClass:
133206f32e7eSjoerg return EmitPredefinedLValue(cast<PredefinedExpr>(E));
133306f32e7eSjoerg case Expr::StringLiteralClass:
133406f32e7eSjoerg return EmitStringLiteralLValue(cast<StringLiteral>(E));
133506f32e7eSjoerg case Expr::ObjCEncodeExprClass:
133606f32e7eSjoerg return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
133706f32e7eSjoerg case Expr::PseudoObjectExprClass:
133806f32e7eSjoerg return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
133906f32e7eSjoerg case Expr::InitListExprClass:
134006f32e7eSjoerg return EmitInitListLValue(cast<InitListExpr>(E));
134106f32e7eSjoerg case Expr::CXXTemporaryObjectExprClass:
134206f32e7eSjoerg case Expr::CXXConstructExprClass:
134306f32e7eSjoerg return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
134406f32e7eSjoerg case Expr::CXXBindTemporaryExprClass:
134506f32e7eSjoerg return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
134606f32e7eSjoerg case Expr::CXXUuidofExprClass:
134706f32e7eSjoerg return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
134806f32e7eSjoerg case Expr::LambdaExprClass:
134906f32e7eSjoerg return EmitAggExprToLValue(E);
135006f32e7eSjoerg
135106f32e7eSjoerg case Expr::ExprWithCleanupsClass: {
135206f32e7eSjoerg const auto *cleanups = cast<ExprWithCleanups>(E);
135306f32e7eSjoerg RunCleanupsScope Scope(*this);
135406f32e7eSjoerg LValue LV = EmitLValue(cleanups->getSubExpr());
135506f32e7eSjoerg if (LV.isSimple()) {
135606f32e7eSjoerg // Defend against branches out of gnu statement expressions surrounded by
135706f32e7eSjoerg // cleanups.
1358*13fbcb42Sjoerg llvm::Value *V = LV.getPointer(*this);
135906f32e7eSjoerg Scope.ForceCleanup({&V});
136006f32e7eSjoerg return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
136106f32e7eSjoerg getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
136206f32e7eSjoerg }
136306f32e7eSjoerg // FIXME: Is it possible to create an ExprWithCleanups that produces a
136406f32e7eSjoerg // bitfield lvalue or some other non-simple lvalue?
136506f32e7eSjoerg return LV;
136606f32e7eSjoerg }
136706f32e7eSjoerg
136806f32e7eSjoerg case Expr::CXXDefaultArgExprClass: {
136906f32e7eSjoerg auto *DAE = cast<CXXDefaultArgExpr>(E);
137006f32e7eSjoerg CXXDefaultArgExprScope Scope(*this, DAE);
137106f32e7eSjoerg return EmitLValue(DAE->getExpr());
137206f32e7eSjoerg }
137306f32e7eSjoerg case Expr::CXXDefaultInitExprClass: {
137406f32e7eSjoerg auto *DIE = cast<CXXDefaultInitExpr>(E);
137506f32e7eSjoerg CXXDefaultInitExprScope Scope(*this, DIE);
137606f32e7eSjoerg return EmitLValue(DIE->getExpr());
137706f32e7eSjoerg }
137806f32e7eSjoerg case Expr::CXXTypeidExprClass:
137906f32e7eSjoerg return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
138006f32e7eSjoerg
138106f32e7eSjoerg case Expr::ObjCMessageExprClass:
138206f32e7eSjoerg return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
138306f32e7eSjoerg case Expr::ObjCIvarRefExprClass:
138406f32e7eSjoerg return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
138506f32e7eSjoerg case Expr::StmtExprClass:
138606f32e7eSjoerg return EmitStmtExprLValue(cast<StmtExpr>(E));
138706f32e7eSjoerg case Expr::UnaryOperatorClass:
138806f32e7eSjoerg return EmitUnaryOpLValue(cast<UnaryOperator>(E));
138906f32e7eSjoerg case Expr::ArraySubscriptExprClass:
139006f32e7eSjoerg return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1391*13fbcb42Sjoerg case Expr::MatrixSubscriptExprClass:
1392*13fbcb42Sjoerg return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
139306f32e7eSjoerg case Expr::OMPArraySectionExprClass:
139406f32e7eSjoerg return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
139506f32e7eSjoerg case Expr::ExtVectorElementExprClass:
139606f32e7eSjoerg return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
139706f32e7eSjoerg case Expr::MemberExprClass:
139806f32e7eSjoerg return EmitMemberExpr(cast<MemberExpr>(E));
139906f32e7eSjoerg case Expr::CompoundLiteralExprClass:
140006f32e7eSjoerg return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
140106f32e7eSjoerg case Expr::ConditionalOperatorClass:
140206f32e7eSjoerg return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
140306f32e7eSjoerg case Expr::BinaryConditionalOperatorClass:
140406f32e7eSjoerg return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
140506f32e7eSjoerg case Expr::ChooseExprClass:
140606f32e7eSjoerg return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
140706f32e7eSjoerg case Expr::OpaqueValueExprClass:
140806f32e7eSjoerg return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
140906f32e7eSjoerg case Expr::SubstNonTypeTemplateParmExprClass:
141006f32e7eSjoerg return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
141106f32e7eSjoerg case Expr::ImplicitCastExprClass:
141206f32e7eSjoerg case Expr::CStyleCastExprClass:
141306f32e7eSjoerg case Expr::CXXFunctionalCastExprClass:
141406f32e7eSjoerg case Expr::CXXStaticCastExprClass:
141506f32e7eSjoerg case Expr::CXXDynamicCastExprClass:
141606f32e7eSjoerg case Expr::CXXReinterpretCastExprClass:
141706f32e7eSjoerg case Expr::CXXConstCastExprClass:
1418*13fbcb42Sjoerg case Expr::CXXAddrspaceCastExprClass:
141906f32e7eSjoerg case Expr::ObjCBridgedCastExprClass:
142006f32e7eSjoerg return EmitCastLValue(cast<CastExpr>(E));
142106f32e7eSjoerg
142206f32e7eSjoerg case Expr::MaterializeTemporaryExprClass:
142306f32e7eSjoerg return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
142406f32e7eSjoerg
142506f32e7eSjoerg case Expr::CoawaitExprClass:
142606f32e7eSjoerg return EmitCoawaitLValue(cast<CoawaitExpr>(E));
142706f32e7eSjoerg case Expr::CoyieldExprClass:
142806f32e7eSjoerg return EmitCoyieldLValue(cast<CoyieldExpr>(E));
142906f32e7eSjoerg }
143006f32e7eSjoerg }
143106f32e7eSjoerg
143206f32e7eSjoerg /// Given an object of the given canonical type, can we safely copy a
143306f32e7eSjoerg /// value out of it based on its initializer?
isConstantEmittableObjectType(QualType type)143406f32e7eSjoerg static bool isConstantEmittableObjectType(QualType type) {
143506f32e7eSjoerg assert(type.isCanonical());
143606f32e7eSjoerg assert(!type->isReferenceType());
143706f32e7eSjoerg
143806f32e7eSjoerg // Must be const-qualified but non-volatile.
143906f32e7eSjoerg Qualifiers qs = type.getLocalQualifiers();
144006f32e7eSjoerg if (!qs.hasConst() || qs.hasVolatile()) return false;
144106f32e7eSjoerg
144206f32e7eSjoerg // Otherwise, all object types satisfy this except C++ classes with
144306f32e7eSjoerg // mutable subobjects or non-trivial copy/destroy behavior.
144406f32e7eSjoerg if (const auto *RT = dyn_cast<RecordType>(type))
144506f32e7eSjoerg if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
144606f32e7eSjoerg if (RD->hasMutableFields() || !RD->isTrivial())
144706f32e7eSjoerg return false;
144806f32e7eSjoerg
144906f32e7eSjoerg return true;
145006f32e7eSjoerg }
145106f32e7eSjoerg
145206f32e7eSjoerg /// Can we constant-emit a load of a reference to a variable of the
145306f32e7eSjoerg /// given type? This is different from predicates like
145406f32e7eSjoerg /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
145506f32e7eSjoerg /// in situations that don't necessarily satisfy the language's rules
145606f32e7eSjoerg /// for this (e.g. C++'s ODR-use rules). For example, we want to able
145706f32e7eSjoerg /// to do this with const float variables even if those variables
145806f32e7eSjoerg /// aren't marked 'constexpr'.
145906f32e7eSjoerg enum ConstantEmissionKind {
146006f32e7eSjoerg CEK_None,
146106f32e7eSjoerg CEK_AsReferenceOnly,
146206f32e7eSjoerg CEK_AsValueOrReference,
146306f32e7eSjoerg CEK_AsValueOnly
146406f32e7eSjoerg };
checkVarTypeForConstantEmission(QualType type)146506f32e7eSjoerg static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
146606f32e7eSjoerg type = type.getCanonicalType();
146706f32e7eSjoerg if (const auto *ref = dyn_cast<ReferenceType>(type)) {
146806f32e7eSjoerg if (isConstantEmittableObjectType(ref->getPointeeType()))
146906f32e7eSjoerg return CEK_AsValueOrReference;
147006f32e7eSjoerg return CEK_AsReferenceOnly;
147106f32e7eSjoerg }
147206f32e7eSjoerg if (isConstantEmittableObjectType(type))
147306f32e7eSjoerg return CEK_AsValueOnly;
147406f32e7eSjoerg return CEK_None;
147506f32e7eSjoerg }
147606f32e7eSjoerg
147706f32e7eSjoerg /// Try to emit a reference to the given value without producing it as
147806f32e7eSjoerg /// an l-value. This is just an optimization, but it avoids us needing
147906f32e7eSjoerg /// to emit global copies of variables if they're named without triggering
148006f32e7eSjoerg /// a formal use in a context where we can't emit a direct reference to them,
148106f32e7eSjoerg /// for instance if a block or lambda or a member of a local class uses a
148206f32e7eSjoerg /// const int variable or constexpr variable from an enclosing function.
148306f32e7eSjoerg CodeGenFunction::ConstantEmission
tryEmitAsConstant(DeclRefExpr * refExpr)148406f32e7eSjoerg CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
148506f32e7eSjoerg ValueDecl *value = refExpr->getDecl();
148606f32e7eSjoerg
148706f32e7eSjoerg // The value needs to be an enum constant or a constant variable.
148806f32e7eSjoerg ConstantEmissionKind CEK;
148906f32e7eSjoerg if (isa<ParmVarDecl>(value)) {
149006f32e7eSjoerg CEK = CEK_None;
149106f32e7eSjoerg } else if (auto *var = dyn_cast<VarDecl>(value)) {
149206f32e7eSjoerg CEK = checkVarTypeForConstantEmission(var->getType());
149306f32e7eSjoerg } else if (isa<EnumConstantDecl>(value)) {
149406f32e7eSjoerg CEK = CEK_AsValueOnly;
149506f32e7eSjoerg } else {
149606f32e7eSjoerg CEK = CEK_None;
149706f32e7eSjoerg }
149806f32e7eSjoerg if (CEK == CEK_None) return ConstantEmission();
149906f32e7eSjoerg
150006f32e7eSjoerg Expr::EvalResult result;
150106f32e7eSjoerg bool resultIsReference;
150206f32e7eSjoerg QualType resultType;
150306f32e7eSjoerg
150406f32e7eSjoerg // It's best to evaluate all the way as an r-value if that's permitted.
150506f32e7eSjoerg if (CEK != CEK_AsReferenceOnly &&
150606f32e7eSjoerg refExpr->EvaluateAsRValue(result, getContext())) {
150706f32e7eSjoerg resultIsReference = false;
150806f32e7eSjoerg resultType = refExpr->getType();
150906f32e7eSjoerg
151006f32e7eSjoerg // Otherwise, try to evaluate as an l-value.
151106f32e7eSjoerg } else if (CEK != CEK_AsValueOnly &&
151206f32e7eSjoerg refExpr->EvaluateAsLValue(result, getContext())) {
151306f32e7eSjoerg resultIsReference = true;
151406f32e7eSjoerg resultType = value->getType();
151506f32e7eSjoerg
151606f32e7eSjoerg // Failure.
151706f32e7eSjoerg } else {
151806f32e7eSjoerg return ConstantEmission();
151906f32e7eSjoerg }
152006f32e7eSjoerg
152106f32e7eSjoerg // In any case, if the initializer has side-effects, abandon ship.
152206f32e7eSjoerg if (result.HasSideEffects)
152306f32e7eSjoerg return ConstantEmission();
152406f32e7eSjoerg
1525*13fbcb42Sjoerg // In CUDA/HIP device compilation, a lambda may capture a reference variable
1526*13fbcb42Sjoerg // referencing a global host variable by copy. In this case the lambda should
1527*13fbcb42Sjoerg // make a copy of the value of the global host variable. The DRE of the
1528*13fbcb42Sjoerg // captured reference variable cannot be emitted as load from the host
1529*13fbcb42Sjoerg // global variable as compile time constant, since the host variable is not
1530*13fbcb42Sjoerg // accessible on device. The DRE of the captured reference variable has to be
1531*13fbcb42Sjoerg // loaded from captures.
1532*13fbcb42Sjoerg if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
1533*13fbcb42Sjoerg refExpr->refersToEnclosingVariableOrCapture()) {
1534*13fbcb42Sjoerg auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
1535*13fbcb42Sjoerg if (MD && MD->getParent()->isLambda() &&
1536*13fbcb42Sjoerg MD->getOverloadedOperator() == OO_Call) {
1537*13fbcb42Sjoerg const APValue::LValueBase &base = result.Val.getLValueBase();
1538*13fbcb42Sjoerg if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1539*13fbcb42Sjoerg if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1540*13fbcb42Sjoerg if (!VD->hasAttr<CUDADeviceAttr>()) {
1541*13fbcb42Sjoerg return ConstantEmission();
1542*13fbcb42Sjoerg }
1543*13fbcb42Sjoerg }
1544*13fbcb42Sjoerg }
1545*13fbcb42Sjoerg }
1546*13fbcb42Sjoerg }
1547*13fbcb42Sjoerg
154806f32e7eSjoerg // Emit as a constant.
154906f32e7eSjoerg auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
155006f32e7eSjoerg result.Val, resultType);
155106f32e7eSjoerg
155206f32e7eSjoerg // Make sure we emit a debug reference to the global variable.
155306f32e7eSjoerg // This should probably fire even for
155406f32e7eSjoerg if (isa<VarDecl>(value)) {
155506f32e7eSjoerg if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
155606f32e7eSjoerg EmitDeclRefExprDbgValue(refExpr, result.Val);
155706f32e7eSjoerg } else {
155806f32e7eSjoerg assert(isa<EnumConstantDecl>(value));
155906f32e7eSjoerg EmitDeclRefExprDbgValue(refExpr, result.Val);
156006f32e7eSjoerg }
156106f32e7eSjoerg
156206f32e7eSjoerg // If we emitted a reference constant, we need to dereference that.
156306f32e7eSjoerg if (resultIsReference)
156406f32e7eSjoerg return ConstantEmission::forReference(C);
156506f32e7eSjoerg
156606f32e7eSjoerg return ConstantEmission::forValue(C);
156706f32e7eSjoerg }
156806f32e7eSjoerg
tryToConvertMemberExprToDeclRefExpr(CodeGenFunction & CGF,const MemberExpr * ME)156906f32e7eSjoerg static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
157006f32e7eSjoerg const MemberExpr *ME) {
157106f32e7eSjoerg if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
157206f32e7eSjoerg // Try to emit static variable member expressions as DREs.
157306f32e7eSjoerg return DeclRefExpr::Create(
157406f32e7eSjoerg CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
157506f32e7eSjoerg /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
157606f32e7eSjoerg ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
157706f32e7eSjoerg }
157806f32e7eSjoerg return nullptr;
157906f32e7eSjoerg }
158006f32e7eSjoerg
158106f32e7eSjoerg CodeGenFunction::ConstantEmission
tryEmitAsConstant(const MemberExpr * ME)158206f32e7eSjoerg CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
158306f32e7eSjoerg if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
158406f32e7eSjoerg return tryEmitAsConstant(DRE);
158506f32e7eSjoerg return ConstantEmission();
158606f32e7eSjoerg }
158706f32e7eSjoerg
emitScalarConstant(const CodeGenFunction::ConstantEmission & Constant,Expr * E)158806f32e7eSjoerg llvm::Value *CodeGenFunction::emitScalarConstant(
158906f32e7eSjoerg const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
159006f32e7eSjoerg assert(Constant && "not a constant");
159106f32e7eSjoerg if (Constant.isReference())
159206f32e7eSjoerg return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
159306f32e7eSjoerg E->getExprLoc())
159406f32e7eSjoerg .getScalarVal();
159506f32e7eSjoerg return Constant.getValue();
159606f32e7eSjoerg }
159706f32e7eSjoerg
EmitLoadOfScalar(LValue lvalue,SourceLocation Loc)159806f32e7eSjoerg llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
159906f32e7eSjoerg SourceLocation Loc) {
1600*13fbcb42Sjoerg return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
160106f32e7eSjoerg lvalue.getType(), Loc, lvalue.getBaseInfo(),
160206f32e7eSjoerg lvalue.getTBAAInfo(), lvalue.isNontemporal());
160306f32e7eSjoerg }
160406f32e7eSjoerg
hasBooleanRepresentation(QualType Ty)160506f32e7eSjoerg static bool hasBooleanRepresentation(QualType Ty) {
160606f32e7eSjoerg if (Ty->isBooleanType())
160706f32e7eSjoerg return true;
160806f32e7eSjoerg
160906f32e7eSjoerg if (const EnumType *ET = Ty->getAs<EnumType>())
161006f32e7eSjoerg return ET->getDecl()->getIntegerType()->isBooleanType();
161106f32e7eSjoerg
161206f32e7eSjoerg if (const AtomicType *AT = Ty->getAs<AtomicType>())
161306f32e7eSjoerg return hasBooleanRepresentation(AT->getValueType());
161406f32e7eSjoerg
161506f32e7eSjoerg return false;
161606f32e7eSjoerg }
161706f32e7eSjoerg
getRangeForType(CodeGenFunction & CGF,QualType Ty,llvm::APInt & Min,llvm::APInt & End,bool StrictEnums,bool IsBool)161806f32e7eSjoerg static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
161906f32e7eSjoerg llvm::APInt &Min, llvm::APInt &End,
162006f32e7eSjoerg bool StrictEnums, bool IsBool) {
162106f32e7eSjoerg const EnumType *ET = Ty->getAs<EnumType>();
162206f32e7eSjoerg bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
162306f32e7eSjoerg ET && !ET->getDecl()->isFixed();
162406f32e7eSjoerg if (!IsBool && !IsRegularCPlusPlusEnum)
162506f32e7eSjoerg return false;
162606f32e7eSjoerg
162706f32e7eSjoerg if (IsBool) {
162806f32e7eSjoerg Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
162906f32e7eSjoerg End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
163006f32e7eSjoerg } else {
163106f32e7eSjoerg const EnumDecl *ED = ET->getDecl();
163206f32e7eSjoerg llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
163306f32e7eSjoerg unsigned Bitwidth = LTy->getScalarSizeInBits();
163406f32e7eSjoerg unsigned NumNegativeBits = ED->getNumNegativeBits();
163506f32e7eSjoerg unsigned NumPositiveBits = ED->getNumPositiveBits();
163606f32e7eSjoerg
163706f32e7eSjoerg if (NumNegativeBits) {
163806f32e7eSjoerg unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
163906f32e7eSjoerg assert(NumBits <= Bitwidth);
164006f32e7eSjoerg End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
164106f32e7eSjoerg Min = -End;
164206f32e7eSjoerg } else {
164306f32e7eSjoerg assert(NumPositiveBits <= Bitwidth);
164406f32e7eSjoerg End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
164506f32e7eSjoerg Min = llvm::APInt(Bitwidth, 0);
164606f32e7eSjoerg }
164706f32e7eSjoerg }
164806f32e7eSjoerg return true;
164906f32e7eSjoerg }
165006f32e7eSjoerg
getRangeForLoadFromType(QualType Ty)165106f32e7eSjoerg llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
165206f32e7eSjoerg llvm::APInt Min, End;
165306f32e7eSjoerg if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
165406f32e7eSjoerg hasBooleanRepresentation(Ty)))
165506f32e7eSjoerg return nullptr;
165606f32e7eSjoerg
165706f32e7eSjoerg llvm::MDBuilder MDHelper(getLLVMContext());
165806f32e7eSjoerg return MDHelper.createRange(Min, End);
165906f32e7eSjoerg }
166006f32e7eSjoerg
EmitScalarRangeCheck(llvm::Value * Value,QualType Ty,SourceLocation Loc)166106f32e7eSjoerg bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
166206f32e7eSjoerg SourceLocation Loc) {
166306f32e7eSjoerg bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
166406f32e7eSjoerg bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
166506f32e7eSjoerg if (!HasBoolCheck && !HasEnumCheck)
166606f32e7eSjoerg return false;
166706f32e7eSjoerg
166806f32e7eSjoerg bool IsBool = hasBooleanRepresentation(Ty) ||
166906f32e7eSjoerg NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
167006f32e7eSjoerg bool NeedsBoolCheck = HasBoolCheck && IsBool;
167106f32e7eSjoerg bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
167206f32e7eSjoerg if (!NeedsBoolCheck && !NeedsEnumCheck)
167306f32e7eSjoerg return false;
167406f32e7eSjoerg
167506f32e7eSjoerg // Single-bit booleans don't need to be checked. Special-case this to avoid
167606f32e7eSjoerg // a bit width mismatch when handling bitfield values. This is handled by
167706f32e7eSjoerg // EmitFromMemory for the non-bitfield case.
167806f32e7eSjoerg if (IsBool &&
167906f32e7eSjoerg cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
168006f32e7eSjoerg return false;
168106f32e7eSjoerg
168206f32e7eSjoerg llvm::APInt Min, End;
168306f32e7eSjoerg if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
168406f32e7eSjoerg return true;
168506f32e7eSjoerg
168606f32e7eSjoerg auto &Ctx = getLLVMContext();
168706f32e7eSjoerg SanitizerScope SanScope(this);
168806f32e7eSjoerg llvm::Value *Check;
168906f32e7eSjoerg --End;
169006f32e7eSjoerg if (!Min) {
169106f32e7eSjoerg Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
169206f32e7eSjoerg } else {
169306f32e7eSjoerg llvm::Value *Upper =
169406f32e7eSjoerg Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
169506f32e7eSjoerg llvm::Value *Lower =
169606f32e7eSjoerg Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
169706f32e7eSjoerg Check = Builder.CreateAnd(Upper, Lower);
169806f32e7eSjoerg }
169906f32e7eSjoerg llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
170006f32e7eSjoerg EmitCheckTypeDescriptor(Ty)};
170106f32e7eSjoerg SanitizerMask Kind =
170206f32e7eSjoerg NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
170306f32e7eSjoerg EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
170406f32e7eSjoerg StaticArgs, EmitCheckValue(Value));
170506f32e7eSjoerg return true;
170606f32e7eSjoerg }
170706f32e7eSjoerg
EmitLoadOfScalar(Address Addr,bool Volatile,QualType Ty,SourceLocation Loc,LValueBaseInfo BaseInfo,TBAAAccessInfo TBAAInfo,bool isNontemporal)170806f32e7eSjoerg llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
170906f32e7eSjoerg QualType Ty,
171006f32e7eSjoerg SourceLocation Loc,
171106f32e7eSjoerg LValueBaseInfo BaseInfo,
171206f32e7eSjoerg TBAAAccessInfo TBAAInfo,
171306f32e7eSjoerg bool isNontemporal) {
171406f32e7eSjoerg if (!CGM.getCodeGenOpts().PreserveVec3Type) {
171506f32e7eSjoerg // For better performance, handle vector loads differently.
171606f32e7eSjoerg if (Ty->isVectorType()) {
171706f32e7eSjoerg const llvm::Type *EltTy = Addr.getElementType();
171806f32e7eSjoerg
1719*13fbcb42Sjoerg const auto *VTy = cast<llvm::FixedVectorType>(EltTy);
172006f32e7eSjoerg
172106f32e7eSjoerg // Handle vectors of size 3 like size 4 for better performance.
172206f32e7eSjoerg if (VTy->getNumElements() == 3) {
172306f32e7eSjoerg
172406f32e7eSjoerg // Bitcast to vec4 type.
1725*13fbcb42Sjoerg auto *vec4Ty = llvm::FixedVectorType::get(VTy->getElementType(), 4);
172606f32e7eSjoerg Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
172706f32e7eSjoerg // Now load value.
172806f32e7eSjoerg llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
172906f32e7eSjoerg
173006f32e7eSjoerg // Shuffle vector to get vec3.
1731*13fbcb42Sjoerg V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2},
1732*13fbcb42Sjoerg "extractVec");
173306f32e7eSjoerg return EmitFromMemory(V, Ty);
173406f32e7eSjoerg }
173506f32e7eSjoerg }
173606f32e7eSjoerg }
173706f32e7eSjoerg
173806f32e7eSjoerg // Atomic operations have to be done on integral types.
173906f32e7eSjoerg LValue AtomicLValue =
174006f32e7eSjoerg LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
174106f32e7eSjoerg if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
174206f32e7eSjoerg return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
174306f32e7eSjoerg }
174406f32e7eSjoerg
174506f32e7eSjoerg llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
174606f32e7eSjoerg if (isNontemporal) {
174706f32e7eSjoerg llvm::MDNode *Node = llvm::MDNode::get(
174806f32e7eSjoerg Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
174906f32e7eSjoerg Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
175006f32e7eSjoerg }
175106f32e7eSjoerg
175206f32e7eSjoerg CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
175306f32e7eSjoerg
175406f32e7eSjoerg if (EmitScalarRangeCheck(Load, Ty, Loc)) {
175506f32e7eSjoerg // In order to prevent the optimizer from throwing away the check, don't
175606f32e7eSjoerg // attach range metadata to the load.
175706f32e7eSjoerg } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
175806f32e7eSjoerg if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
175906f32e7eSjoerg Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
176006f32e7eSjoerg
176106f32e7eSjoerg return EmitFromMemory(Load, Ty);
176206f32e7eSjoerg }
176306f32e7eSjoerg
EmitToMemory(llvm::Value * Value,QualType Ty)176406f32e7eSjoerg llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
176506f32e7eSjoerg // Bool has a different representation in memory than in registers.
176606f32e7eSjoerg if (hasBooleanRepresentation(Ty)) {
176706f32e7eSjoerg // This should really always be an i1, but sometimes it's already
176806f32e7eSjoerg // an i8, and it's awkward to track those cases down.
176906f32e7eSjoerg if (Value->getType()->isIntegerTy(1))
177006f32e7eSjoerg return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
177106f32e7eSjoerg assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
177206f32e7eSjoerg "wrong value rep of bool");
177306f32e7eSjoerg }
177406f32e7eSjoerg
177506f32e7eSjoerg return Value;
177606f32e7eSjoerg }
177706f32e7eSjoerg
EmitFromMemory(llvm::Value * Value,QualType Ty)177806f32e7eSjoerg llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
177906f32e7eSjoerg // Bool has a different representation in memory than in registers.
178006f32e7eSjoerg if (hasBooleanRepresentation(Ty)) {
178106f32e7eSjoerg assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
178206f32e7eSjoerg "wrong value rep of bool");
178306f32e7eSjoerg return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
178406f32e7eSjoerg }
178506f32e7eSjoerg
178606f32e7eSjoerg return Value;
178706f32e7eSjoerg }
178806f32e7eSjoerg
1789*13fbcb42Sjoerg // Convert the pointer of \p Addr to a pointer to a vector (the value type of
1790*13fbcb42Sjoerg // MatrixType), if it points to a array (the memory type of MatrixType).
MaybeConvertMatrixAddress(Address Addr,CodeGenFunction & CGF,bool IsVector=true)1791*13fbcb42Sjoerg static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF,
1792*13fbcb42Sjoerg bool IsVector = true) {
1793*13fbcb42Sjoerg auto *ArrayTy = dyn_cast<llvm::ArrayType>(
1794*13fbcb42Sjoerg cast<llvm::PointerType>(Addr.getPointer()->getType())->getElementType());
1795*13fbcb42Sjoerg if (ArrayTy && IsVector) {
1796*13fbcb42Sjoerg auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
1797*13fbcb42Sjoerg ArrayTy->getNumElements());
1798*13fbcb42Sjoerg
1799*13fbcb42Sjoerg return Address(CGF.Builder.CreateElementBitCast(Addr, VectorTy));
1800*13fbcb42Sjoerg }
1801*13fbcb42Sjoerg auto *VectorTy = dyn_cast<llvm::VectorType>(
1802*13fbcb42Sjoerg cast<llvm::PointerType>(Addr.getPointer()->getType())->getElementType());
1803*13fbcb42Sjoerg if (VectorTy && !IsVector) {
1804*13fbcb42Sjoerg auto *ArrayTy = llvm::ArrayType::get(
1805*13fbcb42Sjoerg VectorTy->getElementType(),
1806*13fbcb42Sjoerg cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
1807*13fbcb42Sjoerg
1808*13fbcb42Sjoerg return Address(CGF.Builder.CreateElementBitCast(Addr, ArrayTy));
1809*13fbcb42Sjoerg }
1810*13fbcb42Sjoerg
1811*13fbcb42Sjoerg return Addr;
1812*13fbcb42Sjoerg }
1813*13fbcb42Sjoerg
1814*13fbcb42Sjoerg // Emit a store of a matrix LValue. This may require casting the original
1815*13fbcb42Sjoerg // pointer to memory address (ArrayType) to a pointer to the value type
1816*13fbcb42Sjoerg // (VectorType).
EmitStoreOfMatrixScalar(llvm::Value * value,LValue lvalue,bool isInit,CodeGenFunction & CGF)1817*13fbcb42Sjoerg static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
1818*13fbcb42Sjoerg bool isInit, CodeGenFunction &CGF) {
1819*13fbcb42Sjoerg Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF,
1820*13fbcb42Sjoerg value->getType()->isVectorTy());
1821*13fbcb42Sjoerg CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
1822*13fbcb42Sjoerg lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
1823*13fbcb42Sjoerg lvalue.isNontemporal());
1824*13fbcb42Sjoerg }
1825*13fbcb42Sjoerg
EmitStoreOfScalar(llvm::Value * Value,Address Addr,bool Volatile,QualType Ty,LValueBaseInfo BaseInfo,TBAAAccessInfo TBAAInfo,bool isInit,bool isNontemporal)182606f32e7eSjoerg void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
182706f32e7eSjoerg bool Volatile, QualType Ty,
182806f32e7eSjoerg LValueBaseInfo BaseInfo,
182906f32e7eSjoerg TBAAAccessInfo TBAAInfo,
183006f32e7eSjoerg bool isInit, bool isNontemporal) {
183106f32e7eSjoerg if (!CGM.getCodeGenOpts().PreserveVec3Type) {
183206f32e7eSjoerg // Handle vectors differently to get better performance.
183306f32e7eSjoerg if (Ty->isVectorType()) {
183406f32e7eSjoerg llvm::Type *SrcTy = Value->getType();
183506f32e7eSjoerg auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
183606f32e7eSjoerg // Handle vec3 special.
1837*13fbcb42Sjoerg if (VecTy && cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) {
183806f32e7eSjoerg // Our source is a vec3, do a shuffle vector to make it a vec4.
1839*13fbcb42Sjoerg Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
1840*13fbcb42Sjoerg "extractVec");
1841*13fbcb42Sjoerg SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
184206f32e7eSjoerg }
184306f32e7eSjoerg if (Addr.getElementType() != SrcTy) {
184406f32e7eSjoerg Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
184506f32e7eSjoerg }
184606f32e7eSjoerg }
184706f32e7eSjoerg }
184806f32e7eSjoerg
184906f32e7eSjoerg Value = EmitToMemory(Value, Ty);
185006f32e7eSjoerg
185106f32e7eSjoerg LValue AtomicLValue =
185206f32e7eSjoerg LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
185306f32e7eSjoerg if (Ty->isAtomicType() ||
185406f32e7eSjoerg (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
185506f32e7eSjoerg EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
185606f32e7eSjoerg return;
185706f32e7eSjoerg }
185806f32e7eSjoerg
185906f32e7eSjoerg llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
186006f32e7eSjoerg if (isNontemporal) {
186106f32e7eSjoerg llvm::MDNode *Node =
186206f32e7eSjoerg llvm::MDNode::get(Store->getContext(),
186306f32e7eSjoerg llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
186406f32e7eSjoerg Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
186506f32e7eSjoerg }
186606f32e7eSjoerg
186706f32e7eSjoerg CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
186806f32e7eSjoerg }
186906f32e7eSjoerg
EmitStoreOfScalar(llvm::Value * value,LValue lvalue,bool isInit)187006f32e7eSjoerg void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
187106f32e7eSjoerg bool isInit) {
1872*13fbcb42Sjoerg if (lvalue.getType()->isConstantMatrixType()) {
1873*13fbcb42Sjoerg EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
1874*13fbcb42Sjoerg return;
1875*13fbcb42Sjoerg }
1876*13fbcb42Sjoerg
1877*13fbcb42Sjoerg EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
187806f32e7eSjoerg lvalue.getType(), lvalue.getBaseInfo(),
187906f32e7eSjoerg lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
188006f32e7eSjoerg }
188106f32e7eSjoerg
1882*13fbcb42Sjoerg // Emit a load of a LValue of matrix type. This may require casting the pointer
1883*13fbcb42Sjoerg // to memory address (ArrayType) to a pointer to the value type (VectorType).
EmitLoadOfMatrixLValue(LValue LV,SourceLocation Loc,CodeGenFunction & CGF)1884*13fbcb42Sjoerg static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
1885*13fbcb42Sjoerg CodeGenFunction &CGF) {
1886*13fbcb42Sjoerg assert(LV.getType()->isConstantMatrixType());
1887*13fbcb42Sjoerg Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
1888*13fbcb42Sjoerg LV.setAddress(Addr);
1889*13fbcb42Sjoerg return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
1890*13fbcb42Sjoerg }
1891*13fbcb42Sjoerg
189206f32e7eSjoerg /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
189306f32e7eSjoerg /// method emits the address of the lvalue, then loads the result as an rvalue,
189406f32e7eSjoerg /// returning the rvalue.
EmitLoadOfLValue(LValue LV,SourceLocation Loc)189506f32e7eSjoerg RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
189606f32e7eSjoerg if (LV.isObjCWeak()) {
189706f32e7eSjoerg // load of a __weak object.
1898*13fbcb42Sjoerg Address AddrWeakObj = LV.getAddress(*this);
189906f32e7eSjoerg return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
190006f32e7eSjoerg AddrWeakObj));
190106f32e7eSjoerg }
190206f32e7eSjoerg if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
190306f32e7eSjoerg // In MRC mode, we do a load+autorelease.
190406f32e7eSjoerg if (!getLangOpts().ObjCAutoRefCount) {
1905*13fbcb42Sjoerg return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
190606f32e7eSjoerg }
190706f32e7eSjoerg
190806f32e7eSjoerg // In ARC mode, we load retained and then consume the value.
1909*13fbcb42Sjoerg llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
191006f32e7eSjoerg Object = EmitObjCConsumeObject(LV.getType(), Object);
191106f32e7eSjoerg return RValue::get(Object);
191206f32e7eSjoerg }
191306f32e7eSjoerg
191406f32e7eSjoerg if (LV.isSimple()) {
191506f32e7eSjoerg assert(!LV.getType()->isFunctionType());
191606f32e7eSjoerg
1917*13fbcb42Sjoerg if (LV.getType()->isConstantMatrixType())
1918*13fbcb42Sjoerg return EmitLoadOfMatrixLValue(LV, Loc, *this);
1919*13fbcb42Sjoerg
192006f32e7eSjoerg // Everything needs a load.
192106f32e7eSjoerg return RValue::get(EmitLoadOfScalar(LV, Loc));
192206f32e7eSjoerg }
192306f32e7eSjoerg
192406f32e7eSjoerg if (LV.isVectorElt()) {
192506f32e7eSjoerg llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
192606f32e7eSjoerg LV.isVolatileQualified());
192706f32e7eSjoerg return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
192806f32e7eSjoerg "vecext"));
192906f32e7eSjoerg }
193006f32e7eSjoerg
193106f32e7eSjoerg // If this is a reference to a subset of the elements of a vector, either
193206f32e7eSjoerg // shuffle the input or extract/insert them as appropriate.
1933*13fbcb42Sjoerg if (LV.isExtVectorElt()) {
193406f32e7eSjoerg return EmitLoadOfExtVectorElementLValue(LV);
1935*13fbcb42Sjoerg }
193606f32e7eSjoerg
193706f32e7eSjoerg // Global Register variables always invoke intrinsics
193806f32e7eSjoerg if (LV.isGlobalReg())
193906f32e7eSjoerg return EmitLoadOfGlobalRegLValue(LV);
194006f32e7eSjoerg
1941*13fbcb42Sjoerg if (LV.isMatrixElt()) {
1942*13fbcb42Sjoerg llvm::LoadInst *Load =
1943*13fbcb42Sjoerg Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
1944*13fbcb42Sjoerg return RValue::get(
1945*13fbcb42Sjoerg Builder.CreateExtractElement(Load, LV.getMatrixIdx(), "matrixext"));
1946*13fbcb42Sjoerg }
1947*13fbcb42Sjoerg
194806f32e7eSjoerg assert(LV.isBitField() && "Unknown LValue type!");
194906f32e7eSjoerg return EmitLoadOfBitfieldLValue(LV, Loc);
195006f32e7eSjoerg }
195106f32e7eSjoerg
EmitLoadOfBitfieldLValue(LValue LV,SourceLocation Loc)195206f32e7eSjoerg RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
195306f32e7eSjoerg SourceLocation Loc) {
195406f32e7eSjoerg const CGBitFieldInfo &Info = LV.getBitFieldInfo();
195506f32e7eSjoerg
195606f32e7eSjoerg // Get the output type.
195706f32e7eSjoerg llvm::Type *ResLTy = ConvertType(LV.getType());
195806f32e7eSjoerg
195906f32e7eSjoerg Address Ptr = LV.getBitFieldAddress();
1960*13fbcb42Sjoerg llvm::Value *Val =
1961*13fbcb42Sjoerg Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
196206f32e7eSjoerg
1963*13fbcb42Sjoerg bool UseVolatile = LV.isVolatileQualified() &&
1964*13fbcb42Sjoerg Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
1965*13fbcb42Sjoerg const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
1966*13fbcb42Sjoerg const unsigned StorageSize =
1967*13fbcb42Sjoerg UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
196806f32e7eSjoerg if (Info.IsSigned) {
1969*13fbcb42Sjoerg assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
1970*13fbcb42Sjoerg unsigned HighBits = StorageSize - Offset - Info.Size;
197106f32e7eSjoerg if (HighBits)
197206f32e7eSjoerg Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1973*13fbcb42Sjoerg if (Offset + HighBits)
1974*13fbcb42Sjoerg Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
197506f32e7eSjoerg } else {
1976*13fbcb42Sjoerg if (Offset)
1977*13fbcb42Sjoerg Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
1978*13fbcb42Sjoerg if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
1979*13fbcb42Sjoerg Val = Builder.CreateAnd(
1980*13fbcb42Sjoerg Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
198106f32e7eSjoerg }
198206f32e7eSjoerg Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
198306f32e7eSjoerg EmitScalarRangeCheck(Val, LV.getType(), Loc);
198406f32e7eSjoerg return RValue::get(Val);
198506f32e7eSjoerg }
198606f32e7eSjoerg
198706f32e7eSjoerg // If this is a reference to a subset of the elements of a vector, create an
198806f32e7eSjoerg // appropriate shufflevector.
EmitLoadOfExtVectorElementLValue(LValue LV)198906f32e7eSjoerg RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
199006f32e7eSjoerg llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
199106f32e7eSjoerg LV.isVolatileQualified());
199206f32e7eSjoerg
199306f32e7eSjoerg const llvm::Constant *Elts = LV.getExtVectorElts();
199406f32e7eSjoerg
199506f32e7eSjoerg // If the result of the expression is a non-vector type, we must be extracting
199606f32e7eSjoerg // a single element. Just codegen as an extractelement.
199706f32e7eSjoerg const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
199806f32e7eSjoerg if (!ExprVT) {
199906f32e7eSjoerg unsigned InIdx = getAccessedFieldNo(0, Elts);
200006f32e7eSjoerg llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
200106f32e7eSjoerg return RValue::get(Builder.CreateExtractElement(Vec, Elt));
200206f32e7eSjoerg }
200306f32e7eSjoerg
200406f32e7eSjoerg // Always use shuffle vector to try to retain the original program structure
200506f32e7eSjoerg unsigned NumResultElts = ExprVT->getNumElements();
200606f32e7eSjoerg
2007*13fbcb42Sjoerg SmallVector<int, 4> Mask;
200806f32e7eSjoerg for (unsigned i = 0; i != NumResultElts; ++i)
2009*13fbcb42Sjoerg Mask.push_back(getAccessedFieldNo(i, Elts));
201006f32e7eSjoerg
2011*13fbcb42Sjoerg Vec = Builder.CreateShuffleVector(Vec, Mask);
201206f32e7eSjoerg return RValue::get(Vec);
201306f32e7eSjoerg }
201406f32e7eSjoerg
201506f32e7eSjoerg /// Generates lvalue for partial ext_vector access.
EmitExtVectorElementLValue(LValue LV)201606f32e7eSjoerg Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
201706f32e7eSjoerg Address VectorAddress = LV.getExtVectorAddress();
2018*13fbcb42Sjoerg QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
201906f32e7eSjoerg llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
202006f32e7eSjoerg
202106f32e7eSjoerg Address CastToPointerElement =
202206f32e7eSjoerg Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
202306f32e7eSjoerg "conv.ptr.element");
202406f32e7eSjoerg
202506f32e7eSjoerg const llvm::Constant *Elts = LV.getExtVectorElts();
202606f32e7eSjoerg unsigned ix = getAccessedFieldNo(0, Elts);
202706f32e7eSjoerg
202806f32e7eSjoerg Address VectorBasePtrPlusIx =
202906f32e7eSjoerg Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
203006f32e7eSjoerg "vector.elt");
203106f32e7eSjoerg
203206f32e7eSjoerg return VectorBasePtrPlusIx;
203306f32e7eSjoerg }
203406f32e7eSjoerg
203506f32e7eSjoerg /// Load of global gamed gegisters are always calls to intrinsics.
EmitLoadOfGlobalRegLValue(LValue LV)203606f32e7eSjoerg RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
203706f32e7eSjoerg assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
203806f32e7eSjoerg "Bad type for register variable");
203906f32e7eSjoerg llvm::MDNode *RegName = cast<llvm::MDNode>(
204006f32e7eSjoerg cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
204106f32e7eSjoerg
204206f32e7eSjoerg // We accept integer and pointer types only
204306f32e7eSjoerg llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
204406f32e7eSjoerg llvm::Type *Ty = OrigTy;
204506f32e7eSjoerg if (OrigTy->isPointerTy())
204606f32e7eSjoerg Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
204706f32e7eSjoerg llvm::Type *Types[] = { Ty };
204806f32e7eSjoerg
204906f32e7eSjoerg llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
205006f32e7eSjoerg llvm::Value *Call = Builder.CreateCall(
205106f32e7eSjoerg F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
205206f32e7eSjoerg if (OrigTy->isPointerTy())
205306f32e7eSjoerg Call = Builder.CreateIntToPtr(Call, OrigTy);
205406f32e7eSjoerg return RValue::get(Call);
205506f32e7eSjoerg }
205606f32e7eSjoerg
205706f32e7eSjoerg /// EmitStoreThroughLValue - Store the specified rvalue into the specified
205806f32e7eSjoerg /// lvalue, where both are guaranteed to the have the same type, and that type
205906f32e7eSjoerg /// is 'Ty'.
EmitStoreThroughLValue(RValue Src,LValue Dst,bool isInit)206006f32e7eSjoerg void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
206106f32e7eSjoerg bool isInit) {
206206f32e7eSjoerg if (!Dst.isSimple()) {
206306f32e7eSjoerg if (Dst.isVectorElt()) {
206406f32e7eSjoerg // Read/modify/write the vector, inserting the new element.
206506f32e7eSjoerg llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
206606f32e7eSjoerg Dst.isVolatileQualified());
206706f32e7eSjoerg Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
206806f32e7eSjoerg Dst.getVectorIdx(), "vecins");
206906f32e7eSjoerg Builder.CreateStore(Vec, Dst.getVectorAddress(),
207006f32e7eSjoerg Dst.isVolatileQualified());
207106f32e7eSjoerg return;
207206f32e7eSjoerg }
207306f32e7eSjoerg
207406f32e7eSjoerg // If this is an update of extended vector elements, insert them as
207506f32e7eSjoerg // appropriate.
207606f32e7eSjoerg if (Dst.isExtVectorElt())
207706f32e7eSjoerg return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
207806f32e7eSjoerg
207906f32e7eSjoerg if (Dst.isGlobalReg())
208006f32e7eSjoerg return EmitStoreThroughGlobalRegLValue(Src, Dst);
208106f32e7eSjoerg
2082*13fbcb42Sjoerg if (Dst.isMatrixElt()) {
2083*13fbcb42Sjoerg llvm::Value *Vec = Builder.CreateLoad(Dst.getMatrixAddress());
2084*13fbcb42Sjoerg Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
2085*13fbcb42Sjoerg Dst.getMatrixIdx(), "matins");
2086*13fbcb42Sjoerg Builder.CreateStore(Vec, Dst.getMatrixAddress(),
2087*13fbcb42Sjoerg Dst.isVolatileQualified());
2088*13fbcb42Sjoerg return;
2089*13fbcb42Sjoerg }
2090*13fbcb42Sjoerg
209106f32e7eSjoerg assert(Dst.isBitField() && "Unknown LValue type");
209206f32e7eSjoerg return EmitStoreThroughBitfieldLValue(Src, Dst);
209306f32e7eSjoerg }
209406f32e7eSjoerg
209506f32e7eSjoerg // There's special magic for assigning into an ARC-qualified l-value.
209606f32e7eSjoerg if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
209706f32e7eSjoerg switch (Lifetime) {
209806f32e7eSjoerg case Qualifiers::OCL_None:
209906f32e7eSjoerg llvm_unreachable("present but none");
210006f32e7eSjoerg
210106f32e7eSjoerg case Qualifiers::OCL_ExplicitNone:
210206f32e7eSjoerg // nothing special
210306f32e7eSjoerg break;
210406f32e7eSjoerg
210506f32e7eSjoerg case Qualifiers::OCL_Strong:
210606f32e7eSjoerg if (isInit) {
210706f32e7eSjoerg Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
210806f32e7eSjoerg break;
210906f32e7eSjoerg }
211006f32e7eSjoerg EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
211106f32e7eSjoerg return;
211206f32e7eSjoerg
211306f32e7eSjoerg case Qualifiers::OCL_Weak:
211406f32e7eSjoerg if (isInit)
211506f32e7eSjoerg // Initialize and then skip the primitive store.
2116*13fbcb42Sjoerg EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
211706f32e7eSjoerg else
2118*13fbcb42Sjoerg EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
2119*13fbcb42Sjoerg /*ignore*/ true);
212006f32e7eSjoerg return;
212106f32e7eSjoerg
212206f32e7eSjoerg case Qualifiers::OCL_Autoreleasing:
212306f32e7eSjoerg Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
212406f32e7eSjoerg Src.getScalarVal()));
212506f32e7eSjoerg // fall into the normal path
212606f32e7eSjoerg break;
212706f32e7eSjoerg }
212806f32e7eSjoerg }
212906f32e7eSjoerg
213006f32e7eSjoerg if (Dst.isObjCWeak() && !Dst.isNonGC()) {
213106f32e7eSjoerg // load of a __weak object.
2132*13fbcb42Sjoerg Address LvalueDst = Dst.getAddress(*this);
213306f32e7eSjoerg llvm::Value *src = Src.getScalarVal();
213406f32e7eSjoerg CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
213506f32e7eSjoerg return;
213606f32e7eSjoerg }
213706f32e7eSjoerg
213806f32e7eSjoerg if (Dst.isObjCStrong() && !Dst.isNonGC()) {
213906f32e7eSjoerg // load of a __strong object.
2140*13fbcb42Sjoerg Address LvalueDst = Dst.getAddress(*this);
214106f32e7eSjoerg llvm::Value *src = Src.getScalarVal();
214206f32e7eSjoerg if (Dst.isObjCIvar()) {
214306f32e7eSjoerg assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
214406f32e7eSjoerg llvm::Type *ResultType = IntPtrTy;
214506f32e7eSjoerg Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
214606f32e7eSjoerg llvm::Value *RHS = dst.getPointer();
214706f32e7eSjoerg RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
214806f32e7eSjoerg llvm::Value *LHS =
214906f32e7eSjoerg Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
215006f32e7eSjoerg "sub.ptr.lhs.cast");
215106f32e7eSjoerg llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
215206f32e7eSjoerg CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
215306f32e7eSjoerg BytesBetween);
215406f32e7eSjoerg } else if (Dst.isGlobalObjCRef()) {
215506f32e7eSjoerg CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
215606f32e7eSjoerg Dst.isThreadLocalRef());
215706f32e7eSjoerg }
215806f32e7eSjoerg else
215906f32e7eSjoerg CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
216006f32e7eSjoerg return;
216106f32e7eSjoerg }
216206f32e7eSjoerg
216306f32e7eSjoerg assert(Src.isScalar() && "Can't emit an agg store with this method");
216406f32e7eSjoerg EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
216506f32e7eSjoerg }
216606f32e7eSjoerg
EmitStoreThroughBitfieldLValue(RValue Src,LValue Dst,llvm::Value ** Result)216706f32e7eSjoerg void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
216806f32e7eSjoerg llvm::Value **Result) {
216906f32e7eSjoerg const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
217006f32e7eSjoerg llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
217106f32e7eSjoerg Address Ptr = Dst.getBitFieldAddress();
217206f32e7eSjoerg
217306f32e7eSjoerg // Get the source value, truncated to the width of the bit-field.
217406f32e7eSjoerg llvm::Value *SrcVal = Src.getScalarVal();
217506f32e7eSjoerg
217606f32e7eSjoerg // Cast the source to the storage type and shift it into place.
217706f32e7eSjoerg SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
217806f32e7eSjoerg /*isSigned=*/false);
217906f32e7eSjoerg llvm::Value *MaskedVal = SrcVal;
218006f32e7eSjoerg
2181*13fbcb42Sjoerg const bool UseVolatile =
2182*13fbcb42Sjoerg CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2183*13fbcb42Sjoerg Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2184*13fbcb42Sjoerg const unsigned StorageSize =
2185*13fbcb42Sjoerg UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2186*13fbcb42Sjoerg const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
218706f32e7eSjoerg // See if there are other bits in the bitfield's storage we'll need to load
218806f32e7eSjoerg // and mask together with source before storing.
2189*13fbcb42Sjoerg if (StorageSize != Info.Size) {
2190*13fbcb42Sjoerg assert(StorageSize > Info.Size && "Invalid bitfield size.");
219106f32e7eSjoerg llvm::Value *Val =
219206f32e7eSjoerg Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
219306f32e7eSjoerg
219406f32e7eSjoerg // Mask the source value as needed.
219506f32e7eSjoerg if (!hasBooleanRepresentation(Dst.getType()))
2196*13fbcb42Sjoerg SrcVal = Builder.CreateAnd(
2197*13fbcb42Sjoerg SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
219806f32e7eSjoerg "bf.value");
219906f32e7eSjoerg MaskedVal = SrcVal;
2200*13fbcb42Sjoerg if (Offset)
2201*13fbcb42Sjoerg SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
220206f32e7eSjoerg
220306f32e7eSjoerg // Mask out the original value.
2204*13fbcb42Sjoerg Val = Builder.CreateAnd(
2205*13fbcb42Sjoerg Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
220606f32e7eSjoerg "bf.clear");
220706f32e7eSjoerg
220806f32e7eSjoerg // Or together the unchanged values and the source value.
220906f32e7eSjoerg SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
221006f32e7eSjoerg } else {
2211*13fbcb42Sjoerg assert(Offset == 0);
2212*13fbcb42Sjoerg // According to the AACPS:
2213*13fbcb42Sjoerg // When a volatile bit-field is written, and its container does not overlap
2214*13fbcb42Sjoerg // with any non-bit-field member, its container must be read exactly once
2215*13fbcb42Sjoerg // and written exactly once using the access width appropriate to the type
2216*13fbcb42Sjoerg // of the container. The two accesses are not atomic.
2217*13fbcb42Sjoerg if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
2218*13fbcb42Sjoerg CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
2219*13fbcb42Sjoerg Builder.CreateLoad(Ptr, true, "bf.load");
222006f32e7eSjoerg }
222106f32e7eSjoerg
222206f32e7eSjoerg // Write the new value back out.
222306f32e7eSjoerg Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
222406f32e7eSjoerg
222506f32e7eSjoerg // Return the new value of the bit-field, if requested.
222606f32e7eSjoerg if (Result) {
222706f32e7eSjoerg llvm::Value *ResultVal = MaskedVal;
222806f32e7eSjoerg
222906f32e7eSjoerg // Sign extend the value if needed.
223006f32e7eSjoerg if (Info.IsSigned) {
2231*13fbcb42Sjoerg assert(Info.Size <= StorageSize);
2232*13fbcb42Sjoerg unsigned HighBits = StorageSize - Info.Size;
223306f32e7eSjoerg if (HighBits) {
223406f32e7eSjoerg ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
223506f32e7eSjoerg ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
223606f32e7eSjoerg }
223706f32e7eSjoerg }
223806f32e7eSjoerg
223906f32e7eSjoerg ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
224006f32e7eSjoerg "bf.result.cast");
224106f32e7eSjoerg *Result = EmitFromMemory(ResultVal, Dst.getType());
224206f32e7eSjoerg }
224306f32e7eSjoerg }
224406f32e7eSjoerg
EmitStoreThroughExtVectorComponentLValue(RValue Src,LValue Dst)224506f32e7eSjoerg void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
224606f32e7eSjoerg LValue Dst) {
224706f32e7eSjoerg // This access turns into a read/modify/write of the vector. Load the input
224806f32e7eSjoerg // value now.
224906f32e7eSjoerg llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
225006f32e7eSjoerg Dst.isVolatileQualified());
225106f32e7eSjoerg const llvm::Constant *Elts = Dst.getExtVectorElts();
225206f32e7eSjoerg
225306f32e7eSjoerg llvm::Value *SrcVal = Src.getScalarVal();
225406f32e7eSjoerg
225506f32e7eSjoerg if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
225606f32e7eSjoerg unsigned NumSrcElts = VTy->getNumElements();
2257*13fbcb42Sjoerg unsigned NumDstElts =
2258*13fbcb42Sjoerg cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
225906f32e7eSjoerg if (NumDstElts == NumSrcElts) {
226006f32e7eSjoerg // Use shuffle vector is the src and destination are the same number of
226106f32e7eSjoerg // elements and restore the vector mask since it is on the side it will be
226206f32e7eSjoerg // stored.
2263*13fbcb42Sjoerg SmallVector<int, 4> Mask(NumDstElts);
226406f32e7eSjoerg for (unsigned i = 0; i != NumSrcElts; ++i)
2265*13fbcb42Sjoerg Mask[getAccessedFieldNo(i, Elts)] = i;
226606f32e7eSjoerg
2267*13fbcb42Sjoerg Vec = Builder.CreateShuffleVector(SrcVal, Mask);
226806f32e7eSjoerg } else if (NumDstElts > NumSrcElts) {
226906f32e7eSjoerg // Extended the source vector to the same length and then shuffle it
227006f32e7eSjoerg // into the destination.
227106f32e7eSjoerg // FIXME: since we're shuffling with undef, can we just use the indices
227206f32e7eSjoerg // into that? This could be simpler.
2273*13fbcb42Sjoerg SmallVector<int, 4> ExtMask;
227406f32e7eSjoerg for (unsigned i = 0; i != NumSrcElts; ++i)
2275*13fbcb42Sjoerg ExtMask.push_back(i);
2276*13fbcb42Sjoerg ExtMask.resize(NumDstElts, -1);
2277*13fbcb42Sjoerg llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
227806f32e7eSjoerg // build identity
2279*13fbcb42Sjoerg SmallVector<int, 4> Mask;
228006f32e7eSjoerg for (unsigned i = 0; i != NumDstElts; ++i)
2281*13fbcb42Sjoerg Mask.push_back(i);
228206f32e7eSjoerg
228306f32e7eSjoerg // When the vector size is odd and .odd or .hi is used, the last element
228406f32e7eSjoerg // of the Elts constant array will be one past the size of the vector.
228506f32e7eSjoerg // Ignore the last element here, if it is greater than the mask size.
228606f32e7eSjoerg if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
228706f32e7eSjoerg NumSrcElts--;
228806f32e7eSjoerg
228906f32e7eSjoerg // modify when what gets shuffled in
229006f32e7eSjoerg for (unsigned i = 0; i != NumSrcElts; ++i)
2291*13fbcb42Sjoerg Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
2292*13fbcb42Sjoerg Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
229306f32e7eSjoerg } else {
229406f32e7eSjoerg // We should never shorten the vector
229506f32e7eSjoerg llvm_unreachable("unexpected shorten vector length");
229606f32e7eSjoerg }
229706f32e7eSjoerg } else {
229806f32e7eSjoerg // If the Src is a scalar (not a vector) it must be updating one element.
229906f32e7eSjoerg unsigned InIdx = getAccessedFieldNo(0, Elts);
230006f32e7eSjoerg llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
230106f32e7eSjoerg Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
230206f32e7eSjoerg }
230306f32e7eSjoerg
230406f32e7eSjoerg Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
230506f32e7eSjoerg Dst.isVolatileQualified());
230606f32e7eSjoerg }
230706f32e7eSjoerg
230806f32e7eSjoerg /// Store of global named registers are always calls to intrinsics.
EmitStoreThroughGlobalRegLValue(RValue Src,LValue Dst)230906f32e7eSjoerg void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
231006f32e7eSjoerg assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
231106f32e7eSjoerg "Bad type for register variable");
231206f32e7eSjoerg llvm::MDNode *RegName = cast<llvm::MDNode>(
231306f32e7eSjoerg cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
231406f32e7eSjoerg assert(RegName && "Register LValue is not metadata");
231506f32e7eSjoerg
231606f32e7eSjoerg // We accept integer and pointer types only
231706f32e7eSjoerg llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
231806f32e7eSjoerg llvm::Type *Ty = OrigTy;
231906f32e7eSjoerg if (OrigTy->isPointerTy())
232006f32e7eSjoerg Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
232106f32e7eSjoerg llvm::Type *Types[] = { Ty };
232206f32e7eSjoerg
232306f32e7eSjoerg llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
232406f32e7eSjoerg llvm::Value *Value = Src.getScalarVal();
232506f32e7eSjoerg if (OrigTy->isPointerTy())
232606f32e7eSjoerg Value = Builder.CreatePtrToInt(Value, Ty);
232706f32e7eSjoerg Builder.CreateCall(
232806f32e7eSjoerg F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
232906f32e7eSjoerg }
233006f32e7eSjoerg
233106f32e7eSjoerg // setObjCGCLValueClass - sets class of the lvalue for the purpose of
233206f32e7eSjoerg // generating write-barries API. It is currently a global, ivar,
233306f32e7eSjoerg // or neither.
setObjCGCLValueClass(const ASTContext & Ctx,const Expr * E,LValue & LV,bool IsMemberAccess=false)233406f32e7eSjoerg static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
233506f32e7eSjoerg LValue &LV,
233606f32e7eSjoerg bool IsMemberAccess=false) {
233706f32e7eSjoerg if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
233806f32e7eSjoerg return;
233906f32e7eSjoerg
234006f32e7eSjoerg if (isa<ObjCIvarRefExpr>(E)) {
234106f32e7eSjoerg QualType ExpTy = E->getType();
234206f32e7eSjoerg if (IsMemberAccess && ExpTy->isPointerType()) {
234306f32e7eSjoerg // If ivar is a structure pointer, assigning to field of
234406f32e7eSjoerg // this struct follows gcc's behavior and makes it a non-ivar
234506f32e7eSjoerg // writer-barrier conservatively.
234606f32e7eSjoerg ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
234706f32e7eSjoerg if (ExpTy->isRecordType()) {
234806f32e7eSjoerg LV.setObjCIvar(false);
234906f32e7eSjoerg return;
235006f32e7eSjoerg }
235106f32e7eSjoerg }
235206f32e7eSjoerg LV.setObjCIvar(true);
235306f32e7eSjoerg auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
235406f32e7eSjoerg LV.setBaseIvarExp(Exp->getBase());
235506f32e7eSjoerg LV.setObjCArray(E->getType()->isArrayType());
235606f32e7eSjoerg return;
235706f32e7eSjoerg }
235806f32e7eSjoerg
235906f32e7eSjoerg if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
236006f32e7eSjoerg if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
236106f32e7eSjoerg if (VD->hasGlobalStorage()) {
236206f32e7eSjoerg LV.setGlobalObjCRef(true);
236306f32e7eSjoerg LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
236406f32e7eSjoerg }
236506f32e7eSjoerg }
236606f32e7eSjoerg LV.setObjCArray(E->getType()->isArrayType());
236706f32e7eSjoerg return;
236806f32e7eSjoerg }
236906f32e7eSjoerg
237006f32e7eSjoerg if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
237106f32e7eSjoerg setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
237206f32e7eSjoerg return;
237306f32e7eSjoerg }
237406f32e7eSjoerg
237506f32e7eSjoerg if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
237606f32e7eSjoerg setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
237706f32e7eSjoerg if (LV.isObjCIvar()) {
237806f32e7eSjoerg // If cast is to a structure pointer, follow gcc's behavior and make it
237906f32e7eSjoerg // a non-ivar write-barrier.
238006f32e7eSjoerg QualType ExpTy = E->getType();
238106f32e7eSjoerg if (ExpTy->isPointerType())
238206f32e7eSjoerg ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
238306f32e7eSjoerg if (ExpTy->isRecordType())
238406f32e7eSjoerg LV.setObjCIvar(false);
238506f32e7eSjoerg }
238606f32e7eSjoerg return;
238706f32e7eSjoerg }
238806f32e7eSjoerg
238906f32e7eSjoerg if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
239006f32e7eSjoerg setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
239106f32e7eSjoerg return;
239206f32e7eSjoerg }
239306f32e7eSjoerg
239406f32e7eSjoerg if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
239506f32e7eSjoerg setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
239606f32e7eSjoerg return;
239706f32e7eSjoerg }
239806f32e7eSjoerg
239906f32e7eSjoerg if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
240006f32e7eSjoerg setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
240106f32e7eSjoerg return;
240206f32e7eSjoerg }
240306f32e7eSjoerg
240406f32e7eSjoerg if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
240506f32e7eSjoerg setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
240606f32e7eSjoerg return;
240706f32e7eSjoerg }
240806f32e7eSjoerg
240906f32e7eSjoerg if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
241006f32e7eSjoerg setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
241106f32e7eSjoerg if (LV.isObjCIvar() && !LV.isObjCArray())
241206f32e7eSjoerg // Using array syntax to assigning to what an ivar points to is not
241306f32e7eSjoerg // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
241406f32e7eSjoerg LV.setObjCIvar(false);
241506f32e7eSjoerg else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
241606f32e7eSjoerg // Using array syntax to assigning to what global points to is not
241706f32e7eSjoerg // same as assigning to the global itself. {id *G;} G[i] = 0;
241806f32e7eSjoerg LV.setGlobalObjCRef(false);
241906f32e7eSjoerg return;
242006f32e7eSjoerg }
242106f32e7eSjoerg
242206f32e7eSjoerg if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
242306f32e7eSjoerg setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
242406f32e7eSjoerg // We don't know if member is an 'ivar', but this flag is looked at
242506f32e7eSjoerg // only in the context of LV.isObjCIvar().
242606f32e7eSjoerg LV.setObjCArray(E->getType()->isArrayType());
242706f32e7eSjoerg return;
242806f32e7eSjoerg }
242906f32e7eSjoerg }
243006f32e7eSjoerg
243106f32e7eSjoerg static llvm::Value *
EmitBitCastOfLValueToProperType(CodeGenFunction & CGF,llvm::Value * V,llvm::Type * IRType,StringRef Name=StringRef ())243206f32e7eSjoerg EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
243306f32e7eSjoerg llvm::Value *V, llvm::Type *IRType,
243406f32e7eSjoerg StringRef Name = StringRef()) {
243506f32e7eSjoerg unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
243606f32e7eSjoerg return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
243706f32e7eSjoerg }
243806f32e7eSjoerg
EmitThreadPrivateVarDeclLValue(CodeGenFunction & CGF,const VarDecl * VD,QualType T,Address Addr,llvm::Type * RealVarTy,SourceLocation Loc)243906f32e7eSjoerg static LValue EmitThreadPrivateVarDeclLValue(
244006f32e7eSjoerg CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
244106f32e7eSjoerg llvm::Type *RealVarTy, SourceLocation Loc) {
2442*13fbcb42Sjoerg if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
2443*13fbcb42Sjoerg Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
2444*13fbcb42Sjoerg CGF, VD, Addr, Loc);
2445*13fbcb42Sjoerg else
2446*13fbcb42Sjoerg Addr =
2447*13fbcb42Sjoerg CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2448*13fbcb42Sjoerg
244906f32e7eSjoerg Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
245006f32e7eSjoerg return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
245106f32e7eSjoerg }
245206f32e7eSjoerg
emitDeclTargetVarDeclLValue(CodeGenFunction & CGF,const VarDecl * VD,QualType T)245306f32e7eSjoerg static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
245406f32e7eSjoerg const VarDecl *VD, QualType T) {
245506f32e7eSjoerg llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
245606f32e7eSjoerg OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
245706f32e7eSjoerg // Return an invalid address if variable is MT_To and unified
245806f32e7eSjoerg // memory is not enabled. For all other cases: MT_Link and
245906f32e7eSjoerg // MT_To with unified memory, return a valid address.
246006f32e7eSjoerg if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
246106f32e7eSjoerg !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
246206f32e7eSjoerg return Address::invalid();
246306f32e7eSjoerg assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
246406f32e7eSjoerg (*Res == OMPDeclareTargetDeclAttr::MT_To &&
246506f32e7eSjoerg CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
246606f32e7eSjoerg "Expected link clause OR to clause with unified memory enabled.");
246706f32e7eSjoerg QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
246806f32e7eSjoerg Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
246906f32e7eSjoerg return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
247006f32e7eSjoerg }
247106f32e7eSjoerg
247206f32e7eSjoerg Address
EmitLoadOfReference(LValue RefLVal,LValueBaseInfo * PointeeBaseInfo,TBAAAccessInfo * PointeeTBAAInfo)247306f32e7eSjoerg CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
247406f32e7eSjoerg LValueBaseInfo *PointeeBaseInfo,
247506f32e7eSjoerg TBAAAccessInfo *PointeeTBAAInfo) {
2476*13fbcb42Sjoerg llvm::LoadInst *Load =
2477*13fbcb42Sjoerg Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
247806f32e7eSjoerg CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
247906f32e7eSjoerg
2480*13fbcb42Sjoerg CharUnits Align = CGM.getNaturalTypeAlignment(
2481*13fbcb42Sjoerg RefLVal.getType()->getPointeeType(), PointeeBaseInfo, PointeeTBAAInfo,
248206f32e7eSjoerg /* forPointeeType= */ true);
248306f32e7eSjoerg return Address(Load, Align);
248406f32e7eSjoerg }
248506f32e7eSjoerg
EmitLoadOfReferenceLValue(LValue RefLVal)248606f32e7eSjoerg LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
248706f32e7eSjoerg LValueBaseInfo PointeeBaseInfo;
248806f32e7eSjoerg TBAAAccessInfo PointeeTBAAInfo;
248906f32e7eSjoerg Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
249006f32e7eSjoerg &PointeeTBAAInfo);
249106f32e7eSjoerg return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
249206f32e7eSjoerg PointeeBaseInfo, PointeeTBAAInfo);
249306f32e7eSjoerg }
249406f32e7eSjoerg
EmitLoadOfPointer(Address Ptr,const PointerType * PtrTy,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)249506f32e7eSjoerg Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
249606f32e7eSjoerg const PointerType *PtrTy,
249706f32e7eSjoerg LValueBaseInfo *BaseInfo,
249806f32e7eSjoerg TBAAAccessInfo *TBAAInfo) {
249906f32e7eSjoerg llvm::Value *Addr = Builder.CreateLoad(Ptr);
2500*13fbcb42Sjoerg return Address(Addr, CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(),
250106f32e7eSjoerg BaseInfo, TBAAInfo,
250206f32e7eSjoerg /*forPointeeType=*/true));
250306f32e7eSjoerg }
250406f32e7eSjoerg
EmitLoadOfPointerLValue(Address PtrAddr,const PointerType * PtrTy)250506f32e7eSjoerg LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
250606f32e7eSjoerg const PointerType *PtrTy) {
250706f32e7eSjoerg LValueBaseInfo BaseInfo;
250806f32e7eSjoerg TBAAAccessInfo TBAAInfo;
250906f32e7eSjoerg Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
251006f32e7eSjoerg return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
251106f32e7eSjoerg }
251206f32e7eSjoerg
EmitGlobalVarDeclLValue(CodeGenFunction & CGF,const Expr * E,const VarDecl * VD)251306f32e7eSjoerg static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
251406f32e7eSjoerg const Expr *E, const VarDecl *VD) {
251506f32e7eSjoerg QualType T = E->getType();
251606f32e7eSjoerg
251706f32e7eSjoerg // If it's thread_local, emit a call to its wrapper function instead.
251806f32e7eSjoerg if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
251906f32e7eSjoerg CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
252006f32e7eSjoerg return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
252106f32e7eSjoerg // Check if the variable is marked as declare target with link clause in
252206f32e7eSjoerg // device codegen.
252306f32e7eSjoerg if (CGF.getLangOpts().OpenMPIsDevice) {
252406f32e7eSjoerg Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
252506f32e7eSjoerg if (Addr.isValid())
252606f32e7eSjoerg return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
252706f32e7eSjoerg }
252806f32e7eSjoerg
252906f32e7eSjoerg llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
253006f32e7eSjoerg llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
253106f32e7eSjoerg V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
253206f32e7eSjoerg CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
253306f32e7eSjoerg Address Addr(V, Alignment);
253406f32e7eSjoerg // Emit reference to the private copy of the variable if it is an OpenMP
253506f32e7eSjoerg // threadprivate variable.
253606f32e7eSjoerg if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
253706f32e7eSjoerg VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
253806f32e7eSjoerg return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
253906f32e7eSjoerg E->getExprLoc());
254006f32e7eSjoerg }
254106f32e7eSjoerg LValue LV = VD->getType()->isReferenceType() ?
254206f32e7eSjoerg CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
254306f32e7eSjoerg AlignmentSource::Decl) :
254406f32e7eSjoerg CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
254506f32e7eSjoerg setObjCGCLValueClass(CGF.getContext(), E, LV);
254606f32e7eSjoerg return LV;
254706f32e7eSjoerg }
254806f32e7eSjoerg
EmitFunctionDeclPointer(CodeGenModule & CGM,GlobalDecl GD)254906f32e7eSjoerg static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2550*13fbcb42Sjoerg GlobalDecl GD) {
2551*13fbcb42Sjoerg const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
255206f32e7eSjoerg if (FD->hasAttr<WeakRefAttr>()) {
255306f32e7eSjoerg ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
255406f32e7eSjoerg return aliasee.getPointer();
255506f32e7eSjoerg }
255606f32e7eSjoerg
2557*13fbcb42Sjoerg llvm::Constant *V = CGM.GetAddrOfFunction(GD);
255806f32e7eSjoerg if (!FD->hasPrototype()) {
255906f32e7eSjoerg if (const FunctionProtoType *Proto =
256006f32e7eSjoerg FD->getType()->getAs<FunctionProtoType>()) {
256106f32e7eSjoerg // Ugly case: for a K&R-style definition, the type of the definition
256206f32e7eSjoerg // isn't the same as the type of a use. Correct for this with a
256306f32e7eSjoerg // bitcast.
256406f32e7eSjoerg QualType NoProtoType =
256506f32e7eSjoerg CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
256606f32e7eSjoerg NoProtoType = CGM.getContext().getPointerType(NoProtoType);
256706f32e7eSjoerg V = llvm::ConstantExpr::getBitCast(V,
256806f32e7eSjoerg CGM.getTypes().ConvertType(NoProtoType));
256906f32e7eSjoerg }
257006f32e7eSjoerg }
257106f32e7eSjoerg return V;
257206f32e7eSjoerg }
257306f32e7eSjoerg
EmitFunctionDeclLValue(CodeGenFunction & CGF,const Expr * E,GlobalDecl GD)2574*13fbcb42Sjoerg static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
2575*13fbcb42Sjoerg GlobalDecl GD) {
2576*13fbcb42Sjoerg const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2577*13fbcb42Sjoerg llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
257806f32e7eSjoerg CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
257906f32e7eSjoerg return CGF.MakeAddrLValue(V, E->getType(), Alignment,
258006f32e7eSjoerg AlignmentSource::Decl);
258106f32e7eSjoerg }
258206f32e7eSjoerg
EmitCapturedFieldLValue(CodeGenFunction & CGF,const FieldDecl * FD,llvm::Value * ThisValue)258306f32e7eSjoerg static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
258406f32e7eSjoerg llvm::Value *ThisValue) {
258506f32e7eSjoerg QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
258606f32e7eSjoerg LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
258706f32e7eSjoerg return CGF.EmitLValueForField(LV, FD);
258806f32e7eSjoerg }
258906f32e7eSjoerg
259006f32e7eSjoerg /// Named Registers are named metadata pointing to the register name
259106f32e7eSjoerg /// which will be read from/written to as an argument to the intrinsic
259206f32e7eSjoerg /// @llvm.read/write_register.
259306f32e7eSjoerg /// So far, only the name is being passed down, but other options such as
259406f32e7eSjoerg /// register type, allocation type or even optimization options could be
259506f32e7eSjoerg /// passed down via the metadata node.
EmitGlobalNamedRegister(const VarDecl * VD,CodeGenModule & CGM)259606f32e7eSjoerg static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
259706f32e7eSjoerg SmallString<64> Name("llvm.named.register.");
259806f32e7eSjoerg AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
259906f32e7eSjoerg assert(Asm->getLabel().size() < 64-Name.size() &&
260006f32e7eSjoerg "Register name too big");
260106f32e7eSjoerg Name.append(Asm->getLabel());
260206f32e7eSjoerg llvm::NamedMDNode *M =
260306f32e7eSjoerg CGM.getModule().getOrInsertNamedMetadata(Name);
260406f32e7eSjoerg if (M->getNumOperands() == 0) {
260506f32e7eSjoerg llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
260606f32e7eSjoerg Asm->getLabel());
260706f32e7eSjoerg llvm::Metadata *Ops[] = {Str};
260806f32e7eSjoerg M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
260906f32e7eSjoerg }
261006f32e7eSjoerg
261106f32e7eSjoerg CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
261206f32e7eSjoerg
261306f32e7eSjoerg llvm::Value *Ptr =
261406f32e7eSjoerg llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
261506f32e7eSjoerg return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
261606f32e7eSjoerg }
261706f32e7eSjoerg
261806f32e7eSjoerg /// Determine whether we can emit a reference to \p VD from the current
261906f32e7eSjoerg /// context, despite not necessarily having seen an odr-use of the variable in
262006f32e7eSjoerg /// this context.
canEmitSpuriousReferenceToVariable(CodeGenFunction & CGF,const DeclRefExpr * E,const VarDecl * VD,bool IsConstant)262106f32e7eSjoerg static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
262206f32e7eSjoerg const DeclRefExpr *E,
262306f32e7eSjoerg const VarDecl *VD,
262406f32e7eSjoerg bool IsConstant) {
262506f32e7eSjoerg // For a variable declared in an enclosing scope, do not emit a spurious
262606f32e7eSjoerg // reference even if we have a capture, as that will emit an unwarranted
262706f32e7eSjoerg // reference to our capture state, and will likely generate worse code than
262806f32e7eSjoerg // emitting a local copy.
262906f32e7eSjoerg if (E->refersToEnclosingVariableOrCapture())
263006f32e7eSjoerg return false;
263106f32e7eSjoerg
263206f32e7eSjoerg // For a local declaration declared in this function, we can always reference
263306f32e7eSjoerg // it even if we don't have an odr-use.
263406f32e7eSjoerg if (VD->hasLocalStorage()) {
263506f32e7eSjoerg return VD->getDeclContext() ==
263606f32e7eSjoerg dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
263706f32e7eSjoerg }
263806f32e7eSjoerg
263906f32e7eSjoerg // For a global declaration, we can emit a reference to it if we know
264006f32e7eSjoerg // for sure that we are able to emit a definition of it.
264106f32e7eSjoerg VD = VD->getDefinition(CGF.getContext());
264206f32e7eSjoerg if (!VD)
264306f32e7eSjoerg return false;
264406f32e7eSjoerg
264506f32e7eSjoerg // Don't emit a spurious reference if it might be to a variable that only
264606f32e7eSjoerg // exists on a different device / target.
264706f32e7eSjoerg // FIXME: This is unnecessarily broad. Check whether this would actually be a
264806f32e7eSjoerg // cross-target reference.
264906f32e7eSjoerg if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
265006f32e7eSjoerg CGF.getLangOpts().OpenCL) {
265106f32e7eSjoerg return false;
265206f32e7eSjoerg }
265306f32e7eSjoerg
265406f32e7eSjoerg // We can emit a spurious reference only if the linkage implies that we'll
265506f32e7eSjoerg // be emitting a non-interposable symbol that will be retained until link
265606f32e7eSjoerg // time.
265706f32e7eSjoerg switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
265806f32e7eSjoerg case llvm::GlobalValue::ExternalLinkage:
265906f32e7eSjoerg case llvm::GlobalValue::LinkOnceODRLinkage:
266006f32e7eSjoerg case llvm::GlobalValue::WeakODRLinkage:
266106f32e7eSjoerg case llvm::GlobalValue::InternalLinkage:
266206f32e7eSjoerg case llvm::GlobalValue::PrivateLinkage:
266306f32e7eSjoerg return true;
266406f32e7eSjoerg default:
266506f32e7eSjoerg return false;
266606f32e7eSjoerg }
266706f32e7eSjoerg }
266806f32e7eSjoerg
EmitDeclRefLValue(const DeclRefExpr * E)266906f32e7eSjoerg LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
267006f32e7eSjoerg const NamedDecl *ND = E->getDecl();
267106f32e7eSjoerg QualType T = E->getType();
267206f32e7eSjoerg
267306f32e7eSjoerg assert(E->isNonOdrUse() != NOUR_Unevaluated &&
267406f32e7eSjoerg "should not emit an unevaluated operand");
267506f32e7eSjoerg
267606f32e7eSjoerg if (const auto *VD = dyn_cast<VarDecl>(ND)) {
267706f32e7eSjoerg // Global Named registers access via intrinsics only
267806f32e7eSjoerg if (VD->getStorageClass() == SC_Register &&
267906f32e7eSjoerg VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
268006f32e7eSjoerg return EmitGlobalNamedRegister(VD, CGM);
268106f32e7eSjoerg
268206f32e7eSjoerg // If this DeclRefExpr does not constitute an odr-use of the variable,
268306f32e7eSjoerg // we're not permitted to emit a reference to it in general, and it might
268406f32e7eSjoerg // not be captured if capture would be necessary for a use. Emit the
268506f32e7eSjoerg // constant value directly instead.
268606f32e7eSjoerg if (E->isNonOdrUse() == NOUR_Constant &&
268706f32e7eSjoerg (VD->getType()->isReferenceType() ||
268806f32e7eSjoerg !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
268906f32e7eSjoerg VD->getAnyInitializer(VD);
269006f32e7eSjoerg llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
269106f32e7eSjoerg E->getLocation(), *VD->evaluateValue(), VD->getType());
269206f32e7eSjoerg assert(Val && "failed to emit constant expression");
269306f32e7eSjoerg
269406f32e7eSjoerg Address Addr = Address::invalid();
269506f32e7eSjoerg if (!VD->getType()->isReferenceType()) {
269606f32e7eSjoerg // Spill the constant value to a global.
269706f32e7eSjoerg Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
269806f32e7eSjoerg getContext().getDeclAlign(VD));
269906f32e7eSjoerg llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
270006f32e7eSjoerg auto *PTy = llvm::PointerType::get(
270106f32e7eSjoerg VarTy, getContext().getTargetAddressSpace(VD->getType()));
270206f32e7eSjoerg if (PTy != Addr.getType())
270306f32e7eSjoerg Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy);
270406f32e7eSjoerg } else {
270506f32e7eSjoerg // Should we be using the alignment of the constant pointer we emitted?
270606f32e7eSjoerg CharUnits Alignment =
2707*13fbcb42Sjoerg CGM.getNaturalTypeAlignment(E->getType(),
270806f32e7eSjoerg /* BaseInfo= */ nullptr,
270906f32e7eSjoerg /* TBAAInfo= */ nullptr,
271006f32e7eSjoerg /* forPointeeType= */ true);
271106f32e7eSjoerg Addr = Address(Val, Alignment);
271206f32e7eSjoerg }
271306f32e7eSjoerg return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
271406f32e7eSjoerg }
271506f32e7eSjoerg
271606f32e7eSjoerg // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
271706f32e7eSjoerg
271806f32e7eSjoerg // Check for captured variables.
271906f32e7eSjoerg if (E->refersToEnclosingVariableOrCapture()) {
272006f32e7eSjoerg VD = VD->getCanonicalDecl();
272106f32e7eSjoerg if (auto *FD = LambdaCaptureFields.lookup(VD))
272206f32e7eSjoerg return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2723*13fbcb42Sjoerg if (CapturedStmtInfo) {
272406f32e7eSjoerg auto I = LocalDeclMap.find(VD);
272506f32e7eSjoerg if (I != LocalDeclMap.end()) {
2726*13fbcb42Sjoerg LValue CapLVal;
272706f32e7eSjoerg if (VD->getType()->isReferenceType())
2728*13fbcb42Sjoerg CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
272906f32e7eSjoerg AlignmentSource::Decl);
2730*13fbcb42Sjoerg else
2731*13fbcb42Sjoerg CapLVal = MakeAddrLValue(I->second, T);
2732*13fbcb42Sjoerg // Mark lvalue as nontemporal if the variable is marked as nontemporal
2733*13fbcb42Sjoerg // in simd context.
2734*13fbcb42Sjoerg if (getLangOpts().OpenMP &&
2735*13fbcb42Sjoerg CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2736*13fbcb42Sjoerg CapLVal.setNontemporal(/*Value=*/true);
2737*13fbcb42Sjoerg return CapLVal;
273806f32e7eSjoerg }
273906f32e7eSjoerg LValue CapLVal =
274006f32e7eSjoerg EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
274106f32e7eSjoerg CapturedStmtInfo->getContextValue());
2742*13fbcb42Sjoerg CapLVal = MakeAddrLValue(
2743*13fbcb42Sjoerg Address(CapLVal.getPointer(*this), getContext().getDeclAlign(VD)),
274406f32e7eSjoerg CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
274506f32e7eSjoerg CapLVal.getTBAAInfo());
2746*13fbcb42Sjoerg // Mark lvalue as nontemporal if the variable is marked as nontemporal
2747*13fbcb42Sjoerg // in simd context.
2748*13fbcb42Sjoerg if (getLangOpts().OpenMP &&
2749*13fbcb42Sjoerg CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2750*13fbcb42Sjoerg CapLVal.setNontemporal(/*Value=*/true);
2751*13fbcb42Sjoerg return CapLVal;
275206f32e7eSjoerg }
275306f32e7eSjoerg
275406f32e7eSjoerg assert(isa<BlockDecl>(CurCodeDecl));
275506f32e7eSjoerg Address addr = GetAddrOfBlockDecl(VD);
275606f32e7eSjoerg return MakeAddrLValue(addr, T, AlignmentSource::Decl);
275706f32e7eSjoerg }
275806f32e7eSjoerg }
275906f32e7eSjoerg
276006f32e7eSjoerg // FIXME: We should be able to assert this for FunctionDecls as well!
276106f32e7eSjoerg // FIXME: We should be able to assert this for all DeclRefExprs, not just
276206f32e7eSjoerg // those with a valid source location.
276306f32e7eSjoerg assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
276406f32e7eSjoerg !E->getLocation().isValid()) &&
276506f32e7eSjoerg "Should not use decl without marking it used!");
276606f32e7eSjoerg
276706f32e7eSjoerg if (ND->hasAttr<WeakRefAttr>()) {
276806f32e7eSjoerg const auto *VD = cast<ValueDecl>(ND);
276906f32e7eSjoerg ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
277006f32e7eSjoerg return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
277106f32e7eSjoerg }
277206f32e7eSjoerg
277306f32e7eSjoerg if (const auto *VD = dyn_cast<VarDecl>(ND)) {
277406f32e7eSjoerg // Check if this is a global variable.
277506f32e7eSjoerg if (VD->hasLinkage() || VD->isStaticDataMember())
277606f32e7eSjoerg return EmitGlobalVarDeclLValue(*this, E, VD);
277706f32e7eSjoerg
277806f32e7eSjoerg Address addr = Address::invalid();
277906f32e7eSjoerg
278006f32e7eSjoerg // The variable should generally be present in the local decl map.
278106f32e7eSjoerg auto iter = LocalDeclMap.find(VD);
278206f32e7eSjoerg if (iter != LocalDeclMap.end()) {
278306f32e7eSjoerg addr = iter->second;
278406f32e7eSjoerg
278506f32e7eSjoerg // Otherwise, it might be static local we haven't emitted yet for
278606f32e7eSjoerg // some reason; most likely, because it's in an outer function.
278706f32e7eSjoerg } else if (VD->isStaticLocal()) {
278806f32e7eSjoerg addr = Address(CGM.getOrCreateStaticVarDecl(
278906f32e7eSjoerg *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false)),
279006f32e7eSjoerg getContext().getDeclAlign(VD));
279106f32e7eSjoerg
279206f32e7eSjoerg // No other cases for now.
279306f32e7eSjoerg } else {
279406f32e7eSjoerg llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
279506f32e7eSjoerg }
279606f32e7eSjoerg
279706f32e7eSjoerg
279806f32e7eSjoerg // Check for OpenMP threadprivate variables.
279906f32e7eSjoerg if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
280006f32e7eSjoerg VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
280106f32e7eSjoerg return EmitThreadPrivateVarDeclLValue(
280206f32e7eSjoerg *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
280306f32e7eSjoerg E->getExprLoc());
280406f32e7eSjoerg }
280506f32e7eSjoerg
280606f32e7eSjoerg // Drill into block byref variables.
280706f32e7eSjoerg bool isBlockByref = VD->isEscapingByref();
280806f32e7eSjoerg if (isBlockByref) {
280906f32e7eSjoerg addr = emitBlockByrefAddress(addr, VD);
281006f32e7eSjoerg }
281106f32e7eSjoerg
281206f32e7eSjoerg // Drill into reference types.
281306f32e7eSjoerg LValue LV = VD->getType()->isReferenceType() ?
281406f32e7eSjoerg EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
281506f32e7eSjoerg MakeAddrLValue(addr, T, AlignmentSource::Decl);
281606f32e7eSjoerg
281706f32e7eSjoerg bool isLocalStorage = VD->hasLocalStorage();
281806f32e7eSjoerg
281906f32e7eSjoerg bool NonGCable = isLocalStorage &&
282006f32e7eSjoerg !VD->getType()->isReferenceType() &&
282106f32e7eSjoerg !isBlockByref;
282206f32e7eSjoerg if (NonGCable) {
282306f32e7eSjoerg LV.getQuals().removeObjCGCAttr();
282406f32e7eSjoerg LV.setNonGC(true);
282506f32e7eSjoerg }
282606f32e7eSjoerg
282706f32e7eSjoerg bool isImpreciseLifetime =
282806f32e7eSjoerg (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
282906f32e7eSjoerg if (isImpreciseLifetime)
283006f32e7eSjoerg LV.setARCPreciseLifetime(ARCImpreciseLifetime);
283106f32e7eSjoerg setObjCGCLValueClass(getContext(), E, LV);
283206f32e7eSjoerg return LV;
283306f32e7eSjoerg }
283406f32e7eSjoerg
2835*13fbcb42Sjoerg if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
2836*13fbcb42Sjoerg LValue LV = EmitFunctionDeclLValue(*this, E, FD);
2837*13fbcb42Sjoerg
2838*13fbcb42Sjoerg // Emit debuginfo for the function declaration if the target wants to.
2839*13fbcb42Sjoerg if (getContext().getTargetInfo().allowDebugInfoForExternalRef()) {
2840*13fbcb42Sjoerg if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) {
2841*13fbcb42Sjoerg auto *Fn =
2842*13fbcb42Sjoerg cast<llvm::Function>(LV.getPointer(*this)->stripPointerCasts());
2843*13fbcb42Sjoerg if (!Fn->getSubprogram())
2844*13fbcb42Sjoerg DI->EmitFunctionDecl(FD, FD->getLocation(), T, Fn);
2845*13fbcb42Sjoerg }
2846*13fbcb42Sjoerg }
2847*13fbcb42Sjoerg
2848*13fbcb42Sjoerg return LV;
2849*13fbcb42Sjoerg }
285006f32e7eSjoerg
285106f32e7eSjoerg // FIXME: While we're emitting a binding from an enclosing scope, all other
285206f32e7eSjoerg // DeclRefExprs we see should be implicitly treated as if they also refer to
285306f32e7eSjoerg // an enclosing scope.
285406f32e7eSjoerg if (const auto *BD = dyn_cast<BindingDecl>(ND))
285506f32e7eSjoerg return EmitLValue(BD->getBinding());
285606f32e7eSjoerg
2857*13fbcb42Sjoerg // We can form DeclRefExprs naming GUID declarations when reconstituting
2858*13fbcb42Sjoerg // non-type template parameters into expressions.
2859*13fbcb42Sjoerg if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
2860*13fbcb42Sjoerg return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
2861*13fbcb42Sjoerg AlignmentSource::Decl);
2862*13fbcb42Sjoerg
2863*13fbcb42Sjoerg if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND))
2864*13fbcb42Sjoerg return MakeAddrLValue(CGM.GetAddrOfTemplateParamObject(TPO), T,
2865*13fbcb42Sjoerg AlignmentSource::Decl);
2866*13fbcb42Sjoerg
286706f32e7eSjoerg llvm_unreachable("Unhandled DeclRefExpr");
286806f32e7eSjoerg }
286906f32e7eSjoerg
EmitUnaryOpLValue(const UnaryOperator * E)287006f32e7eSjoerg LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
287106f32e7eSjoerg // __extension__ doesn't affect lvalue-ness.
287206f32e7eSjoerg if (E->getOpcode() == UO_Extension)
287306f32e7eSjoerg return EmitLValue(E->getSubExpr());
287406f32e7eSjoerg
287506f32e7eSjoerg QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
287606f32e7eSjoerg switch (E->getOpcode()) {
287706f32e7eSjoerg default: llvm_unreachable("Unknown unary operator lvalue!");
287806f32e7eSjoerg case UO_Deref: {
287906f32e7eSjoerg QualType T = E->getSubExpr()->getType()->getPointeeType();
288006f32e7eSjoerg assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
288106f32e7eSjoerg
288206f32e7eSjoerg LValueBaseInfo BaseInfo;
288306f32e7eSjoerg TBAAAccessInfo TBAAInfo;
288406f32e7eSjoerg Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
288506f32e7eSjoerg &TBAAInfo);
288606f32e7eSjoerg LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
288706f32e7eSjoerg LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
288806f32e7eSjoerg
288906f32e7eSjoerg // We should not generate __weak write barrier on indirect reference
289006f32e7eSjoerg // of a pointer to object; as in void foo (__weak id *param); *param = 0;
289106f32e7eSjoerg // But, we continue to generate __strong write barrier on indirect write
289206f32e7eSjoerg // into a pointer to object.
289306f32e7eSjoerg if (getLangOpts().ObjC &&
289406f32e7eSjoerg getLangOpts().getGC() != LangOptions::NonGC &&
289506f32e7eSjoerg LV.isObjCWeak())
289606f32e7eSjoerg LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
289706f32e7eSjoerg return LV;
289806f32e7eSjoerg }
289906f32e7eSjoerg case UO_Real:
290006f32e7eSjoerg case UO_Imag: {
290106f32e7eSjoerg LValue LV = EmitLValue(E->getSubExpr());
290206f32e7eSjoerg assert(LV.isSimple() && "real/imag on non-ordinary l-value");
290306f32e7eSjoerg
290406f32e7eSjoerg // __real is valid on scalars. This is a faster way of testing that.
290506f32e7eSjoerg // __imag can only produce an rvalue on scalars.
290606f32e7eSjoerg if (E->getOpcode() == UO_Real &&
2907*13fbcb42Sjoerg !LV.getAddress(*this).getElementType()->isStructTy()) {
290806f32e7eSjoerg assert(E->getSubExpr()->getType()->isArithmeticType());
290906f32e7eSjoerg return LV;
291006f32e7eSjoerg }
291106f32e7eSjoerg
291206f32e7eSjoerg QualType T = ExprTy->castAs<ComplexType>()->getElementType();
291306f32e7eSjoerg
291406f32e7eSjoerg Address Component =
291506f32e7eSjoerg (E->getOpcode() == UO_Real
2916*13fbcb42Sjoerg ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
2917*13fbcb42Sjoerg : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType()));
291806f32e7eSjoerg LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
291906f32e7eSjoerg CGM.getTBAAInfoForSubobject(LV, T));
292006f32e7eSjoerg ElemLV.getQuals().addQualifiers(LV.getQuals());
292106f32e7eSjoerg return ElemLV;
292206f32e7eSjoerg }
292306f32e7eSjoerg case UO_PreInc:
292406f32e7eSjoerg case UO_PreDec: {
292506f32e7eSjoerg LValue LV = EmitLValue(E->getSubExpr());
292606f32e7eSjoerg bool isInc = E->getOpcode() == UO_PreInc;
292706f32e7eSjoerg
292806f32e7eSjoerg if (E->getType()->isAnyComplexType())
292906f32e7eSjoerg EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
293006f32e7eSjoerg else
293106f32e7eSjoerg EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
293206f32e7eSjoerg return LV;
293306f32e7eSjoerg }
293406f32e7eSjoerg }
293506f32e7eSjoerg }
293606f32e7eSjoerg
EmitStringLiteralLValue(const StringLiteral * E)293706f32e7eSjoerg LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
293806f32e7eSjoerg return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
293906f32e7eSjoerg E->getType(), AlignmentSource::Decl);
294006f32e7eSjoerg }
294106f32e7eSjoerg
EmitObjCEncodeExprLValue(const ObjCEncodeExpr * E)294206f32e7eSjoerg LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
294306f32e7eSjoerg return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
294406f32e7eSjoerg E->getType(), AlignmentSource::Decl);
294506f32e7eSjoerg }
294606f32e7eSjoerg
EmitPredefinedLValue(const PredefinedExpr * E)294706f32e7eSjoerg LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
294806f32e7eSjoerg auto SL = E->getFunctionName();
294906f32e7eSjoerg assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
295006f32e7eSjoerg StringRef FnName = CurFn->getName();
295106f32e7eSjoerg if (FnName.startswith("\01"))
295206f32e7eSjoerg FnName = FnName.substr(1);
295306f32e7eSjoerg StringRef NameItems[] = {
295406f32e7eSjoerg PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
295506f32e7eSjoerg std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
295606f32e7eSjoerg if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
2957*13fbcb42Sjoerg std::string Name = std::string(SL->getString());
295806f32e7eSjoerg if (!Name.empty()) {
295906f32e7eSjoerg unsigned Discriminator =
296006f32e7eSjoerg CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
296106f32e7eSjoerg if (Discriminator)
296206f32e7eSjoerg Name += "_" + Twine(Discriminator + 1).str();
296306f32e7eSjoerg auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
296406f32e7eSjoerg return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
296506f32e7eSjoerg } else {
2966*13fbcb42Sjoerg auto C =
2967*13fbcb42Sjoerg CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
296806f32e7eSjoerg return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
296906f32e7eSjoerg }
297006f32e7eSjoerg }
297106f32e7eSjoerg auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
297206f32e7eSjoerg return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
297306f32e7eSjoerg }
297406f32e7eSjoerg
297506f32e7eSjoerg /// Emit a type description suitable for use by a runtime sanitizer library. The
297606f32e7eSjoerg /// format of a type descriptor is
297706f32e7eSjoerg ///
297806f32e7eSjoerg /// \code
297906f32e7eSjoerg /// { i16 TypeKind, i16 TypeInfo }
298006f32e7eSjoerg /// \endcode
298106f32e7eSjoerg ///
298206f32e7eSjoerg /// followed by an array of i8 containing the type name. TypeKind is 0 for an
298306f32e7eSjoerg /// integer, 1 for a floating point value, and -1 for anything else.
EmitCheckTypeDescriptor(QualType T)298406f32e7eSjoerg llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
298506f32e7eSjoerg // Only emit each type's descriptor once.
298606f32e7eSjoerg if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
298706f32e7eSjoerg return C;
298806f32e7eSjoerg
298906f32e7eSjoerg uint16_t TypeKind = -1;
299006f32e7eSjoerg uint16_t TypeInfo = 0;
299106f32e7eSjoerg
299206f32e7eSjoerg if (T->isIntegerType()) {
299306f32e7eSjoerg TypeKind = 0;
299406f32e7eSjoerg TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
299506f32e7eSjoerg (T->isSignedIntegerType() ? 1 : 0);
299606f32e7eSjoerg } else if (T->isFloatingType()) {
299706f32e7eSjoerg TypeKind = 1;
299806f32e7eSjoerg TypeInfo = getContext().getTypeSize(T);
299906f32e7eSjoerg }
300006f32e7eSjoerg
300106f32e7eSjoerg // Format the type name as if for a diagnostic, including quotes and
300206f32e7eSjoerg // optionally an 'aka'.
300306f32e7eSjoerg SmallString<32> Buffer;
300406f32e7eSjoerg CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
300506f32e7eSjoerg (intptr_t)T.getAsOpaquePtr(),
300606f32e7eSjoerg StringRef(), StringRef(), None, Buffer,
300706f32e7eSjoerg None);
300806f32e7eSjoerg
300906f32e7eSjoerg llvm::Constant *Components[] = {
301006f32e7eSjoerg Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
301106f32e7eSjoerg llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
301206f32e7eSjoerg };
301306f32e7eSjoerg llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
301406f32e7eSjoerg
301506f32e7eSjoerg auto *GV = new llvm::GlobalVariable(
301606f32e7eSjoerg CGM.getModule(), Descriptor->getType(),
301706f32e7eSjoerg /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
301806f32e7eSjoerg GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
301906f32e7eSjoerg CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
302006f32e7eSjoerg
302106f32e7eSjoerg // Remember the descriptor for this type.
302206f32e7eSjoerg CGM.setTypeDescriptorInMap(T, GV);
302306f32e7eSjoerg
302406f32e7eSjoerg return GV;
302506f32e7eSjoerg }
302606f32e7eSjoerg
EmitCheckValue(llvm::Value * V)302706f32e7eSjoerg llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
302806f32e7eSjoerg llvm::Type *TargetTy = IntPtrTy;
302906f32e7eSjoerg
303006f32e7eSjoerg if (V->getType() == TargetTy)
303106f32e7eSjoerg return V;
303206f32e7eSjoerg
303306f32e7eSjoerg // Floating-point types which fit into intptr_t are bitcast to integers
303406f32e7eSjoerg // and then passed directly (after zero-extension, if necessary).
303506f32e7eSjoerg if (V->getType()->isFloatingPointTy()) {
3036*13fbcb42Sjoerg unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedSize();
303706f32e7eSjoerg if (Bits <= TargetTy->getIntegerBitWidth())
303806f32e7eSjoerg V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
303906f32e7eSjoerg Bits));
304006f32e7eSjoerg }
304106f32e7eSjoerg
304206f32e7eSjoerg // Integers which fit in intptr_t are zero-extended and passed directly.
304306f32e7eSjoerg if (V->getType()->isIntegerTy() &&
304406f32e7eSjoerg V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
304506f32e7eSjoerg return Builder.CreateZExt(V, TargetTy);
304606f32e7eSjoerg
304706f32e7eSjoerg // Pointers are passed directly, everything else is passed by address.
304806f32e7eSjoerg if (!V->getType()->isPointerTy()) {
304906f32e7eSjoerg Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
305006f32e7eSjoerg Builder.CreateStore(V, Ptr);
305106f32e7eSjoerg V = Ptr.getPointer();
305206f32e7eSjoerg }
305306f32e7eSjoerg return Builder.CreatePtrToInt(V, TargetTy);
305406f32e7eSjoerg }
305506f32e7eSjoerg
305606f32e7eSjoerg /// Emit a representation of a SourceLocation for passing to a handler
305706f32e7eSjoerg /// in a sanitizer runtime library. The format for this data is:
305806f32e7eSjoerg /// \code
305906f32e7eSjoerg /// struct SourceLocation {
306006f32e7eSjoerg /// const char *Filename;
306106f32e7eSjoerg /// int32_t Line, Column;
306206f32e7eSjoerg /// };
306306f32e7eSjoerg /// \endcode
306406f32e7eSjoerg /// For an invalid SourceLocation, the Filename pointer is null.
EmitCheckSourceLocation(SourceLocation Loc)306506f32e7eSjoerg llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
306606f32e7eSjoerg llvm::Constant *Filename;
306706f32e7eSjoerg int Line, Column;
306806f32e7eSjoerg
306906f32e7eSjoerg PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
307006f32e7eSjoerg if (PLoc.isValid()) {
307106f32e7eSjoerg StringRef FilenameString = PLoc.getFilename();
307206f32e7eSjoerg
307306f32e7eSjoerg int PathComponentsToStrip =
307406f32e7eSjoerg CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
307506f32e7eSjoerg if (PathComponentsToStrip < 0) {
307606f32e7eSjoerg assert(PathComponentsToStrip != INT_MIN);
307706f32e7eSjoerg int PathComponentsToKeep = -PathComponentsToStrip;
307806f32e7eSjoerg auto I = llvm::sys::path::rbegin(FilenameString);
307906f32e7eSjoerg auto E = llvm::sys::path::rend(FilenameString);
308006f32e7eSjoerg while (I != E && --PathComponentsToKeep)
308106f32e7eSjoerg ++I;
308206f32e7eSjoerg
308306f32e7eSjoerg FilenameString = FilenameString.substr(I - E);
308406f32e7eSjoerg } else if (PathComponentsToStrip > 0) {
308506f32e7eSjoerg auto I = llvm::sys::path::begin(FilenameString);
308606f32e7eSjoerg auto E = llvm::sys::path::end(FilenameString);
308706f32e7eSjoerg while (I != E && PathComponentsToStrip--)
308806f32e7eSjoerg ++I;
308906f32e7eSjoerg
309006f32e7eSjoerg if (I != E)
309106f32e7eSjoerg FilenameString =
309206f32e7eSjoerg FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
309306f32e7eSjoerg else
309406f32e7eSjoerg FilenameString = llvm::sys::path::filename(FilenameString);
309506f32e7eSjoerg }
309606f32e7eSjoerg
3097*13fbcb42Sjoerg auto FilenameGV =
3098*13fbcb42Sjoerg CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
309906f32e7eSjoerg CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
310006f32e7eSjoerg cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
310106f32e7eSjoerg Filename = FilenameGV.getPointer();
310206f32e7eSjoerg Line = PLoc.getLine();
310306f32e7eSjoerg Column = PLoc.getColumn();
310406f32e7eSjoerg } else {
310506f32e7eSjoerg Filename = llvm::Constant::getNullValue(Int8PtrTy);
310606f32e7eSjoerg Line = Column = 0;
310706f32e7eSjoerg }
310806f32e7eSjoerg
310906f32e7eSjoerg llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
311006f32e7eSjoerg Builder.getInt32(Column)};
311106f32e7eSjoerg
311206f32e7eSjoerg return llvm::ConstantStruct::getAnon(Data);
311306f32e7eSjoerg }
311406f32e7eSjoerg
311506f32e7eSjoerg namespace {
311606f32e7eSjoerg /// Specify under what conditions this check can be recovered
311706f32e7eSjoerg enum class CheckRecoverableKind {
311806f32e7eSjoerg /// Always terminate program execution if this check fails.
311906f32e7eSjoerg Unrecoverable,
312006f32e7eSjoerg /// Check supports recovering, runtime has both fatal (noreturn) and
312106f32e7eSjoerg /// non-fatal handlers for this check.
312206f32e7eSjoerg Recoverable,
312306f32e7eSjoerg /// Runtime conditionally aborts, always need to support recovery.
312406f32e7eSjoerg AlwaysRecoverable
312506f32e7eSjoerg };
312606f32e7eSjoerg }
312706f32e7eSjoerg
getRecoverableKind(SanitizerMask Kind)312806f32e7eSjoerg static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
312906f32e7eSjoerg assert(Kind.countPopulation() == 1);
313006f32e7eSjoerg if (Kind == SanitizerKind::Function || Kind == SanitizerKind::Vptr)
313106f32e7eSjoerg return CheckRecoverableKind::AlwaysRecoverable;
313206f32e7eSjoerg else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
313306f32e7eSjoerg return CheckRecoverableKind::Unrecoverable;
313406f32e7eSjoerg else
313506f32e7eSjoerg return CheckRecoverableKind::Recoverable;
313606f32e7eSjoerg }
313706f32e7eSjoerg
313806f32e7eSjoerg namespace {
313906f32e7eSjoerg struct SanitizerHandlerInfo {
314006f32e7eSjoerg char const *const Name;
314106f32e7eSjoerg unsigned Version;
314206f32e7eSjoerg };
314306f32e7eSjoerg }
314406f32e7eSjoerg
314506f32e7eSjoerg const SanitizerHandlerInfo SanitizerHandlers[] = {
314606f32e7eSjoerg #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
314706f32e7eSjoerg LIST_SANITIZER_CHECKS
314806f32e7eSjoerg #undef SANITIZER_CHECK
314906f32e7eSjoerg };
315006f32e7eSjoerg
emitCheckHandlerCall(CodeGenFunction & CGF,llvm::FunctionType * FnType,ArrayRef<llvm::Value * > FnArgs,SanitizerHandler CheckHandler,CheckRecoverableKind RecoverKind,bool IsFatal,llvm::BasicBlock * ContBB)315106f32e7eSjoerg static void emitCheckHandlerCall(CodeGenFunction &CGF,
315206f32e7eSjoerg llvm::FunctionType *FnType,
315306f32e7eSjoerg ArrayRef<llvm::Value *> FnArgs,
315406f32e7eSjoerg SanitizerHandler CheckHandler,
315506f32e7eSjoerg CheckRecoverableKind RecoverKind, bool IsFatal,
315606f32e7eSjoerg llvm::BasicBlock *ContBB) {
315706f32e7eSjoerg assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
315806f32e7eSjoerg Optional<ApplyDebugLocation> DL;
315906f32e7eSjoerg if (!CGF.Builder.getCurrentDebugLocation()) {
316006f32e7eSjoerg // Ensure that the call has at least an artificial debug location.
316106f32e7eSjoerg DL.emplace(CGF, SourceLocation());
316206f32e7eSjoerg }
316306f32e7eSjoerg bool NeedsAbortSuffix =
316406f32e7eSjoerg IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
316506f32e7eSjoerg bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
316606f32e7eSjoerg const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
316706f32e7eSjoerg const StringRef CheckName = CheckInfo.Name;
316806f32e7eSjoerg std::string FnName = "__ubsan_handle_" + CheckName.str();
316906f32e7eSjoerg if (CheckInfo.Version && !MinimalRuntime)
317006f32e7eSjoerg FnName += "_v" + llvm::utostr(CheckInfo.Version);
317106f32e7eSjoerg if (MinimalRuntime)
317206f32e7eSjoerg FnName += "_minimal";
317306f32e7eSjoerg if (NeedsAbortSuffix)
317406f32e7eSjoerg FnName += "_abort";
317506f32e7eSjoerg bool MayReturn =
317606f32e7eSjoerg !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
317706f32e7eSjoerg
317806f32e7eSjoerg llvm::AttrBuilder B;
317906f32e7eSjoerg if (!MayReturn) {
318006f32e7eSjoerg B.addAttribute(llvm::Attribute::NoReturn)
318106f32e7eSjoerg .addAttribute(llvm::Attribute::NoUnwind);
318206f32e7eSjoerg }
318306f32e7eSjoerg B.addAttribute(llvm::Attribute::UWTable);
318406f32e7eSjoerg
318506f32e7eSjoerg llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
318606f32e7eSjoerg FnType, FnName,
318706f32e7eSjoerg llvm::AttributeList::get(CGF.getLLVMContext(),
318806f32e7eSjoerg llvm::AttributeList::FunctionIndex, B),
318906f32e7eSjoerg /*Local=*/true);
319006f32e7eSjoerg llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
319106f32e7eSjoerg if (!MayReturn) {
319206f32e7eSjoerg HandlerCall->setDoesNotReturn();
319306f32e7eSjoerg CGF.Builder.CreateUnreachable();
319406f32e7eSjoerg } else {
319506f32e7eSjoerg CGF.Builder.CreateBr(ContBB);
319606f32e7eSjoerg }
319706f32e7eSjoerg }
319806f32e7eSjoerg
EmitCheck(ArrayRef<std::pair<llvm::Value *,SanitizerMask>> Checked,SanitizerHandler CheckHandler,ArrayRef<llvm::Constant * > StaticArgs,ArrayRef<llvm::Value * > DynamicArgs)319906f32e7eSjoerg void CodeGenFunction::EmitCheck(
320006f32e7eSjoerg ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
320106f32e7eSjoerg SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
320206f32e7eSjoerg ArrayRef<llvm::Value *> DynamicArgs) {
320306f32e7eSjoerg assert(IsSanitizerScope);
320406f32e7eSjoerg assert(Checked.size() > 0);
320506f32e7eSjoerg assert(CheckHandler >= 0 &&
320606f32e7eSjoerg size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
320706f32e7eSjoerg const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
320806f32e7eSjoerg
320906f32e7eSjoerg llvm::Value *FatalCond = nullptr;
321006f32e7eSjoerg llvm::Value *RecoverableCond = nullptr;
321106f32e7eSjoerg llvm::Value *TrapCond = nullptr;
321206f32e7eSjoerg for (int i = 0, n = Checked.size(); i < n; ++i) {
321306f32e7eSjoerg llvm::Value *Check = Checked[i].first;
321406f32e7eSjoerg // -fsanitize-trap= overrides -fsanitize-recover=.
321506f32e7eSjoerg llvm::Value *&Cond =
321606f32e7eSjoerg CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
321706f32e7eSjoerg ? TrapCond
321806f32e7eSjoerg : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
321906f32e7eSjoerg ? RecoverableCond
322006f32e7eSjoerg : FatalCond;
322106f32e7eSjoerg Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
322206f32e7eSjoerg }
322306f32e7eSjoerg
322406f32e7eSjoerg if (TrapCond)
3225*13fbcb42Sjoerg EmitTrapCheck(TrapCond, CheckHandler);
322606f32e7eSjoerg if (!FatalCond && !RecoverableCond)
322706f32e7eSjoerg return;
322806f32e7eSjoerg
322906f32e7eSjoerg llvm::Value *JointCond;
323006f32e7eSjoerg if (FatalCond && RecoverableCond)
323106f32e7eSjoerg JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
323206f32e7eSjoerg else
323306f32e7eSjoerg JointCond = FatalCond ? FatalCond : RecoverableCond;
323406f32e7eSjoerg assert(JointCond);
323506f32e7eSjoerg
323606f32e7eSjoerg CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
323706f32e7eSjoerg assert(SanOpts.has(Checked[0].second));
323806f32e7eSjoerg #ifndef NDEBUG
323906f32e7eSjoerg for (int i = 1, n = Checked.size(); i < n; ++i) {
324006f32e7eSjoerg assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
324106f32e7eSjoerg "All recoverable kinds in a single check must be same!");
324206f32e7eSjoerg assert(SanOpts.has(Checked[i].second));
324306f32e7eSjoerg }
324406f32e7eSjoerg #endif
324506f32e7eSjoerg
324606f32e7eSjoerg llvm::BasicBlock *Cont = createBasicBlock("cont");
324706f32e7eSjoerg llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
324806f32e7eSjoerg llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
324906f32e7eSjoerg // Give hint that we very much don't expect to execute the handler
325006f32e7eSjoerg // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
325106f32e7eSjoerg llvm::MDBuilder MDHelper(getLLVMContext());
325206f32e7eSjoerg llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
325306f32e7eSjoerg Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
325406f32e7eSjoerg EmitBlock(Handlers);
325506f32e7eSjoerg
325606f32e7eSjoerg // Handler functions take an i8* pointing to the (handler-specific) static
325706f32e7eSjoerg // information block, followed by a sequence of intptr_t arguments
325806f32e7eSjoerg // representing operand values.
325906f32e7eSjoerg SmallVector<llvm::Value *, 4> Args;
326006f32e7eSjoerg SmallVector<llvm::Type *, 4> ArgTypes;
326106f32e7eSjoerg if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
326206f32e7eSjoerg Args.reserve(DynamicArgs.size() + 1);
326306f32e7eSjoerg ArgTypes.reserve(DynamicArgs.size() + 1);
326406f32e7eSjoerg
326506f32e7eSjoerg // Emit handler arguments and create handler function type.
326606f32e7eSjoerg if (!StaticArgs.empty()) {
326706f32e7eSjoerg llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
326806f32e7eSjoerg auto *InfoPtr =
326906f32e7eSjoerg new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
327006f32e7eSjoerg llvm::GlobalVariable::PrivateLinkage, Info);
327106f32e7eSjoerg InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
327206f32e7eSjoerg CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
327306f32e7eSjoerg Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
327406f32e7eSjoerg ArgTypes.push_back(Int8PtrTy);
327506f32e7eSjoerg }
327606f32e7eSjoerg
327706f32e7eSjoerg for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
327806f32e7eSjoerg Args.push_back(EmitCheckValue(DynamicArgs[i]));
327906f32e7eSjoerg ArgTypes.push_back(IntPtrTy);
328006f32e7eSjoerg }
328106f32e7eSjoerg }
328206f32e7eSjoerg
328306f32e7eSjoerg llvm::FunctionType *FnType =
328406f32e7eSjoerg llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
328506f32e7eSjoerg
328606f32e7eSjoerg if (!FatalCond || !RecoverableCond) {
328706f32e7eSjoerg // Simple case: we need to generate a single handler call, either
328806f32e7eSjoerg // fatal, or non-fatal.
328906f32e7eSjoerg emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
329006f32e7eSjoerg (FatalCond != nullptr), Cont);
329106f32e7eSjoerg } else {
329206f32e7eSjoerg // Emit two handler calls: first one for set of unrecoverable checks,
329306f32e7eSjoerg // another one for recoverable.
329406f32e7eSjoerg llvm::BasicBlock *NonFatalHandlerBB =
329506f32e7eSjoerg createBasicBlock("non_fatal." + CheckName);
329606f32e7eSjoerg llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
329706f32e7eSjoerg Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
329806f32e7eSjoerg EmitBlock(FatalHandlerBB);
329906f32e7eSjoerg emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
330006f32e7eSjoerg NonFatalHandlerBB);
330106f32e7eSjoerg EmitBlock(NonFatalHandlerBB);
330206f32e7eSjoerg emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
330306f32e7eSjoerg Cont);
330406f32e7eSjoerg }
330506f32e7eSjoerg
330606f32e7eSjoerg EmitBlock(Cont);
330706f32e7eSjoerg }
330806f32e7eSjoerg
EmitCfiSlowPathCheck(SanitizerMask Kind,llvm::Value * Cond,llvm::ConstantInt * TypeId,llvm::Value * Ptr,ArrayRef<llvm::Constant * > StaticArgs)330906f32e7eSjoerg void CodeGenFunction::EmitCfiSlowPathCheck(
331006f32e7eSjoerg SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
331106f32e7eSjoerg llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
331206f32e7eSjoerg llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
331306f32e7eSjoerg
331406f32e7eSjoerg llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
331506f32e7eSjoerg llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
331606f32e7eSjoerg
331706f32e7eSjoerg llvm::MDBuilder MDHelper(getLLVMContext());
331806f32e7eSjoerg llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
331906f32e7eSjoerg BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
332006f32e7eSjoerg
332106f32e7eSjoerg EmitBlock(CheckBB);
332206f32e7eSjoerg
332306f32e7eSjoerg bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
332406f32e7eSjoerg
332506f32e7eSjoerg llvm::CallInst *CheckCall;
332606f32e7eSjoerg llvm::FunctionCallee SlowPathFn;
332706f32e7eSjoerg if (WithDiag) {
332806f32e7eSjoerg llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
332906f32e7eSjoerg auto *InfoPtr =
333006f32e7eSjoerg new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
333106f32e7eSjoerg llvm::GlobalVariable::PrivateLinkage, Info);
333206f32e7eSjoerg InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
333306f32e7eSjoerg CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
333406f32e7eSjoerg
333506f32e7eSjoerg SlowPathFn = CGM.getModule().getOrInsertFunction(
333606f32e7eSjoerg "__cfi_slowpath_diag",
333706f32e7eSjoerg llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
333806f32e7eSjoerg false));
333906f32e7eSjoerg CheckCall = Builder.CreateCall(
334006f32e7eSjoerg SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
334106f32e7eSjoerg } else {
334206f32e7eSjoerg SlowPathFn = CGM.getModule().getOrInsertFunction(
334306f32e7eSjoerg "__cfi_slowpath",
334406f32e7eSjoerg llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
334506f32e7eSjoerg CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
334606f32e7eSjoerg }
334706f32e7eSjoerg
334806f32e7eSjoerg CGM.setDSOLocal(
334906f32e7eSjoerg cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
335006f32e7eSjoerg CheckCall->setDoesNotThrow();
335106f32e7eSjoerg
335206f32e7eSjoerg EmitBlock(Cont);
335306f32e7eSjoerg }
335406f32e7eSjoerg
335506f32e7eSjoerg // Emit a stub for __cfi_check function so that the linker knows about this
335606f32e7eSjoerg // symbol in LTO mode.
EmitCfiCheckStub()335706f32e7eSjoerg void CodeGenFunction::EmitCfiCheckStub() {
335806f32e7eSjoerg llvm::Module *M = &CGM.getModule();
335906f32e7eSjoerg auto &Ctx = M->getContext();
336006f32e7eSjoerg llvm::Function *F = llvm::Function::Create(
336106f32e7eSjoerg llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
336206f32e7eSjoerg llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
336306f32e7eSjoerg CGM.setDSOLocal(F);
336406f32e7eSjoerg llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
336506f32e7eSjoerg // FIXME: consider emitting an intrinsic call like
336606f32e7eSjoerg // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
336706f32e7eSjoerg // which can be lowered in CrossDSOCFI pass to the actual contents of
336806f32e7eSjoerg // __cfi_check. This would allow inlining of __cfi_check calls.
336906f32e7eSjoerg llvm::CallInst::Create(
337006f32e7eSjoerg llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
337106f32e7eSjoerg llvm::ReturnInst::Create(Ctx, nullptr, BB);
337206f32e7eSjoerg }
337306f32e7eSjoerg
337406f32e7eSjoerg // This function is basically a switch over the CFI failure kind, which is
337506f32e7eSjoerg // extracted from CFICheckFailData (1st function argument). Each case is either
337606f32e7eSjoerg // llvm.trap or a call to one of the two runtime handlers, based on
337706f32e7eSjoerg // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
337806f32e7eSjoerg // failure kind) traps, but this should really never happen. CFICheckFailData
337906f32e7eSjoerg // can be nullptr if the calling module has -fsanitize-trap behavior for this
338006f32e7eSjoerg // check kind; in this case __cfi_check_fail traps as well.
EmitCfiCheckFail()338106f32e7eSjoerg void CodeGenFunction::EmitCfiCheckFail() {
338206f32e7eSjoerg SanitizerScope SanScope(this);
338306f32e7eSjoerg FunctionArgList Args;
338406f32e7eSjoerg ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
338506f32e7eSjoerg ImplicitParamDecl::Other);
338606f32e7eSjoerg ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
338706f32e7eSjoerg ImplicitParamDecl::Other);
338806f32e7eSjoerg Args.push_back(&ArgData);
338906f32e7eSjoerg Args.push_back(&ArgAddr);
339006f32e7eSjoerg
339106f32e7eSjoerg const CGFunctionInfo &FI =
339206f32e7eSjoerg CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
339306f32e7eSjoerg
339406f32e7eSjoerg llvm::Function *F = llvm::Function::Create(
339506f32e7eSjoerg llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
339606f32e7eSjoerg llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3397*13fbcb42Sjoerg
3398*13fbcb42Sjoerg CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3399*13fbcb42Sjoerg CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
340006f32e7eSjoerg F->setVisibility(llvm::GlobalValue::HiddenVisibility);
340106f32e7eSjoerg
340206f32e7eSjoerg StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
340306f32e7eSjoerg SourceLocation());
340406f32e7eSjoerg
3405*13fbcb42Sjoerg // This function is not affected by NoSanitizeList. This function does
340606f32e7eSjoerg // not have a source location, but "src:*" would still apply. Revert any
340706f32e7eSjoerg // changes to SanOpts made in StartFunction.
340806f32e7eSjoerg SanOpts = CGM.getLangOpts().Sanitize;
340906f32e7eSjoerg
341006f32e7eSjoerg llvm::Value *Data =
341106f32e7eSjoerg EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
341206f32e7eSjoerg CGM.getContext().VoidPtrTy, ArgData.getLocation());
341306f32e7eSjoerg llvm::Value *Addr =
341406f32e7eSjoerg EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
341506f32e7eSjoerg CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
341606f32e7eSjoerg
341706f32e7eSjoerg // Data == nullptr means the calling module has trap behaviour for this check.
341806f32e7eSjoerg llvm::Value *DataIsNotNullPtr =
341906f32e7eSjoerg Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3420*13fbcb42Sjoerg EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
342106f32e7eSjoerg
342206f32e7eSjoerg llvm::StructType *SourceLocationTy =
342306f32e7eSjoerg llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
342406f32e7eSjoerg llvm::StructType *CfiCheckFailDataTy =
342506f32e7eSjoerg llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
342606f32e7eSjoerg
342706f32e7eSjoerg llvm::Value *V = Builder.CreateConstGEP2_32(
342806f32e7eSjoerg CfiCheckFailDataTy,
342906f32e7eSjoerg Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
343006f32e7eSjoerg 0);
343106f32e7eSjoerg Address CheckKindAddr(V, getIntAlign());
343206f32e7eSjoerg llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
343306f32e7eSjoerg
343406f32e7eSjoerg llvm::Value *AllVtables = llvm::MetadataAsValue::get(
343506f32e7eSjoerg CGM.getLLVMContext(),
343606f32e7eSjoerg llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
343706f32e7eSjoerg llvm::Value *ValidVtable = Builder.CreateZExt(
343806f32e7eSjoerg Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
343906f32e7eSjoerg {Addr, AllVtables}),
344006f32e7eSjoerg IntPtrTy);
344106f32e7eSjoerg
344206f32e7eSjoerg const std::pair<int, SanitizerMask> CheckKinds[] = {
344306f32e7eSjoerg {CFITCK_VCall, SanitizerKind::CFIVCall},
344406f32e7eSjoerg {CFITCK_NVCall, SanitizerKind::CFINVCall},
344506f32e7eSjoerg {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
344606f32e7eSjoerg {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
344706f32e7eSjoerg {CFITCK_ICall, SanitizerKind::CFIICall}};
344806f32e7eSjoerg
344906f32e7eSjoerg SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
345006f32e7eSjoerg for (auto CheckKindMaskPair : CheckKinds) {
345106f32e7eSjoerg int Kind = CheckKindMaskPair.first;
345206f32e7eSjoerg SanitizerMask Mask = CheckKindMaskPair.second;
345306f32e7eSjoerg llvm::Value *Cond =
345406f32e7eSjoerg Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
345506f32e7eSjoerg if (CGM.getLangOpts().Sanitize.has(Mask))
345606f32e7eSjoerg EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
345706f32e7eSjoerg {Data, Addr, ValidVtable});
345806f32e7eSjoerg else
3459*13fbcb42Sjoerg EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
346006f32e7eSjoerg }
346106f32e7eSjoerg
346206f32e7eSjoerg FinishFunction();
346306f32e7eSjoerg // The only reference to this function will be created during LTO link.
346406f32e7eSjoerg // Make sure it survives until then.
346506f32e7eSjoerg CGM.addUsedGlobal(F);
346606f32e7eSjoerg }
346706f32e7eSjoerg
EmitUnreachable(SourceLocation Loc)346806f32e7eSjoerg void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
346906f32e7eSjoerg if (SanOpts.has(SanitizerKind::Unreachable)) {
347006f32e7eSjoerg SanitizerScope SanScope(this);
347106f32e7eSjoerg EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
347206f32e7eSjoerg SanitizerKind::Unreachable),
347306f32e7eSjoerg SanitizerHandler::BuiltinUnreachable,
347406f32e7eSjoerg EmitCheckSourceLocation(Loc), None);
347506f32e7eSjoerg }
347606f32e7eSjoerg Builder.CreateUnreachable();
347706f32e7eSjoerg }
347806f32e7eSjoerg
EmitTrapCheck(llvm::Value * Checked,SanitizerHandler CheckHandlerID)3479*13fbcb42Sjoerg void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
3480*13fbcb42Sjoerg SanitizerHandler CheckHandlerID) {
348106f32e7eSjoerg llvm::BasicBlock *Cont = createBasicBlock("cont");
348206f32e7eSjoerg
348306f32e7eSjoerg // If we're optimizing, collapse all calls to trap down to just one per
3484*13fbcb42Sjoerg // check-type per function to save on code size.
3485*13fbcb42Sjoerg if (TrapBBs.size() <= CheckHandlerID)
3486*13fbcb42Sjoerg TrapBBs.resize(CheckHandlerID + 1);
3487*13fbcb42Sjoerg llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
3488*13fbcb42Sjoerg
348906f32e7eSjoerg if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
349006f32e7eSjoerg TrapBB = createBasicBlock("trap");
349106f32e7eSjoerg Builder.CreateCondBr(Checked, Cont, TrapBB);
349206f32e7eSjoerg EmitBlock(TrapBB);
3493*13fbcb42Sjoerg
3494*13fbcb42Sjoerg llvm::CallInst *TrapCall =
3495*13fbcb42Sjoerg Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
3496*13fbcb42Sjoerg llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
3497*13fbcb42Sjoerg
3498*13fbcb42Sjoerg if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3499*13fbcb42Sjoerg auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3500*13fbcb42Sjoerg CGM.getCodeGenOpts().TrapFuncName);
3501*13fbcb42Sjoerg TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
3502*13fbcb42Sjoerg }
350306f32e7eSjoerg TrapCall->setDoesNotReturn();
350406f32e7eSjoerg TrapCall->setDoesNotThrow();
350506f32e7eSjoerg Builder.CreateUnreachable();
350606f32e7eSjoerg } else {
3507*13fbcb42Sjoerg auto Call = TrapBB->begin();
3508*13fbcb42Sjoerg assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
3509*13fbcb42Sjoerg
3510*13fbcb42Sjoerg Call->applyMergedLocation(Call->getDebugLoc(),
3511*13fbcb42Sjoerg Builder.getCurrentDebugLocation());
351206f32e7eSjoerg Builder.CreateCondBr(Checked, Cont, TrapBB);
351306f32e7eSjoerg }
351406f32e7eSjoerg
351506f32e7eSjoerg EmitBlock(Cont);
351606f32e7eSjoerg }
351706f32e7eSjoerg
EmitTrapCall(llvm::Intrinsic::ID IntrID)351806f32e7eSjoerg llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3519*13fbcb42Sjoerg llvm::CallInst *TrapCall =
3520*13fbcb42Sjoerg Builder.CreateCall(CGM.getIntrinsic(IntrID));
352106f32e7eSjoerg
352206f32e7eSjoerg if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
352306f32e7eSjoerg auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
352406f32e7eSjoerg CGM.getCodeGenOpts().TrapFuncName);
352506f32e7eSjoerg TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
352606f32e7eSjoerg }
352706f32e7eSjoerg
352806f32e7eSjoerg return TrapCall;
352906f32e7eSjoerg }
353006f32e7eSjoerg
EmitArrayToPointerDecay(const Expr * E,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)353106f32e7eSjoerg Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
353206f32e7eSjoerg LValueBaseInfo *BaseInfo,
353306f32e7eSjoerg TBAAAccessInfo *TBAAInfo) {
353406f32e7eSjoerg assert(E->getType()->isArrayType() &&
353506f32e7eSjoerg "Array to pointer decay must have array source type!");
353606f32e7eSjoerg
353706f32e7eSjoerg // Expressions of array type can't be bitfields or vector elements.
353806f32e7eSjoerg LValue LV = EmitLValue(E);
3539*13fbcb42Sjoerg Address Addr = LV.getAddress(*this);
354006f32e7eSjoerg
354106f32e7eSjoerg // If the array type was an incomplete type, we need to make sure
354206f32e7eSjoerg // the decay ends up being the right type.
354306f32e7eSjoerg llvm::Type *NewTy = ConvertType(E->getType());
354406f32e7eSjoerg Addr = Builder.CreateElementBitCast(Addr, NewTy);
354506f32e7eSjoerg
354606f32e7eSjoerg // Note that VLA pointers are always decayed, so we don't need to do
354706f32e7eSjoerg // anything here.
354806f32e7eSjoerg if (!E->getType()->isVariableArrayType()) {
354906f32e7eSjoerg assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
355006f32e7eSjoerg "Expected pointer to array");
355106f32e7eSjoerg Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
355206f32e7eSjoerg }
355306f32e7eSjoerg
355406f32e7eSjoerg // The result of this decay conversion points to an array element within the
355506f32e7eSjoerg // base lvalue. However, since TBAA currently does not support representing
355606f32e7eSjoerg // accesses to elements of member arrays, we conservatively represent accesses
355706f32e7eSjoerg // to the pointee object as if it had no any base lvalue specified.
355806f32e7eSjoerg // TODO: Support TBAA for member arrays.
355906f32e7eSjoerg QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
356006f32e7eSjoerg if (BaseInfo) *BaseInfo = LV.getBaseInfo();
356106f32e7eSjoerg if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
356206f32e7eSjoerg
356306f32e7eSjoerg return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
356406f32e7eSjoerg }
356506f32e7eSjoerg
356606f32e7eSjoerg /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
356706f32e7eSjoerg /// array to pointer, return the array subexpression.
isSimpleArrayDecayOperand(const Expr * E)356806f32e7eSjoerg static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
356906f32e7eSjoerg // If this isn't just an array->pointer decay, bail out.
357006f32e7eSjoerg const auto *CE = dyn_cast<CastExpr>(E);
357106f32e7eSjoerg if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
357206f32e7eSjoerg return nullptr;
357306f32e7eSjoerg
357406f32e7eSjoerg // If this is a decay from variable width array, bail out.
357506f32e7eSjoerg const Expr *SubExpr = CE->getSubExpr();
357606f32e7eSjoerg if (SubExpr->getType()->isVariableArrayType())
357706f32e7eSjoerg return nullptr;
357806f32e7eSjoerg
357906f32e7eSjoerg return SubExpr;
358006f32e7eSjoerg }
358106f32e7eSjoerg
emitArraySubscriptGEP(CodeGenFunction & CGF,llvm::Type * elemType,llvm::Value * ptr,ArrayRef<llvm::Value * > indices,bool inbounds,bool signedIndices,SourceLocation loc,const llvm::Twine & name="arrayidx")358206f32e7eSjoerg static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3583*13fbcb42Sjoerg llvm::Type *elemType,
358406f32e7eSjoerg llvm::Value *ptr,
358506f32e7eSjoerg ArrayRef<llvm::Value*> indices,
358606f32e7eSjoerg bool inbounds,
358706f32e7eSjoerg bool signedIndices,
358806f32e7eSjoerg SourceLocation loc,
358906f32e7eSjoerg const llvm::Twine &name = "arrayidx") {
359006f32e7eSjoerg if (inbounds) {
359106f32e7eSjoerg return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
359206f32e7eSjoerg CodeGenFunction::NotSubtraction, loc,
359306f32e7eSjoerg name);
359406f32e7eSjoerg } else {
3595*13fbcb42Sjoerg return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
359606f32e7eSjoerg }
359706f32e7eSjoerg }
359806f32e7eSjoerg
getArrayElementAlign(CharUnits arrayAlign,llvm::Value * idx,CharUnits eltSize)359906f32e7eSjoerg static CharUnits getArrayElementAlign(CharUnits arrayAlign,
360006f32e7eSjoerg llvm::Value *idx,
360106f32e7eSjoerg CharUnits eltSize) {
360206f32e7eSjoerg // If we have a constant index, we can use the exact offset of the
360306f32e7eSjoerg // element we're accessing.
360406f32e7eSjoerg if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
360506f32e7eSjoerg CharUnits offset = constantIdx->getZExtValue() * eltSize;
360606f32e7eSjoerg return arrayAlign.alignmentAtOffset(offset);
360706f32e7eSjoerg
360806f32e7eSjoerg // Otherwise, use the worst-case alignment for any element.
360906f32e7eSjoerg } else {
361006f32e7eSjoerg return arrayAlign.alignmentOfArrayElement(eltSize);
361106f32e7eSjoerg }
361206f32e7eSjoerg }
361306f32e7eSjoerg
getFixedSizeElementType(const ASTContext & ctx,const VariableArrayType * vla)361406f32e7eSjoerg static QualType getFixedSizeElementType(const ASTContext &ctx,
361506f32e7eSjoerg const VariableArrayType *vla) {
361606f32e7eSjoerg QualType eltType;
361706f32e7eSjoerg do {
361806f32e7eSjoerg eltType = vla->getElementType();
361906f32e7eSjoerg } while ((vla = ctx.getAsVariableArrayType(eltType)));
362006f32e7eSjoerg return eltType;
362106f32e7eSjoerg }
362206f32e7eSjoerg
3623*13fbcb42Sjoerg /// Given an array base, check whether its member access belongs to a record
3624*13fbcb42Sjoerg /// with preserve_access_index attribute or not.
IsPreserveAIArrayBase(CodeGenFunction & CGF,const Expr * ArrayBase)3625*13fbcb42Sjoerg static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3626*13fbcb42Sjoerg if (!ArrayBase || !CGF.getDebugInfo())
3627*13fbcb42Sjoerg return false;
3628*13fbcb42Sjoerg
3629*13fbcb42Sjoerg // Only support base as either a MemberExpr or DeclRefExpr.
3630*13fbcb42Sjoerg // DeclRefExpr to cover cases like:
3631*13fbcb42Sjoerg // struct s { int a; int b[10]; };
3632*13fbcb42Sjoerg // struct s *p;
3633*13fbcb42Sjoerg // p[1].a
3634*13fbcb42Sjoerg // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3635*13fbcb42Sjoerg // p->b[5] is a MemberExpr example.
3636*13fbcb42Sjoerg const Expr *E = ArrayBase->IgnoreImpCasts();
3637*13fbcb42Sjoerg if (const auto *ME = dyn_cast<MemberExpr>(E))
3638*13fbcb42Sjoerg return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3639*13fbcb42Sjoerg
3640*13fbcb42Sjoerg if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3641*13fbcb42Sjoerg const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
3642*13fbcb42Sjoerg if (!VarDef)
3643*13fbcb42Sjoerg return false;
3644*13fbcb42Sjoerg
3645*13fbcb42Sjoerg const auto *PtrT = VarDef->getType()->getAs<PointerType>();
3646*13fbcb42Sjoerg if (!PtrT)
3647*13fbcb42Sjoerg return false;
3648*13fbcb42Sjoerg
3649*13fbcb42Sjoerg const auto *PointeeT = PtrT->getPointeeType()
3650*13fbcb42Sjoerg ->getUnqualifiedDesugaredType();
3651*13fbcb42Sjoerg if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
3652*13fbcb42Sjoerg return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3653*13fbcb42Sjoerg return false;
3654*13fbcb42Sjoerg }
3655*13fbcb42Sjoerg
3656*13fbcb42Sjoerg return false;
3657*13fbcb42Sjoerg }
3658*13fbcb42Sjoerg
emitArraySubscriptGEP(CodeGenFunction & CGF,Address addr,ArrayRef<llvm::Value * > indices,QualType eltType,bool inbounds,bool signedIndices,SourceLocation loc,QualType * arrayType=nullptr,const Expr * Base=nullptr,const llvm::Twine & name="arrayidx")365906f32e7eSjoerg static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
366006f32e7eSjoerg ArrayRef<llvm::Value *> indices,
366106f32e7eSjoerg QualType eltType, bool inbounds,
366206f32e7eSjoerg bool signedIndices, SourceLocation loc,
366306f32e7eSjoerg QualType *arrayType = nullptr,
3664*13fbcb42Sjoerg const Expr *Base = nullptr,
366506f32e7eSjoerg const llvm::Twine &name = "arrayidx") {
366606f32e7eSjoerg // All the indices except that last must be zero.
366706f32e7eSjoerg #ifndef NDEBUG
366806f32e7eSjoerg for (auto idx : indices.drop_back())
366906f32e7eSjoerg assert(isa<llvm::ConstantInt>(idx) &&
367006f32e7eSjoerg cast<llvm::ConstantInt>(idx)->isZero());
367106f32e7eSjoerg #endif
367206f32e7eSjoerg
367306f32e7eSjoerg // Determine the element size of the statically-sized base. This is
367406f32e7eSjoerg // the thing that the indices are expressed in terms of.
367506f32e7eSjoerg if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
367606f32e7eSjoerg eltType = getFixedSizeElementType(CGF.getContext(), vla);
367706f32e7eSjoerg }
367806f32e7eSjoerg
367906f32e7eSjoerg // We can use that to compute the best alignment of the element.
368006f32e7eSjoerg CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
368106f32e7eSjoerg CharUnits eltAlign =
368206f32e7eSjoerg getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
368306f32e7eSjoerg
368406f32e7eSjoerg llvm::Value *eltPtr;
368506f32e7eSjoerg auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
3686*13fbcb42Sjoerg if (!LastIndex ||
3687*13fbcb42Sjoerg (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
368806f32e7eSjoerg eltPtr = emitArraySubscriptGEP(
3689*13fbcb42Sjoerg CGF, addr.getElementType(), addr.getPointer(), indices, inbounds,
3690*13fbcb42Sjoerg signedIndices, loc, name);
369106f32e7eSjoerg } else {
369206f32e7eSjoerg // Remember the original array subscript for bpf target
369306f32e7eSjoerg unsigned idx = LastIndex->getZExtValue();
369406f32e7eSjoerg llvm::DIType *DbgInfo = nullptr;
369506f32e7eSjoerg if (arrayType)
369606f32e7eSjoerg DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
3697*13fbcb42Sjoerg eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
3698*13fbcb42Sjoerg addr.getPointer(),
369906f32e7eSjoerg indices.size() - 1,
370006f32e7eSjoerg idx, DbgInfo);
370106f32e7eSjoerg }
370206f32e7eSjoerg
370306f32e7eSjoerg return Address(eltPtr, eltAlign);
370406f32e7eSjoerg }
370506f32e7eSjoerg
EmitArraySubscriptExpr(const ArraySubscriptExpr * E,bool Accessed)370606f32e7eSjoerg LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
370706f32e7eSjoerg bool Accessed) {
370806f32e7eSjoerg // The index must always be an integer, which is not an aggregate. Emit it
370906f32e7eSjoerg // in lexical order (this complexity is, sadly, required by C++17).
371006f32e7eSjoerg llvm::Value *IdxPre =
371106f32e7eSjoerg (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
371206f32e7eSjoerg bool SignedIndices = false;
371306f32e7eSjoerg auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
371406f32e7eSjoerg auto *Idx = IdxPre;
371506f32e7eSjoerg if (E->getLHS() != E->getIdx()) {
371606f32e7eSjoerg assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
371706f32e7eSjoerg Idx = EmitScalarExpr(E->getIdx());
371806f32e7eSjoerg }
371906f32e7eSjoerg
372006f32e7eSjoerg QualType IdxTy = E->getIdx()->getType();
372106f32e7eSjoerg bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
372206f32e7eSjoerg SignedIndices |= IdxSigned;
372306f32e7eSjoerg
372406f32e7eSjoerg if (SanOpts.has(SanitizerKind::ArrayBounds))
372506f32e7eSjoerg EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
372606f32e7eSjoerg
372706f32e7eSjoerg // Extend or truncate the index type to 32 or 64-bits.
372806f32e7eSjoerg if (Promote && Idx->getType() != IntPtrTy)
372906f32e7eSjoerg Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
373006f32e7eSjoerg
373106f32e7eSjoerg return Idx;
373206f32e7eSjoerg };
373306f32e7eSjoerg IdxPre = nullptr;
373406f32e7eSjoerg
373506f32e7eSjoerg // If the base is a vector type, then we are forming a vector element lvalue
373606f32e7eSjoerg // with this subscript.
373706f32e7eSjoerg if (E->getBase()->getType()->isVectorType() &&
373806f32e7eSjoerg !isa<ExtVectorElementExpr>(E->getBase())) {
373906f32e7eSjoerg // Emit the vector as an lvalue to get its address.
374006f32e7eSjoerg LValue LHS = EmitLValue(E->getBase());
374106f32e7eSjoerg auto *Idx = EmitIdxAfterBase(/*Promote*/false);
374206f32e7eSjoerg assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3743*13fbcb42Sjoerg return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
3744*13fbcb42Sjoerg E->getBase()->getType(), LHS.getBaseInfo(),
3745*13fbcb42Sjoerg TBAAAccessInfo());
374606f32e7eSjoerg }
374706f32e7eSjoerg
374806f32e7eSjoerg // All the other cases basically behave like simple offsetting.
374906f32e7eSjoerg
375006f32e7eSjoerg // Handle the extvector case we ignored above.
375106f32e7eSjoerg if (isa<ExtVectorElementExpr>(E->getBase())) {
375206f32e7eSjoerg LValue LV = EmitLValue(E->getBase());
375306f32e7eSjoerg auto *Idx = EmitIdxAfterBase(/*Promote*/true);
375406f32e7eSjoerg Address Addr = EmitExtVectorElementLValue(LV);
375506f32e7eSjoerg
375606f32e7eSjoerg QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
375706f32e7eSjoerg Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
375806f32e7eSjoerg SignedIndices, E->getExprLoc());
375906f32e7eSjoerg return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
376006f32e7eSjoerg CGM.getTBAAInfoForSubobject(LV, EltType));
376106f32e7eSjoerg }
376206f32e7eSjoerg
376306f32e7eSjoerg LValueBaseInfo EltBaseInfo;
376406f32e7eSjoerg TBAAAccessInfo EltTBAAInfo;
376506f32e7eSjoerg Address Addr = Address::invalid();
376606f32e7eSjoerg if (const VariableArrayType *vla =
376706f32e7eSjoerg getContext().getAsVariableArrayType(E->getType())) {
376806f32e7eSjoerg // The base must be a pointer, which is not an aggregate. Emit
376906f32e7eSjoerg // it. It needs to be emitted first in case it's what captures
377006f32e7eSjoerg // the VLA bounds.
377106f32e7eSjoerg Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
377206f32e7eSjoerg auto *Idx = EmitIdxAfterBase(/*Promote*/true);
377306f32e7eSjoerg
377406f32e7eSjoerg // The element count here is the total number of non-VLA elements.
377506f32e7eSjoerg llvm::Value *numElements = getVLASize(vla).NumElts;
377606f32e7eSjoerg
377706f32e7eSjoerg // Effectively, the multiply by the VLA size is part of the GEP.
377806f32e7eSjoerg // GEP indexes are signed, and scaling an index isn't permitted to
377906f32e7eSjoerg // signed-overflow, so we use the same semantics for our explicit
378006f32e7eSjoerg // multiply. We suppress this if overflow is not undefined behavior.
378106f32e7eSjoerg if (getLangOpts().isSignedOverflowDefined()) {
378206f32e7eSjoerg Idx = Builder.CreateMul(Idx, numElements);
378306f32e7eSjoerg } else {
378406f32e7eSjoerg Idx = Builder.CreateNSWMul(Idx, numElements);
378506f32e7eSjoerg }
378606f32e7eSjoerg
378706f32e7eSjoerg Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
378806f32e7eSjoerg !getLangOpts().isSignedOverflowDefined(),
378906f32e7eSjoerg SignedIndices, E->getExprLoc());
379006f32e7eSjoerg
379106f32e7eSjoerg } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
379206f32e7eSjoerg // Indexing over an interface, as in "NSString *P; P[4];"
379306f32e7eSjoerg
379406f32e7eSjoerg // Emit the base pointer.
379506f32e7eSjoerg Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
379606f32e7eSjoerg auto *Idx = EmitIdxAfterBase(/*Promote*/true);
379706f32e7eSjoerg
379806f32e7eSjoerg CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
379906f32e7eSjoerg llvm::Value *InterfaceSizeVal =
380006f32e7eSjoerg llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
380106f32e7eSjoerg
380206f32e7eSjoerg llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
380306f32e7eSjoerg
380406f32e7eSjoerg // We don't necessarily build correct LLVM struct types for ObjC
380506f32e7eSjoerg // interfaces, so we can't rely on GEP to do this scaling
380606f32e7eSjoerg // correctly, so we need to cast to i8*. FIXME: is this actually
380706f32e7eSjoerg // true? A lot of other things in the fragile ABI would break...
380806f32e7eSjoerg llvm::Type *OrigBaseTy = Addr.getType();
380906f32e7eSjoerg Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
381006f32e7eSjoerg
381106f32e7eSjoerg // Do the GEP.
381206f32e7eSjoerg CharUnits EltAlign =
381306f32e7eSjoerg getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
381406f32e7eSjoerg llvm::Value *EltPtr =
3815*13fbcb42Sjoerg emitArraySubscriptGEP(*this, Addr.getElementType(), Addr.getPointer(),
3816*13fbcb42Sjoerg ScaledIdx, false, SignedIndices, E->getExprLoc());
381706f32e7eSjoerg Addr = Address(EltPtr, EltAlign);
381806f32e7eSjoerg
381906f32e7eSjoerg // Cast back.
382006f32e7eSjoerg Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
382106f32e7eSjoerg } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
382206f32e7eSjoerg // If this is A[i] where A is an array, the frontend will have decayed the
382306f32e7eSjoerg // base to be a ArrayToPointerDecay implicit cast. While correct, it is
382406f32e7eSjoerg // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
382506f32e7eSjoerg // "gep x, i" here. Emit one "gep A, 0, i".
382606f32e7eSjoerg assert(Array->getType()->isArrayType() &&
382706f32e7eSjoerg "Array to pointer decay must have array source type!");
382806f32e7eSjoerg LValue ArrayLV;
382906f32e7eSjoerg // For simple multidimensional array indexing, set the 'accessed' flag for
383006f32e7eSjoerg // better bounds-checking of the base expression.
383106f32e7eSjoerg if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
383206f32e7eSjoerg ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
383306f32e7eSjoerg else
383406f32e7eSjoerg ArrayLV = EmitLValue(Array);
383506f32e7eSjoerg auto *Idx = EmitIdxAfterBase(/*Promote*/true);
383606f32e7eSjoerg
383706f32e7eSjoerg // Propagate the alignment from the array itself to the result.
383806f32e7eSjoerg QualType arrayType = Array->getType();
383906f32e7eSjoerg Addr = emitArraySubscriptGEP(
3840*13fbcb42Sjoerg *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
384106f32e7eSjoerg E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3842*13fbcb42Sjoerg E->getExprLoc(), &arrayType, E->getBase());
384306f32e7eSjoerg EltBaseInfo = ArrayLV.getBaseInfo();
384406f32e7eSjoerg EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
384506f32e7eSjoerg } else {
384606f32e7eSjoerg // The base must be a pointer; emit it with an estimate of its alignment.
384706f32e7eSjoerg Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
384806f32e7eSjoerg auto *Idx = EmitIdxAfterBase(/*Promote*/true);
384906f32e7eSjoerg QualType ptrType = E->getBase()->getType();
385006f32e7eSjoerg Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
385106f32e7eSjoerg !getLangOpts().isSignedOverflowDefined(),
3852*13fbcb42Sjoerg SignedIndices, E->getExprLoc(), &ptrType,
3853*13fbcb42Sjoerg E->getBase());
385406f32e7eSjoerg }
385506f32e7eSjoerg
385606f32e7eSjoerg LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
385706f32e7eSjoerg
385806f32e7eSjoerg if (getLangOpts().ObjC &&
385906f32e7eSjoerg getLangOpts().getGC() != LangOptions::NonGC) {
386006f32e7eSjoerg LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
386106f32e7eSjoerg setObjCGCLValueClass(getContext(), E, LV);
386206f32e7eSjoerg }
386306f32e7eSjoerg return LV;
386406f32e7eSjoerg }
386506f32e7eSjoerg
EmitMatrixSubscriptExpr(const MatrixSubscriptExpr * E)3866*13fbcb42Sjoerg LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
3867*13fbcb42Sjoerg assert(
3868*13fbcb42Sjoerg !E->isIncomplete() &&
3869*13fbcb42Sjoerg "incomplete matrix subscript expressions should be rejected during Sema");
3870*13fbcb42Sjoerg LValue Base = EmitLValue(E->getBase());
3871*13fbcb42Sjoerg llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
3872*13fbcb42Sjoerg llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
3873*13fbcb42Sjoerg llvm::Value *NumRows = Builder.getIntN(
3874*13fbcb42Sjoerg RowIdx->getType()->getScalarSizeInBits(),
3875*13fbcb42Sjoerg E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
3876*13fbcb42Sjoerg llvm::Value *FinalIdx =
3877*13fbcb42Sjoerg Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
3878*13fbcb42Sjoerg return LValue::MakeMatrixElt(
3879*13fbcb42Sjoerg MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
3880*13fbcb42Sjoerg E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
3881*13fbcb42Sjoerg }
3882*13fbcb42Sjoerg
emitOMPArraySectionBase(CodeGenFunction & CGF,const Expr * Base,LValueBaseInfo & BaseInfo,TBAAAccessInfo & TBAAInfo,QualType BaseTy,QualType ElTy,bool IsLowerBound)388306f32e7eSjoerg static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
388406f32e7eSjoerg LValueBaseInfo &BaseInfo,
388506f32e7eSjoerg TBAAAccessInfo &TBAAInfo,
388606f32e7eSjoerg QualType BaseTy, QualType ElTy,
388706f32e7eSjoerg bool IsLowerBound) {
388806f32e7eSjoerg LValue BaseLVal;
388906f32e7eSjoerg if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
389006f32e7eSjoerg BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
389106f32e7eSjoerg if (BaseTy->isArrayType()) {
3892*13fbcb42Sjoerg Address Addr = BaseLVal.getAddress(CGF);
389306f32e7eSjoerg BaseInfo = BaseLVal.getBaseInfo();
389406f32e7eSjoerg
389506f32e7eSjoerg // If the array type was an incomplete type, we need to make sure
389606f32e7eSjoerg // the decay ends up being the right type.
389706f32e7eSjoerg llvm::Type *NewTy = CGF.ConvertType(BaseTy);
389806f32e7eSjoerg Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
389906f32e7eSjoerg
390006f32e7eSjoerg // Note that VLA pointers are always decayed, so we don't need to do
390106f32e7eSjoerg // anything here.
390206f32e7eSjoerg if (!BaseTy->isVariableArrayType()) {
390306f32e7eSjoerg assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
390406f32e7eSjoerg "Expected pointer to array");
390506f32e7eSjoerg Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
390606f32e7eSjoerg }
390706f32e7eSjoerg
390806f32e7eSjoerg return CGF.Builder.CreateElementBitCast(Addr,
390906f32e7eSjoerg CGF.ConvertTypeForMem(ElTy));
391006f32e7eSjoerg }
391106f32e7eSjoerg LValueBaseInfo TypeBaseInfo;
391206f32e7eSjoerg TBAAAccessInfo TypeTBAAInfo;
3913*13fbcb42Sjoerg CharUnits Align =
3914*13fbcb42Sjoerg CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
391506f32e7eSjoerg BaseInfo.mergeForCast(TypeBaseInfo);
391606f32e7eSjoerg TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
3917*13fbcb42Sjoerg return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)), Align);
391806f32e7eSjoerg }
391906f32e7eSjoerg return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
392006f32e7eSjoerg }
392106f32e7eSjoerg
EmitOMPArraySectionExpr(const OMPArraySectionExpr * E,bool IsLowerBound)392206f32e7eSjoerg LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
392306f32e7eSjoerg bool IsLowerBound) {
392406f32e7eSjoerg QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
392506f32e7eSjoerg QualType ResultExprTy;
392606f32e7eSjoerg if (auto *AT = getContext().getAsArrayType(BaseTy))
392706f32e7eSjoerg ResultExprTy = AT->getElementType();
392806f32e7eSjoerg else
392906f32e7eSjoerg ResultExprTy = BaseTy->getPointeeType();
393006f32e7eSjoerg llvm::Value *Idx = nullptr;
3931*13fbcb42Sjoerg if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
393206f32e7eSjoerg // Requesting lower bound or upper bound, but without provided length and
393306f32e7eSjoerg // without ':' symbol for the default length -> length = 1.
393406f32e7eSjoerg // Idx = LowerBound ?: 0;
393506f32e7eSjoerg if (auto *LowerBound = E->getLowerBound()) {
393606f32e7eSjoerg Idx = Builder.CreateIntCast(
393706f32e7eSjoerg EmitScalarExpr(LowerBound), IntPtrTy,
393806f32e7eSjoerg LowerBound->getType()->hasSignedIntegerRepresentation());
393906f32e7eSjoerg } else
394006f32e7eSjoerg Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
394106f32e7eSjoerg } else {
394206f32e7eSjoerg // Try to emit length or lower bound as constant. If this is possible, 1
394306f32e7eSjoerg // is subtracted from constant length or lower bound. Otherwise, emit LLVM
394406f32e7eSjoerg // IR (LB + Len) - 1.
394506f32e7eSjoerg auto &C = CGM.getContext();
394606f32e7eSjoerg auto *Length = E->getLength();
394706f32e7eSjoerg llvm::APSInt ConstLength;
394806f32e7eSjoerg if (Length) {
394906f32e7eSjoerg // Idx = LowerBound + Length - 1;
3950*13fbcb42Sjoerg if (Optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
3951*13fbcb42Sjoerg ConstLength = CL->zextOrTrunc(PointerWidthInBits);
395206f32e7eSjoerg Length = nullptr;
395306f32e7eSjoerg }
395406f32e7eSjoerg auto *LowerBound = E->getLowerBound();
395506f32e7eSjoerg llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3956*13fbcb42Sjoerg if (LowerBound) {
3957*13fbcb42Sjoerg if (Optional<llvm::APSInt> LB = LowerBound->getIntegerConstantExpr(C)) {
3958*13fbcb42Sjoerg ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
395906f32e7eSjoerg LowerBound = nullptr;
396006f32e7eSjoerg }
3961*13fbcb42Sjoerg }
396206f32e7eSjoerg if (!Length)
396306f32e7eSjoerg --ConstLength;
396406f32e7eSjoerg else if (!LowerBound)
396506f32e7eSjoerg --ConstLowerBound;
396606f32e7eSjoerg
396706f32e7eSjoerg if (Length || LowerBound) {
396806f32e7eSjoerg auto *LowerBoundVal =
396906f32e7eSjoerg LowerBound
397006f32e7eSjoerg ? Builder.CreateIntCast(
397106f32e7eSjoerg EmitScalarExpr(LowerBound), IntPtrTy,
397206f32e7eSjoerg LowerBound->getType()->hasSignedIntegerRepresentation())
397306f32e7eSjoerg : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
397406f32e7eSjoerg auto *LengthVal =
397506f32e7eSjoerg Length
397606f32e7eSjoerg ? Builder.CreateIntCast(
397706f32e7eSjoerg EmitScalarExpr(Length), IntPtrTy,
397806f32e7eSjoerg Length->getType()->hasSignedIntegerRepresentation())
397906f32e7eSjoerg : llvm::ConstantInt::get(IntPtrTy, ConstLength);
398006f32e7eSjoerg Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
398106f32e7eSjoerg /*HasNUW=*/false,
398206f32e7eSjoerg !getLangOpts().isSignedOverflowDefined());
398306f32e7eSjoerg if (Length && LowerBound) {
398406f32e7eSjoerg Idx = Builder.CreateSub(
398506f32e7eSjoerg Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
398606f32e7eSjoerg /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
398706f32e7eSjoerg }
398806f32e7eSjoerg } else
398906f32e7eSjoerg Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
399006f32e7eSjoerg } else {
399106f32e7eSjoerg // Idx = ArraySize - 1;
399206f32e7eSjoerg QualType ArrayTy = BaseTy->isPointerType()
399306f32e7eSjoerg ? E->getBase()->IgnoreParenImpCasts()->getType()
399406f32e7eSjoerg : BaseTy;
399506f32e7eSjoerg if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
399606f32e7eSjoerg Length = VAT->getSizeExpr();
3997*13fbcb42Sjoerg if (Optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
3998*13fbcb42Sjoerg ConstLength = *L;
399906f32e7eSjoerg Length = nullptr;
4000*13fbcb42Sjoerg }
400106f32e7eSjoerg } else {
400206f32e7eSjoerg auto *CAT = C.getAsConstantArrayType(ArrayTy);
400306f32e7eSjoerg ConstLength = CAT->getSize();
400406f32e7eSjoerg }
400506f32e7eSjoerg if (Length) {
400606f32e7eSjoerg auto *LengthVal = Builder.CreateIntCast(
400706f32e7eSjoerg EmitScalarExpr(Length), IntPtrTy,
400806f32e7eSjoerg Length->getType()->hasSignedIntegerRepresentation());
400906f32e7eSjoerg Idx = Builder.CreateSub(
401006f32e7eSjoerg LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
401106f32e7eSjoerg /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
401206f32e7eSjoerg } else {
401306f32e7eSjoerg ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
401406f32e7eSjoerg --ConstLength;
401506f32e7eSjoerg Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
401606f32e7eSjoerg }
401706f32e7eSjoerg }
401806f32e7eSjoerg }
401906f32e7eSjoerg assert(Idx);
402006f32e7eSjoerg
402106f32e7eSjoerg Address EltPtr = Address::invalid();
402206f32e7eSjoerg LValueBaseInfo BaseInfo;
402306f32e7eSjoerg TBAAAccessInfo TBAAInfo;
402406f32e7eSjoerg if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
402506f32e7eSjoerg // The base must be a pointer, which is not an aggregate. Emit
402606f32e7eSjoerg // it. It needs to be emitted first in case it's what captures
402706f32e7eSjoerg // the VLA bounds.
402806f32e7eSjoerg Address Base =
402906f32e7eSjoerg emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
403006f32e7eSjoerg BaseTy, VLA->getElementType(), IsLowerBound);
403106f32e7eSjoerg // The element count here is the total number of non-VLA elements.
403206f32e7eSjoerg llvm::Value *NumElements = getVLASize(VLA).NumElts;
403306f32e7eSjoerg
403406f32e7eSjoerg // Effectively, the multiply by the VLA size is part of the GEP.
403506f32e7eSjoerg // GEP indexes are signed, and scaling an index isn't permitted to
403606f32e7eSjoerg // signed-overflow, so we use the same semantics for our explicit
403706f32e7eSjoerg // multiply. We suppress this if overflow is not undefined behavior.
403806f32e7eSjoerg if (getLangOpts().isSignedOverflowDefined())
403906f32e7eSjoerg Idx = Builder.CreateMul(Idx, NumElements);
404006f32e7eSjoerg else
404106f32e7eSjoerg Idx = Builder.CreateNSWMul(Idx, NumElements);
404206f32e7eSjoerg EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
404306f32e7eSjoerg !getLangOpts().isSignedOverflowDefined(),
404406f32e7eSjoerg /*signedIndices=*/false, E->getExprLoc());
404506f32e7eSjoerg } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
404606f32e7eSjoerg // If this is A[i] where A is an array, the frontend will have decayed the
404706f32e7eSjoerg // base to be a ArrayToPointerDecay implicit cast. While correct, it is
404806f32e7eSjoerg // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
404906f32e7eSjoerg // "gep x, i" here. Emit one "gep A, 0, i".
405006f32e7eSjoerg assert(Array->getType()->isArrayType() &&
405106f32e7eSjoerg "Array to pointer decay must have array source type!");
405206f32e7eSjoerg LValue ArrayLV;
405306f32e7eSjoerg // For simple multidimensional array indexing, set the 'accessed' flag for
405406f32e7eSjoerg // better bounds-checking of the base expression.
405506f32e7eSjoerg if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
405606f32e7eSjoerg ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
405706f32e7eSjoerg else
405806f32e7eSjoerg ArrayLV = EmitLValue(Array);
405906f32e7eSjoerg
406006f32e7eSjoerg // Propagate the alignment from the array itself to the result.
406106f32e7eSjoerg EltPtr = emitArraySubscriptGEP(
4062*13fbcb42Sjoerg *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
406306f32e7eSjoerg ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
406406f32e7eSjoerg /*signedIndices=*/false, E->getExprLoc());
406506f32e7eSjoerg BaseInfo = ArrayLV.getBaseInfo();
406606f32e7eSjoerg TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
406706f32e7eSjoerg } else {
406806f32e7eSjoerg Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
406906f32e7eSjoerg TBAAInfo, BaseTy, ResultExprTy,
407006f32e7eSjoerg IsLowerBound);
407106f32e7eSjoerg EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
407206f32e7eSjoerg !getLangOpts().isSignedOverflowDefined(),
407306f32e7eSjoerg /*signedIndices=*/false, E->getExprLoc());
407406f32e7eSjoerg }
407506f32e7eSjoerg
407606f32e7eSjoerg return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
407706f32e7eSjoerg }
407806f32e7eSjoerg
407906f32e7eSjoerg LValue CodeGenFunction::
EmitExtVectorElementExpr(const ExtVectorElementExpr * E)408006f32e7eSjoerg EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
408106f32e7eSjoerg // Emit the base vector as an l-value.
408206f32e7eSjoerg LValue Base;
408306f32e7eSjoerg
408406f32e7eSjoerg // ExtVectorElementExpr's base can either be a vector or pointer to vector.
408506f32e7eSjoerg if (E->isArrow()) {
408606f32e7eSjoerg // If it is a pointer to a vector, emit the address and form an lvalue with
408706f32e7eSjoerg // it.
408806f32e7eSjoerg LValueBaseInfo BaseInfo;
408906f32e7eSjoerg TBAAAccessInfo TBAAInfo;
409006f32e7eSjoerg Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4091*13fbcb42Sjoerg const auto *PT = E->getBase()->getType()->castAs<PointerType>();
409206f32e7eSjoerg Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
409306f32e7eSjoerg Base.getQuals().removeObjCGCAttr();
409406f32e7eSjoerg } else if (E->getBase()->isGLValue()) {
409506f32e7eSjoerg // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
409606f32e7eSjoerg // emit the base as an lvalue.
409706f32e7eSjoerg assert(E->getBase()->getType()->isVectorType());
409806f32e7eSjoerg Base = EmitLValue(E->getBase());
409906f32e7eSjoerg } else {
410006f32e7eSjoerg // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
410106f32e7eSjoerg assert(E->getBase()->getType()->isVectorType() &&
410206f32e7eSjoerg "Result must be a vector");
410306f32e7eSjoerg llvm::Value *Vec = EmitScalarExpr(E->getBase());
410406f32e7eSjoerg
410506f32e7eSjoerg // Store the vector to memory (because LValue wants an address).
410606f32e7eSjoerg Address VecMem = CreateMemTemp(E->getBase()->getType());
410706f32e7eSjoerg Builder.CreateStore(Vec, VecMem);
410806f32e7eSjoerg Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
410906f32e7eSjoerg AlignmentSource::Decl);
411006f32e7eSjoerg }
411106f32e7eSjoerg
411206f32e7eSjoerg QualType type =
411306f32e7eSjoerg E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
411406f32e7eSjoerg
411506f32e7eSjoerg // Encode the element access list into a vector of unsigned indices.
411606f32e7eSjoerg SmallVector<uint32_t, 4> Indices;
411706f32e7eSjoerg E->getEncodedElementAccess(Indices);
411806f32e7eSjoerg
411906f32e7eSjoerg if (Base.isSimple()) {
412006f32e7eSjoerg llvm::Constant *CV =
412106f32e7eSjoerg llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4122*13fbcb42Sjoerg return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
412306f32e7eSjoerg Base.getBaseInfo(), TBAAAccessInfo());
412406f32e7eSjoerg }
412506f32e7eSjoerg assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
412606f32e7eSjoerg
412706f32e7eSjoerg llvm::Constant *BaseElts = Base.getExtVectorElts();
412806f32e7eSjoerg SmallVector<llvm::Constant *, 4> CElts;
412906f32e7eSjoerg
413006f32e7eSjoerg for (unsigned i = 0, e = Indices.size(); i != e; ++i)
413106f32e7eSjoerg CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
413206f32e7eSjoerg llvm::Constant *CV = llvm::ConstantVector::get(CElts);
413306f32e7eSjoerg return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
413406f32e7eSjoerg Base.getBaseInfo(), TBAAAccessInfo());
413506f32e7eSjoerg }
413606f32e7eSjoerg
EmitMemberExpr(const MemberExpr * E)413706f32e7eSjoerg LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
413806f32e7eSjoerg if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
413906f32e7eSjoerg EmitIgnoredExpr(E->getBase());
414006f32e7eSjoerg return EmitDeclRefLValue(DRE);
414106f32e7eSjoerg }
414206f32e7eSjoerg
414306f32e7eSjoerg Expr *BaseExpr = E->getBase();
414406f32e7eSjoerg // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
414506f32e7eSjoerg LValue BaseLV;
414606f32e7eSjoerg if (E->isArrow()) {
414706f32e7eSjoerg LValueBaseInfo BaseInfo;
414806f32e7eSjoerg TBAAAccessInfo TBAAInfo;
414906f32e7eSjoerg Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
415006f32e7eSjoerg QualType PtrTy = BaseExpr->getType()->getPointeeType();
415106f32e7eSjoerg SanitizerSet SkippedChecks;
415206f32e7eSjoerg bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
415306f32e7eSjoerg if (IsBaseCXXThis)
415406f32e7eSjoerg SkippedChecks.set(SanitizerKind::Alignment, true);
415506f32e7eSjoerg if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
415606f32e7eSjoerg SkippedChecks.set(SanitizerKind::Null, true);
415706f32e7eSjoerg EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
415806f32e7eSjoerg /*Alignment=*/CharUnits::Zero(), SkippedChecks);
415906f32e7eSjoerg BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
416006f32e7eSjoerg } else
416106f32e7eSjoerg BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
416206f32e7eSjoerg
416306f32e7eSjoerg NamedDecl *ND = E->getMemberDecl();
416406f32e7eSjoerg if (auto *Field = dyn_cast<FieldDecl>(ND)) {
416506f32e7eSjoerg LValue LV = EmitLValueForField(BaseLV, Field);
416606f32e7eSjoerg setObjCGCLValueClass(getContext(), E, LV);
4167*13fbcb42Sjoerg if (getLangOpts().OpenMP) {
4168*13fbcb42Sjoerg // If the member was explicitly marked as nontemporal, mark it as
4169*13fbcb42Sjoerg // nontemporal. If the base lvalue is marked as nontemporal, mark access
4170*13fbcb42Sjoerg // to children as nontemporal too.
4171*13fbcb42Sjoerg if ((IsWrappedCXXThis(BaseExpr) &&
4172*13fbcb42Sjoerg CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
4173*13fbcb42Sjoerg BaseLV.isNontemporal())
4174*13fbcb42Sjoerg LV.setNontemporal(/*Value=*/true);
4175*13fbcb42Sjoerg }
417606f32e7eSjoerg return LV;
417706f32e7eSjoerg }
417806f32e7eSjoerg
417906f32e7eSjoerg if (const auto *FD = dyn_cast<FunctionDecl>(ND))
418006f32e7eSjoerg return EmitFunctionDeclLValue(*this, E, FD);
418106f32e7eSjoerg
418206f32e7eSjoerg llvm_unreachable("Unhandled member declaration!");
418306f32e7eSjoerg }
418406f32e7eSjoerg
418506f32e7eSjoerg /// Given that we are currently emitting a lambda, emit an l-value for
418606f32e7eSjoerg /// one of its members.
EmitLValueForLambdaField(const FieldDecl * Field)418706f32e7eSjoerg LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
4188*13fbcb42Sjoerg if (CurCodeDecl) {
418906f32e7eSjoerg assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
419006f32e7eSjoerg assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
4191*13fbcb42Sjoerg }
419206f32e7eSjoerg QualType LambdaTagType =
419306f32e7eSjoerg getContext().getTagDeclType(Field->getParent());
419406f32e7eSjoerg LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
419506f32e7eSjoerg return EmitLValueForField(LambdaLV, Field);
419606f32e7eSjoerg }
419706f32e7eSjoerg
419806f32e7eSjoerg /// Get the field index in the debug info. The debug info structure/union
419906f32e7eSjoerg /// will ignore the unnamed bitfields.
getDebugInfoFIndex(const RecordDecl * Rec,unsigned FieldIndex)420006f32e7eSjoerg unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
420106f32e7eSjoerg unsigned FieldIndex) {
420206f32e7eSjoerg unsigned I = 0, Skipped = 0;
420306f32e7eSjoerg
420406f32e7eSjoerg for (auto F : Rec->getDefinition()->fields()) {
420506f32e7eSjoerg if (I == FieldIndex)
420606f32e7eSjoerg break;
420706f32e7eSjoerg if (F->isUnnamedBitfield())
420806f32e7eSjoerg Skipped++;
420906f32e7eSjoerg I++;
421006f32e7eSjoerg }
421106f32e7eSjoerg
421206f32e7eSjoerg return FieldIndex - Skipped;
421306f32e7eSjoerg }
421406f32e7eSjoerg
421506f32e7eSjoerg /// Get the address of a zero-sized field within a record. The resulting
421606f32e7eSjoerg /// address doesn't necessarily have the right type.
emitAddrOfZeroSizeField(CodeGenFunction & CGF,Address Base,const FieldDecl * Field)421706f32e7eSjoerg static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
421806f32e7eSjoerg const FieldDecl *Field) {
421906f32e7eSjoerg CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
422006f32e7eSjoerg CGF.getContext().getFieldOffset(Field));
422106f32e7eSjoerg if (Offset.isZero())
422206f32e7eSjoerg return Base;
422306f32e7eSjoerg Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
422406f32e7eSjoerg return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
422506f32e7eSjoerg }
422606f32e7eSjoerg
422706f32e7eSjoerg /// Drill down to the storage of a field without walking into
422806f32e7eSjoerg /// reference types.
422906f32e7eSjoerg ///
423006f32e7eSjoerg /// The resulting address doesn't necessarily have the right type.
emitAddrOfFieldStorage(CodeGenFunction & CGF,Address base,const FieldDecl * field)423106f32e7eSjoerg static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
423206f32e7eSjoerg const FieldDecl *field) {
423306f32e7eSjoerg if (field->isZeroSize(CGF.getContext()))
423406f32e7eSjoerg return emitAddrOfZeroSizeField(CGF, base, field);
423506f32e7eSjoerg
423606f32e7eSjoerg const RecordDecl *rec = field->getParent();
423706f32e7eSjoerg
423806f32e7eSjoerg unsigned idx =
423906f32e7eSjoerg CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
424006f32e7eSjoerg
424106f32e7eSjoerg return CGF.Builder.CreateStructGEP(base, idx, field->getName());
424206f32e7eSjoerg }
424306f32e7eSjoerg
emitPreserveStructAccess(CodeGenFunction & CGF,LValue base,Address addr,const FieldDecl * field)4244*13fbcb42Sjoerg static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
4245*13fbcb42Sjoerg Address addr, const FieldDecl *field) {
424606f32e7eSjoerg const RecordDecl *rec = field->getParent();
4247*13fbcb42Sjoerg llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
4248*13fbcb42Sjoerg base.getType(), rec->getLocation());
424906f32e7eSjoerg
425006f32e7eSjoerg unsigned idx =
425106f32e7eSjoerg CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
425206f32e7eSjoerg
425306f32e7eSjoerg return CGF.Builder.CreatePreserveStructAccessIndex(
4254*13fbcb42Sjoerg addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
425506f32e7eSjoerg }
425606f32e7eSjoerg
hasAnyVptr(const QualType Type,const ASTContext & Context)425706f32e7eSjoerg static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
425806f32e7eSjoerg const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
425906f32e7eSjoerg if (!RD)
426006f32e7eSjoerg return false;
426106f32e7eSjoerg
426206f32e7eSjoerg if (RD->isDynamicClass())
426306f32e7eSjoerg return true;
426406f32e7eSjoerg
426506f32e7eSjoerg for (const auto &Base : RD->bases())
426606f32e7eSjoerg if (hasAnyVptr(Base.getType(), Context))
426706f32e7eSjoerg return true;
426806f32e7eSjoerg
426906f32e7eSjoerg for (const FieldDecl *Field : RD->fields())
427006f32e7eSjoerg if (hasAnyVptr(Field->getType(), Context))
427106f32e7eSjoerg return true;
427206f32e7eSjoerg
427306f32e7eSjoerg return false;
427406f32e7eSjoerg }
427506f32e7eSjoerg
EmitLValueForField(LValue base,const FieldDecl * field)427606f32e7eSjoerg LValue CodeGenFunction::EmitLValueForField(LValue base,
427706f32e7eSjoerg const FieldDecl *field) {
427806f32e7eSjoerg LValueBaseInfo BaseInfo = base.getBaseInfo();
427906f32e7eSjoerg
428006f32e7eSjoerg if (field->isBitField()) {
428106f32e7eSjoerg const CGRecordLayout &RL =
428206f32e7eSjoerg CGM.getTypes().getCGRecordLayout(field->getParent());
428306f32e7eSjoerg const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4284*13fbcb42Sjoerg const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
4285*13fbcb42Sjoerg CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
4286*13fbcb42Sjoerg Info.VolatileStorageSize != 0 &&
4287*13fbcb42Sjoerg field->getType()
4288*13fbcb42Sjoerg .withCVRQualifiers(base.getVRQualifiers())
4289*13fbcb42Sjoerg .isVolatileQualified();
4290*13fbcb42Sjoerg Address Addr = base.getAddress(*this);
429106f32e7eSjoerg unsigned Idx = RL.getLLVMFieldNo(field);
4292*13fbcb42Sjoerg const RecordDecl *rec = field->getParent();
4293*13fbcb42Sjoerg if (!UseVolatile) {
4294*13fbcb42Sjoerg if (!IsInPreservedAIRegion &&
4295*13fbcb42Sjoerg (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
429606f32e7eSjoerg if (Idx != 0)
429706f32e7eSjoerg // For structs, we GEP to the field that the record layout suggests.
429806f32e7eSjoerg Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
429906f32e7eSjoerg } else {
430006f32e7eSjoerg llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
430106f32e7eSjoerg getContext().getRecordType(rec), rec->getLocation());
4302*13fbcb42Sjoerg Addr = Builder.CreatePreserveStructAccessIndex(
4303*13fbcb42Sjoerg Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
430406f32e7eSjoerg DbgInfo);
430506f32e7eSjoerg }
4306*13fbcb42Sjoerg }
4307*13fbcb42Sjoerg const unsigned SS =
4308*13fbcb42Sjoerg UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
430906f32e7eSjoerg // Get the access type.
4310*13fbcb42Sjoerg llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
431106f32e7eSjoerg if (Addr.getElementType() != FieldIntTy)
431206f32e7eSjoerg Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
4313*13fbcb42Sjoerg if (UseVolatile) {
4314*13fbcb42Sjoerg const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
4315*13fbcb42Sjoerg if (VolatileOffset)
4316*13fbcb42Sjoerg Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
4317*13fbcb42Sjoerg }
431806f32e7eSjoerg
431906f32e7eSjoerg QualType fieldType =
432006f32e7eSjoerg field->getType().withCVRQualifiers(base.getVRQualifiers());
432106f32e7eSjoerg // TODO: Support TBAA for bit fields.
432206f32e7eSjoerg LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
432306f32e7eSjoerg return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
432406f32e7eSjoerg TBAAAccessInfo());
432506f32e7eSjoerg }
432606f32e7eSjoerg
432706f32e7eSjoerg // Fields of may-alias structures are may-alias themselves.
432806f32e7eSjoerg // FIXME: this should get propagated down through anonymous structs
432906f32e7eSjoerg // and unions.
433006f32e7eSjoerg QualType FieldType = field->getType();
433106f32e7eSjoerg const RecordDecl *rec = field->getParent();
433206f32e7eSjoerg AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
433306f32e7eSjoerg LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
433406f32e7eSjoerg TBAAAccessInfo FieldTBAAInfo;
433506f32e7eSjoerg if (base.getTBAAInfo().isMayAlias() ||
433606f32e7eSjoerg rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
433706f32e7eSjoerg FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
433806f32e7eSjoerg } else if (rec->isUnion()) {
433906f32e7eSjoerg // TODO: Support TBAA for unions.
434006f32e7eSjoerg FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
434106f32e7eSjoerg } else {
434206f32e7eSjoerg // If no base type been assigned for the base access, then try to generate
434306f32e7eSjoerg // one for this base lvalue.
434406f32e7eSjoerg FieldTBAAInfo = base.getTBAAInfo();
434506f32e7eSjoerg if (!FieldTBAAInfo.BaseType) {
434606f32e7eSjoerg FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
434706f32e7eSjoerg assert(!FieldTBAAInfo.Offset &&
434806f32e7eSjoerg "Nonzero offset for an access with no base type!");
434906f32e7eSjoerg }
435006f32e7eSjoerg
435106f32e7eSjoerg // Adjust offset to be relative to the base type.
435206f32e7eSjoerg const ASTRecordLayout &Layout =
435306f32e7eSjoerg getContext().getASTRecordLayout(field->getParent());
435406f32e7eSjoerg unsigned CharWidth = getContext().getCharWidth();
435506f32e7eSjoerg if (FieldTBAAInfo.BaseType)
435606f32e7eSjoerg FieldTBAAInfo.Offset +=
435706f32e7eSjoerg Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
435806f32e7eSjoerg
435906f32e7eSjoerg // Update the final access type and size.
436006f32e7eSjoerg FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
436106f32e7eSjoerg FieldTBAAInfo.Size =
436206f32e7eSjoerg getContext().getTypeSizeInChars(FieldType).getQuantity();
436306f32e7eSjoerg }
436406f32e7eSjoerg
4365*13fbcb42Sjoerg Address addr = base.getAddress(*this);
436606f32e7eSjoerg if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
436706f32e7eSjoerg if (CGM.getCodeGenOpts().StrictVTablePointers &&
436806f32e7eSjoerg ClassDef->isDynamicClass()) {
436906f32e7eSjoerg // Getting to any field of dynamic object requires stripping dynamic
437006f32e7eSjoerg // information provided by invariant.group. This is because accessing
437106f32e7eSjoerg // fields may leak the real address of dynamic object, which could result
437206f32e7eSjoerg // in miscompilation when leaked pointer would be compared.
437306f32e7eSjoerg auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
437406f32e7eSjoerg addr = Address(stripped, addr.getAlignment());
437506f32e7eSjoerg }
437606f32e7eSjoerg }
437706f32e7eSjoerg
437806f32e7eSjoerg unsigned RecordCVR = base.getVRQualifiers();
437906f32e7eSjoerg if (rec->isUnion()) {
438006f32e7eSjoerg // For unions, there is no pointer adjustment.
438106f32e7eSjoerg if (CGM.getCodeGenOpts().StrictVTablePointers &&
438206f32e7eSjoerg hasAnyVptr(FieldType, getContext()))
438306f32e7eSjoerg // Because unions can easily skip invariant.barriers, we need to add
438406f32e7eSjoerg // a barrier every time CXXRecord field with vptr is referenced.
438506f32e7eSjoerg addr = Address(Builder.CreateLaunderInvariantGroup(addr.getPointer()),
438606f32e7eSjoerg addr.getAlignment());
438706f32e7eSjoerg
4388*13fbcb42Sjoerg if (IsInPreservedAIRegion ||
4389*13fbcb42Sjoerg (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
439006f32e7eSjoerg // Remember the original union field index
4391*13fbcb42Sjoerg llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
4392*13fbcb42Sjoerg rec->getLocation());
439306f32e7eSjoerg addr = Address(
439406f32e7eSjoerg Builder.CreatePreserveUnionAccessIndex(
439506f32e7eSjoerg addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
439606f32e7eSjoerg addr.getAlignment());
439706f32e7eSjoerg }
439806f32e7eSjoerg
439906f32e7eSjoerg if (FieldType->isReferenceType())
440006f32e7eSjoerg addr = Builder.CreateElementBitCast(
440106f32e7eSjoerg addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
440206f32e7eSjoerg } else {
4403*13fbcb42Sjoerg if (!IsInPreservedAIRegion &&
4404*13fbcb42Sjoerg (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
440506f32e7eSjoerg // For structs, we GEP to the field that the record layout suggests.
440606f32e7eSjoerg addr = emitAddrOfFieldStorage(*this, addr, field);
440706f32e7eSjoerg else
440806f32e7eSjoerg // Remember the original struct field index
4409*13fbcb42Sjoerg addr = emitPreserveStructAccess(*this, base, addr, field);
441006f32e7eSjoerg }
441106f32e7eSjoerg
441206f32e7eSjoerg // If this is a reference field, load the reference right now.
441306f32e7eSjoerg if (FieldType->isReferenceType()) {
441406f32e7eSjoerg LValue RefLVal =
441506f32e7eSjoerg MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
441606f32e7eSjoerg if (RecordCVR & Qualifiers::Volatile)
441706f32e7eSjoerg RefLVal.getQuals().addVolatile();
441806f32e7eSjoerg addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
441906f32e7eSjoerg
442006f32e7eSjoerg // Qualifiers on the struct don't apply to the referencee.
442106f32e7eSjoerg RecordCVR = 0;
442206f32e7eSjoerg FieldType = FieldType->getPointeeType();
442306f32e7eSjoerg }
442406f32e7eSjoerg
442506f32e7eSjoerg // Make sure that the address is pointing to the right type. This is critical
442606f32e7eSjoerg // for both unions and structs. A union needs a bitcast, a struct element
442706f32e7eSjoerg // will need a bitcast if the LLVM type laid out doesn't match the desired
442806f32e7eSjoerg // type.
442906f32e7eSjoerg addr = Builder.CreateElementBitCast(
443006f32e7eSjoerg addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
443106f32e7eSjoerg
443206f32e7eSjoerg if (field->hasAttr<AnnotateAttr>())
443306f32e7eSjoerg addr = EmitFieldAnnotations(field, addr);
443406f32e7eSjoerg
443506f32e7eSjoerg LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
443606f32e7eSjoerg LV.getQuals().addCVRQualifiers(RecordCVR);
443706f32e7eSjoerg
443806f32e7eSjoerg // __weak attribute on a field is ignored.
443906f32e7eSjoerg if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
444006f32e7eSjoerg LV.getQuals().removeObjCGCAttr();
444106f32e7eSjoerg
444206f32e7eSjoerg return LV;
444306f32e7eSjoerg }
444406f32e7eSjoerg
444506f32e7eSjoerg LValue
EmitLValueForFieldInitialization(LValue Base,const FieldDecl * Field)444606f32e7eSjoerg CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
444706f32e7eSjoerg const FieldDecl *Field) {
444806f32e7eSjoerg QualType FieldType = Field->getType();
444906f32e7eSjoerg
445006f32e7eSjoerg if (!FieldType->isReferenceType())
445106f32e7eSjoerg return EmitLValueForField(Base, Field);
445206f32e7eSjoerg
4453*13fbcb42Sjoerg Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
445406f32e7eSjoerg
445506f32e7eSjoerg // Make sure that the address is pointing to the right type.
445606f32e7eSjoerg llvm::Type *llvmType = ConvertTypeForMem(FieldType);
445706f32e7eSjoerg V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
445806f32e7eSjoerg
445906f32e7eSjoerg // TODO: Generate TBAA information that describes this access as a structure
446006f32e7eSjoerg // member access and not just an access to an object of the field's type. This
446106f32e7eSjoerg // should be similar to what we do in EmitLValueForField().
446206f32e7eSjoerg LValueBaseInfo BaseInfo = Base.getBaseInfo();
446306f32e7eSjoerg AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
446406f32e7eSjoerg LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
446506f32e7eSjoerg return MakeAddrLValue(V, FieldType, FieldBaseInfo,
446606f32e7eSjoerg CGM.getTBAAInfoForSubobject(Base, FieldType));
446706f32e7eSjoerg }
446806f32e7eSjoerg
EmitCompoundLiteralLValue(const CompoundLiteralExpr * E)446906f32e7eSjoerg LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
447006f32e7eSjoerg if (E->isFileScope()) {
447106f32e7eSjoerg ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
447206f32e7eSjoerg return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
447306f32e7eSjoerg }
447406f32e7eSjoerg if (E->getType()->isVariablyModifiedType())
447506f32e7eSjoerg // make sure to emit the VLA size.
447606f32e7eSjoerg EmitVariablyModifiedType(E->getType());
447706f32e7eSjoerg
447806f32e7eSjoerg Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
447906f32e7eSjoerg const Expr *InitExpr = E->getInitializer();
448006f32e7eSjoerg LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
448106f32e7eSjoerg
448206f32e7eSjoerg EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
448306f32e7eSjoerg /*Init*/ true);
448406f32e7eSjoerg
4485*13fbcb42Sjoerg // Block-scope compound literals are destroyed at the end of the enclosing
4486*13fbcb42Sjoerg // scope in C.
4487*13fbcb42Sjoerg if (!getLangOpts().CPlusPlus)
4488*13fbcb42Sjoerg if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
4489*13fbcb42Sjoerg pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
4490*13fbcb42Sjoerg E->getType(), getDestroyer(DtorKind),
4491*13fbcb42Sjoerg DtorKind & EHCleanup);
4492*13fbcb42Sjoerg
449306f32e7eSjoerg return Result;
449406f32e7eSjoerg }
449506f32e7eSjoerg
EmitInitListLValue(const InitListExpr * E)449606f32e7eSjoerg LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
449706f32e7eSjoerg if (!E->isGLValue())
449806f32e7eSjoerg // Initializing an aggregate temporary in C++11: T{...}.
449906f32e7eSjoerg return EmitAggExprToLValue(E);
450006f32e7eSjoerg
450106f32e7eSjoerg // An lvalue initializer list must be initializing a reference.
450206f32e7eSjoerg assert(E->isTransparent() && "non-transparent glvalue init list");
450306f32e7eSjoerg return EmitLValue(E->getInit(0));
450406f32e7eSjoerg }
450506f32e7eSjoerg
450606f32e7eSjoerg /// Emit the operand of a glvalue conditional operator. This is either a glvalue
450706f32e7eSjoerg /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
450806f32e7eSjoerg /// LValue is returned and the current block has been terminated.
EmitLValueOrThrowExpression(CodeGenFunction & CGF,const Expr * Operand)450906f32e7eSjoerg static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
451006f32e7eSjoerg const Expr *Operand) {
451106f32e7eSjoerg if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
451206f32e7eSjoerg CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
451306f32e7eSjoerg return None;
451406f32e7eSjoerg }
451506f32e7eSjoerg
451606f32e7eSjoerg return CGF.EmitLValue(Operand);
451706f32e7eSjoerg }
451806f32e7eSjoerg
451906f32e7eSjoerg LValue CodeGenFunction::
EmitConditionalOperatorLValue(const AbstractConditionalOperator * expr)452006f32e7eSjoerg EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
452106f32e7eSjoerg if (!expr->isGLValue()) {
452206f32e7eSjoerg // ?: here should be an aggregate.
452306f32e7eSjoerg assert(hasAggregateEvaluationKind(expr->getType()) &&
452406f32e7eSjoerg "Unexpected conditional operator!");
452506f32e7eSjoerg return EmitAggExprToLValue(expr);
452606f32e7eSjoerg }
452706f32e7eSjoerg
452806f32e7eSjoerg OpaqueValueMapping binding(*this, expr);
452906f32e7eSjoerg
453006f32e7eSjoerg const Expr *condExpr = expr->getCond();
453106f32e7eSjoerg bool CondExprBool;
453206f32e7eSjoerg if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
453306f32e7eSjoerg const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
453406f32e7eSjoerg if (!CondExprBool) std::swap(live, dead);
453506f32e7eSjoerg
453606f32e7eSjoerg if (!ContainsLabel(dead)) {
453706f32e7eSjoerg // If the true case is live, we need to track its region.
453806f32e7eSjoerg if (CondExprBool)
453906f32e7eSjoerg incrementProfileCounter(expr);
4540*13fbcb42Sjoerg // If a throw expression we emit it and return an undefined lvalue
4541*13fbcb42Sjoerg // because it can't be used.
4542*13fbcb42Sjoerg if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(live->IgnoreParens())) {
4543*13fbcb42Sjoerg EmitCXXThrowExpr(ThrowExpr);
4544*13fbcb42Sjoerg llvm::Type *Ty =
4545*13fbcb42Sjoerg llvm::PointerType::getUnqual(ConvertType(dead->getType()));
4546*13fbcb42Sjoerg return MakeAddrLValue(
4547*13fbcb42Sjoerg Address(llvm::UndefValue::get(Ty), CharUnits::One()),
4548*13fbcb42Sjoerg dead->getType());
4549*13fbcb42Sjoerg }
455006f32e7eSjoerg return EmitLValue(live);
455106f32e7eSjoerg }
455206f32e7eSjoerg }
455306f32e7eSjoerg
455406f32e7eSjoerg llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
455506f32e7eSjoerg llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
455606f32e7eSjoerg llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
455706f32e7eSjoerg
455806f32e7eSjoerg ConditionalEvaluation eval(*this);
455906f32e7eSjoerg EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
456006f32e7eSjoerg
456106f32e7eSjoerg // Any temporaries created here are conditional.
456206f32e7eSjoerg EmitBlock(lhsBlock);
456306f32e7eSjoerg incrementProfileCounter(expr);
456406f32e7eSjoerg eval.begin(*this);
456506f32e7eSjoerg Optional<LValue> lhs =
456606f32e7eSjoerg EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
456706f32e7eSjoerg eval.end(*this);
456806f32e7eSjoerg
456906f32e7eSjoerg if (lhs && !lhs->isSimple())
457006f32e7eSjoerg return EmitUnsupportedLValue(expr, "conditional operator");
457106f32e7eSjoerg
457206f32e7eSjoerg lhsBlock = Builder.GetInsertBlock();
457306f32e7eSjoerg if (lhs)
457406f32e7eSjoerg Builder.CreateBr(contBlock);
457506f32e7eSjoerg
457606f32e7eSjoerg // Any temporaries created here are conditional.
457706f32e7eSjoerg EmitBlock(rhsBlock);
457806f32e7eSjoerg eval.begin(*this);
457906f32e7eSjoerg Optional<LValue> rhs =
458006f32e7eSjoerg EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
458106f32e7eSjoerg eval.end(*this);
458206f32e7eSjoerg if (rhs && !rhs->isSimple())
458306f32e7eSjoerg return EmitUnsupportedLValue(expr, "conditional operator");
458406f32e7eSjoerg rhsBlock = Builder.GetInsertBlock();
458506f32e7eSjoerg
458606f32e7eSjoerg EmitBlock(contBlock);
458706f32e7eSjoerg
458806f32e7eSjoerg if (lhs && rhs) {
4589*13fbcb42Sjoerg llvm::PHINode *phi =
4590*13fbcb42Sjoerg Builder.CreatePHI(lhs->getPointer(*this)->getType(), 2, "cond-lvalue");
4591*13fbcb42Sjoerg phi->addIncoming(lhs->getPointer(*this), lhsBlock);
4592*13fbcb42Sjoerg phi->addIncoming(rhs->getPointer(*this), rhsBlock);
459306f32e7eSjoerg Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
459406f32e7eSjoerg AlignmentSource alignSource =
459506f32e7eSjoerg std::max(lhs->getBaseInfo().getAlignmentSource(),
459606f32e7eSjoerg rhs->getBaseInfo().getAlignmentSource());
459706f32e7eSjoerg TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
459806f32e7eSjoerg lhs->getTBAAInfo(), rhs->getTBAAInfo());
459906f32e7eSjoerg return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
460006f32e7eSjoerg TBAAInfo);
460106f32e7eSjoerg } else {
460206f32e7eSjoerg assert((lhs || rhs) &&
460306f32e7eSjoerg "both operands of glvalue conditional are throw-expressions?");
460406f32e7eSjoerg return lhs ? *lhs : *rhs;
460506f32e7eSjoerg }
460606f32e7eSjoerg }
460706f32e7eSjoerg
460806f32e7eSjoerg /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
460906f32e7eSjoerg /// type. If the cast is to a reference, we can have the usual lvalue result,
461006f32e7eSjoerg /// otherwise if a cast is needed by the code generator in an lvalue context,
461106f32e7eSjoerg /// then it must mean that we need the address of an aggregate in order to
461206f32e7eSjoerg /// access one of its members. This can happen for all the reasons that casts
461306f32e7eSjoerg /// are permitted with aggregate result, including noop aggregate casts, and
461406f32e7eSjoerg /// cast from scalar to union.
EmitCastLValue(const CastExpr * E)461506f32e7eSjoerg LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
461606f32e7eSjoerg switch (E->getCastKind()) {
461706f32e7eSjoerg case CK_ToVoid:
461806f32e7eSjoerg case CK_BitCast:
461906f32e7eSjoerg case CK_LValueToRValueBitCast:
462006f32e7eSjoerg case CK_ArrayToPointerDecay:
462106f32e7eSjoerg case CK_FunctionToPointerDecay:
462206f32e7eSjoerg case CK_NullToMemberPointer:
462306f32e7eSjoerg case CK_NullToPointer:
462406f32e7eSjoerg case CK_IntegralToPointer:
462506f32e7eSjoerg case CK_PointerToIntegral:
462606f32e7eSjoerg case CK_PointerToBoolean:
462706f32e7eSjoerg case CK_VectorSplat:
462806f32e7eSjoerg case CK_IntegralCast:
462906f32e7eSjoerg case CK_BooleanToSignedIntegral:
463006f32e7eSjoerg case CK_IntegralToBoolean:
463106f32e7eSjoerg case CK_IntegralToFloating:
463206f32e7eSjoerg case CK_FloatingToIntegral:
463306f32e7eSjoerg case CK_FloatingToBoolean:
463406f32e7eSjoerg case CK_FloatingCast:
463506f32e7eSjoerg case CK_FloatingRealToComplex:
463606f32e7eSjoerg case CK_FloatingComplexToReal:
463706f32e7eSjoerg case CK_FloatingComplexToBoolean:
463806f32e7eSjoerg case CK_FloatingComplexCast:
463906f32e7eSjoerg case CK_FloatingComplexToIntegralComplex:
464006f32e7eSjoerg case CK_IntegralRealToComplex:
464106f32e7eSjoerg case CK_IntegralComplexToReal:
464206f32e7eSjoerg case CK_IntegralComplexToBoolean:
464306f32e7eSjoerg case CK_IntegralComplexCast:
464406f32e7eSjoerg case CK_IntegralComplexToFloatingComplex:
464506f32e7eSjoerg case CK_DerivedToBaseMemberPointer:
464606f32e7eSjoerg case CK_BaseToDerivedMemberPointer:
464706f32e7eSjoerg case CK_MemberPointerToBoolean:
464806f32e7eSjoerg case CK_ReinterpretMemberPointer:
464906f32e7eSjoerg case CK_AnyPointerToBlockPointerCast:
465006f32e7eSjoerg case CK_ARCProduceObject:
465106f32e7eSjoerg case CK_ARCConsumeObject:
465206f32e7eSjoerg case CK_ARCReclaimReturnedObject:
465306f32e7eSjoerg case CK_ARCExtendBlockObject:
465406f32e7eSjoerg case CK_CopyAndAutoreleaseBlockObject:
465506f32e7eSjoerg case CK_IntToOCLSampler:
4656*13fbcb42Sjoerg case CK_FloatingToFixedPoint:
4657*13fbcb42Sjoerg case CK_FixedPointToFloating:
465806f32e7eSjoerg case CK_FixedPointCast:
465906f32e7eSjoerg case CK_FixedPointToBoolean:
466006f32e7eSjoerg case CK_FixedPointToIntegral:
466106f32e7eSjoerg case CK_IntegralToFixedPoint:
4662*13fbcb42Sjoerg case CK_MatrixCast:
466306f32e7eSjoerg return EmitUnsupportedLValue(E, "unexpected cast lvalue");
466406f32e7eSjoerg
466506f32e7eSjoerg case CK_Dependent:
466606f32e7eSjoerg llvm_unreachable("dependent cast kind in IR gen!");
466706f32e7eSjoerg
466806f32e7eSjoerg case CK_BuiltinFnToFnPtr:
466906f32e7eSjoerg llvm_unreachable("builtin functions are handled elsewhere");
467006f32e7eSjoerg
467106f32e7eSjoerg // These are never l-values; just use the aggregate emission code.
467206f32e7eSjoerg case CK_NonAtomicToAtomic:
467306f32e7eSjoerg case CK_AtomicToNonAtomic:
467406f32e7eSjoerg return EmitAggExprToLValue(E);
467506f32e7eSjoerg
467606f32e7eSjoerg case CK_Dynamic: {
467706f32e7eSjoerg LValue LV = EmitLValue(E->getSubExpr());
4678*13fbcb42Sjoerg Address V = LV.getAddress(*this);
467906f32e7eSjoerg const auto *DCE = cast<CXXDynamicCastExpr>(E);
468006f32e7eSjoerg return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
468106f32e7eSjoerg }
468206f32e7eSjoerg
468306f32e7eSjoerg case CK_ConstructorConversion:
468406f32e7eSjoerg case CK_UserDefinedConversion:
468506f32e7eSjoerg case CK_CPointerToObjCPointerCast:
468606f32e7eSjoerg case CK_BlockPointerToObjCPointerCast:
468706f32e7eSjoerg case CK_NoOp:
468806f32e7eSjoerg case CK_LValueToRValue:
468906f32e7eSjoerg return EmitLValue(E->getSubExpr());
469006f32e7eSjoerg
469106f32e7eSjoerg case CK_UncheckedDerivedToBase:
469206f32e7eSjoerg case CK_DerivedToBase: {
4693*13fbcb42Sjoerg const auto *DerivedClassTy =
4694*13fbcb42Sjoerg E->getSubExpr()->getType()->castAs<RecordType>();
469506f32e7eSjoerg auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
469606f32e7eSjoerg
469706f32e7eSjoerg LValue LV = EmitLValue(E->getSubExpr());
4698*13fbcb42Sjoerg Address This = LV.getAddress(*this);
469906f32e7eSjoerg
470006f32e7eSjoerg // Perform the derived-to-base conversion
470106f32e7eSjoerg Address Base = GetAddressOfBaseClass(
470206f32e7eSjoerg This, DerivedClassDecl, E->path_begin(), E->path_end(),
470306f32e7eSjoerg /*NullCheckValue=*/false, E->getExprLoc());
470406f32e7eSjoerg
470506f32e7eSjoerg // TODO: Support accesses to members of base classes in TBAA. For now, we
470606f32e7eSjoerg // conservatively pretend that the complete object is of the base class
470706f32e7eSjoerg // type.
470806f32e7eSjoerg return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
470906f32e7eSjoerg CGM.getTBAAInfoForSubobject(LV, E->getType()));
471006f32e7eSjoerg }
471106f32e7eSjoerg case CK_ToUnion:
471206f32e7eSjoerg return EmitAggExprToLValue(E);
471306f32e7eSjoerg case CK_BaseToDerived: {
4714*13fbcb42Sjoerg const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
471506f32e7eSjoerg auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
471606f32e7eSjoerg
471706f32e7eSjoerg LValue LV = EmitLValue(E->getSubExpr());
471806f32e7eSjoerg
471906f32e7eSjoerg // Perform the base-to-derived conversion
4720*13fbcb42Sjoerg Address Derived = GetAddressOfDerivedClass(
4721*13fbcb42Sjoerg LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
472206f32e7eSjoerg /*NullCheckValue=*/false);
472306f32e7eSjoerg
472406f32e7eSjoerg // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
472506f32e7eSjoerg // performed and the object is not of the derived type.
472606f32e7eSjoerg if (sanitizePerformTypeCheck())
472706f32e7eSjoerg EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
472806f32e7eSjoerg Derived.getPointer(), E->getType());
472906f32e7eSjoerg
473006f32e7eSjoerg if (SanOpts.has(SanitizerKind::CFIDerivedCast))
473106f32e7eSjoerg EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
473206f32e7eSjoerg /*MayBeNull=*/false, CFITCK_DerivedCast,
473306f32e7eSjoerg E->getBeginLoc());
473406f32e7eSjoerg
473506f32e7eSjoerg return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
473606f32e7eSjoerg CGM.getTBAAInfoForSubobject(LV, E->getType()));
473706f32e7eSjoerg }
473806f32e7eSjoerg case CK_LValueBitCast: {
473906f32e7eSjoerg // This must be a reinterpret_cast (or c-style equivalent).
474006f32e7eSjoerg const auto *CE = cast<ExplicitCastExpr>(E);
474106f32e7eSjoerg
474206f32e7eSjoerg CGM.EmitExplicitCastExprType(CE, this);
474306f32e7eSjoerg LValue LV = EmitLValue(E->getSubExpr());
4744*13fbcb42Sjoerg Address V = Builder.CreateBitCast(LV.getAddress(*this),
474506f32e7eSjoerg ConvertType(CE->getTypeAsWritten()));
474606f32e7eSjoerg
474706f32e7eSjoerg if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
474806f32e7eSjoerg EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
474906f32e7eSjoerg /*MayBeNull=*/false, CFITCK_UnrelatedCast,
475006f32e7eSjoerg E->getBeginLoc());
475106f32e7eSjoerg
475206f32e7eSjoerg return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
475306f32e7eSjoerg CGM.getTBAAInfoForSubobject(LV, E->getType()));
475406f32e7eSjoerg }
475506f32e7eSjoerg case CK_AddressSpaceConversion: {
475606f32e7eSjoerg LValue LV = EmitLValue(E->getSubExpr());
475706f32e7eSjoerg QualType DestTy = getContext().getPointerType(E->getType());
475806f32e7eSjoerg llvm::Value *V = getTargetHooks().performAddrSpaceCast(
4759*13fbcb42Sjoerg *this, LV.getPointer(*this),
4760*13fbcb42Sjoerg E->getSubExpr()->getType().getAddressSpace(),
476106f32e7eSjoerg E->getType().getAddressSpace(), ConvertType(DestTy));
4762*13fbcb42Sjoerg return MakeAddrLValue(Address(V, LV.getAddress(*this).getAlignment()),
476306f32e7eSjoerg E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
476406f32e7eSjoerg }
476506f32e7eSjoerg case CK_ObjCObjectLValueCast: {
476606f32e7eSjoerg LValue LV = EmitLValue(E->getSubExpr());
4767*13fbcb42Sjoerg Address V = Builder.CreateElementBitCast(LV.getAddress(*this),
476806f32e7eSjoerg ConvertType(E->getType()));
476906f32e7eSjoerg return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
477006f32e7eSjoerg CGM.getTBAAInfoForSubobject(LV, E->getType()));
477106f32e7eSjoerg }
477206f32e7eSjoerg case CK_ZeroToOCLOpaqueType:
477306f32e7eSjoerg llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
477406f32e7eSjoerg }
477506f32e7eSjoerg
477606f32e7eSjoerg llvm_unreachable("Unhandled lvalue cast kind?");
477706f32e7eSjoerg }
477806f32e7eSjoerg
EmitOpaqueValueLValue(const OpaqueValueExpr * e)477906f32e7eSjoerg LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
478006f32e7eSjoerg assert(OpaqueValueMappingData::shouldBindAsLValue(e));
478106f32e7eSjoerg return getOrCreateOpaqueLValueMapping(e);
478206f32e7eSjoerg }
478306f32e7eSjoerg
478406f32e7eSjoerg LValue
getOrCreateOpaqueLValueMapping(const OpaqueValueExpr * e)478506f32e7eSjoerg CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
478606f32e7eSjoerg assert(OpaqueValueMapping::shouldBindAsLValue(e));
478706f32e7eSjoerg
478806f32e7eSjoerg llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
478906f32e7eSjoerg it = OpaqueLValues.find(e);
479006f32e7eSjoerg
479106f32e7eSjoerg if (it != OpaqueLValues.end())
479206f32e7eSjoerg return it->second;
479306f32e7eSjoerg
479406f32e7eSjoerg assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
479506f32e7eSjoerg return EmitLValue(e->getSourceExpr());
479606f32e7eSjoerg }
479706f32e7eSjoerg
479806f32e7eSjoerg RValue
getOrCreateOpaqueRValueMapping(const OpaqueValueExpr * e)479906f32e7eSjoerg CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
480006f32e7eSjoerg assert(!OpaqueValueMapping::shouldBindAsLValue(e));
480106f32e7eSjoerg
480206f32e7eSjoerg llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
480306f32e7eSjoerg it = OpaqueRValues.find(e);
480406f32e7eSjoerg
480506f32e7eSjoerg if (it != OpaqueRValues.end())
480606f32e7eSjoerg return it->second;
480706f32e7eSjoerg
480806f32e7eSjoerg assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
480906f32e7eSjoerg return EmitAnyExpr(e->getSourceExpr());
481006f32e7eSjoerg }
481106f32e7eSjoerg
EmitRValueForField(LValue LV,const FieldDecl * FD,SourceLocation Loc)481206f32e7eSjoerg RValue CodeGenFunction::EmitRValueForField(LValue LV,
481306f32e7eSjoerg const FieldDecl *FD,
481406f32e7eSjoerg SourceLocation Loc) {
481506f32e7eSjoerg QualType FT = FD->getType();
481606f32e7eSjoerg LValue FieldLV = EmitLValueForField(LV, FD);
481706f32e7eSjoerg switch (getEvaluationKind(FT)) {
481806f32e7eSjoerg case TEK_Complex:
481906f32e7eSjoerg return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
482006f32e7eSjoerg case TEK_Aggregate:
4821*13fbcb42Sjoerg return FieldLV.asAggregateRValue(*this);
482206f32e7eSjoerg case TEK_Scalar:
482306f32e7eSjoerg // This routine is used to load fields one-by-one to perform a copy, so
482406f32e7eSjoerg // don't load reference fields.
482506f32e7eSjoerg if (FD->getType()->isReferenceType())
4826*13fbcb42Sjoerg return RValue::get(FieldLV.getPointer(*this));
4827*13fbcb42Sjoerg // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
4828*13fbcb42Sjoerg // primitive load.
4829*13fbcb42Sjoerg if (FieldLV.isBitField())
483006f32e7eSjoerg return EmitLoadOfLValue(FieldLV, Loc);
4831*13fbcb42Sjoerg return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
483206f32e7eSjoerg }
483306f32e7eSjoerg llvm_unreachable("bad evaluation kind");
483406f32e7eSjoerg }
483506f32e7eSjoerg
483606f32e7eSjoerg //===--------------------------------------------------------------------===//
483706f32e7eSjoerg // Expression Emission
483806f32e7eSjoerg //===--------------------------------------------------------------------===//
483906f32e7eSjoerg
EmitCallExpr(const CallExpr * E,ReturnValueSlot ReturnValue)484006f32e7eSjoerg RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
484106f32e7eSjoerg ReturnValueSlot ReturnValue) {
484206f32e7eSjoerg // Builtins never have block type.
484306f32e7eSjoerg if (E->getCallee()->getType()->isBlockPointerType())
484406f32e7eSjoerg return EmitBlockCallExpr(E, ReturnValue);
484506f32e7eSjoerg
484606f32e7eSjoerg if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
484706f32e7eSjoerg return EmitCXXMemberCallExpr(CE, ReturnValue);
484806f32e7eSjoerg
484906f32e7eSjoerg if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
485006f32e7eSjoerg return EmitCUDAKernelCallExpr(CE, ReturnValue);
485106f32e7eSjoerg
485206f32e7eSjoerg if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
485306f32e7eSjoerg if (const CXXMethodDecl *MD =
485406f32e7eSjoerg dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
485506f32e7eSjoerg return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
485606f32e7eSjoerg
485706f32e7eSjoerg CGCallee callee = EmitCallee(E->getCallee());
485806f32e7eSjoerg
485906f32e7eSjoerg if (callee.isBuiltin()) {
486006f32e7eSjoerg return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
486106f32e7eSjoerg E, ReturnValue);
486206f32e7eSjoerg }
486306f32e7eSjoerg
486406f32e7eSjoerg if (callee.isPseudoDestructor()) {
486506f32e7eSjoerg return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
486606f32e7eSjoerg }
486706f32e7eSjoerg
486806f32e7eSjoerg return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
486906f32e7eSjoerg }
487006f32e7eSjoerg
487106f32e7eSjoerg /// Emit a CallExpr without considering whether it might be a subclass.
EmitSimpleCallExpr(const CallExpr * E,ReturnValueSlot ReturnValue)487206f32e7eSjoerg RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
487306f32e7eSjoerg ReturnValueSlot ReturnValue) {
487406f32e7eSjoerg CGCallee Callee = EmitCallee(E->getCallee());
487506f32e7eSjoerg return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
487606f32e7eSjoerg }
487706f32e7eSjoerg
EmitDirectCallee(CodeGenFunction & CGF,GlobalDecl GD)4878*13fbcb42Sjoerg static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
4879*13fbcb42Sjoerg const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4880*13fbcb42Sjoerg
488106f32e7eSjoerg if (auto builtinID = FD->getBuiltinID()) {
4882*13fbcb42Sjoerg // Replaceable builtin provide their own implementation of a builtin. Unless
4883*13fbcb42Sjoerg // we are in the builtin implementation itself, don't call the actual
4884*13fbcb42Sjoerg // builtin. If we are in the builtin implementation, avoid trivial infinite
4885*13fbcb42Sjoerg // recursion.
4886*13fbcb42Sjoerg if (!FD->isInlineBuiltinDeclaration() ||
4887*13fbcb42Sjoerg CGF.CurFn->getName() == FD->getName())
488806f32e7eSjoerg return CGCallee::forBuiltin(builtinID, FD);
488906f32e7eSjoerg }
489006f32e7eSjoerg
4891*13fbcb42Sjoerg llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
4892*13fbcb42Sjoerg if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
4893*13fbcb42Sjoerg FD->hasAttr<CUDAGlobalAttr>())
4894*13fbcb42Sjoerg CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
4895*13fbcb42Sjoerg cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
4896*13fbcb42Sjoerg return CGCallee::forDirect(CalleePtr, GD);
489706f32e7eSjoerg }
489806f32e7eSjoerg
EmitCallee(const Expr * E)489906f32e7eSjoerg CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
490006f32e7eSjoerg E = E->IgnoreParens();
490106f32e7eSjoerg
490206f32e7eSjoerg // Look through function-to-pointer decay.
490306f32e7eSjoerg if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
490406f32e7eSjoerg if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
490506f32e7eSjoerg ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
490606f32e7eSjoerg return EmitCallee(ICE->getSubExpr());
490706f32e7eSjoerg }
490806f32e7eSjoerg
490906f32e7eSjoerg // Resolve direct calls.
491006f32e7eSjoerg } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
491106f32e7eSjoerg if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
491206f32e7eSjoerg return EmitDirectCallee(*this, FD);
491306f32e7eSjoerg }
491406f32e7eSjoerg } else if (auto ME = dyn_cast<MemberExpr>(E)) {
491506f32e7eSjoerg if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
491606f32e7eSjoerg EmitIgnoredExpr(ME->getBase());
491706f32e7eSjoerg return EmitDirectCallee(*this, FD);
491806f32e7eSjoerg }
491906f32e7eSjoerg
492006f32e7eSjoerg // Look through template substitutions.
492106f32e7eSjoerg } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
492206f32e7eSjoerg return EmitCallee(NTTP->getReplacement());
492306f32e7eSjoerg
492406f32e7eSjoerg // Treat pseudo-destructor calls differently.
492506f32e7eSjoerg } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
492606f32e7eSjoerg return CGCallee::forPseudoDestructor(PDE);
492706f32e7eSjoerg }
492806f32e7eSjoerg
492906f32e7eSjoerg // Otherwise, we have an indirect reference.
493006f32e7eSjoerg llvm::Value *calleePtr;
493106f32e7eSjoerg QualType functionType;
493206f32e7eSjoerg if (auto ptrType = E->getType()->getAs<PointerType>()) {
493306f32e7eSjoerg calleePtr = EmitScalarExpr(E);
493406f32e7eSjoerg functionType = ptrType->getPointeeType();
493506f32e7eSjoerg } else {
493606f32e7eSjoerg functionType = E->getType();
4937*13fbcb42Sjoerg calleePtr = EmitLValue(E).getPointer(*this);
493806f32e7eSjoerg }
493906f32e7eSjoerg assert(functionType->isFunctionType());
494006f32e7eSjoerg
494106f32e7eSjoerg GlobalDecl GD;
494206f32e7eSjoerg if (const auto *VD =
494306f32e7eSjoerg dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
494406f32e7eSjoerg GD = GlobalDecl(VD);
494506f32e7eSjoerg
494606f32e7eSjoerg CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
494706f32e7eSjoerg CGCallee callee(calleeInfo, calleePtr);
494806f32e7eSjoerg return callee;
494906f32e7eSjoerg }
495006f32e7eSjoerg
EmitBinaryOperatorLValue(const BinaryOperator * E)495106f32e7eSjoerg LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
495206f32e7eSjoerg // Comma expressions just emit their LHS then their RHS as an l-value.
495306f32e7eSjoerg if (E->getOpcode() == BO_Comma) {
495406f32e7eSjoerg EmitIgnoredExpr(E->getLHS());
495506f32e7eSjoerg EnsureInsertPoint();
495606f32e7eSjoerg return EmitLValue(E->getRHS());
495706f32e7eSjoerg }
495806f32e7eSjoerg
495906f32e7eSjoerg if (E->getOpcode() == BO_PtrMemD ||
496006f32e7eSjoerg E->getOpcode() == BO_PtrMemI)
496106f32e7eSjoerg return EmitPointerToDataMemberBinaryExpr(E);
496206f32e7eSjoerg
496306f32e7eSjoerg assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
496406f32e7eSjoerg
496506f32e7eSjoerg // Note that in all of these cases, __block variables need the RHS
496606f32e7eSjoerg // evaluated first just in case the variable gets moved by the RHS.
496706f32e7eSjoerg
496806f32e7eSjoerg switch (getEvaluationKind(E->getType())) {
496906f32e7eSjoerg case TEK_Scalar: {
497006f32e7eSjoerg switch (E->getLHS()->getType().getObjCLifetime()) {
497106f32e7eSjoerg case Qualifiers::OCL_Strong:
497206f32e7eSjoerg return EmitARCStoreStrong(E, /*ignored*/ false).first;
497306f32e7eSjoerg
497406f32e7eSjoerg case Qualifiers::OCL_Autoreleasing:
497506f32e7eSjoerg return EmitARCStoreAutoreleasing(E).first;
497606f32e7eSjoerg
497706f32e7eSjoerg // No reason to do any of these differently.
497806f32e7eSjoerg case Qualifiers::OCL_None:
497906f32e7eSjoerg case Qualifiers::OCL_ExplicitNone:
498006f32e7eSjoerg case Qualifiers::OCL_Weak:
498106f32e7eSjoerg break;
498206f32e7eSjoerg }
498306f32e7eSjoerg
498406f32e7eSjoerg RValue RV = EmitAnyExpr(E->getRHS());
498506f32e7eSjoerg LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
498606f32e7eSjoerg if (RV.isScalar())
498706f32e7eSjoerg EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
498806f32e7eSjoerg EmitStoreThroughLValue(RV, LV);
4989*13fbcb42Sjoerg if (getLangOpts().OpenMP)
4990*13fbcb42Sjoerg CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
4991*13fbcb42Sjoerg E->getLHS());
499206f32e7eSjoerg return LV;
499306f32e7eSjoerg }
499406f32e7eSjoerg
499506f32e7eSjoerg case TEK_Complex:
499606f32e7eSjoerg return EmitComplexAssignmentLValue(E);
499706f32e7eSjoerg
499806f32e7eSjoerg case TEK_Aggregate:
499906f32e7eSjoerg return EmitAggExprToLValue(E);
500006f32e7eSjoerg }
500106f32e7eSjoerg llvm_unreachable("bad evaluation kind");
500206f32e7eSjoerg }
500306f32e7eSjoerg
EmitCallExprLValue(const CallExpr * E)500406f32e7eSjoerg LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
500506f32e7eSjoerg RValue RV = EmitCallExpr(E);
500606f32e7eSjoerg
500706f32e7eSjoerg if (!RV.isScalar())
500806f32e7eSjoerg return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
500906f32e7eSjoerg AlignmentSource::Decl);
501006f32e7eSjoerg
501106f32e7eSjoerg assert(E->getCallReturnType(getContext())->isReferenceType() &&
501206f32e7eSjoerg "Can't have a scalar return unless the return type is a "
501306f32e7eSjoerg "reference type!");
501406f32e7eSjoerg
501506f32e7eSjoerg return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
501606f32e7eSjoerg }
501706f32e7eSjoerg
EmitVAArgExprLValue(const VAArgExpr * E)501806f32e7eSjoerg LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
501906f32e7eSjoerg // FIXME: This shouldn't require another copy.
502006f32e7eSjoerg return EmitAggExprToLValue(E);
502106f32e7eSjoerg }
502206f32e7eSjoerg
EmitCXXConstructLValue(const CXXConstructExpr * E)502306f32e7eSjoerg LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
502406f32e7eSjoerg assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
502506f32e7eSjoerg && "binding l-value to type which needs a temporary");
502606f32e7eSjoerg AggValueSlot Slot = CreateAggTemp(E->getType());
502706f32e7eSjoerg EmitCXXConstructExpr(E, Slot);
502806f32e7eSjoerg return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
502906f32e7eSjoerg }
503006f32e7eSjoerg
503106f32e7eSjoerg LValue
EmitCXXTypeidLValue(const CXXTypeidExpr * E)503206f32e7eSjoerg CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
503306f32e7eSjoerg return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
503406f32e7eSjoerg }
503506f32e7eSjoerg
EmitCXXUuidofExpr(const CXXUuidofExpr * E)503606f32e7eSjoerg Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
5037*13fbcb42Sjoerg return Builder.CreateElementBitCast(CGM.GetAddrOfMSGuidDecl(E->getGuidDecl()),
503806f32e7eSjoerg ConvertType(E->getType()));
503906f32e7eSjoerg }
504006f32e7eSjoerg
EmitCXXUuidofLValue(const CXXUuidofExpr * E)504106f32e7eSjoerg LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
504206f32e7eSjoerg return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
504306f32e7eSjoerg AlignmentSource::Decl);
504406f32e7eSjoerg }
504506f32e7eSjoerg
504606f32e7eSjoerg LValue
EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr * E)504706f32e7eSjoerg CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
504806f32e7eSjoerg AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
504906f32e7eSjoerg Slot.setExternallyDestructed();
505006f32e7eSjoerg EmitAggExpr(E->getSubExpr(), Slot);
505106f32e7eSjoerg EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
505206f32e7eSjoerg return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
505306f32e7eSjoerg }
505406f32e7eSjoerg
EmitObjCMessageExprLValue(const ObjCMessageExpr * E)505506f32e7eSjoerg LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
505606f32e7eSjoerg RValue RV = EmitObjCMessageExpr(E);
505706f32e7eSjoerg
505806f32e7eSjoerg if (!RV.isScalar())
505906f32e7eSjoerg return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
506006f32e7eSjoerg AlignmentSource::Decl);
506106f32e7eSjoerg
506206f32e7eSjoerg assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
506306f32e7eSjoerg "Can't have a scalar return unless the return type is a "
506406f32e7eSjoerg "reference type!");
506506f32e7eSjoerg
506606f32e7eSjoerg return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
506706f32e7eSjoerg }
506806f32e7eSjoerg
EmitObjCSelectorLValue(const ObjCSelectorExpr * E)506906f32e7eSjoerg LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
507006f32e7eSjoerg Address V =
507106f32e7eSjoerg CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
507206f32e7eSjoerg return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
507306f32e7eSjoerg }
507406f32e7eSjoerg
EmitIvarOffset(const ObjCInterfaceDecl * Interface,const ObjCIvarDecl * Ivar)507506f32e7eSjoerg llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
507606f32e7eSjoerg const ObjCIvarDecl *Ivar) {
507706f32e7eSjoerg return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
507806f32e7eSjoerg }
507906f32e7eSjoerg
EmitLValueForIvar(QualType ObjectTy,llvm::Value * BaseValue,const ObjCIvarDecl * Ivar,unsigned CVRQualifiers)508006f32e7eSjoerg LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
508106f32e7eSjoerg llvm::Value *BaseValue,
508206f32e7eSjoerg const ObjCIvarDecl *Ivar,
508306f32e7eSjoerg unsigned CVRQualifiers) {
508406f32e7eSjoerg return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
508506f32e7eSjoerg Ivar, CVRQualifiers);
508606f32e7eSjoerg }
508706f32e7eSjoerg
EmitObjCIvarRefLValue(const ObjCIvarRefExpr * E)508806f32e7eSjoerg LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
508906f32e7eSjoerg // FIXME: A lot of the code below could be shared with EmitMemberExpr.
509006f32e7eSjoerg llvm::Value *BaseValue = nullptr;
509106f32e7eSjoerg const Expr *BaseExpr = E->getBase();
509206f32e7eSjoerg Qualifiers BaseQuals;
509306f32e7eSjoerg QualType ObjectTy;
509406f32e7eSjoerg if (E->isArrow()) {
509506f32e7eSjoerg BaseValue = EmitScalarExpr(BaseExpr);
509606f32e7eSjoerg ObjectTy = BaseExpr->getType()->getPointeeType();
509706f32e7eSjoerg BaseQuals = ObjectTy.getQualifiers();
509806f32e7eSjoerg } else {
509906f32e7eSjoerg LValue BaseLV = EmitLValue(BaseExpr);
5100*13fbcb42Sjoerg BaseValue = BaseLV.getPointer(*this);
510106f32e7eSjoerg ObjectTy = BaseExpr->getType();
510206f32e7eSjoerg BaseQuals = ObjectTy.getQualifiers();
510306f32e7eSjoerg }
510406f32e7eSjoerg
510506f32e7eSjoerg LValue LV =
510606f32e7eSjoerg EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
510706f32e7eSjoerg BaseQuals.getCVRQualifiers());
510806f32e7eSjoerg setObjCGCLValueClass(getContext(), E, LV);
510906f32e7eSjoerg return LV;
511006f32e7eSjoerg }
511106f32e7eSjoerg
EmitStmtExprLValue(const StmtExpr * E)511206f32e7eSjoerg LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
511306f32e7eSjoerg // Can only get l-value for message expression returning aggregate type
511406f32e7eSjoerg RValue RV = EmitAnyExprToTemp(E);
511506f32e7eSjoerg return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
511606f32e7eSjoerg AlignmentSource::Decl);
511706f32e7eSjoerg }
511806f32e7eSjoerg
EmitCall(QualType CalleeType,const CGCallee & OrigCallee,const CallExpr * E,ReturnValueSlot ReturnValue,llvm::Value * Chain)511906f32e7eSjoerg RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
512006f32e7eSjoerg const CallExpr *E, ReturnValueSlot ReturnValue,
512106f32e7eSjoerg llvm::Value *Chain) {
512206f32e7eSjoerg // Get the actual function type. The callee type will always be a pointer to
512306f32e7eSjoerg // function type or a block pointer type.
512406f32e7eSjoerg assert(CalleeType->isFunctionPointerType() &&
512506f32e7eSjoerg "Call must have function pointer type!");
512606f32e7eSjoerg
512706f32e7eSjoerg const Decl *TargetDecl =
512806f32e7eSjoerg OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
512906f32e7eSjoerg
513006f32e7eSjoerg CalleeType = getContext().getCanonicalType(CalleeType);
513106f32e7eSjoerg
513206f32e7eSjoerg auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
513306f32e7eSjoerg
513406f32e7eSjoerg CGCallee Callee = OrigCallee;
513506f32e7eSjoerg
513606f32e7eSjoerg if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
513706f32e7eSjoerg (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
513806f32e7eSjoerg if (llvm::Constant *PrefixSig =
513906f32e7eSjoerg CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
514006f32e7eSjoerg SanitizerScope SanScope(this);
514106f32e7eSjoerg // Remove any (C++17) exception specifications, to allow calling e.g. a
514206f32e7eSjoerg // noexcept function through a non-noexcept pointer.
514306f32e7eSjoerg auto ProtoTy =
514406f32e7eSjoerg getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
514506f32e7eSjoerg llvm::Constant *FTRTTIConst =
514606f32e7eSjoerg CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
5147*13fbcb42Sjoerg llvm::Type *PrefixSigType = PrefixSig->getType();
514806f32e7eSjoerg llvm::StructType *PrefixStructTy = llvm::StructType::get(
5149*13fbcb42Sjoerg CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
515006f32e7eSjoerg
515106f32e7eSjoerg llvm::Value *CalleePtr = Callee.getFunctionPointer();
515206f32e7eSjoerg
515306f32e7eSjoerg llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
515406f32e7eSjoerg CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
515506f32e7eSjoerg llvm::Value *CalleeSigPtr =
515606f32e7eSjoerg Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
515706f32e7eSjoerg llvm::Value *CalleeSig =
5158*13fbcb42Sjoerg Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
515906f32e7eSjoerg llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
516006f32e7eSjoerg
516106f32e7eSjoerg llvm::BasicBlock *Cont = createBasicBlock("cont");
516206f32e7eSjoerg llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
516306f32e7eSjoerg Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
516406f32e7eSjoerg
516506f32e7eSjoerg EmitBlock(TypeCheck);
516606f32e7eSjoerg llvm::Value *CalleeRTTIPtr =
516706f32e7eSjoerg Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
516806f32e7eSjoerg llvm::Value *CalleeRTTIEncoded =
5169*13fbcb42Sjoerg Builder.CreateAlignedLoad(Int32Ty, CalleeRTTIPtr, getPointerAlign());
517006f32e7eSjoerg llvm::Value *CalleeRTTI =
517106f32e7eSjoerg DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
517206f32e7eSjoerg llvm::Value *CalleeRTTIMatch =
517306f32e7eSjoerg Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
517406f32e7eSjoerg llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
517506f32e7eSjoerg EmitCheckTypeDescriptor(CalleeType)};
517606f32e7eSjoerg EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
517706f32e7eSjoerg SanitizerHandler::FunctionTypeMismatch, StaticData,
517806f32e7eSjoerg {CalleePtr, CalleeRTTI, FTRTTIConst});
517906f32e7eSjoerg
518006f32e7eSjoerg Builder.CreateBr(Cont);
518106f32e7eSjoerg EmitBlock(Cont);
518206f32e7eSjoerg }
518306f32e7eSjoerg }
518406f32e7eSjoerg
518506f32e7eSjoerg const auto *FnType = cast<FunctionType>(PointeeType);
518606f32e7eSjoerg
518706f32e7eSjoerg // If we are checking indirect calls and this call is indirect, check that the
518806f32e7eSjoerg // function pointer is a member of the bit set for the function type.
518906f32e7eSjoerg if (SanOpts.has(SanitizerKind::CFIICall) &&
519006f32e7eSjoerg (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
519106f32e7eSjoerg SanitizerScope SanScope(this);
519206f32e7eSjoerg EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
519306f32e7eSjoerg
519406f32e7eSjoerg llvm::Metadata *MD;
519506f32e7eSjoerg if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
519606f32e7eSjoerg MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
519706f32e7eSjoerg else
519806f32e7eSjoerg MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
519906f32e7eSjoerg
520006f32e7eSjoerg llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
520106f32e7eSjoerg
520206f32e7eSjoerg llvm::Value *CalleePtr = Callee.getFunctionPointer();
520306f32e7eSjoerg llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
520406f32e7eSjoerg llvm::Value *TypeTest = Builder.CreateCall(
520506f32e7eSjoerg CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
520606f32e7eSjoerg
520706f32e7eSjoerg auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
520806f32e7eSjoerg llvm::Constant *StaticData[] = {
520906f32e7eSjoerg llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
521006f32e7eSjoerg EmitCheckSourceLocation(E->getBeginLoc()),
521106f32e7eSjoerg EmitCheckTypeDescriptor(QualType(FnType, 0)),
521206f32e7eSjoerg };
521306f32e7eSjoerg if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
521406f32e7eSjoerg EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
521506f32e7eSjoerg CastedCallee, StaticData);
521606f32e7eSjoerg } else {
521706f32e7eSjoerg EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
521806f32e7eSjoerg SanitizerHandler::CFICheckFail, StaticData,
521906f32e7eSjoerg {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
522006f32e7eSjoerg }
522106f32e7eSjoerg }
522206f32e7eSjoerg
522306f32e7eSjoerg CallArgList Args;
522406f32e7eSjoerg if (Chain)
522506f32e7eSjoerg Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
522606f32e7eSjoerg CGM.getContext().VoidPtrTy);
522706f32e7eSjoerg
522806f32e7eSjoerg // C++17 requires that we evaluate arguments to a call using assignment syntax
522906f32e7eSjoerg // right-to-left, and that we evaluate arguments to certain other operators
523006f32e7eSjoerg // left-to-right. Note that we allow this to override the order dictated by
523106f32e7eSjoerg // the calling convention on the MS ABI, which means that parameter
523206f32e7eSjoerg // destruction order is not necessarily reverse construction order.
523306f32e7eSjoerg // FIXME: Revisit this based on C++ committee response to unimplementability.
523406f32e7eSjoerg EvaluationOrder Order = EvaluationOrder::Default;
523506f32e7eSjoerg if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
523606f32e7eSjoerg if (OCE->isAssignmentOp())
523706f32e7eSjoerg Order = EvaluationOrder::ForceRightToLeft;
523806f32e7eSjoerg else {
523906f32e7eSjoerg switch (OCE->getOperator()) {
524006f32e7eSjoerg case OO_LessLess:
524106f32e7eSjoerg case OO_GreaterGreater:
524206f32e7eSjoerg case OO_AmpAmp:
524306f32e7eSjoerg case OO_PipePipe:
524406f32e7eSjoerg case OO_Comma:
524506f32e7eSjoerg case OO_ArrowStar:
524606f32e7eSjoerg Order = EvaluationOrder::ForceLeftToRight;
524706f32e7eSjoerg break;
524806f32e7eSjoerg default:
524906f32e7eSjoerg break;
525006f32e7eSjoerg }
525106f32e7eSjoerg }
525206f32e7eSjoerg }
525306f32e7eSjoerg
525406f32e7eSjoerg EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
525506f32e7eSjoerg E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
525606f32e7eSjoerg
525706f32e7eSjoerg const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
525806f32e7eSjoerg Args, FnType, /*ChainCall=*/Chain);
525906f32e7eSjoerg
526006f32e7eSjoerg // C99 6.5.2.2p6:
526106f32e7eSjoerg // If the expression that denotes the called function has a type
526206f32e7eSjoerg // that does not include a prototype, [the default argument
526306f32e7eSjoerg // promotions are performed]. If the number of arguments does not
526406f32e7eSjoerg // equal the number of parameters, the behavior is undefined. If
526506f32e7eSjoerg // the function is defined with a type that includes a prototype,
526606f32e7eSjoerg // and either the prototype ends with an ellipsis (, ...) or the
526706f32e7eSjoerg // types of the arguments after promotion are not compatible with
526806f32e7eSjoerg // the types of the parameters, the behavior is undefined. If the
526906f32e7eSjoerg // function is defined with a type that does not include a
527006f32e7eSjoerg // prototype, and the types of the arguments after promotion are
527106f32e7eSjoerg // not compatible with those of the parameters after promotion,
527206f32e7eSjoerg // the behavior is undefined [except in some trivial cases].
527306f32e7eSjoerg // That is, in the general case, we should assume that a call
527406f32e7eSjoerg // through an unprototyped function type works like a *non-variadic*
527506f32e7eSjoerg // call. The way we make this work is to cast to the exact type
527606f32e7eSjoerg // of the promoted arguments.
527706f32e7eSjoerg //
527806f32e7eSjoerg // Chain calls use this same code path to add the invisible chain parameter
527906f32e7eSjoerg // to the function type.
528006f32e7eSjoerg if (isa<FunctionNoProtoType>(FnType) || Chain) {
528106f32e7eSjoerg llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
5282*13fbcb42Sjoerg int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
5283*13fbcb42Sjoerg CalleeTy = CalleeTy->getPointerTo(AS);
528406f32e7eSjoerg
528506f32e7eSjoerg llvm::Value *CalleePtr = Callee.getFunctionPointer();
528606f32e7eSjoerg CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
528706f32e7eSjoerg Callee.setFunctionPointer(CalleePtr);
528806f32e7eSjoerg }
528906f32e7eSjoerg
5290*13fbcb42Sjoerg // HIP function pointer contains kernel handle when it is used in triple
5291*13fbcb42Sjoerg // chevron. The kernel stub needs to be loaded from kernel handle and used
5292*13fbcb42Sjoerg // as callee.
5293*13fbcb42Sjoerg if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
5294*13fbcb42Sjoerg isa<CUDAKernelCallExpr>(E) &&
5295*13fbcb42Sjoerg (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5296*13fbcb42Sjoerg llvm::Value *Handle = Callee.getFunctionPointer();
5297*13fbcb42Sjoerg auto *Cast =
5298*13fbcb42Sjoerg Builder.CreateBitCast(Handle, Handle->getType()->getPointerTo());
5299*13fbcb42Sjoerg auto *Stub = Builder.CreateLoad(Address(Cast, CGM.getPointerAlign()));
5300*13fbcb42Sjoerg Callee.setFunctionPointer(Stub);
5301*13fbcb42Sjoerg }
530206f32e7eSjoerg llvm::CallBase *CallOrInvoke = nullptr;
530306f32e7eSjoerg RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
5304*13fbcb42Sjoerg E == MustTailCall, E->getExprLoc());
530506f32e7eSjoerg
530606f32e7eSjoerg // Generate function declaration DISuprogram in order to be used
530706f32e7eSjoerg // in debug info about call sites.
530806f32e7eSjoerg if (CGDebugInfo *DI = getDebugInfo()) {
530906f32e7eSjoerg if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl))
531006f32e7eSjoerg DI->EmitFuncDeclForCallSite(CallOrInvoke, QualType(FnType, 0),
531106f32e7eSjoerg CalleeDecl);
531206f32e7eSjoerg }
531306f32e7eSjoerg
531406f32e7eSjoerg return Call;
531506f32e7eSjoerg }
531606f32e7eSjoerg
531706f32e7eSjoerg LValue CodeGenFunction::
EmitPointerToDataMemberBinaryExpr(const BinaryOperator * E)531806f32e7eSjoerg EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
531906f32e7eSjoerg Address BaseAddr = Address::invalid();
532006f32e7eSjoerg if (E->getOpcode() == BO_PtrMemI) {
532106f32e7eSjoerg BaseAddr = EmitPointerWithAlignment(E->getLHS());
532206f32e7eSjoerg } else {
5323*13fbcb42Sjoerg BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
532406f32e7eSjoerg }
532506f32e7eSjoerg
532606f32e7eSjoerg llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
5327*13fbcb42Sjoerg const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
532806f32e7eSjoerg
532906f32e7eSjoerg LValueBaseInfo BaseInfo;
533006f32e7eSjoerg TBAAAccessInfo TBAAInfo;
533106f32e7eSjoerg Address MemberAddr =
533206f32e7eSjoerg EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
533306f32e7eSjoerg &TBAAInfo);
533406f32e7eSjoerg
533506f32e7eSjoerg return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
533606f32e7eSjoerg }
533706f32e7eSjoerg
533806f32e7eSjoerg /// Given the address of a temporary variable, produce an r-value of
533906f32e7eSjoerg /// its type.
convertTempToRValue(Address addr,QualType type,SourceLocation loc)534006f32e7eSjoerg RValue CodeGenFunction::convertTempToRValue(Address addr,
534106f32e7eSjoerg QualType type,
534206f32e7eSjoerg SourceLocation loc) {
534306f32e7eSjoerg LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
534406f32e7eSjoerg switch (getEvaluationKind(type)) {
534506f32e7eSjoerg case TEK_Complex:
534606f32e7eSjoerg return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
534706f32e7eSjoerg case TEK_Aggregate:
5348*13fbcb42Sjoerg return lvalue.asAggregateRValue(*this);
534906f32e7eSjoerg case TEK_Scalar:
535006f32e7eSjoerg return RValue::get(EmitLoadOfScalar(lvalue, loc));
535106f32e7eSjoerg }
535206f32e7eSjoerg llvm_unreachable("bad evaluation kind");
535306f32e7eSjoerg }
535406f32e7eSjoerg
SetFPAccuracy(llvm::Value * Val,float Accuracy)535506f32e7eSjoerg void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
535606f32e7eSjoerg assert(Val->getType()->isFPOrFPVectorTy());
535706f32e7eSjoerg if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
535806f32e7eSjoerg return;
535906f32e7eSjoerg
536006f32e7eSjoerg llvm::MDBuilder MDHelper(getLLVMContext());
536106f32e7eSjoerg llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
536206f32e7eSjoerg
536306f32e7eSjoerg cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
536406f32e7eSjoerg }
536506f32e7eSjoerg
536606f32e7eSjoerg namespace {
536706f32e7eSjoerg struct LValueOrRValue {
536806f32e7eSjoerg LValue LV;
536906f32e7eSjoerg RValue RV;
537006f32e7eSjoerg };
537106f32e7eSjoerg }
537206f32e7eSjoerg
emitPseudoObjectExpr(CodeGenFunction & CGF,const PseudoObjectExpr * E,bool forLValue,AggValueSlot slot)537306f32e7eSjoerg static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
537406f32e7eSjoerg const PseudoObjectExpr *E,
537506f32e7eSjoerg bool forLValue,
537606f32e7eSjoerg AggValueSlot slot) {
537706f32e7eSjoerg SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
537806f32e7eSjoerg
537906f32e7eSjoerg // Find the result expression, if any.
538006f32e7eSjoerg const Expr *resultExpr = E->getResultExpr();
538106f32e7eSjoerg LValueOrRValue result;
538206f32e7eSjoerg
538306f32e7eSjoerg for (PseudoObjectExpr::const_semantics_iterator
538406f32e7eSjoerg i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
538506f32e7eSjoerg const Expr *semantic = *i;
538606f32e7eSjoerg
538706f32e7eSjoerg // If this semantic expression is an opaque value, bind it
538806f32e7eSjoerg // to the result of its source expression.
538906f32e7eSjoerg if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
539006f32e7eSjoerg // Skip unique OVEs.
539106f32e7eSjoerg if (ov->isUnique()) {
539206f32e7eSjoerg assert(ov != resultExpr &&
539306f32e7eSjoerg "A unique OVE cannot be used as the result expression");
539406f32e7eSjoerg continue;
539506f32e7eSjoerg }
539606f32e7eSjoerg
539706f32e7eSjoerg // If this is the result expression, we may need to evaluate
539806f32e7eSjoerg // directly into the slot.
539906f32e7eSjoerg typedef CodeGenFunction::OpaqueValueMappingData OVMA;
540006f32e7eSjoerg OVMA opaqueData;
540106f32e7eSjoerg if (ov == resultExpr && ov->isRValue() && !forLValue &&
540206f32e7eSjoerg CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
540306f32e7eSjoerg CGF.EmitAggExpr(ov->getSourceExpr(), slot);
540406f32e7eSjoerg LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
540506f32e7eSjoerg AlignmentSource::Decl);
540606f32e7eSjoerg opaqueData = OVMA::bind(CGF, ov, LV);
540706f32e7eSjoerg result.RV = slot.asRValue();
540806f32e7eSjoerg
540906f32e7eSjoerg // Otherwise, emit as normal.
541006f32e7eSjoerg } else {
541106f32e7eSjoerg opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
541206f32e7eSjoerg
541306f32e7eSjoerg // If this is the result, also evaluate the result now.
541406f32e7eSjoerg if (ov == resultExpr) {
541506f32e7eSjoerg if (forLValue)
541606f32e7eSjoerg result.LV = CGF.EmitLValue(ov);
541706f32e7eSjoerg else
541806f32e7eSjoerg result.RV = CGF.EmitAnyExpr(ov, slot);
541906f32e7eSjoerg }
542006f32e7eSjoerg }
542106f32e7eSjoerg
542206f32e7eSjoerg opaques.push_back(opaqueData);
542306f32e7eSjoerg
542406f32e7eSjoerg // Otherwise, if the expression is the result, evaluate it
542506f32e7eSjoerg // and remember the result.
542606f32e7eSjoerg } else if (semantic == resultExpr) {
542706f32e7eSjoerg if (forLValue)
542806f32e7eSjoerg result.LV = CGF.EmitLValue(semantic);
542906f32e7eSjoerg else
543006f32e7eSjoerg result.RV = CGF.EmitAnyExpr(semantic, slot);
543106f32e7eSjoerg
543206f32e7eSjoerg // Otherwise, evaluate the expression in an ignored context.
543306f32e7eSjoerg } else {
543406f32e7eSjoerg CGF.EmitIgnoredExpr(semantic);
543506f32e7eSjoerg }
543606f32e7eSjoerg }
543706f32e7eSjoerg
543806f32e7eSjoerg // Unbind all the opaques now.
543906f32e7eSjoerg for (unsigned i = 0, e = opaques.size(); i != e; ++i)
544006f32e7eSjoerg opaques[i].unbind(CGF);
544106f32e7eSjoerg
544206f32e7eSjoerg return result;
544306f32e7eSjoerg }
544406f32e7eSjoerg
EmitPseudoObjectRValue(const PseudoObjectExpr * E,AggValueSlot slot)544506f32e7eSjoerg RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
544606f32e7eSjoerg AggValueSlot slot) {
544706f32e7eSjoerg return emitPseudoObjectExpr(*this, E, false, slot).RV;
544806f32e7eSjoerg }
544906f32e7eSjoerg
EmitPseudoObjectLValue(const PseudoObjectExpr * E)545006f32e7eSjoerg LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
545106f32e7eSjoerg return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
545206f32e7eSjoerg }
5453