10b57cec5SDimitry Andric //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This contains code to emit Expr nodes as LLVM code.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
13*5f7ddb14SDimitry Andric #include "CGCUDARuntime.h"
140b57cec5SDimitry Andric #include "CGCXXABI.h"
150b57cec5SDimitry Andric #include "CGCall.h"
160b57cec5SDimitry Andric #include "CGCleanup.h"
170b57cec5SDimitry Andric #include "CGDebugInfo.h"
180b57cec5SDimitry Andric #include "CGObjCRuntime.h"
190b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
200b57cec5SDimitry Andric #include "CGRecordLayout.h"
210b57cec5SDimitry Andric #include "CodeGenFunction.h"
220b57cec5SDimitry Andric #include "CodeGenModule.h"
230b57cec5SDimitry Andric #include "ConstantEmitter.h"
240b57cec5SDimitry Andric #include "TargetInfo.h"
250b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
260b57cec5SDimitry Andric #include "clang/AST/Attr.h"
270b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
280b57cec5SDimitry Andric #include "clang/AST/NSAPI.h"
290b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
300b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
315ffd83dbSDimitry Andric #include "clang/Basic/SourceManager.h"
320b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
330b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
340b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
350b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
360b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
370b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
380b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
390b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
400b57cec5SDimitry Andric #include "llvm/Support/Path.h"
41*5f7ddb14SDimitry Andric #include "llvm/Support/SaveAndRestore.h"
420b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SanitizerStats.h"
430b57cec5SDimitry Andric
440b57cec5SDimitry Andric #include <string>
450b57cec5SDimitry Andric
460b57cec5SDimitry Andric using namespace clang;
470b57cec5SDimitry Andric using namespace CodeGen;
480b57cec5SDimitry Andric
490b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
500b57cec5SDimitry Andric // Miscellaneous Helper Methods
510b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
520b57cec5SDimitry Andric
EmitCastToVoidPtr(llvm::Value * value)530b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
540b57cec5SDimitry Andric unsigned addressSpace =
550b57cec5SDimitry Andric cast<llvm::PointerType>(value->getType())->getAddressSpace();
560b57cec5SDimitry Andric
570b57cec5SDimitry Andric llvm::PointerType *destType = Int8PtrTy;
580b57cec5SDimitry Andric if (addressSpace)
590b57cec5SDimitry Andric destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
600b57cec5SDimitry Andric
610b57cec5SDimitry Andric if (value->getType() == destType) return value;
620b57cec5SDimitry Andric return Builder.CreateBitCast(value, destType);
630b57cec5SDimitry Andric }
640b57cec5SDimitry Andric
650b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry
660b57cec5SDimitry Andric /// block.
CreateTempAllocaWithoutCast(llvm::Type * Ty,CharUnits Align,const Twine & Name,llvm::Value * ArraySize)670b57cec5SDimitry Andric Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
680b57cec5SDimitry Andric CharUnits Align,
690b57cec5SDimitry Andric const Twine &Name,
700b57cec5SDimitry Andric llvm::Value *ArraySize) {
710b57cec5SDimitry Andric auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
72a7dea167SDimitry Andric Alloca->setAlignment(Align.getAsAlign());
730b57cec5SDimitry Andric return Address(Alloca, Align);
740b57cec5SDimitry Andric }
750b57cec5SDimitry Andric
760b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry
770b57cec5SDimitry Andric /// 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)780b57cec5SDimitry Andric Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
790b57cec5SDimitry Andric const Twine &Name,
800b57cec5SDimitry Andric llvm::Value *ArraySize,
810b57cec5SDimitry Andric Address *AllocaAddr) {
820b57cec5SDimitry Andric auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
830b57cec5SDimitry Andric if (AllocaAddr)
840b57cec5SDimitry Andric *AllocaAddr = Alloca;
850b57cec5SDimitry Andric llvm::Value *V = Alloca.getPointer();
860b57cec5SDimitry Andric // Alloca always returns a pointer in alloca address space, which may
870b57cec5SDimitry Andric // be different from the type defined by the language. For example,
880b57cec5SDimitry Andric // in C++ the auto variables are in the default address space. Therefore
890b57cec5SDimitry Andric // cast alloca to the default address space when necessary.
900b57cec5SDimitry Andric if (getASTAllocaAddressSpace() != LangAS::Default) {
910b57cec5SDimitry Andric auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
920b57cec5SDimitry Andric llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
930b57cec5SDimitry Andric // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
940b57cec5SDimitry Andric // otherwise alloca is inserted at the current insertion point of the
950b57cec5SDimitry Andric // builder.
960b57cec5SDimitry Andric if (!ArraySize)
970b57cec5SDimitry Andric Builder.SetInsertPoint(AllocaInsertPt);
980b57cec5SDimitry Andric V = getTargetHooks().performAddrSpaceCast(
990b57cec5SDimitry Andric *this, V, getASTAllocaAddressSpace(), LangAS::Default,
1000b57cec5SDimitry Andric Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
1010b57cec5SDimitry Andric }
1020b57cec5SDimitry Andric
1030b57cec5SDimitry Andric return Address(V, Align);
1040b57cec5SDimitry Andric }
1050b57cec5SDimitry Andric
1060b57cec5SDimitry Andric /// CreateTempAlloca - This creates an alloca and inserts it into the entry
1070b57cec5SDimitry Andric /// block if \p ArraySize is nullptr, otherwise inserts it at the current
1080b57cec5SDimitry Andric /// insertion point of the builder.
CreateTempAlloca(llvm::Type * Ty,const Twine & Name,llvm::Value * ArraySize)1090b57cec5SDimitry Andric llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
1100b57cec5SDimitry Andric const Twine &Name,
1110b57cec5SDimitry Andric llvm::Value *ArraySize) {
1120b57cec5SDimitry Andric if (ArraySize)
1130b57cec5SDimitry Andric return Builder.CreateAlloca(Ty, ArraySize, Name);
1140b57cec5SDimitry Andric return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
1150b57cec5SDimitry Andric ArraySize, Name, AllocaInsertPt);
1160b57cec5SDimitry Andric }
1170b57cec5SDimitry Andric
1180b57cec5SDimitry Andric /// CreateDefaultAlignTempAlloca - This creates an alloca with the
1190b57cec5SDimitry Andric /// default alignment of the corresponding LLVM type, which is *not*
1200b57cec5SDimitry Andric /// guaranteed to be related in any way to the expected alignment of
1210b57cec5SDimitry Andric /// an AST type that might have been lowered to Ty.
CreateDefaultAlignTempAlloca(llvm::Type * Ty,const Twine & Name)1220b57cec5SDimitry Andric Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1230b57cec5SDimitry Andric const Twine &Name) {
1240b57cec5SDimitry Andric CharUnits Align =
1250b57cec5SDimitry Andric CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
1260b57cec5SDimitry Andric return CreateTempAlloca(Ty, Align, Name);
1270b57cec5SDimitry Andric }
1280b57cec5SDimitry Andric
InitTempAlloca(Address Var,llvm::Value * Init)1290b57cec5SDimitry Andric void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
130af732203SDimitry Andric auto *Alloca = Var.getPointer();
131af732203SDimitry Andric assert(isa<llvm::AllocaInst>(Alloca) ||
132af732203SDimitry Andric (isa<llvm::AddrSpaceCastInst>(Alloca) &&
133af732203SDimitry Andric isa<llvm::AllocaInst>(
134af732203SDimitry Andric cast<llvm::AddrSpaceCastInst>(Alloca)->getPointerOperand())));
135af732203SDimitry Andric
136af732203SDimitry Andric auto *Store = new llvm::StoreInst(Init, Alloca, /*volatile*/ false,
1375ffd83dbSDimitry Andric Var.getAlignment().getAsAlign());
1380b57cec5SDimitry Andric llvm::BasicBlock *Block = AllocaInsertPt->getParent();
1390b57cec5SDimitry Andric Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric
CreateIRTemp(QualType Ty,const Twine & Name)1420b57cec5SDimitry Andric Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
1430b57cec5SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(Ty);
1440b57cec5SDimitry Andric return CreateTempAlloca(ConvertType(Ty), Align, Name);
1450b57cec5SDimitry Andric }
1460b57cec5SDimitry Andric
CreateMemTemp(QualType Ty,const Twine & Name,Address * Alloca)1470b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
1480b57cec5SDimitry Andric Address *Alloca) {
1490b57cec5SDimitry Andric // FIXME: Should we prefer the preferred type alignment here?
1500b57cec5SDimitry Andric return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
1510b57cec5SDimitry Andric }
1520b57cec5SDimitry Andric
CreateMemTemp(QualType Ty,CharUnits Align,const Twine & Name,Address * Alloca)1530b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
1540b57cec5SDimitry Andric const Twine &Name, Address *Alloca) {
1555ffd83dbSDimitry Andric Address Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
1560b57cec5SDimitry Andric /*ArraySize=*/nullptr, Alloca);
1575ffd83dbSDimitry Andric
1585ffd83dbSDimitry Andric if (Ty->isConstantMatrixType()) {
1595ffd83dbSDimitry Andric auto *ArrayTy = cast<llvm::ArrayType>(Result.getType()->getElementType());
1605ffd83dbSDimitry Andric auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
1615ffd83dbSDimitry Andric ArrayTy->getNumElements());
1625ffd83dbSDimitry Andric
1635ffd83dbSDimitry Andric Result = Address(
1645ffd83dbSDimitry Andric Builder.CreateBitCast(Result.getPointer(), VectorTy->getPointerTo()),
1655ffd83dbSDimitry Andric Result.getAlignment());
1665ffd83dbSDimitry Andric }
1675ffd83dbSDimitry Andric return Result;
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric
CreateMemTempWithoutCast(QualType Ty,CharUnits Align,const Twine & Name)1700b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
1710b57cec5SDimitry Andric const Twine &Name) {
1720b57cec5SDimitry Andric return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric
CreateMemTempWithoutCast(QualType Ty,const Twine & Name)1750b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
1760b57cec5SDimitry Andric const Twine &Name) {
1770b57cec5SDimitry Andric return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
1780b57cec5SDimitry Andric Name);
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric
1810b57cec5SDimitry Andric /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1820b57cec5SDimitry Andric /// expression and compare the result against zero, returning an Int1Ty value.
EvaluateExprAsBool(const Expr * E)1830b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
1840b57cec5SDimitry Andric PGO.setCurrentStmt(E);
1850b57cec5SDimitry Andric if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
1860b57cec5SDimitry Andric llvm::Value *MemPtr = EmitScalarExpr(E);
1870b57cec5SDimitry Andric return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
1880b57cec5SDimitry Andric }
1890b57cec5SDimitry Andric
1900b57cec5SDimitry Andric QualType BoolTy = getContext().BoolTy;
1910b57cec5SDimitry Andric SourceLocation Loc = E->getExprLoc();
192af732203SDimitry Andric CGFPOptionsRAII FPOptsRAII(*this, E);
1930b57cec5SDimitry Andric if (!E->getType()->isAnyComplexType())
1940b57cec5SDimitry Andric return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
1950b57cec5SDimitry Andric
1960b57cec5SDimitry Andric return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
1970b57cec5SDimitry Andric Loc);
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric
2000b57cec5SDimitry Andric /// EmitIgnoredExpr - Emit code to compute the specified expression,
2010b57cec5SDimitry Andric /// ignoring the result.
EmitIgnoredExpr(const Expr * E)2020b57cec5SDimitry Andric void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
203*5f7ddb14SDimitry Andric if (E->isPRValue())
2040b57cec5SDimitry Andric return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
2050b57cec5SDimitry Andric
2060b57cec5SDimitry Andric // Just emit it as an l-value and drop the result.
2070b57cec5SDimitry Andric EmitLValue(E);
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric
2100b57cec5SDimitry Andric /// EmitAnyExpr - Emit code to compute the specified expression which
2110b57cec5SDimitry Andric /// can have any type. The result is returned as an RValue struct.
2120b57cec5SDimitry Andric /// If this is an aggregate expression, AggSlot indicates where the
2130b57cec5SDimitry Andric /// result should be returned.
EmitAnyExpr(const Expr * E,AggValueSlot aggSlot,bool ignoreResult)2140b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
2150b57cec5SDimitry Andric AggValueSlot aggSlot,
2160b57cec5SDimitry Andric bool ignoreResult) {
2170b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) {
2180b57cec5SDimitry Andric case TEK_Scalar:
2190b57cec5SDimitry Andric return RValue::get(EmitScalarExpr(E, ignoreResult));
2200b57cec5SDimitry Andric case TEK_Complex:
2210b57cec5SDimitry Andric return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
2220b57cec5SDimitry Andric case TEK_Aggregate:
2230b57cec5SDimitry Andric if (!ignoreResult && aggSlot.isIgnored())
2240b57cec5SDimitry Andric aggSlot = CreateAggTemp(E->getType(), "agg-temp");
2250b57cec5SDimitry Andric EmitAggExpr(E, aggSlot);
2260b57cec5SDimitry Andric return aggSlot.asRValue();
2270b57cec5SDimitry Andric }
2280b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric
2310b57cec5SDimitry Andric /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
2320b57cec5SDimitry Andric /// always be accessible even if no aggregate location is provided.
EmitAnyExprToTemp(const Expr * E)2330b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
2340b57cec5SDimitry Andric AggValueSlot AggSlot = AggValueSlot::ignored();
2350b57cec5SDimitry Andric
2360b57cec5SDimitry Andric if (hasAggregateEvaluationKind(E->getType()))
2370b57cec5SDimitry Andric AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
2380b57cec5SDimitry Andric return EmitAnyExpr(E, AggSlot);
2390b57cec5SDimitry Andric }
2400b57cec5SDimitry Andric
2410b57cec5SDimitry Andric /// EmitAnyExprToMem - Evaluate an expression into a given memory
2420b57cec5SDimitry Andric /// location.
EmitAnyExprToMem(const Expr * E,Address Location,Qualifiers Quals,bool IsInit)2430b57cec5SDimitry Andric void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
2440b57cec5SDimitry Andric Address Location,
2450b57cec5SDimitry Andric Qualifiers Quals,
2460b57cec5SDimitry Andric bool IsInit) {
2470b57cec5SDimitry Andric // FIXME: This function should take an LValue as an argument.
2480b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) {
2490b57cec5SDimitry Andric case TEK_Complex:
2500b57cec5SDimitry Andric EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
2510b57cec5SDimitry Andric /*isInit*/ false);
2520b57cec5SDimitry Andric return;
2530b57cec5SDimitry Andric
2540b57cec5SDimitry Andric case TEK_Aggregate: {
2550b57cec5SDimitry Andric EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
2560b57cec5SDimitry Andric AggValueSlot::IsDestructed_t(IsInit),
2570b57cec5SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
2580b57cec5SDimitry Andric AggValueSlot::IsAliased_t(!IsInit),
2590b57cec5SDimitry Andric AggValueSlot::MayOverlap));
2600b57cec5SDimitry Andric return;
2610b57cec5SDimitry Andric }
2620b57cec5SDimitry Andric
2630b57cec5SDimitry Andric case TEK_Scalar: {
2640b57cec5SDimitry Andric RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
2650b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Location, E->getType());
2660b57cec5SDimitry Andric EmitStoreThroughLValue(RV, LV);
2670b57cec5SDimitry Andric return;
2680b57cec5SDimitry Andric }
2690b57cec5SDimitry Andric }
2700b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
2710b57cec5SDimitry Andric }
2720b57cec5SDimitry Andric
2730b57cec5SDimitry Andric static void
pushTemporaryCleanup(CodeGenFunction & CGF,const MaterializeTemporaryExpr * M,const Expr * E,Address ReferenceTemporary)2740b57cec5SDimitry Andric pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
2750b57cec5SDimitry Andric const Expr *E, Address ReferenceTemporary) {
2760b57cec5SDimitry Andric // Objective-C++ ARC:
2770b57cec5SDimitry Andric // If we are binding a reference to a temporary that has ownership, we
2780b57cec5SDimitry Andric // need to perform retain/release operations on the temporary.
2790b57cec5SDimitry Andric //
2800b57cec5SDimitry Andric // FIXME: This should be looking at E, not M.
2810b57cec5SDimitry Andric if (auto Lifetime = M->getType().getObjCLifetime()) {
2820b57cec5SDimitry Andric switch (Lifetime) {
2830b57cec5SDimitry Andric case Qualifiers::OCL_None:
2840b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone:
2850b57cec5SDimitry Andric // Carry on to normal cleanup handling.
2860b57cec5SDimitry Andric break;
2870b57cec5SDimitry Andric
2880b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing:
2890b57cec5SDimitry Andric // Nothing to do; cleaned up by an autorelease pool.
2900b57cec5SDimitry Andric return;
2910b57cec5SDimitry Andric
2920b57cec5SDimitry Andric case Qualifiers::OCL_Strong:
2930b57cec5SDimitry Andric case Qualifiers::OCL_Weak:
2940b57cec5SDimitry Andric switch (StorageDuration Duration = M->getStorageDuration()) {
2950b57cec5SDimitry Andric case SD_Static:
2960b57cec5SDimitry Andric // Note: we intentionally do not register a cleanup to release
2970b57cec5SDimitry Andric // the object on program termination.
2980b57cec5SDimitry Andric return;
2990b57cec5SDimitry Andric
3000b57cec5SDimitry Andric case SD_Thread:
3010b57cec5SDimitry Andric // FIXME: We should probably register a cleanup in this case.
3020b57cec5SDimitry Andric return;
3030b57cec5SDimitry Andric
3040b57cec5SDimitry Andric case SD_Automatic:
3050b57cec5SDimitry Andric case SD_FullExpression:
3060b57cec5SDimitry Andric CodeGenFunction::Destroyer *Destroy;
3070b57cec5SDimitry Andric CleanupKind CleanupKind;
3080b57cec5SDimitry Andric if (Lifetime == Qualifiers::OCL_Strong) {
3090b57cec5SDimitry Andric const ValueDecl *VD = M->getExtendingDecl();
3100b57cec5SDimitry Andric bool Precise =
3110b57cec5SDimitry Andric VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
3120b57cec5SDimitry Andric CleanupKind = CGF.getARCCleanupKind();
3130b57cec5SDimitry Andric Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
3140b57cec5SDimitry Andric : &CodeGenFunction::destroyARCStrongImprecise;
3150b57cec5SDimitry Andric } else {
3160b57cec5SDimitry Andric // __weak objects always get EH cleanups; otherwise, exceptions
3170b57cec5SDimitry Andric // could cause really nasty crashes instead of mere leaks.
3180b57cec5SDimitry Andric CleanupKind = NormalAndEHCleanup;
3190b57cec5SDimitry Andric Destroy = &CodeGenFunction::destroyARCWeak;
3200b57cec5SDimitry Andric }
3210b57cec5SDimitry Andric if (Duration == SD_FullExpression)
3220b57cec5SDimitry Andric CGF.pushDestroy(CleanupKind, ReferenceTemporary,
3230b57cec5SDimitry Andric M->getType(), *Destroy,
3240b57cec5SDimitry Andric CleanupKind & EHCleanup);
3250b57cec5SDimitry Andric else
3260b57cec5SDimitry Andric CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
3270b57cec5SDimitry Andric M->getType(),
3280b57cec5SDimitry Andric *Destroy, CleanupKind & EHCleanup);
3290b57cec5SDimitry Andric return;
3300b57cec5SDimitry Andric
3310b57cec5SDimitry Andric case SD_Dynamic:
3320b57cec5SDimitry Andric llvm_unreachable("temporary cannot have dynamic storage duration");
3330b57cec5SDimitry Andric }
3340b57cec5SDimitry Andric llvm_unreachable("unknown storage duration");
3350b57cec5SDimitry Andric }
3360b57cec5SDimitry Andric }
3370b57cec5SDimitry Andric
3380b57cec5SDimitry Andric CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
3390b57cec5SDimitry Andric if (const RecordType *RT =
3400b57cec5SDimitry Andric E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
3410b57cec5SDimitry Andric // Get the destructor for the reference temporary.
3420b57cec5SDimitry Andric auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3430b57cec5SDimitry Andric if (!ClassDecl->hasTrivialDestructor())
3440b57cec5SDimitry Andric ReferenceTemporaryDtor = ClassDecl->getDestructor();
3450b57cec5SDimitry Andric }
3460b57cec5SDimitry Andric
3470b57cec5SDimitry Andric if (!ReferenceTemporaryDtor)
3480b57cec5SDimitry Andric return;
3490b57cec5SDimitry Andric
3500b57cec5SDimitry Andric // Call the destructor for the temporary.
3510b57cec5SDimitry Andric switch (M->getStorageDuration()) {
3520b57cec5SDimitry Andric case SD_Static:
3530b57cec5SDimitry Andric case SD_Thread: {
3540b57cec5SDimitry Andric llvm::FunctionCallee CleanupFn;
3550b57cec5SDimitry Andric llvm::Constant *CleanupArg;
3560b57cec5SDimitry Andric if (E->getType()->isArrayType()) {
3570b57cec5SDimitry Andric CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
3580b57cec5SDimitry Andric ReferenceTemporary, E->getType(),
3590b57cec5SDimitry Andric CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
3600b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
3610b57cec5SDimitry Andric CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
3620b57cec5SDimitry Andric } else {
3630b57cec5SDimitry Andric CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
3640b57cec5SDimitry Andric GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
3650b57cec5SDimitry Andric CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
3660b57cec5SDimitry Andric }
3670b57cec5SDimitry Andric CGF.CGM.getCXXABI().registerGlobalDtor(
3680b57cec5SDimitry Andric CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
3690b57cec5SDimitry Andric break;
3700b57cec5SDimitry Andric }
3710b57cec5SDimitry Andric
3720b57cec5SDimitry Andric case SD_FullExpression:
3730b57cec5SDimitry Andric CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
3740b57cec5SDimitry Andric CodeGenFunction::destroyCXXObject,
3750b57cec5SDimitry Andric CGF.getLangOpts().Exceptions);
3760b57cec5SDimitry Andric break;
3770b57cec5SDimitry Andric
3780b57cec5SDimitry Andric case SD_Automatic:
3790b57cec5SDimitry Andric CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
3800b57cec5SDimitry Andric ReferenceTemporary, E->getType(),
3810b57cec5SDimitry Andric CodeGenFunction::destroyCXXObject,
3820b57cec5SDimitry Andric CGF.getLangOpts().Exceptions);
3830b57cec5SDimitry Andric break;
3840b57cec5SDimitry Andric
3850b57cec5SDimitry Andric case SD_Dynamic:
3860b57cec5SDimitry Andric llvm_unreachable("temporary cannot have dynamic storage duration");
3870b57cec5SDimitry Andric }
3880b57cec5SDimitry Andric }
3890b57cec5SDimitry Andric
createReferenceTemporary(CodeGenFunction & CGF,const MaterializeTemporaryExpr * M,const Expr * Inner,Address * Alloca=nullptr)3900b57cec5SDimitry Andric static Address createReferenceTemporary(CodeGenFunction &CGF,
3910b57cec5SDimitry Andric const MaterializeTemporaryExpr *M,
3920b57cec5SDimitry Andric const Expr *Inner,
3930b57cec5SDimitry Andric Address *Alloca = nullptr) {
3940b57cec5SDimitry Andric auto &TCG = CGF.getTargetHooks();
3950b57cec5SDimitry Andric switch (M->getStorageDuration()) {
3960b57cec5SDimitry Andric case SD_FullExpression:
3970b57cec5SDimitry Andric case SD_Automatic: {
3980b57cec5SDimitry Andric // If we have a constant temporary array or record try to promote it into a
3990b57cec5SDimitry Andric // constant global under the same rules a normal constant would've been
4000b57cec5SDimitry Andric // promoted. This is easier on the optimizer and generally emits fewer
4010b57cec5SDimitry Andric // instructions.
4020b57cec5SDimitry Andric QualType Ty = Inner->getType();
4030b57cec5SDimitry Andric if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
4040b57cec5SDimitry Andric (Ty->isArrayType() || Ty->isRecordType()) &&
4050b57cec5SDimitry Andric CGF.CGM.isTypeConstant(Ty, true))
4060b57cec5SDimitry Andric if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
407*5f7ddb14SDimitry Andric auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
4080b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable(
4090b57cec5SDimitry Andric CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
4100b57cec5SDimitry Andric llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
4110b57cec5SDimitry Andric llvm::GlobalValue::NotThreadLocal,
4120b57cec5SDimitry Andric CGF.getContext().getTargetAddressSpace(AS));
4130b57cec5SDimitry Andric CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
414a7dea167SDimitry Andric GV->setAlignment(alignment.getAsAlign());
4150b57cec5SDimitry Andric llvm::Constant *C = GV;
4160b57cec5SDimitry Andric if (AS != LangAS::Default)
4170b57cec5SDimitry Andric C = TCG.performAddrSpaceCast(
4180b57cec5SDimitry Andric CGF.CGM, GV, AS, LangAS::Default,
4190b57cec5SDimitry Andric GV->getValueType()->getPointerTo(
4200b57cec5SDimitry Andric CGF.getContext().getTargetAddressSpace(LangAS::Default)));
4210b57cec5SDimitry Andric // FIXME: Should we put the new global into a COMDAT?
4220b57cec5SDimitry Andric return Address(C, alignment);
4230b57cec5SDimitry Andric }
4240b57cec5SDimitry Andric return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
4250b57cec5SDimitry Andric }
4260b57cec5SDimitry Andric case SD_Thread:
4270b57cec5SDimitry Andric case SD_Static:
4280b57cec5SDimitry Andric return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
4290b57cec5SDimitry Andric
4300b57cec5SDimitry Andric case SD_Dynamic:
4310b57cec5SDimitry Andric llvm_unreachable("temporary can't have dynamic storage duration");
4320b57cec5SDimitry Andric }
4330b57cec5SDimitry Andric llvm_unreachable("unknown storage duration");
4340b57cec5SDimitry Andric }
4350b57cec5SDimitry Andric
4365ffd83dbSDimitry Andric /// Helper method to check if the underlying ABI is AAPCS
isAAPCS(const TargetInfo & TargetInfo)4375ffd83dbSDimitry Andric static bool isAAPCS(const TargetInfo &TargetInfo) {
4385ffd83dbSDimitry Andric return TargetInfo.getABI().startswith("aapcs");
4395ffd83dbSDimitry Andric }
4405ffd83dbSDimitry Andric
4410b57cec5SDimitry Andric LValue CodeGenFunction::
EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * M)4420b57cec5SDimitry Andric EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
443480093f4SDimitry Andric const Expr *E = M->getSubExpr();
4440b57cec5SDimitry Andric
4450b57cec5SDimitry Andric assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
4460b57cec5SDimitry Andric !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
4470b57cec5SDimitry Andric "Reference should never be pseudo-strong!");
4480b57cec5SDimitry Andric
4490b57cec5SDimitry Andric // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
4500b57cec5SDimitry Andric // as that will cause the lifetime adjustment to be lost for ARC
4510b57cec5SDimitry Andric auto ownership = M->getType().getObjCLifetime();
4520b57cec5SDimitry Andric if (ownership != Qualifiers::OCL_None &&
4530b57cec5SDimitry Andric ownership != Qualifiers::OCL_ExplicitNone) {
4540b57cec5SDimitry Andric Address Object = createReferenceTemporary(*this, M, E);
4550b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
4560b57cec5SDimitry Andric Object = Address(llvm::ConstantExpr::getBitCast(Var,
4570b57cec5SDimitry Andric ConvertTypeForMem(E->getType())
4580b57cec5SDimitry Andric ->getPointerTo(Object.getAddressSpace())),
4590b57cec5SDimitry Andric Object.getAlignment());
4600b57cec5SDimitry Andric
4610b57cec5SDimitry Andric // createReferenceTemporary will promote the temporary to a global with a
4620b57cec5SDimitry Andric // constant initializer if it can. It can only do this to a value of
4630b57cec5SDimitry Andric // ARC-manageable type if the value is global and therefore "immune" to
4640b57cec5SDimitry Andric // ref-counting operations. Therefore we have no need to emit either a
4650b57cec5SDimitry Andric // dynamic initialization or a cleanup and we can just return the address
4660b57cec5SDimitry Andric // of the temporary.
4670b57cec5SDimitry Andric if (Var->hasInitializer())
4680b57cec5SDimitry Andric return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
4690b57cec5SDimitry Andric
4700b57cec5SDimitry Andric Var->setInitializer(CGM.EmitNullConstant(E->getType()));
4710b57cec5SDimitry Andric }
4720b57cec5SDimitry Andric LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
4730b57cec5SDimitry Andric AlignmentSource::Decl);
4740b57cec5SDimitry Andric
4750b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) {
4760b57cec5SDimitry Andric default: llvm_unreachable("expected scalar or aggregate expression");
4770b57cec5SDimitry Andric case TEK_Scalar:
4780b57cec5SDimitry Andric EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
4790b57cec5SDimitry Andric break;
4800b57cec5SDimitry Andric case TEK_Aggregate: {
4810b57cec5SDimitry Andric EmitAggExpr(E, AggValueSlot::forAddr(Object,
4820b57cec5SDimitry Andric E->getType().getQualifiers(),
4830b57cec5SDimitry Andric AggValueSlot::IsDestructed,
4840b57cec5SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
4850b57cec5SDimitry Andric AggValueSlot::IsNotAliased,
4860b57cec5SDimitry Andric AggValueSlot::DoesNotOverlap));
4870b57cec5SDimitry Andric break;
4880b57cec5SDimitry Andric }
4890b57cec5SDimitry Andric }
4900b57cec5SDimitry Andric
4910b57cec5SDimitry Andric pushTemporaryCleanup(*this, M, E, Object);
4920b57cec5SDimitry Andric return RefTempDst;
4930b57cec5SDimitry Andric }
4940b57cec5SDimitry Andric
4950b57cec5SDimitry Andric SmallVector<const Expr *, 2> CommaLHSs;
4960b57cec5SDimitry Andric SmallVector<SubobjectAdjustment, 2> Adjustments;
4970b57cec5SDimitry Andric E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4980b57cec5SDimitry Andric
4990b57cec5SDimitry Andric for (const auto &Ignored : CommaLHSs)
5000b57cec5SDimitry Andric EmitIgnoredExpr(Ignored);
5010b57cec5SDimitry Andric
5020b57cec5SDimitry Andric if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
5030b57cec5SDimitry Andric if (opaque->getType()->isRecordType()) {
5040b57cec5SDimitry Andric assert(Adjustments.empty());
5050b57cec5SDimitry Andric return EmitOpaqueValueLValue(opaque);
5060b57cec5SDimitry Andric }
5070b57cec5SDimitry Andric }
5080b57cec5SDimitry Andric
5090b57cec5SDimitry Andric // Create and initialize the reference temporary.
5100b57cec5SDimitry Andric Address Alloca = Address::invalid();
5110b57cec5SDimitry Andric Address Object = createReferenceTemporary(*this, M, E, &Alloca);
5120b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>(
5130b57cec5SDimitry Andric Object.getPointer()->stripPointerCasts())) {
5140b57cec5SDimitry Andric Object = Address(llvm::ConstantExpr::getBitCast(
5150b57cec5SDimitry Andric cast<llvm::Constant>(Object.getPointer()),
5160b57cec5SDimitry Andric ConvertTypeForMem(E->getType())->getPointerTo()),
5170b57cec5SDimitry Andric Object.getAlignment());
5180b57cec5SDimitry Andric // If the temporary is a global and has a constant initializer or is a
5190b57cec5SDimitry Andric // constant temporary that we promoted to a global, we may have already
5200b57cec5SDimitry Andric // initialized it.
5210b57cec5SDimitry Andric if (!Var->hasInitializer()) {
5220b57cec5SDimitry Andric Var->setInitializer(CGM.EmitNullConstant(E->getType()));
5230b57cec5SDimitry Andric EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
5240b57cec5SDimitry Andric }
5250b57cec5SDimitry Andric } else {
5260b57cec5SDimitry Andric switch (M->getStorageDuration()) {
5270b57cec5SDimitry Andric case SD_Automatic:
5280b57cec5SDimitry Andric if (auto *Size = EmitLifetimeStart(
5290b57cec5SDimitry Andric CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
5300b57cec5SDimitry Andric Alloca.getPointer())) {
5310b57cec5SDimitry Andric pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
5320b57cec5SDimitry Andric Alloca, Size);
5330b57cec5SDimitry Andric }
5340b57cec5SDimitry Andric break;
5350b57cec5SDimitry Andric
5360b57cec5SDimitry Andric case SD_FullExpression: {
5370b57cec5SDimitry Andric if (!ShouldEmitLifetimeMarkers)
5380b57cec5SDimitry Andric break;
5390b57cec5SDimitry Andric
5400b57cec5SDimitry Andric // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
5410b57cec5SDimitry Andric // marker. Instead, start the lifetime of a conditional temporary earlier
542a7dea167SDimitry Andric // so that it's unconditional. Don't do this with sanitizers which need
543a7dea167SDimitry Andric // more precise lifetime marks.
5440b57cec5SDimitry Andric ConditionalEvaluation *OldConditional = nullptr;
5450b57cec5SDimitry Andric CGBuilderTy::InsertPoint OldIP;
5460b57cec5SDimitry Andric if (isInConditionalBranch() && !E->getType().isDestructedType() &&
547a7dea167SDimitry Andric !SanOpts.has(SanitizerKind::HWAddress) &&
548a7dea167SDimitry Andric !SanOpts.has(SanitizerKind::Memory) &&
5490b57cec5SDimitry Andric !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) {
5500b57cec5SDimitry Andric OldConditional = OutermostConditional;
5510b57cec5SDimitry Andric OutermostConditional = nullptr;
5520b57cec5SDimitry Andric
5530b57cec5SDimitry Andric OldIP = Builder.saveIP();
5540b57cec5SDimitry Andric llvm::BasicBlock *Block = OldConditional->getStartingBlock();
5550b57cec5SDimitry Andric Builder.restoreIP(CGBuilderTy::InsertPoint(
5560b57cec5SDimitry Andric Block, llvm::BasicBlock::iterator(Block->back())));
5570b57cec5SDimitry Andric }
5580b57cec5SDimitry Andric
5590b57cec5SDimitry Andric if (auto *Size = EmitLifetimeStart(
5600b57cec5SDimitry Andric CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
5610b57cec5SDimitry Andric Alloca.getPointer())) {
5620b57cec5SDimitry Andric pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
5630b57cec5SDimitry Andric Size);
5640b57cec5SDimitry Andric }
5650b57cec5SDimitry Andric
5660b57cec5SDimitry Andric if (OldConditional) {
5670b57cec5SDimitry Andric OutermostConditional = OldConditional;
5680b57cec5SDimitry Andric Builder.restoreIP(OldIP);
5690b57cec5SDimitry Andric }
5700b57cec5SDimitry Andric break;
5710b57cec5SDimitry Andric }
5720b57cec5SDimitry Andric
5730b57cec5SDimitry Andric default:
5740b57cec5SDimitry Andric break;
5750b57cec5SDimitry Andric }
5760b57cec5SDimitry Andric EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
5770b57cec5SDimitry Andric }
5780b57cec5SDimitry Andric pushTemporaryCleanup(*this, M, E, Object);
5790b57cec5SDimitry Andric
5800b57cec5SDimitry Andric // Perform derived-to-base casts and/or field accesses, to get from the
5810b57cec5SDimitry Andric // temporary object we created (and, potentially, for which we extended
5820b57cec5SDimitry Andric // the lifetime) to the subobject we're binding the reference to.
5830b57cec5SDimitry Andric for (unsigned I = Adjustments.size(); I != 0; --I) {
5840b57cec5SDimitry Andric SubobjectAdjustment &Adjustment = Adjustments[I-1];
5850b57cec5SDimitry Andric switch (Adjustment.Kind) {
5860b57cec5SDimitry Andric case SubobjectAdjustment::DerivedToBaseAdjustment:
5870b57cec5SDimitry Andric Object =
5880b57cec5SDimitry Andric GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
5890b57cec5SDimitry Andric Adjustment.DerivedToBase.BasePath->path_begin(),
5900b57cec5SDimitry Andric Adjustment.DerivedToBase.BasePath->path_end(),
5910b57cec5SDimitry Andric /*NullCheckValue=*/ false, E->getExprLoc());
5920b57cec5SDimitry Andric break;
5930b57cec5SDimitry Andric
5940b57cec5SDimitry Andric case SubobjectAdjustment::FieldAdjustment: {
5950b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
5960b57cec5SDimitry Andric LV = EmitLValueForField(LV, Adjustment.Field);
5970b57cec5SDimitry Andric assert(LV.isSimple() &&
5980b57cec5SDimitry Andric "materialized temporary field is not a simple lvalue");
599480093f4SDimitry Andric Object = LV.getAddress(*this);
6000b57cec5SDimitry Andric break;
6010b57cec5SDimitry Andric }
6020b57cec5SDimitry Andric
6030b57cec5SDimitry Andric case SubobjectAdjustment::MemberPointerAdjustment: {
6040b57cec5SDimitry Andric llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
6050b57cec5SDimitry Andric Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
6060b57cec5SDimitry Andric Adjustment.Ptr.MPT);
6070b57cec5SDimitry Andric break;
6080b57cec5SDimitry Andric }
6090b57cec5SDimitry Andric }
6100b57cec5SDimitry Andric }
6110b57cec5SDimitry Andric
6120b57cec5SDimitry Andric return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
6130b57cec5SDimitry Andric }
6140b57cec5SDimitry Andric
6150b57cec5SDimitry Andric RValue
EmitReferenceBindingToExpr(const Expr * E)6160b57cec5SDimitry Andric CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
6170b57cec5SDimitry Andric // Emit the expression as an lvalue.
6180b57cec5SDimitry Andric LValue LV = EmitLValue(E);
6190b57cec5SDimitry Andric assert(LV.isSimple());
620480093f4SDimitry Andric llvm::Value *Value = LV.getPointer(*this);
6210b57cec5SDimitry Andric
6220b57cec5SDimitry Andric if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
6230b57cec5SDimitry Andric // C++11 [dcl.ref]p5 (as amended by core issue 453):
6240b57cec5SDimitry Andric // If a glvalue to which a reference is directly bound designates neither
6250b57cec5SDimitry Andric // an existing object or function of an appropriate type nor a region of
6260b57cec5SDimitry Andric // storage of suitable size and alignment to contain an object of the
6270b57cec5SDimitry Andric // reference's type, the behavior is undefined.
6280b57cec5SDimitry Andric QualType Ty = E->getType();
6290b57cec5SDimitry Andric EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
6300b57cec5SDimitry Andric }
6310b57cec5SDimitry Andric
6320b57cec5SDimitry Andric return RValue::get(Value);
6330b57cec5SDimitry Andric }
6340b57cec5SDimitry Andric
6350b57cec5SDimitry Andric
6360b57cec5SDimitry Andric /// getAccessedFieldNo - Given an encoded value and a result number, return the
6370b57cec5SDimitry Andric /// input field number being accessed.
getAccessedFieldNo(unsigned Idx,const llvm::Constant * Elts)6380b57cec5SDimitry Andric unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
6390b57cec5SDimitry Andric const llvm::Constant *Elts) {
6400b57cec5SDimitry Andric return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
6410b57cec5SDimitry Andric ->getZExtValue();
6420b57cec5SDimitry Andric }
6430b57cec5SDimitry Andric
6440b57cec5SDimitry Andric /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
emitHash16Bytes(CGBuilderTy & Builder,llvm::Value * Low,llvm::Value * High)6450b57cec5SDimitry Andric static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
6460b57cec5SDimitry Andric llvm::Value *High) {
6470b57cec5SDimitry Andric llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
6480b57cec5SDimitry Andric llvm::Value *K47 = Builder.getInt64(47);
6490b57cec5SDimitry Andric llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
6500b57cec5SDimitry Andric llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
6510b57cec5SDimitry Andric llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
6520b57cec5SDimitry Andric llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
6530b57cec5SDimitry Andric return Builder.CreateMul(B1, KMul);
6540b57cec5SDimitry Andric }
6550b57cec5SDimitry Andric
isNullPointerAllowed(TypeCheckKind TCK)6560b57cec5SDimitry Andric bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
6570b57cec5SDimitry Andric return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
6580b57cec5SDimitry Andric TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
6590b57cec5SDimitry Andric }
6600b57cec5SDimitry Andric
isVptrCheckRequired(TypeCheckKind TCK,QualType Ty)6610b57cec5SDimitry Andric bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
6620b57cec5SDimitry Andric CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6630b57cec5SDimitry Andric return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
6640b57cec5SDimitry Andric (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
6650b57cec5SDimitry Andric TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
6660b57cec5SDimitry Andric TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
6670b57cec5SDimitry Andric }
6680b57cec5SDimitry Andric
sanitizePerformTypeCheck() const6690b57cec5SDimitry Andric bool CodeGenFunction::sanitizePerformTypeCheck() const {
6700b57cec5SDimitry Andric return SanOpts.has(SanitizerKind::Null) |
6710b57cec5SDimitry Andric SanOpts.has(SanitizerKind::Alignment) |
6720b57cec5SDimitry Andric SanOpts.has(SanitizerKind::ObjectSize) |
6730b57cec5SDimitry Andric SanOpts.has(SanitizerKind::Vptr);
6740b57cec5SDimitry Andric }
6750b57cec5SDimitry Andric
EmitTypeCheck(TypeCheckKind TCK,SourceLocation Loc,llvm::Value * Ptr,QualType Ty,CharUnits Alignment,SanitizerSet SkippedChecks,llvm::Value * ArraySize)6760b57cec5SDimitry Andric void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
6770b57cec5SDimitry Andric llvm::Value *Ptr, QualType Ty,
6780b57cec5SDimitry Andric CharUnits Alignment,
6790b57cec5SDimitry Andric SanitizerSet SkippedChecks,
6800b57cec5SDimitry Andric llvm::Value *ArraySize) {
6810b57cec5SDimitry Andric if (!sanitizePerformTypeCheck())
6820b57cec5SDimitry Andric return;
6830b57cec5SDimitry Andric
6840b57cec5SDimitry Andric // Don't check pointers outside the default address space. The null check
6850b57cec5SDimitry Andric // isn't correct, the object-size check isn't supported by LLVM, and we can't
6860b57cec5SDimitry Andric // communicate the addresses to the runtime handler for the vptr check.
6870b57cec5SDimitry Andric if (Ptr->getType()->getPointerAddressSpace())
6880b57cec5SDimitry Andric return;
6890b57cec5SDimitry Andric
6900b57cec5SDimitry Andric // Don't check pointers to volatile data. The behavior here is implementation-
6910b57cec5SDimitry Andric // defined.
6920b57cec5SDimitry Andric if (Ty.isVolatileQualified())
6930b57cec5SDimitry Andric return;
6940b57cec5SDimitry Andric
6950b57cec5SDimitry Andric SanitizerScope SanScope(this);
6960b57cec5SDimitry Andric
6970b57cec5SDimitry Andric SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
6980b57cec5SDimitry Andric llvm::BasicBlock *Done = nullptr;
6990b57cec5SDimitry Andric
7000b57cec5SDimitry Andric // Quickly determine whether we have a pointer to an alloca. It's possible
7010b57cec5SDimitry Andric // to skip null checks, and some alignment checks, for these pointers. This
7020b57cec5SDimitry Andric // can reduce compile-time significantly.
703a7dea167SDimitry Andric auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
7040b57cec5SDimitry Andric
7050b57cec5SDimitry Andric llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
7060b57cec5SDimitry Andric llvm::Value *IsNonNull = nullptr;
7070b57cec5SDimitry Andric bool IsGuaranteedNonNull =
7080b57cec5SDimitry Andric SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
7090b57cec5SDimitry Andric bool AllowNullPointers = isNullPointerAllowed(TCK);
7100b57cec5SDimitry Andric if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
7110b57cec5SDimitry Andric !IsGuaranteedNonNull) {
7120b57cec5SDimitry Andric // The glvalue must not be an empty glvalue.
7130b57cec5SDimitry Andric IsNonNull = Builder.CreateIsNotNull(Ptr);
7140b57cec5SDimitry Andric
7150b57cec5SDimitry Andric // The IR builder can constant-fold the null check if the pointer points to
7160b57cec5SDimitry Andric // a constant.
7170b57cec5SDimitry Andric IsGuaranteedNonNull = IsNonNull == True;
7180b57cec5SDimitry Andric
7190b57cec5SDimitry Andric // Skip the null check if the pointer is known to be non-null.
7200b57cec5SDimitry Andric if (!IsGuaranteedNonNull) {
7210b57cec5SDimitry Andric if (AllowNullPointers) {
7220b57cec5SDimitry Andric // When performing pointer casts, it's OK if the value is null.
7230b57cec5SDimitry Andric // Skip the remaining checks in that case.
7240b57cec5SDimitry Andric Done = createBasicBlock("null");
7250b57cec5SDimitry Andric llvm::BasicBlock *Rest = createBasicBlock("not.null");
7260b57cec5SDimitry Andric Builder.CreateCondBr(IsNonNull, Rest, Done);
7270b57cec5SDimitry Andric EmitBlock(Rest);
7280b57cec5SDimitry Andric } else {
7290b57cec5SDimitry Andric Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
7300b57cec5SDimitry Andric }
7310b57cec5SDimitry Andric }
7320b57cec5SDimitry Andric }
7330b57cec5SDimitry Andric
7340b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ObjectSize) &&
7350b57cec5SDimitry Andric !SkippedChecks.has(SanitizerKind::ObjectSize) &&
7360b57cec5SDimitry Andric !Ty->isIncompleteType()) {
7375ffd83dbSDimitry Andric uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
7380b57cec5SDimitry Andric llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
7390b57cec5SDimitry Andric if (ArraySize)
7400b57cec5SDimitry Andric Size = Builder.CreateMul(Size, ArraySize);
7410b57cec5SDimitry Andric
7420b57cec5SDimitry Andric // Degenerate case: new X[0] does not need an objectsize check.
7430b57cec5SDimitry Andric llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
7440b57cec5SDimitry Andric if (!ConstantSize || !ConstantSize->isNullValue()) {
7450b57cec5SDimitry Andric // The glvalue must refer to a large enough storage region.
7460b57cec5SDimitry Andric // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
7470b57cec5SDimitry Andric // to check this.
7480b57cec5SDimitry Andric // FIXME: Get object address space
7490b57cec5SDimitry Andric llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
7500b57cec5SDimitry Andric llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
7510b57cec5SDimitry Andric llvm::Value *Min = Builder.getFalse();
7520b57cec5SDimitry Andric llvm::Value *NullIsUnknown = Builder.getFalse();
7530b57cec5SDimitry Andric llvm::Value *Dynamic = Builder.getFalse();
7540b57cec5SDimitry Andric llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
7550b57cec5SDimitry Andric llvm::Value *LargeEnough = Builder.CreateICmpUGE(
7560b57cec5SDimitry Andric Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
7570b57cec5SDimitry Andric Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
7580b57cec5SDimitry Andric }
7590b57cec5SDimitry Andric }
7600b57cec5SDimitry Andric
7610b57cec5SDimitry Andric uint64_t AlignVal = 0;
7620b57cec5SDimitry Andric llvm::Value *PtrAsInt = nullptr;
7630b57cec5SDimitry Andric
7640b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Alignment) &&
7650b57cec5SDimitry Andric !SkippedChecks.has(SanitizerKind::Alignment)) {
7660b57cec5SDimitry Andric AlignVal = Alignment.getQuantity();
7670b57cec5SDimitry Andric if (!Ty->isIncompleteType() && !AlignVal)
7685ffd83dbSDimitry Andric AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
7695ffd83dbSDimitry Andric /*ForPointeeType=*/true)
7705ffd83dbSDimitry Andric .getQuantity();
7710b57cec5SDimitry Andric
7720b57cec5SDimitry Andric // The glvalue must be suitably aligned.
7730b57cec5SDimitry Andric if (AlignVal > 1 &&
7740b57cec5SDimitry Andric (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
7750b57cec5SDimitry Andric PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
7760b57cec5SDimitry Andric llvm::Value *Align = Builder.CreateAnd(
7770b57cec5SDimitry Andric PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
7780b57cec5SDimitry Andric llvm::Value *Aligned =
7790b57cec5SDimitry Andric Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
7800b57cec5SDimitry Andric if (Aligned != True)
7810b57cec5SDimitry Andric Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
7820b57cec5SDimitry Andric }
7830b57cec5SDimitry Andric }
7840b57cec5SDimitry Andric
7850b57cec5SDimitry Andric if (Checks.size() > 0) {
7860b57cec5SDimitry Andric // Make sure we're not losing information. Alignment needs to be a power of
7870b57cec5SDimitry Andric // 2
7880b57cec5SDimitry Andric assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
7890b57cec5SDimitry Andric llvm::Constant *StaticData[] = {
7900b57cec5SDimitry Andric EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
7910b57cec5SDimitry Andric llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
7920b57cec5SDimitry Andric llvm::ConstantInt::get(Int8Ty, TCK)};
7930b57cec5SDimitry Andric EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
7940b57cec5SDimitry Andric PtrAsInt ? PtrAsInt : Ptr);
7950b57cec5SDimitry Andric }
7960b57cec5SDimitry Andric
7970b57cec5SDimitry Andric // If possible, check that the vptr indicates that there is a subobject of
7980b57cec5SDimitry Andric // type Ty at offset zero within this object.
7990b57cec5SDimitry Andric //
8000b57cec5SDimitry Andric // C++11 [basic.life]p5,6:
8010b57cec5SDimitry Andric // [For storage which does not refer to an object within its lifetime]
8020b57cec5SDimitry Andric // The program has undefined behavior if:
8030b57cec5SDimitry Andric // -- the [pointer or glvalue] is used to access a non-static data member
8040b57cec5SDimitry Andric // or call a non-static member function
8050b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Vptr) &&
8060b57cec5SDimitry Andric !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
8070b57cec5SDimitry Andric // Ensure that the pointer is non-null before loading it. If there is no
8080b57cec5SDimitry Andric // compile-time guarantee, reuse the run-time null check or emit a new one.
8090b57cec5SDimitry Andric if (!IsGuaranteedNonNull) {
8100b57cec5SDimitry Andric if (!IsNonNull)
8110b57cec5SDimitry Andric IsNonNull = Builder.CreateIsNotNull(Ptr);
8120b57cec5SDimitry Andric if (!Done)
8130b57cec5SDimitry Andric Done = createBasicBlock("vptr.null");
8140b57cec5SDimitry Andric llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
8150b57cec5SDimitry Andric Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
8160b57cec5SDimitry Andric EmitBlock(VptrNotNull);
8170b57cec5SDimitry Andric }
8180b57cec5SDimitry Andric
8190b57cec5SDimitry Andric // Compute a hash of the mangled name of the type.
8200b57cec5SDimitry Andric //
8210b57cec5SDimitry Andric // FIXME: This is not guaranteed to be deterministic! Move to a
8220b57cec5SDimitry Andric // fingerprinting mechanism once LLVM provides one. For the time
8230b57cec5SDimitry Andric // being the implementation happens to be deterministic.
8240b57cec5SDimitry Andric SmallString<64> MangledName;
8250b57cec5SDimitry Andric llvm::raw_svector_ostream Out(MangledName);
8260b57cec5SDimitry Andric CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
8270b57cec5SDimitry Andric Out);
8280b57cec5SDimitry Andric
829*5f7ddb14SDimitry Andric // Contained in NoSanitizeList based on the mangled type.
830*5f7ddb14SDimitry Andric if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
831*5f7ddb14SDimitry Andric Out.str())) {
8320b57cec5SDimitry Andric llvm::hash_code TypeHash = hash_value(Out.str());
8330b57cec5SDimitry Andric
8340b57cec5SDimitry Andric // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
8350b57cec5SDimitry Andric llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
8360b57cec5SDimitry Andric llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
8370b57cec5SDimitry Andric Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
8380b57cec5SDimitry Andric llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
8390b57cec5SDimitry Andric llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
8400b57cec5SDimitry Andric
8410b57cec5SDimitry Andric llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
8420b57cec5SDimitry Andric Hash = Builder.CreateTrunc(Hash, IntPtrTy);
8430b57cec5SDimitry Andric
8440b57cec5SDimitry Andric // Look the hash up in our cache.
8450b57cec5SDimitry Andric const int CacheSize = 128;
8460b57cec5SDimitry Andric llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
8470b57cec5SDimitry Andric llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
8480b57cec5SDimitry Andric "__ubsan_vptr_type_cache");
8490b57cec5SDimitry Andric llvm::Value *Slot = Builder.CreateAnd(Hash,
8500b57cec5SDimitry Andric llvm::ConstantInt::get(IntPtrTy,
8510b57cec5SDimitry Andric CacheSize-1));
8520b57cec5SDimitry Andric llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
853*5f7ddb14SDimitry Andric llvm::Value *CacheVal = Builder.CreateAlignedLoad(
854*5f7ddb14SDimitry Andric IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
8550b57cec5SDimitry Andric getPointerAlign());
8560b57cec5SDimitry Andric
8570b57cec5SDimitry Andric // If the hash isn't in the cache, call a runtime handler to perform the
8580b57cec5SDimitry Andric // hard work of checking whether the vptr is for an object of the right
8590b57cec5SDimitry Andric // type. This will either fill in the cache and return, or produce a
8600b57cec5SDimitry Andric // diagnostic.
8610b57cec5SDimitry Andric llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
8620b57cec5SDimitry Andric llvm::Constant *StaticData[] = {
8630b57cec5SDimitry Andric EmitCheckSourceLocation(Loc),
8640b57cec5SDimitry Andric EmitCheckTypeDescriptor(Ty),
8650b57cec5SDimitry Andric CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
8660b57cec5SDimitry Andric llvm::ConstantInt::get(Int8Ty, TCK)
8670b57cec5SDimitry Andric };
8680b57cec5SDimitry Andric llvm::Value *DynamicData[] = { Ptr, Hash };
8690b57cec5SDimitry Andric EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
8700b57cec5SDimitry Andric SanitizerHandler::DynamicTypeCacheMiss, StaticData,
8710b57cec5SDimitry Andric DynamicData);
8720b57cec5SDimitry Andric }
8730b57cec5SDimitry Andric }
8740b57cec5SDimitry Andric
8750b57cec5SDimitry Andric if (Done) {
8760b57cec5SDimitry Andric Builder.CreateBr(Done);
8770b57cec5SDimitry Andric EmitBlock(Done);
8780b57cec5SDimitry Andric }
8790b57cec5SDimitry Andric }
8800b57cec5SDimitry Andric
8810b57cec5SDimitry Andric /// Determine whether this expression refers to a flexible array member in a
8820b57cec5SDimitry Andric /// struct. We disable array bounds checks for such members.
isFlexibleArrayMemberExpr(const Expr * E)8830b57cec5SDimitry Andric static bool isFlexibleArrayMemberExpr(const Expr *E) {
8840b57cec5SDimitry Andric // For compatibility with existing code, we treat arrays of length 0 or
8850b57cec5SDimitry Andric // 1 as flexible array members.
8865ffd83dbSDimitry Andric // FIXME: This is inconsistent with the warning code in SemaChecking. Unify
8875ffd83dbSDimitry Andric // the two mechanisms.
8880b57cec5SDimitry Andric const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
8890b57cec5SDimitry Andric if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
8905ffd83dbSDimitry Andric // FIXME: Sema doesn't treat [1] as a flexible array member if the bound
8915ffd83dbSDimitry Andric // was produced by macro expansion.
8920b57cec5SDimitry Andric if (CAT->getSize().ugt(1))
8930b57cec5SDimitry Andric return false;
8940b57cec5SDimitry Andric } else if (!isa<IncompleteArrayType>(AT))
8950b57cec5SDimitry Andric return false;
8960b57cec5SDimitry Andric
8970b57cec5SDimitry Andric E = E->IgnoreParens();
8980b57cec5SDimitry Andric
8990b57cec5SDimitry Andric // A flexible array member must be the last member in the class.
9000b57cec5SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(E)) {
9010b57cec5SDimitry Andric // FIXME: If the base type of the member expr is not FD->getParent(),
9020b57cec5SDimitry Andric // this should not be treated as a flexible array member access.
9030b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
9045ffd83dbSDimitry Andric // FIXME: Sema doesn't treat a T[1] union member as a flexible array
9055ffd83dbSDimitry Andric // member, only a T[0] or T[] member gets that treatment.
9065ffd83dbSDimitry Andric if (FD->getParent()->isUnion())
9075ffd83dbSDimitry Andric return true;
9080b57cec5SDimitry Andric RecordDecl::field_iterator FI(
9090b57cec5SDimitry Andric DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
9100b57cec5SDimitry Andric return ++FI == FD->getParent()->field_end();
9110b57cec5SDimitry Andric }
9120b57cec5SDimitry Andric } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
9130b57cec5SDimitry Andric return IRE->getDecl()->getNextIvar() == nullptr;
9140b57cec5SDimitry Andric }
9150b57cec5SDimitry Andric
9160b57cec5SDimitry Andric return false;
9170b57cec5SDimitry Andric }
9180b57cec5SDimitry Andric
LoadPassedObjectSize(const Expr * E,QualType EltTy)9190b57cec5SDimitry Andric llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
9200b57cec5SDimitry Andric QualType EltTy) {
9210b57cec5SDimitry Andric ASTContext &C = getContext();
9220b57cec5SDimitry Andric uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
9230b57cec5SDimitry Andric if (!EltSize)
9240b57cec5SDimitry Andric return nullptr;
9250b57cec5SDimitry Andric
9260b57cec5SDimitry Andric auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
9270b57cec5SDimitry Andric if (!ArrayDeclRef)
9280b57cec5SDimitry Andric return nullptr;
9290b57cec5SDimitry Andric
9300b57cec5SDimitry Andric auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
9310b57cec5SDimitry Andric if (!ParamDecl)
9320b57cec5SDimitry Andric return nullptr;
9330b57cec5SDimitry Andric
9340b57cec5SDimitry Andric auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
9350b57cec5SDimitry Andric if (!POSAttr)
9360b57cec5SDimitry Andric return nullptr;
9370b57cec5SDimitry Andric
9380b57cec5SDimitry Andric // Don't load the size if it's a lower bound.
9390b57cec5SDimitry Andric int POSType = POSAttr->getType();
9400b57cec5SDimitry Andric if (POSType != 0 && POSType != 1)
9410b57cec5SDimitry Andric return nullptr;
9420b57cec5SDimitry Andric
9430b57cec5SDimitry Andric // Find the implicit size parameter.
9440b57cec5SDimitry Andric auto PassedSizeIt = SizeArguments.find(ParamDecl);
9450b57cec5SDimitry Andric if (PassedSizeIt == SizeArguments.end())
9460b57cec5SDimitry Andric return nullptr;
9470b57cec5SDimitry Andric
9480b57cec5SDimitry Andric const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
9490b57cec5SDimitry Andric assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
9500b57cec5SDimitry Andric Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
9510b57cec5SDimitry Andric llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
9520b57cec5SDimitry Andric C.getSizeType(), E->getExprLoc());
9530b57cec5SDimitry Andric llvm::Value *SizeOfElement =
9540b57cec5SDimitry Andric llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
9550b57cec5SDimitry Andric return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
9560b57cec5SDimitry Andric }
9570b57cec5SDimitry Andric
9580b57cec5SDimitry Andric /// If Base is known to point to the start of an array, return the length of
9590b57cec5SDimitry Andric /// that array. Return 0 if the length cannot be determined.
getArrayIndexingBound(CodeGenFunction & CGF,const Expr * Base,QualType & IndexedType)9600b57cec5SDimitry Andric static llvm::Value *getArrayIndexingBound(
9610b57cec5SDimitry Andric CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
9620b57cec5SDimitry Andric // For the vector indexing extension, the bound is the number of elements.
9630b57cec5SDimitry Andric if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
9640b57cec5SDimitry Andric IndexedType = Base->getType();
9650b57cec5SDimitry Andric return CGF.Builder.getInt32(VT->getNumElements());
9660b57cec5SDimitry Andric }
9670b57cec5SDimitry Andric
9680b57cec5SDimitry Andric Base = Base->IgnoreParens();
9690b57cec5SDimitry Andric
9700b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CastExpr>(Base)) {
9710b57cec5SDimitry Andric if (CE->getCastKind() == CK_ArrayToPointerDecay &&
9720b57cec5SDimitry Andric !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
9730b57cec5SDimitry Andric IndexedType = CE->getSubExpr()->getType();
9740b57cec5SDimitry Andric const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
9750b57cec5SDimitry Andric if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9760b57cec5SDimitry Andric return CGF.Builder.getInt(CAT->getSize());
9770b57cec5SDimitry Andric else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
9780b57cec5SDimitry Andric return CGF.getVLASize(VAT).NumElts;
9790b57cec5SDimitry Andric // Ignore pass_object_size here. It's not applicable on decayed pointers.
9800b57cec5SDimitry Andric }
9810b57cec5SDimitry Andric }
9820b57cec5SDimitry Andric
9830b57cec5SDimitry Andric QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
9840b57cec5SDimitry Andric if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
9850b57cec5SDimitry Andric IndexedType = Base->getType();
9860b57cec5SDimitry Andric return POS;
9870b57cec5SDimitry Andric }
9880b57cec5SDimitry Andric
9890b57cec5SDimitry Andric return nullptr;
9900b57cec5SDimitry Andric }
9910b57cec5SDimitry Andric
EmitBoundsCheck(const Expr * E,const Expr * Base,llvm::Value * Index,QualType IndexType,bool Accessed)9920b57cec5SDimitry Andric void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
9930b57cec5SDimitry Andric llvm::Value *Index, QualType IndexType,
9940b57cec5SDimitry Andric bool Accessed) {
9950b57cec5SDimitry Andric assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
9960b57cec5SDimitry Andric "should not be called unless adding bounds checks");
9970b57cec5SDimitry Andric SanitizerScope SanScope(this);
9980b57cec5SDimitry Andric
9990b57cec5SDimitry Andric QualType IndexedType;
10000b57cec5SDimitry Andric llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
10010b57cec5SDimitry Andric if (!Bound)
10020b57cec5SDimitry Andric return;
10030b57cec5SDimitry Andric
10040b57cec5SDimitry Andric bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
10050b57cec5SDimitry Andric llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
10060b57cec5SDimitry Andric llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
10070b57cec5SDimitry Andric
10080b57cec5SDimitry Andric llvm::Constant *StaticData[] = {
10090b57cec5SDimitry Andric EmitCheckSourceLocation(E->getExprLoc()),
10100b57cec5SDimitry Andric EmitCheckTypeDescriptor(IndexedType),
10110b57cec5SDimitry Andric EmitCheckTypeDescriptor(IndexType)
10120b57cec5SDimitry Andric };
10130b57cec5SDimitry Andric llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
10140b57cec5SDimitry Andric : Builder.CreateICmpULE(IndexVal, BoundVal);
10150b57cec5SDimitry Andric EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
10160b57cec5SDimitry Andric SanitizerHandler::OutOfBounds, StaticData, Index);
10170b57cec5SDimitry Andric }
10180b57cec5SDimitry Andric
10190b57cec5SDimitry Andric
10200b57cec5SDimitry Andric CodeGenFunction::ComplexPairTy CodeGenFunction::
EmitComplexPrePostIncDec(const UnaryOperator * E,LValue LV,bool isInc,bool isPre)10210b57cec5SDimitry Andric EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
10220b57cec5SDimitry Andric bool isInc, bool isPre) {
10230b57cec5SDimitry Andric ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
10240b57cec5SDimitry Andric
10250b57cec5SDimitry Andric llvm::Value *NextVal;
10260b57cec5SDimitry Andric if (isa<llvm::IntegerType>(InVal.first->getType())) {
10270b57cec5SDimitry Andric uint64_t AmountVal = isInc ? 1 : -1;
10280b57cec5SDimitry Andric NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
10290b57cec5SDimitry Andric
10300b57cec5SDimitry Andric // Add the inc/dec to the real part.
10310b57cec5SDimitry Andric NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
10320b57cec5SDimitry Andric } else {
1033a7dea167SDimitry Andric QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
10340b57cec5SDimitry Andric llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
10350b57cec5SDimitry Andric if (!isInc)
10360b57cec5SDimitry Andric FVal.changeSign();
10370b57cec5SDimitry Andric NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
10380b57cec5SDimitry Andric
10390b57cec5SDimitry Andric // Add the inc/dec to the real part.
10400b57cec5SDimitry Andric NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
10410b57cec5SDimitry Andric }
10420b57cec5SDimitry Andric
10430b57cec5SDimitry Andric ComplexPairTy IncVal(NextVal, InVal.second);
10440b57cec5SDimitry Andric
10450b57cec5SDimitry Andric // Store the updated result through the lvalue.
10460b57cec5SDimitry Andric EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1047480093f4SDimitry Andric if (getLangOpts().OpenMP)
1048480093f4SDimitry Andric CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1049480093f4SDimitry Andric E->getSubExpr());
10500b57cec5SDimitry Andric
10510b57cec5SDimitry Andric // If this is a postinc, return the value read from memory, otherwise use the
10520b57cec5SDimitry Andric // updated value.
10530b57cec5SDimitry Andric return isPre ? IncVal : InVal;
10540b57cec5SDimitry Andric }
10550b57cec5SDimitry Andric
EmitExplicitCastExprType(const ExplicitCastExpr * E,CodeGenFunction * CGF)10560b57cec5SDimitry Andric void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
10570b57cec5SDimitry Andric CodeGenFunction *CGF) {
10580b57cec5SDimitry Andric // Bind VLAs in the cast type.
10590b57cec5SDimitry Andric if (CGF && E->getType()->isVariablyModifiedType())
10600b57cec5SDimitry Andric CGF->EmitVariablyModifiedType(E->getType());
10610b57cec5SDimitry Andric
10620b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo())
10630b57cec5SDimitry Andric DI->EmitExplicitCastType(E->getType());
10640b57cec5SDimitry Andric }
10650b57cec5SDimitry Andric
10660b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10670b57cec5SDimitry Andric // LValue Expression Emission
10680b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10690b57cec5SDimitry Andric
10700b57cec5SDimitry Andric /// EmitPointerWithAlignment - Given an expression of pointer type, try to
10710b57cec5SDimitry Andric /// derive a more accurate bound on the alignment of the pointer.
EmitPointerWithAlignment(const Expr * E,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)10720b57cec5SDimitry Andric Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
10730b57cec5SDimitry Andric LValueBaseInfo *BaseInfo,
10740b57cec5SDimitry Andric TBAAAccessInfo *TBAAInfo) {
10750b57cec5SDimitry Andric // We allow this with ObjC object pointers because of fragile ABIs.
10760b57cec5SDimitry Andric assert(E->getType()->isPointerType() ||
10770b57cec5SDimitry Andric E->getType()->isObjCObjectPointerType());
10780b57cec5SDimitry Andric E = E->IgnoreParens();
10790b57cec5SDimitry Andric
10800b57cec5SDimitry Andric // Casts:
10810b57cec5SDimitry Andric if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10820b57cec5SDimitry Andric if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
10830b57cec5SDimitry Andric CGM.EmitExplicitCastExprType(ECE, this);
10840b57cec5SDimitry Andric
10850b57cec5SDimitry Andric switch (CE->getCastKind()) {
10860b57cec5SDimitry Andric // Non-converting casts (but not C's implicit conversion from void*).
10870b57cec5SDimitry Andric case CK_BitCast:
10880b57cec5SDimitry Andric case CK_NoOp:
10890b57cec5SDimitry Andric case CK_AddressSpaceConversion:
10900b57cec5SDimitry Andric if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
10910b57cec5SDimitry Andric if (PtrTy->getPointeeType()->isVoidType())
10920b57cec5SDimitry Andric break;
10930b57cec5SDimitry Andric
10940b57cec5SDimitry Andric LValueBaseInfo InnerBaseInfo;
10950b57cec5SDimitry Andric TBAAAccessInfo InnerTBAAInfo;
10960b57cec5SDimitry Andric Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
10970b57cec5SDimitry Andric &InnerBaseInfo,
10980b57cec5SDimitry Andric &InnerTBAAInfo);
10990b57cec5SDimitry Andric if (BaseInfo) *BaseInfo = InnerBaseInfo;
11000b57cec5SDimitry Andric if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
11010b57cec5SDimitry Andric
11020b57cec5SDimitry Andric if (isa<ExplicitCastExpr>(CE)) {
11030b57cec5SDimitry Andric LValueBaseInfo TargetTypeBaseInfo;
11040b57cec5SDimitry Andric TBAAAccessInfo TargetTypeTBAAInfo;
11055ffd83dbSDimitry Andric CharUnits Align = CGM.getNaturalPointeeTypeAlignment(
11065ffd83dbSDimitry Andric E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
11070b57cec5SDimitry Andric if (TBAAInfo)
11080b57cec5SDimitry Andric *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
11090b57cec5SDimitry Andric TargetTypeTBAAInfo);
11100b57cec5SDimitry Andric // If the source l-value is opaque, honor the alignment of the
11110b57cec5SDimitry Andric // casted-to type.
11120b57cec5SDimitry Andric if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
11130b57cec5SDimitry Andric if (BaseInfo)
11140b57cec5SDimitry Andric BaseInfo->mergeForCast(TargetTypeBaseInfo);
11150b57cec5SDimitry Andric Addr = Address(Addr.getPointer(), Align);
11160b57cec5SDimitry Andric }
11170b57cec5SDimitry Andric }
11180b57cec5SDimitry Andric
11190b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
11200b57cec5SDimitry Andric CE->getCastKind() == CK_BitCast) {
11210b57cec5SDimitry Andric if (auto PT = E->getType()->getAs<PointerType>())
11220b57cec5SDimitry Andric EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
11230b57cec5SDimitry Andric /*MayBeNull=*/true,
11240b57cec5SDimitry Andric CodeGenFunction::CFITCK_UnrelatedCast,
11250b57cec5SDimitry Andric CE->getBeginLoc());
11260b57cec5SDimitry Andric }
11270b57cec5SDimitry Andric return CE->getCastKind() != CK_AddressSpaceConversion
11280b57cec5SDimitry Andric ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
11290b57cec5SDimitry Andric : Builder.CreateAddrSpaceCast(Addr,
11300b57cec5SDimitry Andric ConvertType(E->getType()));
11310b57cec5SDimitry Andric }
11320b57cec5SDimitry Andric break;
11330b57cec5SDimitry Andric
11340b57cec5SDimitry Andric // Array-to-pointer decay.
11350b57cec5SDimitry Andric case CK_ArrayToPointerDecay:
11360b57cec5SDimitry Andric return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
11370b57cec5SDimitry Andric
11380b57cec5SDimitry Andric // Derived-to-base conversions.
11390b57cec5SDimitry Andric case CK_UncheckedDerivedToBase:
11400b57cec5SDimitry Andric case CK_DerivedToBase: {
11410b57cec5SDimitry Andric // TODO: Support accesses to members of base classes in TBAA. For now, we
11420b57cec5SDimitry Andric // conservatively pretend that the complete object is of the base class
11430b57cec5SDimitry Andric // type.
11440b57cec5SDimitry Andric if (TBAAInfo)
11450b57cec5SDimitry Andric *TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
11460b57cec5SDimitry Andric Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
11470b57cec5SDimitry Andric auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
11480b57cec5SDimitry Andric return GetAddressOfBaseClass(Addr, Derived,
11490b57cec5SDimitry Andric CE->path_begin(), CE->path_end(),
11500b57cec5SDimitry Andric ShouldNullCheckClassCastValue(CE),
11510b57cec5SDimitry Andric CE->getExprLoc());
11520b57cec5SDimitry Andric }
11530b57cec5SDimitry Andric
11540b57cec5SDimitry Andric // TODO: Is there any reason to treat base-to-derived conversions
11550b57cec5SDimitry Andric // specially?
11560b57cec5SDimitry Andric default:
11570b57cec5SDimitry Andric break;
11580b57cec5SDimitry Andric }
11590b57cec5SDimitry Andric }
11600b57cec5SDimitry Andric
11610b57cec5SDimitry Andric // Unary &.
11620b57cec5SDimitry Andric if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11630b57cec5SDimitry Andric if (UO->getOpcode() == UO_AddrOf) {
11640b57cec5SDimitry Andric LValue LV = EmitLValue(UO->getSubExpr());
11650b57cec5SDimitry Andric if (BaseInfo) *BaseInfo = LV.getBaseInfo();
11660b57cec5SDimitry Andric if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1167480093f4SDimitry Andric return LV.getAddress(*this);
11680b57cec5SDimitry Andric }
11690b57cec5SDimitry Andric }
11700b57cec5SDimitry Andric
11710b57cec5SDimitry Andric // TODO: conditional operators, comma.
11720b57cec5SDimitry Andric
11730b57cec5SDimitry Andric // Otherwise, use the alignment of the type.
11745ffd83dbSDimitry Andric CharUnits Align =
11755ffd83dbSDimitry Andric CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo, TBAAInfo);
11760b57cec5SDimitry Andric return Address(EmitScalarExpr(E), Align);
11770b57cec5SDimitry Andric }
11780b57cec5SDimitry Andric
EmitNonNullRValueCheck(RValue RV,QualType T)1179af732203SDimitry Andric llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
1180af732203SDimitry Andric llvm::Value *V = RV.getScalarVal();
1181af732203SDimitry Andric if (auto MPT = T->getAs<MemberPointerType>())
1182af732203SDimitry Andric return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1183af732203SDimitry Andric return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1184af732203SDimitry Andric }
1185af732203SDimitry Andric
GetUndefRValue(QualType Ty)11860b57cec5SDimitry Andric RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
11870b57cec5SDimitry Andric if (Ty->isVoidType())
11880b57cec5SDimitry Andric return RValue::get(nullptr);
11890b57cec5SDimitry Andric
11900b57cec5SDimitry Andric switch (getEvaluationKind(Ty)) {
11910b57cec5SDimitry Andric case TEK_Complex: {
11920b57cec5SDimitry Andric llvm::Type *EltTy =
11930b57cec5SDimitry Andric ConvertType(Ty->castAs<ComplexType>()->getElementType());
11940b57cec5SDimitry Andric llvm::Value *U = llvm::UndefValue::get(EltTy);
11950b57cec5SDimitry Andric return RValue::getComplex(std::make_pair(U, U));
11960b57cec5SDimitry Andric }
11970b57cec5SDimitry Andric
11980b57cec5SDimitry Andric // If this is a use of an undefined aggregate type, the aggregate must have an
11990b57cec5SDimitry Andric // identifiable address. Just because the contents of the value are undefined
12000b57cec5SDimitry Andric // doesn't mean that the address can't be taken and compared.
12010b57cec5SDimitry Andric case TEK_Aggregate: {
12020b57cec5SDimitry Andric Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
12030b57cec5SDimitry Andric return RValue::getAggregate(DestPtr);
12040b57cec5SDimitry Andric }
12050b57cec5SDimitry Andric
12060b57cec5SDimitry Andric case TEK_Scalar:
12070b57cec5SDimitry Andric return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
12080b57cec5SDimitry Andric }
12090b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
12100b57cec5SDimitry Andric }
12110b57cec5SDimitry Andric
EmitUnsupportedRValue(const Expr * E,const char * Name)12120b57cec5SDimitry Andric RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
12130b57cec5SDimitry Andric const char *Name) {
12140b57cec5SDimitry Andric ErrorUnsupported(E, Name);
12150b57cec5SDimitry Andric return GetUndefRValue(E->getType());
12160b57cec5SDimitry Andric }
12170b57cec5SDimitry Andric
EmitUnsupportedLValue(const Expr * E,const char * Name)12180b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
12190b57cec5SDimitry Andric const char *Name) {
12200b57cec5SDimitry Andric ErrorUnsupported(E, Name);
12210b57cec5SDimitry Andric llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
12220b57cec5SDimitry Andric return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
12230b57cec5SDimitry Andric E->getType());
12240b57cec5SDimitry Andric }
12250b57cec5SDimitry Andric
IsWrappedCXXThis(const Expr * Obj)12260b57cec5SDimitry Andric bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
12270b57cec5SDimitry Andric const Expr *Base = Obj;
12280b57cec5SDimitry Andric while (!isa<CXXThisExpr>(Base)) {
12290b57cec5SDimitry Andric // The result of a dynamic_cast can be null.
12300b57cec5SDimitry Andric if (isa<CXXDynamicCastExpr>(Base))
12310b57cec5SDimitry Andric return false;
12320b57cec5SDimitry Andric
12330b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CastExpr>(Base)) {
12340b57cec5SDimitry Andric Base = CE->getSubExpr();
12350b57cec5SDimitry Andric } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
12360b57cec5SDimitry Andric Base = PE->getSubExpr();
12370b57cec5SDimitry Andric } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
12380b57cec5SDimitry Andric if (UO->getOpcode() == UO_Extension)
12390b57cec5SDimitry Andric Base = UO->getSubExpr();
12400b57cec5SDimitry Andric else
12410b57cec5SDimitry Andric return false;
12420b57cec5SDimitry Andric } else {
12430b57cec5SDimitry Andric return false;
12440b57cec5SDimitry Andric }
12450b57cec5SDimitry Andric }
12460b57cec5SDimitry Andric return true;
12470b57cec5SDimitry Andric }
12480b57cec5SDimitry Andric
EmitCheckedLValue(const Expr * E,TypeCheckKind TCK)12490b57cec5SDimitry Andric LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
12500b57cec5SDimitry Andric LValue LV;
12510b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
12520b57cec5SDimitry Andric LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
12530b57cec5SDimitry Andric else
12540b57cec5SDimitry Andric LV = EmitLValue(E);
12550b57cec5SDimitry Andric if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
12560b57cec5SDimitry Andric SanitizerSet SkippedChecks;
12570b57cec5SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(E)) {
12580b57cec5SDimitry Andric bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
12590b57cec5SDimitry Andric if (IsBaseCXXThis)
12600b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Alignment, true);
12610b57cec5SDimitry Andric if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
12620b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Null, true);
12630b57cec5SDimitry Andric }
1264480093f4SDimitry Andric EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
1265480093f4SDimitry Andric LV.getAlignment(), SkippedChecks);
12660b57cec5SDimitry Andric }
12670b57cec5SDimitry Andric return LV;
12680b57cec5SDimitry Andric }
12690b57cec5SDimitry Andric
12700b57cec5SDimitry Andric /// EmitLValue - Emit code to compute a designator that specifies the location
12710b57cec5SDimitry Andric /// of the expression.
12720b57cec5SDimitry Andric ///
12730b57cec5SDimitry Andric /// This can return one of two things: a simple address or a bitfield reference.
12740b57cec5SDimitry Andric /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
12750b57cec5SDimitry Andric /// an LLVM pointer type.
12760b57cec5SDimitry Andric ///
12770b57cec5SDimitry Andric /// If this returns a bitfield reference, nothing about the pointee type of the
12780b57cec5SDimitry Andric /// LLVM value is known: For example, it may not be a pointer to an integer.
12790b57cec5SDimitry Andric ///
12800b57cec5SDimitry Andric /// If this returns a normal address, and if the lvalue's C type is fixed size,
12810b57cec5SDimitry Andric /// this method guarantees that the returned pointer type will point to an LLVM
12820b57cec5SDimitry Andric /// type of the same size of the lvalue's type. If the lvalue has a variable
12830b57cec5SDimitry Andric /// length type, this is not possible.
12840b57cec5SDimitry Andric ///
EmitLValue(const Expr * E)12850b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValue(const Expr *E) {
12860b57cec5SDimitry Andric ApplyDebugLocation DL(*this, E);
12870b57cec5SDimitry Andric switch (E->getStmtClass()) {
12880b57cec5SDimitry Andric default: return EmitUnsupportedLValue(E, "l-value expression");
12890b57cec5SDimitry Andric
12900b57cec5SDimitry Andric case Expr::ObjCPropertyRefExprClass:
12910b57cec5SDimitry Andric llvm_unreachable("cannot emit a property reference directly");
12920b57cec5SDimitry Andric
12930b57cec5SDimitry Andric case Expr::ObjCSelectorExprClass:
12940b57cec5SDimitry Andric return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
12950b57cec5SDimitry Andric case Expr::ObjCIsaExprClass:
12960b57cec5SDimitry Andric return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
12970b57cec5SDimitry Andric case Expr::BinaryOperatorClass:
12980b57cec5SDimitry Andric return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
12990b57cec5SDimitry Andric case Expr::CompoundAssignOperatorClass: {
13000b57cec5SDimitry Andric QualType Ty = E->getType();
13010b57cec5SDimitry Andric if (const AtomicType *AT = Ty->getAs<AtomicType>())
13020b57cec5SDimitry Andric Ty = AT->getValueType();
13030b57cec5SDimitry Andric if (!Ty->isAnyComplexType())
13040b57cec5SDimitry Andric return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
13050b57cec5SDimitry Andric return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
13060b57cec5SDimitry Andric }
13070b57cec5SDimitry Andric case Expr::CallExprClass:
13080b57cec5SDimitry Andric case Expr::CXXMemberCallExprClass:
13090b57cec5SDimitry Andric case Expr::CXXOperatorCallExprClass:
13100b57cec5SDimitry Andric case Expr::UserDefinedLiteralClass:
13110b57cec5SDimitry Andric return EmitCallExprLValue(cast<CallExpr>(E));
1312a7dea167SDimitry Andric case Expr::CXXRewrittenBinaryOperatorClass:
1313a7dea167SDimitry Andric return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm());
13140b57cec5SDimitry Andric case Expr::VAArgExprClass:
13150b57cec5SDimitry Andric return EmitVAArgExprLValue(cast<VAArgExpr>(E));
13160b57cec5SDimitry Andric case Expr::DeclRefExprClass:
13170b57cec5SDimitry Andric return EmitDeclRefLValue(cast<DeclRefExpr>(E));
13185ffd83dbSDimitry Andric case Expr::ConstantExprClass: {
13195ffd83dbSDimitry Andric const ConstantExpr *CE = cast<ConstantExpr>(E);
13205ffd83dbSDimitry Andric if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
13215ffd83dbSDimitry Andric QualType RetType = cast<CallExpr>(CE->getSubExpr()->IgnoreImplicit())
13225ffd83dbSDimitry Andric ->getCallReturnType(getContext());
13235ffd83dbSDimitry Andric return MakeNaturalAlignAddrLValue(Result, RetType);
13245ffd83dbSDimitry Andric }
13250b57cec5SDimitry Andric return EmitLValue(cast<ConstantExpr>(E)->getSubExpr());
13265ffd83dbSDimitry Andric }
13270b57cec5SDimitry Andric case Expr::ParenExprClass:
13280b57cec5SDimitry Andric return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
13290b57cec5SDimitry Andric case Expr::GenericSelectionExprClass:
13300b57cec5SDimitry Andric return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
13310b57cec5SDimitry Andric case Expr::PredefinedExprClass:
13320b57cec5SDimitry Andric return EmitPredefinedLValue(cast<PredefinedExpr>(E));
13330b57cec5SDimitry Andric case Expr::StringLiteralClass:
13340b57cec5SDimitry Andric return EmitStringLiteralLValue(cast<StringLiteral>(E));
13350b57cec5SDimitry Andric case Expr::ObjCEncodeExprClass:
13360b57cec5SDimitry Andric return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
13370b57cec5SDimitry Andric case Expr::PseudoObjectExprClass:
13380b57cec5SDimitry Andric return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
13390b57cec5SDimitry Andric case Expr::InitListExprClass:
13400b57cec5SDimitry Andric return EmitInitListLValue(cast<InitListExpr>(E));
13410b57cec5SDimitry Andric case Expr::CXXTemporaryObjectExprClass:
13420b57cec5SDimitry Andric case Expr::CXXConstructExprClass:
13430b57cec5SDimitry Andric return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
13440b57cec5SDimitry Andric case Expr::CXXBindTemporaryExprClass:
13450b57cec5SDimitry Andric return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
13460b57cec5SDimitry Andric case Expr::CXXUuidofExprClass:
13470b57cec5SDimitry Andric return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
13480b57cec5SDimitry Andric case Expr::LambdaExprClass:
13490b57cec5SDimitry Andric return EmitAggExprToLValue(E);
13500b57cec5SDimitry Andric
13510b57cec5SDimitry Andric case Expr::ExprWithCleanupsClass: {
13520b57cec5SDimitry Andric const auto *cleanups = cast<ExprWithCleanups>(E);
13530b57cec5SDimitry Andric RunCleanupsScope Scope(*this);
13540b57cec5SDimitry Andric LValue LV = EmitLValue(cleanups->getSubExpr());
13550b57cec5SDimitry Andric if (LV.isSimple()) {
13560b57cec5SDimitry Andric // Defend against branches out of gnu statement expressions surrounded by
13570b57cec5SDimitry Andric // cleanups.
1358480093f4SDimitry Andric llvm::Value *V = LV.getPointer(*this);
13590b57cec5SDimitry Andric Scope.ForceCleanup({&V});
13600b57cec5SDimitry Andric return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
13610b57cec5SDimitry Andric getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
13620b57cec5SDimitry Andric }
13630b57cec5SDimitry Andric // FIXME: Is it possible to create an ExprWithCleanups that produces a
13640b57cec5SDimitry Andric // bitfield lvalue or some other non-simple lvalue?
13650b57cec5SDimitry Andric return LV;
13660b57cec5SDimitry Andric }
13670b57cec5SDimitry Andric
13680b57cec5SDimitry Andric case Expr::CXXDefaultArgExprClass: {
13690b57cec5SDimitry Andric auto *DAE = cast<CXXDefaultArgExpr>(E);
13700b57cec5SDimitry Andric CXXDefaultArgExprScope Scope(*this, DAE);
13710b57cec5SDimitry Andric return EmitLValue(DAE->getExpr());
13720b57cec5SDimitry Andric }
13730b57cec5SDimitry Andric case Expr::CXXDefaultInitExprClass: {
13740b57cec5SDimitry Andric auto *DIE = cast<CXXDefaultInitExpr>(E);
13750b57cec5SDimitry Andric CXXDefaultInitExprScope Scope(*this, DIE);
13760b57cec5SDimitry Andric return EmitLValue(DIE->getExpr());
13770b57cec5SDimitry Andric }
13780b57cec5SDimitry Andric case Expr::CXXTypeidExprClass:
13790b57cec5SDimitry Andric return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
13800b57cec5SDimitry Andric
13810b57cec5SDimitry Andric case Expr::ObjCMessageExprClass:
13820b57cec5SDimitry Andric return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
13830b57cec5SDimitry Andric case Expr::ObjCIvarRefExprClass:
13840b57cec5SDimitry Andric return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
13850b57cec5SDimitry Andric case Expr::StmtExprClass:
13860b57cec5SDimitry Andric return EmitStmtExprLValue(cast<StmtExpr>(E));
13870b57cec5SDimitry Andric case Expr::UnaryOperatorClass:
13880b57cec5SDimitry Andric return EmitUnaryOpLValue(cast<UnaryOperator>(E));
13890b57cec5SDimitry Andric case Expr::ArraySubscriptExprClass:
13900b57cec5SDimitry Andric return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
13915ffd83dbSDimitry Andric case Expr::MatrixSubscriptExprClass:
13925ffd83dbSDimitry Andric return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
13930b57cec5SDimitry Andric case Expr::OMPArraySectionExprClass:
13940b57cec5SDimitry Andric return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
13950b57cec5SDimitry Andric case Expr::ExtVectorElementExprClass:
13960b57cec5SDimitry Andric return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
13970b57cec5SDimitry Andric case Expr::MemberExprClass:
13980b57cec5SDimitry Andric return EmitMemberExpr(cast<MemberExpr>(E));
13990b57cec5SDimitry Andric case Expr::CompoundLiteralExprClass:
14000b57cec5SDimitry Andric return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
14010b57cec5SDimitry Andric case Expr::ConditionalOperatorClass:
14020b57cec5SDimitry Andric return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
14030b57cec5SDimitry Andric case Expr::BinaryConditionalOperatorClass:
14040b57cec5SDimitry Andric return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
14050b57cec5SDimitry Andric case Expr::ChooseExprClass:
14060b57cec5SDimitry Andric return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
14070b57cec5SDimitry Andric case Expr::OpaqueValueExprClass:
14080b57cec5SDimitry Andric return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
14090b57cec5SDimitry Andric case Expr::SubstNonTypeTemplateParmExprClass:
14100b57cec5SDimitry Andric return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
14110b57cec5SDimitry Andric case Expr::ImplicitCastExprClass:
14120b57cec5SDimitry Andric case Expr::CStyleCastExprClass:
14130b57cec5SDimitry Andric case Expr::CXXFunctionalCastExprClass:
14140b57cec5SDimitry Andric case Expr::CXXStaticCastExprClass:
14150b57cec5SDimitry Andric case Expr::CXXDynamicCastExprClass:
14160b57cec5SDimitry Andric case Expr::CXXReinterpretCastExprClass:
14170b57cec5SDimitry Andric case Expr::CXXConstCastExprClass:
14185ffd83dbSDimitry Andric case Expr::CXXAddrspaceCastExprClass:
14190b57cec5SDimitry Andric case Expr::ObjCBridgedCastExprClass:
14200b57cec5SDimitry Andric return EmitCastLValue(cast<CastExpr>(E));
14210b57cec5SDimitry Andric
14220b57cec5SDimitry Andric case Expr::MaterializeTemporaryExprClass:
14230b57cec5SDimitry Andric return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
14240b57cec5SDimitry Andric
14250b57cec5SDimitry Andric case Expr::CoawaitExprClass:
14260b57cec5SDimitry Andric return EmitCoawaitLValue(cast<CoawaitExpr>(E));
14270b57cec5SDimitry Andric case Expr::CoyieldExprClass:
14280b57cec5SDimitry Andric return EmitCoyieldLValue(cast<CoyieldExpr>(E));
14290b57cec5SDimitry Andric }
14300b57cec5SDimitry Andric }
14310b57cec5SDimitry Andric
14320b57cec5SDimitry Andric /// Given an object of the given canonical type, can we safely copy a
14330b57cec5SDimitry Andric /// value out of it based on its initializer?
isConstantEmittableObjectType(QualType type)14340b57cec5SDimitry Andric static bool isConstantEmittableObjectType(QualType type) {
14350b57cec5SDimitry Andric assert(type.isCanonical());
14360b57cec5SDimitry Andric assert(!type->isReferenceType());
14370b57cec5SDimitry Andric
14380b57cec5SDimitry Andric // Must be const-qualified but non-volatile.
14390b57cec5SDimitry Andric Qualifiers qs = type.getLocalQualifiers();
14400b57cec5SDimitry Andric if (!qs.hasConst() || qs.hasVolatile()) return false;
14410b57cec5SDimitry Andric
14420b57cec5SDimitry Andric // Otherwise, all object types satisfy this except C++ classes with
14430b57cec5SDimitry Andric // mutable subobjects or non-trivial copy/destroy behavior.
14440b57cec5SDimitry Andric if (const auto *RT = dyn_cast<RecordType>(type))
14450b57cec5SDimitry Andric if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
14460b57cec5SDimitry Andric if (RD->hasMutableFields() || !RD->isTrivial())
14470b57cec5SDimitry Andric return false;
14480b57cec5SDimitry Andric
14490b57cec5SDimitry Andric return true;
14500b57cec5SDimitry Andric }
14510b57cec5SDimitry Andric
14520b57cec5SDimitry Andric /// Can we constant-emit a load of a reference to a variable of the
14530b57cec5SDimitry Andric /// given type? This is different from predicates like
14540b57cec5SDimitry Andric /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
14550b57cec5SDimitry Andric /// in situations that don't necessarily satisfy the language's rules
14560b57cec5SDimitry Andric /// for this (e.g. C++'s ODR-use rules). For example, we want to able
14570b57cec5SDimitry Andric /// to do this with const float variables even if those variables
14580b57cec5SDimitry Andric /// aren't marked 'constexpr'.
14590b57cec5SDimitry Andric enum ConstantEmissionKind {
14600b57cec5SDimitry Andric CEK_None,
14610b57cec5SDimitry Andric CEK_AsReferenceOnly,
14620b57cec5SDimitry Andric CEK_AsValueOrReference,
14630b57cec5SDimitry Andric CEK_AsValueOnly
14640b57cec5SDimitry Andric };
checkVarTypeForConstantEmission(QualType type)14650b57cec5SDimitry Andric static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
14660b57cec5SDimitry Andric type = type.getCanonicalType();
14670b57cec5SDimitry Andric if (const auto *ref = dyn_cast<ReferenceType>(type)) {
14680b57cec5SDimitry Andric if (isConstantEmittableObjectType(ref->getPointeeType()))
14690b57cec5SDimitry Andric return CEK_AsValueOrReference;
14700b57cec5SDimitry Andric return CEK_AsReferenceOnly;
14710b57cec5SDimitry Andric }
14720b57cec5SDimitry Andric if (isConstantEmittableObjectType(type))
14730b57cec5SDimitry Andric return CEK_AsValueOnly;
14740b57cec5SDimitry Andric return CEK_None;
14750b57cec5SDimitry Andric }
14760b57cec5SDimitry Andric
14770b57cec5SDimitry Andric /// Try to emit a reference to the given value without producing it as
14780b57cec5SDimitry Andric /// an l-value. This is just an optimization, but it avoids us needing
14790b57cec5SDimitry Andric /// to emit global copies of variables if they're named without triggering
14800b57cec5SDimitry Andric /// a formal use in a context where we can't emit a direct reference to them,
14810b57cec5SDimitry Andric /// for instance if a block or lambda or a member of a local class uses a
14820b57cec5SDimitry Andric /// const int variable or constexpr variable from an enclosing function.
14830b57cec5SDimitry Andric CodeGenFunction::ConstantEmission
tryEmitAsConstant(DeclRefExpr * refExpr)14840b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
14850b57cec5SDimitry Andric ValueDecl *value = refExpr->getDecl();
14860b57cec5SDimitry Andric
14870b57cec5SDimitry Andric // The value needs to be an enum constant or a constant variable.
14880b57cec5SDimitry Andric ConstantEmissionKind CEK;
14890b57cec5SDimitry Andric if (isa<ParmVarDecl>(value)) {
14900b57cec5SDimitry Andric CEK = CEK_None;
14910b57cec5SDimitry Andric } else if (auto *var = dyn_cast<VarDecl>(value)) {
14920b57cec5SDimitry Andric CEK = checkVarTypeForConstantEmission(var->getType());
14930b57cec5SDimitry Andric } else if (isa<EnumConstantDecl>(value)) {
14940b57cec5SDimitry Andric CEK = CEK_AsValueOnly;
14950b57cec5SDimitry Andric } else {
14960b57cec5SDimitry Andric CEK = CEK_None;
14970b57cec5SDimitry Andric }
14980b57cec5SDimitry Andric if (CEK == CEK_None) return ConstantEmission();
14990b57cec5SDimitry Andric
15000b57cec5SDimitry Andric Expr::EvalResult result;
15010b57cec5SDimitry Andric bool resultIsReference;
15020b57cec5SDimitry Andric QualType resultType;
15030b57cec5SDimitry Andric
15040b57cec5SDimitry Andric // It's best to evaluate all the way as an r-value if that's permitted.
15050b57cec5SDimitry Andric if (CEK != CEK_AsReferenceOnly &&
15060b57cec5SDimitry Andric refExpr->EvaluateAsRValue(result, getContext())) {
15070b57cec5SDimitry Andric resultIsReference = false;
15080b57cec5SDimitry Andric resultType = refExpr->getType();
15090b57cec5SDimitry Andric
15100b57cec5SDimitry Andric // Otherwise, try to evaluate as an l-value.
15110b57cec5SDimitry Andric } else if (CEK != CEK_AsValueOnly &&
15120b57cec5SDimitry Andric refExpr->EvaluateAsLValue(result, getContext())) {
15130b57cec5SDimitry Andric resultIsReference = true;
15140b57cec5SDimitry Andric resultType = value->getType();
15150b57cec5SDimitry Andric
15160b57cec5SDimitry Andric // Failure.
15170b57cec5SDimitry Andric } else {
15180b57cec5SDimitry Andric return ConstantEmission();
15190b57cec5SDimitry Andric }
15200b57cec5SDimitry Andric
15210b57cec5SDimitry Andric // In any case, if the initializer has side-effects, abandon ship.
15220b57cec5SDimitry Andric if (result.HasSideEffects)
15230b57cec5SDimitry Andric return ConstantEmission();
15240b57cec5SDimitry Andric
1525af732203SDimitry Andric // In CUDA/HIP device compilation, a lambda may capture a reference variable
1526af732203SDimitry Andric // referencing a global host variable by copy. In this case the lambda should
1527af732203SDimitry Andric // make a copy of the value of the global host variable. The DRE of the
1528af732203SDimitry Andric // captured reference variable cannot be emitted as load from the host
1529af732203SDimitry Andric // global variable as compile time constant, since the host variable is not
1530af732203SDimitry Andric // accessible on device. The DRE of the captured reference variable has to be
1531af732203SDimitry Andric // loaded from captures.
1532af732203SDimitry Andric if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
1533af732203SDimitry Andric refExpr->refersToEnclosingVariableOrCapture()) {
1534af732203SDimitry Andric auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
1535af732203SDimitry Andric if (MD && MD->getParent()->isLambda() &&
1536af732203SDimitry Andric MD->getOverloadedOperator() == OO_Call) {
1537af732203SDimitry Andric const APValue::LValueBase &base = result.Val.getLValueBase();
1538af732203SDimitry Andric if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1539af732203SDimitry Andric if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1540af732203SDimitry Andric if (!VD->hasAttr<CUDADeviceAttr>()) {
1541af732203SDimitry Andric return ConstantEmission();
1542af732203SDimitry Andric }
1543af732203SDimitry Andric }
1544af732203SDimitry Andric }
1545af732203SDimitry Andric }
1546af732203SDimitry Andric }
1547af732203SDimitry Andric
15480b57cec5SDimitry Andric // Emit as a constant.
15490b57cec5SDimitry Andric auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
15500b57cec5SDimitry Andric result.Val, resultType);
15510b57cec5SDimitry Andric
15520b57cec5SDimitry Andric // Make sure we emit a debug reference to the global variable.
15530b57cec5SDimitry Andric // This should probably fire even for
15540b57cec5SDimitry Andric if (isa<VarDecl>(value)) {
15550b57cec5SDimitry Andric if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
15560b57cec5SDimitry Andric EmitDeclRefExprDbgValue(refExpr, result.Val);
15570b57cec5SDimitry Andric } else {
15580b57cec5SDimitry Andric assert(isa<EnumConstantDecl>(value));
15590b57cec5SDimitry Andric EmitDeclRefExprDbgValue(refExpr, result.Val);
15600b57cec5SDimitry Andric }
15610b57cec5SDimitry Andric
15620b57cec5SDimitry Andric // If we emitted a reference constant, we need to dereference that.
15630b57cec5SDimitry Andric if (resultIsReference)
15640b57cec5SDimitry Andric return ConstantEmission::forReference(C);
15650b57cec5SDimitry Andric
15660b57cec5SDimitry Andric return ConstantEmission::forValue(C);
15670b57cec5SDimitry Andric }
15680b57cec5SDimitry Andric
tryToConvertMemberExprToDeclRefExpr(CodeGenFunction & CGF,const MemberExpr * ME)15690b57cec5SDimitry Andric static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
15700b57cec5SDimitry Andric const MemberExpr *ME) {
15710b57cec5SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
15720b57cec5SDimitry Andric // Try to emit static variable member expressions as DREs.
15730b57cec5SDimitry Andric return DeclRefExpr::Create(
15740b57cec5SDimitry Andric CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
15750b57cec5SDimitry Andric /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
15760b57cec5SDimitry Andric ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
15770b57cec5SDimitry Andric }
15780b57cec5SDimitry Andric return nullptr;
15790b57cec5SDimitry Andric }
15800b57cec5SDimitry Andric
15810b57cec5SDimitry Andric CodeGenFunction::ConstantEmission
tryEmitAsConstant(const MemberExpr * ME)15820b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
15830b57cec5SDimitry Andric if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
15840b57cec5SDimitry Andric return tryEmitAsConstant(DRE);
15850b57cec5SDimitry Andric return ConstantEmission();
15860b57cec5SDimitry Andric }
15870b57cec5SDimitry Andric
emitScalarConstant(const CodeGenFunction::ConstantEmission & Constant,Expr * E)15880b57cec5SDimitry Andric llvm::Value *CodeGenFunction::emitScalarConstant(
15890b57cec5SDimitry Andric const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
15900b57cec5SDimitry Andric assert(Constant && "not a constant");
15910b57cec5SDimitry Andric if (Constant.isReference())
15920b57cec5SDimitry Andric return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
15930b57cec5SDimitry Andric E->getExprLoc())
15940b57cec5SDimitry Andric .getScalarVal();
15950b57cec5SDimitry Andric return Constant.getValue();
15960b57cec5SDimitry Andric }
15970b57cec5SDimitry Andric
EmitLoadOfScalar(LValue lvalue,SourceLocation Loc)15980b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
15990b57cec5SDimitry Andric SourceLocation Loc) {
1600480093f4SDimitry Andric return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
16010b57cec5SDimitry Andric lvalue.getType(), Loc, lvalue.getBaseInfo(),
16020b57cec5SDimitry Andric lvalue.getTBAAInfo(), lvalue.isNontemporal());
16030b57cec5SDimitry Andric }
16040b57cec5SDimitry Andric
hasBooleanRepresentation(QualType Ty)16050b57cec5SDimitry Andric static bool hasBooleanRepresentation(QualType Ty) {
16060b57cec5SDimitry Andric if (Ty->isBooleanType())
16070b57cec5SDimitry Andric return true;
16080b57cec5SDimitry Andric
16090b57cec5SDimitry Andric if (const EnumType *ET = Ty->getAs<EnumType>())
16100b57cec5SDimitry Andric return ET->getDecl()->getIntegerType()->isBooleanType();
16110b57cec5SDimitry Andric
16120b57cec5SDimitry Andric if (const AtomicType *AT = Ty->getAs<AtomicType>())
16130b57cec5SDimitry Andric return hasBooleanRepresentation(AT->getValueType());
16140b57cec5SDimitry Andric
16150b57cec5SDimitry Andric return false;
16160b57cec5SDimitry Andric }
16170b57cec5SDimitry Andric
getRangeForType(CodeGenFunction & CGF,QualType Ty,llvm::APInt & Min,llvm::APInt & End,bool StrictEnums,bool IsBool)16180b57cec5SDimitry Andric static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
16190b57cec5SDimitry Andric llvm::APInt &Min, llvm::APInt &End,
16200b57cec5SDimitry Andric bool StrictEnums, bool IsBool) {
16210b57cec5SDimitry Andric const EnumType *ET = Ty->getAs<EnumType>();
16220b57cec5SDimitry Andric bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
16230b57cec5SDimitry Andric ET && !ET->getDecl()->isFixed();
16240b57cec5SDimitry Andric if (!IsBool && !IsRegularCPlusPlusEnum)
16250b57cec5SDimitry Andric return false;
16260b57cec5SDimitry Andric
16270b57cec5SDimitry Andric if (IsBool) {
16280b57cec5SDimitry Andric Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
16290b57cec5SDimitry Andric End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
16300b57cec5SDimitry Andric } else {
16310b57cec5SDimitry Andric const EnumDecl *ED = ET->getDecl();
16320b57cec5SDimitry Andric llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
16330b57cec5SDimitry Andric unsigned Bitwidth = LTy->getScalarSizeInBits();
16340b57cec5SDimitry Andric unsigned NumNegativeBits = ED->getNumNegativeBits();
16350b57cec5SDimitry Andric unsigned NumPositiveBits = ED->getNumPositiveBits();
16360b57cec5SDimitry Andric
16370b57cec5SDimitry Andric if (NumNegativeBits) {
16380b57cec5SDimitry Andric unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
16390b57cec5SDimitry Andric assert(NumBits <= Bitwidth);
16400b57cec5SDimitry Andric End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
16410b57cec5SDimitry Andric Min = -End;
16420b57cec5SDimitry Andric } else {
16430b57cec5SDimitry Andric assert(NumPositiveBits <= Bitwidth);
16440b57cec5SDimitry Andric End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
16450b57cec5SDimitry Andric Min = llvm::APInt(Bitwidth, 0);
16460b57cec5SDimitry Andric }
16470b57cec5SDimitry Andric }
16480b57cec5SDimitry Andric return true;
16490b57cec5SDimitry Andric }
16500b57cec5SDimitry Andric
getRangeForLoadFromType(QualType Ty)16510b57cec5SDimitry Andric llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
16520b57cec5SDimitry Andric llvm::APInt Min, End;
16530b57cec5SDimitry Andric if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
16540b57cec5SDimitry Andric hasBooleanRepresentation(Ty)))
16550b57cec5SDimitry Andric return nullptr;
16560b57cec5SDimitry Andric
16570b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext());
16580b57cec5SDimitry Andric return MDHelper.createRange(Min, End);
16590b57cec5SDimitry Andric }
16600b57cec5SDimitry Andric
EmitScalarRangeCheck(llvm::Value * Value,QualType Ty,SourceLocation Loc)16610b57cec5SDimitry Andric bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
16620b57cec5SDimitry Andric SourceLocation Loc) {
16630b57cec5SDimitry Andric bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
16640b57cec5SDimitry Andric bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
16650b57cec5SDimitry Andric if (!HasBoolCheck && !HasEnumCheck)
16660b57cec5SDimitry Andric return false;
16670b57cec5SDimitry Andric
16680b57cec5SDimitry Andric bool IsBool = hasBooleanRepresentation(Ty) ||
16690b57cec5SDimitry Andric NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
16700b57cec5SDimitry Andric bool NeedsBoolCheck = HasBoolCheck && IsBool;
16710b57cec5SDimitry Andric bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
16720b57cec5SDimitry Andric if (!NeedsBoolCheck && !NeedsEnumCheck)
16730b57cec5SDimitry Andric return false;
16740b57cec5SDimitry Andric
16750b57cec5SDimitry Andric // Single-bit booleans don't need to be checked. Special-case this to avoid
16760b57cec5SDimitry Andric // a bit width mismatch when handling bitfield values. This is handled by
16770b57cec5SDimitry Andric // EmitFromMemory for the non-bitfield case.
16780b57cec5SDimitry Andric if (IsBool &&
16790b57cec5SDimitry Andric cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
16800b57cec5SDimitry Andric return false;
16810b57cec5SDimitry Andric
16820b57cec5SDimitry Andric llvm::APInt Min, End;
16830b57cec5SDimitry Andric if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
16840b57cec5SDimitry Andric return true;
16850b57cec5SDimitry Andric
16860b57cec5SDimitry Andric auto &Ctx = getLLVMContext();
16870b57cec5SDimitry Andric SanitizerScope SanScope(this);
16880b57cec5SDimitry Andric llvm::Value *Check;
16890b57cec5SDimitry Andric --End;
16900b57cec5SDimitry Andric if (!Min) {
16910b57cec5SDimitry Andric Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
16920b57cec5SDimitry Andric } else {
16930b57cec5SDimitry Andric llvm::Value *Upper =
16940b57cec5SDimitry Andric Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
16950b57cec5SDimitry Andric llvm::Value *Lower =
16960b57cec5SDimitry Andric Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
16970b57cec5SDimitry Andric Check = Builder.CreateAnd(Upper, Lower);
16980b57cec5SDimitry Andric }
16990b57cec5SDimitry Andric llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
17000b57cec5SDimitry Andric EmitCheckTypeDescriptor(Ty)};
17010b57cec5SDimitry Andric SanitizerMask Kind =
17020b57cec5SDimitry Andric NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
17030b57cec5SDimitry Andric EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
17040b57cec5SDimitry Andric StaticArgs, EmitCheckValue(Value));
17050b57cec5SDimitry Andric return true;
17060b57cec5SDimitry Andric }
17070b57cec5SDimitry Andric
EmitLoadOfScalar(Address Addr,bool Volatile,QualType Ty,SourceLocation Loc,LValueBaseInfo BaseInfo,TBAAAccessInfo TBAAInfo,bool isNontemporal)17080b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
17090b57cec5SDimitry Andric QualType Ty,
17100b57cec5SDimitry Andric SourceLocation Loc,
17110b57cec5SDimitry Andric LValueBaseInfo BaseInfo,
17120b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo,
17130b57cec5SDimitry Andric bool isNontemporal) {
17140b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().PreserveVec3Type) {
17150b57cec5SDimitry Andric // For better performance, handle vector loads differently.
17160b57cec5SDimitry Andric if (Ty->isVectorType()) {
17170b57cec5SDimitry Andric const llvm::Type *EltTy = Addr.getElementType();
17180b57cec5SDimitry Andric
1719af732203SDimitry Andric const auto *VTy = cast<llvm::FixedVectorType>(EltTy);
17200b57cec5SDimitry Andric
17210b57cec5SDimitry Andric // Handle vectors of size 3 like size 4 for better performance.
17220b57cec5SDimitry Andric if (VTy->getNumElements() == 3) {
17230b57cec5SDimitry Andric
17240b57cec5SDimitry Andric // Bitcast to vec4 type.
17255ffd83dbSDimitry Andric auto *vec4Ty = llvm::FixedVectorType::get(VTy->getElementType(), 4);
17260b57cec5SDimitry Andric Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
17270b57cec5SDimitry Andric // Now load value.
17280b57cec5SDimitry Andric llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
17290b57cec5SDimitry Andric
17300b57cec5SDimitry Andric // Shuffle vector to get vec3.
1731af732203SDimitry Andric V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2},
1732af732203SDimitry Andric "extractVec");
17330b57cec5SDimitry Andric return EmitFromMemory(V, Ty);
17340b57cec5SDimitry Andric }
17350b57cec5SDimitry Andric }
17360b57cec5SDimitry Andric }
17370b57cec5SDimitry Andric
17380b57cec5SDimitry Andric // Atomic operations have to be done on integral types.
17390b57cec5SDimitry Andric LValue AtomicLValue =
17400b57cec5SDimitry Andric LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
17410b57cec5SDimitry Andric if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
17420b57cec5SDimitry Andric return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
17430b57cec5SDimitry Andric }
17440b57cec5SDimitry Andric
17450b57cec5SDimitry Andric llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
17460b57cec5SDimitry Andric if (isNontemporal) {
17470b57cec5SDimitry Andric llvm::MDNode *Node = llvm::MDNode::get(
17480b57cec5SDimitry Andric Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
17490b57cec5SDimitry Andric Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
17500b57cec5SDimitry Andric }
17510b57cec5SDimitry Andric
17520b57cec5SDimitry Andric CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
17530b57cec5SDimitry Andric
17540b57cec5SDimitry Andric if (EmitScalarRangeCheck(Load, Ty, Loc)) {
17550b57cec5SDimitry Andric // In order to prevent the optimizer from throwing away the check, don't
17560b57cec5SDimitry Andric // attach range metadata to the load.
17570b57cec5SDimitry Andric } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
17580b57cec5SDimitry Andric if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
17590b57cec5SDimitry Andric Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
17600b57cec5SDimitry Andric
17610b57cec5SDimitry Andric return EmitFromMemory(Load, Ty);
17620b57cec5SDimitry Andric }
17630b57cec5SDimitry Andric
EmitToMemory(llvm::Value * Value,QualType Ty)17640b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
17650b57cec5SDimitry Andric // Bool has a different representation in memory than in registers.
17660b57cec5SDimitry Andric if (hasBooleanRepresentation(Ty)) {
17670b57cec5SDimitry Andric // This should really always be an i1, but sometimes it's already
17680b57cec5SDimitry Andric // an i8, and it's awkward to track those cases down.
17690b57cec5SDimitry Andric if (Value->getType()->isIntegerTy(1))
17700b57cec5SDimitry Andric return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
17710b57cec5SDimitry Andric assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
17720b57cec5SDimitry Andric "wrong value rep of bool");
17730b57cec5SDimitry Andric }
17740b57cec5SDimitry Andric
17750b57cec5SDimitry Andric return Value;
17760b57cec5SDimitry Andric }
17770b57cec5SDimitry Andric
EmitFromMemory(llvm::Value * Value,QualType Ty)17780b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
17790b57cec5SDimitry Andric // Bool has a different representation in memory than in registers.
17800b57cec5SDimitry Andric if (hasBooleanRepresentation(Ty)) {
17810b57cec5SDimitry Andric assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
17820b57cec5SDimitry Andric "wrong value rep of bool");
17830b57cec5SDimitry Andric return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
17840b57cec5SDimitry Andric }
17850b57cec5SDimitry Andric
17860b57cec5SDimitry Andric return Value;
17870b57cec5SDimitry Andric }
17880b57cec5SDimitry Andric
17895ffd83dbSDimitry Andric // Convert the pointer of \p Addr to a pointer to a vector (the value type of
17905ffd83dbSDimitry Andric // MatrixType), if it points to a array (the memory type of MatrixType).
MaybeConvertMatrixAddress(Address Addr,CodeGenFunction & CGF,bool IsVector=true)17915ffd83dbSDimitry Andric static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF,
17925ffd83dbSDimitry Andric bool IsVector = true) {
17935ffd83dbSDimitry Andric auto *ArrayTy = dyn_cast<llvm::ArrayType>(
17945ffd83dbSDimitry Andric cast<llvm::PointerType>(Addr.getPointer()->getType())->getElementType());
17955ffd83dbSDimitry Andric if (ArrayTy && IsVector) {
17965ffd83dbSDimitry Andric auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
17975ffd83dbSDimitry Andric ArrayTy->getNumElements());
17985ffd83dbSDimitry Andric
17995ffd83dbSDimitry Andric return Address(CGF.Builder.CreateElementBitCast(Addr, VectorTy));
18005ffd83dbSDimitry Andric }
18015ffd83dbSDimitry Andric auto *VectorTy = dyn_cast<llvm::VectorType>(
18025ffd83dbSDimitry Andric cast<llvm::PointerType>(Addr.getPointer()->getType())->getElementType());
18035ffd83dbSDimitry Andric if (VectorTy && !IsVector) {
1804af732203SDimitry Andric auto *ArrayTy = llvm::ArrayType::get(
1805af732203SDimitry Andric VectorTy->getElementType(),
1806af732203SDimitry Andric cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
18075ffd83dbSDimitry Andric
18085ffd83dbSDimitry Andric return Address(CGF.Builder.CreateElementBitCast(Addr, ArrayTy));
18095ffd83dbSDimitry Andric }
18105ffd83dbSDimitry Andric
18115ffd83dbSDimitry Andric return Addr;
18125ffd83dbSDimitry Andric }
18135ffd83dbSDimitry Andric
18145ffd83dbSDimitry Andric // Emit a store of a matrix LValue. This may require casting the original
18155ffd83dbSDimitry Andric // pointer to memory address (ArrayType) to a pointer to the value type
18165ffd83dbSDimitry Andric // (VectorType).
EmitStoreOfMatrixScalar(llvm::Value * value,LValue lvalue,bool isInit,CodeGenFunction & CGF)18175ffd83dbSDimitry Andric static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
18185ffd83dbSDimitry Andric bool isInit, CodeGenFunction &CGF) {
18195ffd83dbSDimitry Andric Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF,
18205ffd83dbSDimitry Andric value->getType()->isVectorTy());
18215ffd83dbSDimitry Andric CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
18225ffd83dbSDimitry Andric lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
18235ffd83dbSDimitry Andric lvalue.isNontemporal());
18245ffd83dbSDimitry Andric }
18255ffd83dbSDimitry Andric
EmitStoreOfScalar(llvm::Value * Value,Address Addr,bool Volatile,QualType Ty,LValueBaseInfo BaseInfo,TBAAAccessInfo TBAAInfo,bool isInit,bool isNontemporal)18260b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
18270b57cec5SDimitry Andric bool Volatile, QualType Ty,
18280b57cec5SDimitry Andric LValueBaseInfo BaseInfo,
18290b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo,
18300b57cec5SDimitry Andric bool isInit, bool isNontemporal) {
18310b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().PreserveVec3Type) {
18320b57cec5SDimitry Andric // Handle vectors differently to get better performance.
18330b57cec5SDimitry Andric if (Ty->isVectorType()) {
18340b57cec5SDimitry Andric llvm::Type *SrcTy = Value->getType();
18350b57cec5SDimitry Andric auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
18360b57cec5SDimitry Andric // Handle vec3 special.
1837af732203SDimitry Andric if (VecTy && cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) {
18380b57cec5SDimitry Andric // Our source is a vec3, do a shuffle vector to make it a vec4.
1839af732203SDimitry Andric Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
18405ffd83dbSDimitry Andric "extractVec");
18415ffd83dbSDimitry Andric SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
18420b57cec5SDimitry Andric }
18430b57cec5SDimitry Andric if (Addr.getElementType() != SrcTy) {
18440b57cec5SDimitry Andric Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
18450b57cec5SDimitry Andric }
18460b57cec5SDimitry Andric }
18470b57cec5SDimitry Andric }
18480b57cec5SDimitry Andric
18490b57cec5SDimitry Andric Value = EmitToMemory(Value, Ty);
18500b57cec5SDimitry Andric
18510b57cec5SDimitry Andric LValue AtomicLValue =
18520b57cec5SDimitry Andric LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
18530b57cec5SDimitry Andric if (Ty->isAtomicType() ||
18540b57cec5SDimitry Andric (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
18550b57cec5SDimitry Andric EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
18560b57cec5SDimitry Andric return;
18570b57cec5SDimitry Andric }
18580b57cec5SDimitry Andric
18590b57cec5SDimitry Andric llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
18600b57cec5SDimitry Andric if (isNontemporal) {
18610b57cec5SDimitry Andric llvm::MDNode *Node =
18620b57cec5SDimitry Andric llvm::MDNode::get(Store->getContext(),
18630b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
18640b57cec5SDimitry Andric Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
18650b57cec5SDimitry Andric }
18660b57cec5SDimitry Andric
18670b57cec5SDimitry Andric CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
18680b57cec5SDimitry Andric }
18690b57cec5SDimitry Andric
EmitStoreOfScalar(llvm::Value * value,LValue lvalue,bool isInit)18700b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
18710b57cec5SDimitry Andric bool isInit) {
18725ffd83dbSDimitry Andric if (lvalue.getType()->isConstantMatrixType()) {
18735ffd83dbSDimitry Andric EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
18745ffd83dbSDimitry Andric return;
18755ffd83dbSDimitry Andric }
18765ffd83dbSDimitry Andric
1877480093f4SDimitry Andric EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
18780b57cec5SDimitry Andric lvalue.getType(), lvalue.getBaseInfo(),
18790b57cec5SDimitry Andric lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
18800b57cec5SDimitry Andric }
18810b57cec5SDimitry Andric
18825ffd83dbSDimitry Andric // Emit a load of a LValue of matrix type. This may require casting the pointer
18835ffd83dbSDimitry Andric // to memory address (ArrayType) to a pointer to the value type (VectorType).
EmitLoadOfMatrixLValue(LValue LV,SourceLocation Loc,CodeGenFunction & CGF)18845ffd83dbSDimitry Andric static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
18855ffd83dbSDimitry Andric CodeGenFunction &CGF) {
18865ffd83dbSDimitry Andric assert(LV.getType()->isConstantMatrixType());
18875ffd83dbSDimitry Andric Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
18885ffd83dbSDimitry Andric LV.setAddress(Addr);
18895ffd83dbSDimitry Andric return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
18905ffd83dbSDimitry Andric }
18915ffd83dbSDimitry Andric
18920b57cec5SDimitry Andric /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
18930b57cec5SDimitry Andric /// method emits the address of the lvalue, then loads the result as an rvalue,
18940b57cec5SDimitry Andric /// returning the rvalue.
EmitLoadOfLValue(LValue LV,SourceLocation Loc)18950b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
18960b57cec5SDimitry Andric if (LV.isObjCWeak()) {
18970b57cec5SDimitry Andric // load of a __weak object.
1898480093f4SDimitry Andric Address AddrWeakObj = LV.getAddress(*this);
18990b57cec5SDimitry Andric return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
19000b57cec5SDimitry Andric AddrWeakObj));
19010b57cec5SDimitry Andric }
19020b57cec5SDimitry Andric if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
19030b57cec5SDimitry Andric // In MRC mode, we do a load+autorelease.
19040b57cec5SDimitry Andric if (!getLangOpts().ObjCAutoRefCount) {
1905480093f4SDimitry Andric return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
19060b57cec5SDimitry Andric }
19070b57cec5SDimitry Andric
19080b57cec5SDimitry Andric // In ARC mode, we load retained and then consume the value.
1909480093f4SDimitry Andric llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
19100b57cec5SDimitry Andric Object = EmitObjCConsumeObject(LV.getType(), Object);
19110b57cec5SDimitry Andric return RValue::get(Object);
19120b57cec5SDimitry Andric }
19130b57cec5SDimitry Andric
19140b57cec5SDimitry Andric if (LV.isSimple()) {
19150b57cec5SDimitry Andric assert(!LV.getType()->isFunctionType());
19160b57cec5SDimitry Andric
19175ffd83dbSDimitry Andric if (LV.getType()->isConstantMatrixType())
19185ffd83dbSDimitry Andric return EmitLoadOfMatrixLValue(LV, Loc, *this);
19195ffd83dbSDimitry Andric
19200b57cec5SDimitry Andric // Everything needs a load.
19210b57cec5SDimitry Andric return RValue::get(EmitLoadOfScalar(LV, Loc));
19220b57cec5SDimitry Andric }
19230b57cec5SDimitry Andric
19240b57cec5SDimitry Andric if (LV.isVectorElt()) {
19250b57cec5SDimitry Andric llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
19260b57cec5SDimitry Andric LV.isVolatileQualified());
19270b57cec5SDimitry Andric return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
19280b57cec5SDimitry Andric "vecext"));
19290b57cec5SDimitry Andric }
19300b57cec5SDimitry Andric
19310b57cec5SDimitry Andric // If this is a reference to a subset of the elements of a vector, either
19320b57cec5SDimitry Andric // shuffle the input or extract/insert them as appropriate.
19335ffd83dbSDimitry Andric if (LV.isExtVectorElt()) {
19340b57cec5SDimitry Andric return EmitLoadOfExtVectorElementLValue(LV);
19355ffd83dbSDimitry Andric }
19360b57cec5SDimitry Andric
19370b57cec5SDimitry Andric // Global Register variables always invoke intrinsics
19380b57cec5SDimitry Andric if (LV.isGlobalReg())
19390b57cec5SDimitry Andric return EmitLoadOfGlobalRegLValue(LV);
19400b57cec5SDimitry Andric
19415ffd83dbSDimitry Andric if (LV.isMatrixElt()) {
19425ffd83dbSDimitry Andric llvm::LoadInst *Load =
19435ffd83dbSDimitry Andric Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
19445ffd83dbSDimitry Andric return RValue::get(
19455ffd83dbSDimitry Andric Builder.CreateExtractElement(Load, LV.getMatrixIdx(), "matrixext"));
19465ffd83dbSDimitry Andric }
19475ffd83dbSDimitry Andric
19480b57cec5SDimitry Andric assert(LV.isBitField() && "Unknown LValue type!");
19490b57cec5SDimitry Andric return EmitLoadOfBitfieldLValue(LV, Loc);
19500b57cec5SDimitry Andric }
19510b57cec5SDimitry Andric
EmitLoadOfBitfieldLValue(LValue LV,SourceLocation Loc)19520b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
19530b57cec5SDimitry Andric SourceLocation Loc) {
19540b57cec5SDimitry Andric const CGBitFieldInfo &Info = LV.getBitFieldInfo();
19550b57cec5SDimitry Andric
19560b57cec5SDimitry Andric // Get the output type.
19570b57cec5SDimitry Andric llvm::Type *ResLTy = ConvertType(LV.getType());
19580b57cec5SDimitry Andric
19590b57cec5SDimitry Andric Address Ptr = LV.getBitFieldAddress();
1960af732203SDimitry Andric llvm::Value *Val =
1961af732203SDimitry Andric Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
19620b57cec5SDimitry Andric
1963af732203SDimitry Andric bool UseVolatile = LV.isVolatileQualified() &&
1964af732203SDimitry Andric Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
1965af732203SDimitry Andric const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
1966af732203SDimitry Andric const unsigned StorageSize =
1967af732203SDimitry Andric UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
19680b57cec5SDimitry Andric if (Info.IsSigned) {
1969af732203SDimitry Andric assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
1970af732203SDimitry Andric unsigned HighBits = StorageSize - Offset - Info.Size;
19710b57cec5SDimitry Andric if (HighBits)
19720b57cec5SDimitry Andric Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1973af732203SDimitry Andric if (Offset + HighBits)
1974af732203SDimitry Andric Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
19750b57cec5SDimitry Andric } else {
1976af732203SDimitry Andric if (Offset)
1977af732203SDimitry Andric Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
1978af732203SDimitry Andric if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
1979af732203SDimitry Andric Val = Builder.CreateAnd(
1980af732203SDimitry Andric Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
19810b57cec5SDimitry Andric }
19820b57cec5SDimitry Andric Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
19830b57cec5SDimitry Andric EmitScalarRangeCheck(Val, LV.getType(), Loc);
19840b57cec5SDimitry Andric return RValue::get(Val);
19850b57cec5SDimitry Andric }
19860b57cec5SDimitry Andric
19870b57cec5SDimitry Andric // If this is a reference to a subset of the elements of a vector, create an
19880b57cec5SDimitry Andric // appropriate shufflevector.
EmitLoadOfExtVectorElementLValue(LValue LV)19890b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
19900b57cec5SDimitry Andric llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
19910b57cec5SDimitry Andric LV.isVolatileQualified());
19920b57cec5SDimitry Andric
19930b57cec5SDimitry Andric const llvm::Constant *Elts = LV.getExtVectorElts();
19940b57cec5SDimitry Andric
19950b57cec5SDimitry Andric // If the result of the expression is a non-vector type, we must be extracting
19960b57cec5SDimitry Andric // a single element. Just codegen as an extractelement.
19970b57cec5SDimitry Andric const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
19980b57cec5SDimitry Andric if (!ExprVT) {
19990b57cec5SDimitry Andric unsigned InIdx = getAccessedFieldNo(0, Elts);
20000b57cec5SDimitry Andric llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
20010b57cec5SDimitry Andric return RValue::get(Builder.CreateExtractElement(Vec, Elt));
20020b57cec5SDimitry Andric }
20030b57cec5SDimitry Andric
20040b57cec5SDimitry Andric // Always use shuffle vector to try to retain the original program structure
20050b57cec5SDimitry Andric unsigned NumResultElts = ExprVT->getNumElements();
20060b57cec5SDimitry Andric
20075ffd83dbSDimitry Andric SmallVector<int, 4> Mask;
20080b57cec5SDimitry Andric for (unsigned i = 0; i != NumResultElts; ++i)
20095ffd83dbSDimitry Andric Mask.push_back(getAccessedFieldNo(i, Elts));
20100b57cec5SDimitry Andric
2011af732203SDimitry Andric Vec = Builder.CreateShuffleVector(Vec, Mask);
20120b57cec5SDimitry Andric return RValue::get(Vec);
20130b57cec5SDimitry Andric }
20140b57cec5SDimitry Andric
20150b57cec5SDimitry Andric /// Generates lvalue for partial ext_vector access.
EmitExtVectorElementLValue(LValue LV)20160b57cec5SDimitry Andric Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
20170b57cec5SDimitry Andric Address VectorAddress = LV.getExtVectorAddress();
2018480093f4SDimitry Andric QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
20190b57cec5SDimitry Andric llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
20200b57cec5SDimitry Andric
20210b57cec5SDimitry Andric Address CastToPointerElement =
20220b57cec5SDimitry Andric Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
20230b57cec5SDimitry Andric "conv.ptr.element");
20240b57cec5SDimitry Andric
20250b57cec5SDimitry Andric const llvm::Constant *Elts = LV.getExtVectorElts();
20260b57cec5SDimitry Andric unsigned ix = getAccessedFieldNo(0, Elts);
20270b57cec5SDimitry Andric
20280b57cec5SDimitry Andric Address VectorBasePtrPlusIx =
20290b57cec5SDimitry Andric Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
20300b57cec5SDimitry Andric "vector.elt");
20310b57cec5SDimitry Andric
20320b57cec5SDimitry Andric return VectorBasePtrPlusIx;
20330b57cec5SDimitry Andric }
20340b57cec5SDimitry Andric
20350b57cec5SDimitry Andric /// Load of global gamed gegisters are always calls to intrinsics.
EmitLoadOfGlobalRegLValue(LValue LV)20360b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
20370b57cec5SDimitry Andric assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
20380b57cec5SDimitry Andric "Bad type for register variable");
20390b57cec5SDimitry Andric llvm::MDNode *RegName = cast<llvm::MDNode>(
20400b57cec5SDimitry Andric cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
20410b57cec5SDimitry Andric
20420b57cec5SDimitry Andric // We accept integer and pointer types only
20430b57cec5SDimitry Andric llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
20440b57cec5SDimitry Andric llvm::Type *Ty = OrigTy;
20450b57cec5SDimitry Andric if (OrigTy->isPointerTy())
20460b57cec5SDimitry Andric Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
20470b57cec5SDimitry Andric llvm::Type *Types[] = { Ty };
20480b57cec5SDimitry Andric
20490b57cec5SDimitry Andric llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
20500b57cec5SDimitry Andric llvm::Value *Call = Builder.CreateCall(
20510b57cec5SDimitry Andric F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
20520b57cec5SDimitry Andric if (OrigTy->isPointerTy())
20530b57cec5SDimitry Andric Call = Builder.CreateIntToPtr(Call, OrigTy);
20540b57cec5SDimitry Andric return RValue::get(Call);
20550b57cec5SDimitry Andric }
20560b57cec5SDimitry Andric
20570b57cec5SDimitry Andric /// EmitStoreThroughLValue - Store the specified rvalue into the specified
20580b57cec5SDimitry Andric /// lvalue, where both are guaranteed to the have the same type, and that type
20590b57cec5SDimitry Andric /// is 'Ty'.
EmitStoreThroughLValue(RValue Src,LValue Dst,bool isInit)20600b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
20610b57cec5SDimitry Andric bool isInit) {
20620b57cec5SDimitry Andric if (!Dst.isSimple()) {
20630b57cec5SDimitry Andric if (Dst.isVectorElt()) {
20640b57cec5SDimitry Andric // Read/modify/write the vector, inserting the new element.
20650b57cec5SDimitry Andric llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
20660b57cec5SDimitry Andric Dst.isVolatileQualified());
20670b57cec5SDimitry Andric Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
20680b57cec5SDimitry Andric Dst.getVectorIdx(), "vecins");
20690b57cec5SDimitry Andric Builder.CreateStore(Vec, Dst.getVectorAddress(),
20700b57cec5SDimitry Andric Dst.isVolatileQualified());
20710b57cec5SDimitry Andric return;
20720b57cec5SDimitry Andric }
20730b57cec5SDimitry Andric
20740b57cec5SDimitry Andric // If this is an update of extended vector elements, insert them as
20750b57cec5SDimitry Andric // appropriate.
20760b57cec5SDimitry Andric if (Dst.isExtVectorElt())
20770b57cec5SDimitry Andric return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
20780b57cec5SDimitry Andric
20790b57cec5SDimitry Andric if (Dst.isGlobalReg())
20800b57cec5SDimitry Andric return EmitStoreThroughGlobalRegLValue(Src, Dst);
20810b57cec5SDimitry Andric
20825ffd83dbSDimitry Andric if (Dst.isMatrixElt()) {
20835ffd83dbSDimitry Andric llvm::Value *Vec = Builder.CreateLoad(Dst.getMatrixAddress());
20845ffd83dbSDimitry Andric Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
20855ffd83dbSDimitry Andric Dst.getMatrixIdx(), "matins");
20865ffd83dbSDimitry Andric Builder.CreateStore(Vec, Dst.getMatrixAddress(),
20875ffd83dbSDimitry Andric Dst.isVolatileQualified());
20885ffd83dbSDimitry Andric return;
20895ffd83dbSDimitry Andric }
20905ffd83dbSDimitry Andric
20910b57cec5SDimitry Andric assert(Dst.isBitField() && "Unknown LValue type");
20920b57cec5SDimitry Andric return EmitStoreThroughBitfieldLValue(Src, Dst);
20930b57cec5SDimitry Andric }
20940b57cec5SDimitry Andric
20950b57cec5SDimitry Andric // There's special magic for assigning into an ARC-qualified l-value.
20960b57cec5SDimitry Andric if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
20970b57cec5SDimitry Andric switch (Lifetime) {
20980b57cec5SDimitry Andric case Qualifiers::OCL_None:
20990b57cec5SDimitry Andric llvm_unreachable("present but none");
21000b57cec5SDimitry Andric
21010b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone:
21020b57cec5SDimitry Andric // nothing special
21030b57cec5SDimitry Andric break;
21040b57cec5SDimitry Andric
21050b57cec5SDimitry Andric case Qualifiers::OCL_Strong:
21060b57cec5SDimitry Andric if (isInit) {
21070b57cec5SDimitry Andric Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
21080b57cec5SDimitry Andric break;
21090b57cec5SDimitry Andric }
21100b57cec5SDimitry Andric EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
21110b57cec5SDimitry Andric return;
21120b57cec5SDimitry Andric
21130b57cec5SDimitry Andric case Qualifiers::OCL_Weak:
21140b57cec5SDimitry Andric if (isInit)
21150b57cec5SDimitry Andric // Initialize and then skip the primitive store.
2116480093f4SDimitry Andric EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
21170b57cec5SDimitry Andric else
2118480093f4SDimitry Andric EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
2119480093f4SDimitry Andric /*ignore*/ true);
21200b57cec5SDimitry Andric return;
21210b57cec5SDimitry Andric
21220b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing:
21230b57cec5SDimitry Andric Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
21240b57cec5SDimitry Andric Src.getScalarVal()));
21250b57cec5SDimitry Andric // fall into the normal path
21260b57cec5SDimitry Andric break;
21270b57cec5SDimitry Andric }
21280b57cec5SDimitry Andric }
21290b57cec5SDimitry Andric
21300b57cec5SDimitry Andric if (Dst.isObjCWeak() && !Dst.isNonGC()) {
21310b57cec5SDimitry Andric // load of a __weak object.
2132480093f4SDimitry Andric Address LvalueDst = Dst.getAddress(*this);
21330b57cec5SDimitry Andric llvm::Value *src = Src.getScalarVal();
21340b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
21350b57cec5SDimitry Andric return;
21360b57cec5SDimitry Andric }
21370b57cec5SDimitry Andric
21380b57cec5SDimitry Andric if (Dst.isObjCStrong() && !Dst.isNonGC()) {
21390b57cec5SDimitry Andric // load of a __strong object.
2140480093f4SDimitry Andric Address LvalueDst = Dst.getAddress(*this);
21410b57cec5SDimitry Andric llvm::Value *src = Src.getScalarVal();
21420b57cec5SDimitry Andric if (Dst.isObjCIvar()) {
21430b57cec5SDimitry Andric assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
21440b57cec5SDimitry Andric llvm::Type *ResultType = IntPtrTy;
21450b57cec5SDimitry Andric Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
21460b57cec5SDimitry Andric llvm::Value *RHS = dst.getPointer();
21470b57cec5SDimitry Andric RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
21480b57cec5SDimitry Andric llvm::Value *LHS =
21490b57cec5SDimitry Andric Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
21500b57cec5SDimitry Andric "sub.ptr.lhs.cast");
21510b57cec5SDimitry Andric llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
21520b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
21530b57cec5SDimitry Andric BytesBetween);
21540b57cec5SDimitry Andric } else if (Dst.isGlobalObjCRef()) {
21550b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
21560b57cec5SDimitry Andric Dst.isThreadLocalRef());
21570b57cec5SDimitry Andric }
21580b57cec5SDimitry Andric else
21590b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
21600b57cec5SDimitry Andric return;
21610b57cec5SDimitry Andric }
21620b57cec5SDimitry Andric
21630b57cec5SDimitry Andric assert(Src.isScalar() && "Can't emit an agg store with this method");
21640b57cec5SDimitry Andric EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
21650b57cec5SDimitry Andric }
21660b57cec5SDimitry Andric
EmitStoreThroughBitfieldLValue(RValue Src,LValue Dst,llvm::Value ** Result)21670b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
21680b57cec5SDimitry Andric llvm::Value **Result) {
21690b57cec5SDimitry Andric const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
21700b57cec5SDimitry Andric llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
21710b57cec5SDimitry Andric Address Ptr = Dst.getBitFieldAddress();
21720b57cec5SDimitry Andric
21730b57cec5SDimitry Andric // Get the source value, truncated to the width of the bit-field.
21740b57cec5SDimitry Andric llvm::Value *SrcVal = Src.getScalarVal();
21750b57cec5SDimitry Andric
21760b57cec5SDimitry Andric // Cast the source to the storage type and shift it into place.
21770b57cec5SDimitry Andric SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
21780b57cec5SDimitry Andric /*isSigned=*/false);
21790b57cec5SDimitry Andric llvm::Value *MaskedVal = SrcVal;
21800b57cec5SDimitry Andric
2181af732203SDimitry Andric const bool UseVolatile =
2182af732203SDimitry Andric CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2183af732203SDimitry Andric Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2184af732203SDimitry Andric const unsigned StorageSize =
2185af732203SDimitry Andric UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2186af732203SDimitry Andric const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
21870b57cec5SDimitry Andric // See if there are other bits in the bitfield's storage we'll need to load
21880b57cec5SDimitry Andric // and mask together with source before storing.
2189af732203SDimitry Andric if (StorageSize != Info.Size) {
2190af732203SDimitry Andric assert(StorageSize > Info.Size && "Invalid bitfield size.");
21910b57cec5SDimitry Andric llvm::Value *Val =
21920b57cec5SDimitry Andric Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
21930b57cec5SDimitry Andric
21940b57cec5SDimitry Andric // Mask the source value as needed.
21950b57cec5SDimitry Andric if (!hasBooleanRepresentation(Dst.getType()))
2196af732203SDimitry Andric SrcVal = Builder.CreateAnd(
2197af732203SDimitry Andric SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
21980b57cec5SDimitry Andric "bf.value");
21990b57cec5SDimitry Andric MaskedVal = SrcVal;
2200af732203SDimitry Andric if (Offset)
2201af732203SDimitry Andric SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
22020b57cec5SDimitry Andric
22030b57cec5SDimitry Andric // Mask out the original value.
2204af732203SDimitry Andric Val = Builder.CreateAnd(
2205af732203SDimitry Andric Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
22060b57cec5SDimitry Andric "bf.clear");
22070b57cec5SDimitry Andric
22080b57cec5SDimitry Andric // Or together the unchanged values and the source value.
22090b57cec5SDimitry Andric SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
22100b57cec5SDimitry Andric } else {
2211af732203SDimitry Andric assert(Offset == 0);
22125ffd83dbSDimitry Andric // According to the AACPS:
22135ffd83dbSDimitry Andric // When a volatile bit-field is written, and its container does not overlap
2214af732203SDimitry Andric // with any non-bit-field member, its container must be read exactly once
2215af732203SDimitry Andric // and written exactly once using the access width appropriate to the type
2216af732203SDimitry Andric // of the container. The two accesses are not atomic.
22175ffd83dbSDimitry Andric if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
22185ffd83dbSDimitry Andric CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
22195ffd83dbSDimitry Andric Builder.CreateLoad(Ptr, true, "bf.load");
22200b57cec5SDimitry Andric }
22210b57cec5SDimitry Andric
22220b57cec5SDimitry Andric // Write the new value back out.
22230b57cec5SDimitry Andric Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
22240b57cec5SDimitry Andric
22250b57cec5SDimitry Andric // Return the new value of the bit-field, if requested.
22260b57cec5SDimitry Andric if (Result) {
22270b57cec5SDimitry Andric llvm::Value *ResultVal = MaskedVal;
22280b57cec5SDimitry Andric
22290b57cec5SDimitry Andric // Sign extend the value if needed.
22300b57cec5SDimitry Andric if (Info.IsSigned) {
2231af732203SDimitry Andric assert(Info.Size <= StorageSize);
2232af732203SDimitry Andric unsigned HighBits = StorageSize - Info.Size;
22330b57cec5SDimitry Andric if (HighBits) {
22340b57cec5SDimitry Andric ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
22350b57cec5SDimitry Andric ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
22360b57cec5SDimitry Andric }
22370b57cec5SDimitry Andric }
22380b57cec5SDimitry Andric
22390b57cec5SDimitry Andric ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
22400b57cec5SDimitry Andric "bf.result.cast");
22410b57cec5SDimitry Andric *Result = EmitFromMemory(ResultVal, Dst.getType());
22420b57cec5SDimitry Andric }
22430b57cec5SDimitry Andric }
22440b57cec5SDimitry Andric
EmitStoreThroughExtVectorComponentLValue(RValue Src,LValue Dst)22450b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
22460b57cec5SDimitry Andric LValue Dst) {
22470b57cec5SDimitry Andric // This access turns into a read/modify/write of the vector. Load the input
22480b57cec5SDimitry Andric // value now.
22490b57cec5SDimitry Andric llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
22500b57cec5SDimitry Andric Dst.isVolatileQualified());
22510b57cec5SDimitry Andric const llvm::Constant *Elts = Dst.getExtVectorElts();
22520b57cec5SDimitry Andric
22530b57cec5SDimitry Andric llvm::Value *SrcVal = Src.getScalarVal();
22540b57cec5SDimitry Andric
22550b57cec5SDimitry Andric if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
22560b57cec5SDimitry Andric unsigned NumSrcElts = VTy->getNumElements();
22575ffd83dbSDimitry Andric unsigned NumDstElts =
2258af732203SDimitry Andric cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
22590b57cec5SDimitry Andric if (NumDstElts == NumSrcElts) {
22600b57cec5SDimitry Andric // Use shuffle vector is the src and destination are the same number of
22610b57cec5SDimitry Andric // elements and restore the vector mask since it is on the side it will be
22620b57cec5SDimitry Andric // stored.
22635ffd83dbSDimitry Andric SmallVector<int, 4> Mask(NumDstElts);
22640b57cec5SDimitry Andric for (unsigned i = 0; i != NumSrcElts; ++i)
22655ffd83dbSDimitry Andric Mask[getAccessedFieldNo(i, Elts)] = i;
22660b57cec5SDimitry Andric
2267af732203SDimitry Andric Vec = Builder.CreateShuffleVector(SrcVal, Mask);
22680b57cec5SDimitry Andric } else if (NumDstElts > NumSrcElts) {
22690b57cec5SDimitry Andric // Extended the source vector to the same length and then shuffle it
22700b57cec5SDimitry Andric // into the destination.
22710b57cec5SDimitry Andric // FIXME: since we're shuffling with undef, can we just use the indices
22720b57cec5SDimitry Andric // into that? This could be simpler.
22735ffd83dbSDimitry Andric SmallVector<int, 4> ExtMask;
22740b57cec5SDimitry Andric for (unsigned i = 0; i != NumSrcElts; ++i)
22755ffd83dbSDimitry Andric ExtMask.push_back(i);
22765ffd83dbSDimitry Andric ExtMask.resize(NumDstElts, -1);
2277af732203SDimitry Andric llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
22780b57cec5SDimitry Andric // build identity
22795ffd83dbSDimitry Andric SmallVector<int, 4> Mask;
22800b57cec5SDimitry Andric for (unsigned i = 0; i != NumDstElts; ++i)
22815ffd83dbSDimitry Andric Mask.push_back(i);
22820b57cec5SDimitry Andric
22830b57cec5SDimitry Andric // When the vector size is odd and .odd or .hi is used, the last element
22840b57cec5SDimitry Andric // of the Elts constant array will be one past the size of the vector.
22850b57cec5SDimitry Andric // Ignore the last element here, if it is greater than the mask size.
22860b57cec5SDimitry Andric if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
22870b57cec5SDimitry Andric NumSrcElts--;
22880b57cec5SDimitry Andric
22890b57cec5SDimitry Andric // modify when what gets shuffled in
22900b57cec5SDimitry Andric for (unsigned i = 0; i != NumSrcElts; ++i)
22915ffd83dbSDimitry Andric Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
22925ffd83dbSDimitry Andric Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
22930b57cec5SDimitry Andric } else {
22940b57cec5SDimitry Andric // We should never shorten the vector
22950b57cec5SDimitry Andric llvm_unreachable("unexpected shorten vector length");
22960b57cec5SDimitry Andric }
22970b57cec5SDimitry Andric } else {
22980b57cec5SDimitry Andric // If the Src is a scalar (not a vector) it must be updating one element.
22990b57cec5SDimitry Andric unsigned InIdx = getAccessedFieldNo(0, Elts);
23000b57cec5SDimitry Andric llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
23010b57cec5SDimitry Andric Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
23020b57cec5SDimitry Andric }
23030b57cec5SDimitry Andric
23040b57cec5SDimitry Andric Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
23050b57cec5SDimitry Andric Dst.isVolatileQualified());
23060b57cec5SDimitry Andric }
23070b57cec5SDimitry Andric
23080b57cec5SDimitry Andric /// Store of global named registers are always calls to intrinsics.
EmitStoreThroughGlobalRegLValue(RValue Src,LValue Dst)23090b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
23100b57cec5SDimitry Andric assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
23110b57cec5SDimitry Andric "Bad type for register variable");
23120b57cec5SDimitry Andric llvm::MDNode *RegName = cast<llvm::MDNode>(
23130b57cec5SDimitry Andric cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
23140b57cec5SDimitry Andric assert(RegName && "Register LValue is not metadata");
23150b57cec5SDimitry Andric
23160b57cec5SDimitry Andric // We accept integer and pointer types only
23170b57cec5SDimitry Andric llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
23180b57cec5SDimitry Andric llvm::Type *Ty = OrigTy;
23190b57cec5SDimitry Andric if (OrigTy->isPointerTy())
23200b57cec5SDimitry Andric Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
23210b57cec5SDimitry Andric llvm::Type *Types[] = { Ty };
23220b57cec5SDimitry Andric
23230b57cec5SDimitry Andric llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
23240b57cec5SDimitry Andric llvm::Value *Value = Src.getScalarVal();
23250b57cec5SDimitry Andric if (OrigTy->isPointerTy())
23260b57cec5SDimitry Andric Value = Builder.CreatePtrToInt(Value, Ty);
23270b57cec5SDimitry Andric Builder.CreateCall(
23280b57cec5SDimitry Andric F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
23290b57cec5SDimitry Andric }
23300b57cec5SDimitry Andric
23310b57cec5SDimitry Andric // setObjCGCLValueClass - sets class of the lvalue for the purpose of
23320b57cec5SDimitry Andric // generating write-barries API. It is currently a global, ivar,
23330b57cec5SDimitry Andric // or neither.
setObjCGCLValueClass(const ASTContext & Ctx,const Expr * E,LValue & LV,bool IsMemberAccess=false)23340b57cec5SDimitry Andric static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
23350b57cec5SDimitry Andric LValue &LV,
23360b57cec5SDimitry Andric bool IsMemberAccess=false) {
23370b57cec5SDimitry Andric if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
23380b57cec5SDimitry Andric return;
23390b57cec5SDimitry Andric
23400b57cec5SDimitry Andric if (isa<ObjCIvarRefExpr>(E)) {
23410b57cec5SDimitry Andric QualType ExpTy = E->getType();
23420b57cec5SDimitry Andric if (IsMemberAccess && ExpTy->isPointerType()) {
23430b57cec5SDimitry Andric // If ivar is a structure pointer, assigning to field of
23440b57cec5SDimitry Andric // this struct follows gcc's behavior and makes it a non-ivar
23450b57cec5SDimitry Andric // writer-barrier conservatively.
2346a7dea167SDimitry Andric ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
23470b57cec5SDimitry Andric if (ExpTy->isRecordType()) {
23480b57cec5SDimitry Andric LV.setObjCIvar(false);
23490b57cec5SDimitry Andric return;
23500b57cec5SDimitry Andric }
23510b57cec5SDimitry Andric }
23520b57cec5SDimitry Andric LV.setObjCIvar(true);
23530b57cec5SDimitry Andric auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
23540b57cec5SDimitry Andric LV.setBaseIvarExp(Exp->getBase());
23550b57cec5SDimitry Andric LV.setObjCArray(E->getType()->isArrayType());
23560b57cec5SDimitry Andric return;
23570b57cec5SDimitry Andric }
23580b57cec5SDimitry Andric
23590b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
23600b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
23610b57cec5SDimitry Andric if (VD->hasGlobalStorage()) {
23620b57cec5SDimitry Andric LV.setGlobalObjCRef(true);
23630b57cec5SDimitry Andric LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
23640b57cec5SDimitry Andric }
23650b57cec5SDimitry Andric }
23660b57cec5SDimitry Andric LV.setObjCArray(E->getType()->isArrayType());
23670b57cec5SDimitry Andric return;
23680b57cec5SDimitry Andric }
23690b57cec5SDimitry Andric
23700b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
23710b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
23720b57cec5SDimitry Andric return;
23730b57cec5SDimitry Andric }
23740b57cec5SDimitry Andric
23750b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
23760b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
23770b57cec5SDimitry Andric if (LV.isObjCIvar()) {
23780b57cec5SDimitry Andric // If cast is to a structure pointer, follow gcc's behavior and make it
23790b57cec5SDimitry Andric // a non-ivar write-barrier.
23800b57cec5SDimitry Andric QualType ExpTy = E->getType();
23810b57cec5SDimitry Andric if (ExpTy->isPointerType())
2382a7dea167SDimitry Andric ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
23830b57cec5SDimitry Andric if (ExpTy->isRecordType())
23840b57cec5SDimitry Andric LV.setObjCIvar(false);
23850b57cec5SDimitry Andric }
23860b57cec5SDimitry Andric return;
23870b57cec5SDimitry Andric }
23880b57cec5SDimitry Andric
23890b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
23900b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
23910b57cec5SDimitry Andric return;
23920b57cec5SDimitry Andric }
23930b57cec5SDimitry Andric
23940b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
23950b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
23960b57cec5SDimitry Andric return;
23970b57cec5SDimitry Andric }
23980b57cec5SDimitry Andric
23990b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
24000b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
24010b57cec5SDimitry Andric return;
24020b57cec5SDimitry Andric }
24030b57cec5SDimitry Andric
24040b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
24050b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
24060b57cec5SDimitry Andric return;
24070b57cec5SDimitry Andric }
24080b57cec5SDimitry Andric
24090b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
24100b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
24110b57cec5SDimitry Andric if (LV.isObjCIvar() && !LV.isObjCArray())
24120b57cec5SDimitry Andric // Using array syntax to assigning to what an ivar points to is not
24130b57cec5SDimitry Andric // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
24140b57cec5SDimitry Andric LV.setObjCIvar(false);
24150b57cec5SDimitry Andric else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
24160b57cec5SDimitry Andric // Using array syntax to assigning to what global points to is not
24170b57cec5SDimitry Andric // same as assigning to the global itself. {id *G;} G[i] = 0;
24180b57cec5SDimitry Andric LV.setGlobalObjCRef(false);
24190b57cec5SDimitry Andric return;
24200b57cec5SDimitry Andric }
24210b57cec5SDimitry Andric
24220b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
24230b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
24240b57cec5SDimitry Andric // We don't know if member is an 'ivar', but this flag is looked at
24250b57cec5SDimitry Andric // only in the context of LV.isObjCIvar().
24260b57cec5SDimitry Andric LV.setObjCArray(E->getType()->isArrayType());
24270b57cec5SDimitry Andric return;
24280b57cec5SDimitry Andric }
24290b57cec5SDimitry Andric }
24300b57cec5SDimitry Andric
24310b57cec5SDimitry Andric static llvm::Value *
EmitBitCastOfLValueToProperType(CodeGenFunction & CGF,llvm::Value * V,llvm::Type * IRType,StringRef Name=StringRef ())24320b57cec5SDimitry Andric EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
24330b57cec5SDimitry Andric llvm::Value *V, llvm::Type *IRType,
24340b57cec5SDimitry Andric StringRef Name = StringRef()) {
24350b57cec5SDimitry Andric unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
24360b57cec5SDimitry Andric return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
24370b57cec5SDimitry Andric }
24380b57cec5SDimitry Andric
EmitThreadPrivateVarDeclLValue(CodeGenFunction & CGF,const VarDecl * VD,QualType T,Address Addr,llvm::Type * RealVarTy,SourceLocation Loc)24390b57cec5SDimitry Andric static LValue EmitThreadPrivateVarDeclLValue(
24400b57cec5SDimitry Andric CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
24410b57cec5SDimitry Andric llvm::Type *RealVarTy, SourceLocation Loc) {
24425ffd83dbSDimitry Andric if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
24435ffd83dbSDimitry Andric Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
24445ffd83dbSDimitry Andric CGF, VD, Addr, Loc);
24455ffd83dbSDimitry Andric else
24465ffd83dbSDimitry Andric Addr =
24475ffd83dbSDimitry Andric CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
24485ffd83dbSDimitry Andric
24490b57cec5SDimitry Andric Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
24500b57cec5SDimitry Andric return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
24510b57cec5SDimitry Andric }
24520b57cec5SDimitry Andric
emitDeclTargetVarDeclLValue(CodeGenFunction & CGF,const VarDecl * VD,QualType T)24530b57cec5SDimitry Andric static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
24540b57cec5SDimitry Andric const VarDecl *VD, QualType T) {
24550b57cec5SDimitry Andric llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
24560b57cec5SDimitry Andric OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
24570b57cec5SDimitry Andric // Return an invalid address if variable is MT_To and unified
24580b57cec5SDimitry Andric // memory is not enabled. For all other cases: MT_Link and
24590b57cec5SDimitry Andric // MT_To with unified memory, return a valid address.
24600b57cec5SDimitry Andric if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
24610b57cec5SDimitry Andric !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
24620b57cec5SDimitry Andric return Address::invalid();
24630b57cec5SDimitry Andric assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
24640b57cec5SDimitry Andric (*Res == OMPDeclareTargetDeclAttr::MT_To &&
24650b57cec5SDimitry Andric CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
24660b57cec5SDimitry Andric "Expected link clause OR to clause with unified memory enabled.");
24670b57cec5SDimitry Andric QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
24680b57cec5SDimitry Andric Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
24690b57cec5SDimitry Andric return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
24700b57cec5SDimitry Andric }
24710b57cec5SDimitry Andric
24720b57cec5SDimitry Andric Address
EmitLoadOfReference(LValue RefLVal,LValueBaseInfo * PointeeBaseInfo,TBAAAccessInfo * PointeeTBAAInfo)24730b57cec5SDimitry Andric CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
24740b57cec5SDimitry Andric LValueBaseInfo *PointeeBaseInfo,
24750b57cec5SDimitry Andric TBAAAccessInfo *PointeeTBAAInfo) {
2476480093f4SDimitry Andric llvm::LoadInst *Load =
2477480093f4SDimitry Andric Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
24780b57cec5SDimitry Andric CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
24790b57cec5SDimitry Andric
24805ffd83dbSDimitry Andric CharUnits Align = CGM.getNaturalTypeAlignment(
24815ffd83dbSDimitry Andric RefLVal.getType()->getPointeeType(), PointeeBaseInfo, PointeeTBAAInfo,
24820b57cec5SDimitry Andric /* forPointeeType= */ true);
24830b57cec5SDimitry Andric return Address(Load, Align);
24840b57cec5SDimitry Andric }
24850b57cec5SDimitry Andric
EmitLoadOfReferenceLValue(LValue RefLVal)24860b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
24870b57cec5SDimitry Andric LValueBaseInfo PointeeBaseInfo;
24880b57cec5SDimitry Andric TBAAAccessInfo PointeeTBAAInfo;
24890b57cec5SDimitry Andric Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
24900b57cec5SDimitry Andric &PointeeTBAAInfo);
24910b57cec5SDimitry Andric return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
24920b57cec5SDimitry Andric PointeeBaseInfo, PointeeTBAAInfo);
24930b57cec5SDimitry Andric }
24940b57cec5SDimitry Andric
EmitLoadOfPointer(Address Ptr,const PointerType * PtrTy,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)24950b57cec5SDimitry Andric Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
24960b57cec5SDimitry Andric const PointerType *PtrTy,
24970b57cec5SDimitry Andric LValueBaseInfo *BaseInfo,
24980b57cec5SDimitry Andric TBAAAccessInfo *TBAAInfo) {
24990b57cec5SDimitry Andric llvm::Value *Addr = Builder.CreateLoad(Ptr);
25005ffd83dbSDimitry Andric return Address(Addr, CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(),
25010b57cec5SDimitry Andric BaseInfo, TBAAInfo,
25020b57cec5SDimitry Andric /*forPointeeType=*/true));
25030b57cec5SDimitry Andric }
25040b57cec5SDimitry Andric
EmitLoadOfPointerLValue(Address PtrAddr,const PointerType * PtrTy)25050b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
25060b57cec5SDimitry Andric const PointerType *PtrTy) {
25070b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
25080b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
25090b57cec5SDimitry Andric Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
25100b57cec5SDimitry Andric return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
25110b57cec5SDimitry Andric }
25120b57cec5SDimitry Andric
EmitGlobalVarDeclLValue(CodeGenFunction & CGF,const Expr * E,const VarDecl * VD)25130b57cec5SDimitry Andric static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
25140b57cec5SDimitry Andric const Expr *E, const VarDecl *VD) {
25150b57cec5SDimitry Andric QualType T = E->getType();
25160b57cec5SDimitry Andric
25170b57cec5SDimitry Andric // If it's thread_local, emit a call to its wrapper function instead.
25180b57cec5SDimitry Andric if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2519a7dea167SDimitry Andric CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
25200b57cec5SDimitry Andric return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
25210b57cec5SDimitry Andric // Check if the variable is marked as declare target with link clause in
25220b57cec5SDimitry Andric // device codegen.
25230b57cec5SDimitry Andric if (CGF.getLangOpts().OpenMPIsDevice) {
25240b57cec5SDimitry Andric Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
25250b57cec5SDimitry Andric if (Addr.isValid())
25260b57cec5SDimitry Andric return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
25270b57cec5SDimitry Andric }
25280b57cec5SDimitry Andric
25290b57cec5SDimitry Andric llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
25300b57cec5SDimitry Andric llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
25310b57cec5SDimitry Andric V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
25320b57cec5SDimitry Andric CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
25330b57cec5SDimitry Andric Address Addr(V, Alignment);
25340b57cec5SDimitry Andric // Emit reference to the private copy of the variable if it is an OpenMP
25350b57cec5SDimitry Andric // threadprivate variable.
25360b57cec5SDimitry Andric if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
25370b57cec5SDimitry Andric VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
25380b57cec5SDimitry Andric return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
25390b57cec5SDimitry Andric E->getExprLoc());
25400b57cec5SDimitry Andric }
25410b57cec5SDimitry Andric LValue LV = VD->getType()->isReferenceType() ?
25420b57cec5SDimitry Andric CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
25430b57cec5SDimitry Andric AlignmentSource::Decl) :
25440b57cec5SDimitry Andric CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
25450b57cec5SDimitry Andric setObjCGCLValueClass(CGF.getContext(), E, LV);
25460b57cec5SDimitry Andric return LV;
25470b57cec5SDimitry Andric }
25480b57cec5SDimitry Andric
EmitFunctionDeclPointer(CodeGenModule & CGM,GlobalDecl GD)25490b57cec5SDimitry Andric static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
25505ffd83dbSDimitry Andric GlobalDecl GD) {
25515ffd83dbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
25520b57cec5SDimitry Andric if (FD->hasAttr<WeakRefAttr>()) {
25530b57cec5SDimitry Andric ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
25540b57cec5SDimitry Andric return aliasee.getPointer();
25550b57cec5SDimitry Andric }
25560b57cec5SDimitry Andric
25575ffd83dbSDimitry Andric llvm::Constant *V = CGM.GetAddrOfFunction(GD);
25580b57cec5SDimitry Andric if (!FD->hasPrototype()) {
25590b57cec5SDimitry Andric if (const FunctionProtoType *Proto =
25600b57cec5SDimitry Andric FD->getType()->getAs<FunctionProtoType>()) {
25610b57cec5SDimitry Andric // Ugly case: for a K&R-style definition, the type of the definition
25620b57cec5SDimitry Andric // isn't the same as the type of a use. Correct for this with a
25630b57cec5SDimitry Andric // bitcast.
25640b57cec5SDimitry Andric QualType NoProtoType =
25650b57cec5SDimitry Andric CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
25660b57cec5SDimitry Andric NoProtoType = CGM.getContext().getPointerType(NoProtoType);
25670b57cec5SDimitry Andric V = llvm::ConstantExpr::getBitCast(V,
25680b57cec5SDimitry Andric CGM.getTypes().ConvertType(NoProtoType));
25690b57cec5SDimitry Andric }
25700b57cec5SDimitry Andric }
25710b57cec5SDimitry Andric return V;
25720b57cec5SDimitry Andric }
25730b57cec5SDimitry Andric
EmitFunctionDeclLValue(CodeGenFunction & CGF,const Expr * E,GlobalDecl GD)25745ffd83dbSDimitry Andric static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
25755ffd83dbSDimitry Andric GlobalDecl GD) {
25765ffd83dbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
25775ffd83dbSDimitry Andric llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
25780b57cec5SDimitry Andric CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
25790b57cec5SDimitry Andric return CGF.MakeAddrLValue(V, E->getType(), Alignment,
25800b57cec5SDimitry Andric AlignmentSource::Decl);
25810b57cec5SDimitry Andric }
25820b57cec5SDimitry Andric
EmitCapturedFieldLValue(CodeGenFunction & CGF,const FieldDecl * FD,llvm::Value * ThisValue)25830b57cec5SDimitry Andric static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
25840b57cec5SDimitry Andric llvm::Value *ThisValue) {
25850b57cec5SDimitry Andric QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
25860b57cec5SDimitry Andric LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
25870b57cec5SDimitry Andric return CGF.EmitLValueForField(LV, FD);
25880b57cec5SDimitry Andric }
25890b57cec5SDimitry Andric
25900b57cec5SDimitry Andric /// Named Registers are named metadata pointing to the register name
25910b57cec5SDimitry Andric /// which will be read from/written to as an argument to the intrinsic
25920b57cec5SDimitry Andric /// @llvm.read/write_register.
25930b57cec5SDimitry Andric /// So far, only the name is being passed down, but other options such as
25940b57cec5SDimitry Andric /// register type, allocation type or even optimization options could be
25950b57cec5SDimitry Andric /// passed down via the metadata node.
EmitGlobalNamedRegister(const VarDecl * VD,CodeGenModule & CGM)25960b57cec5SDimitry Andric static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
25970b57cec5SDimitry Andric SmallString<64> Name("llvm.named.register.");
25980b57cec5SDimitry Andric AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
25990b57cec5SDimitry Andric assert(Asm->getLabel().size() < 64-Name.size() &&
26000b57cec5SDimitry Andric "Register name too big");
26010b57cec5SDimitry Andric Name.append(Asm->getLabel());
26020b57cec5SDimitry Andric llvm::NamedMDNode *M =
26030b57cec5SDimitry Andric CGM.getModule().getOrInsertNamedMetadata(Name);
26040b57cec5SDimitry Andric if (M->getNumOperands() == 0) {
26050b57cec5SDimitry Andric llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
26060b57cec5SDimitry Andric Asm->getLabel());
26070b57cec5SDimitry Andric llvm::Metadata *Ops[] = {Str};
26080b57cec5SDimitry Andric M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
26090b57cec5SDimitry Andric }
26100b57cec5SDimitry Andric
26110b57cec5SDimitry Andric CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
26120b57cec5SDimitry Andric
26130b57cec5SDimitry Andric llvm::Value *Ptr =
26140b57cec5SDimitry Andric llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
26150b57cec5SDimitry Andric return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
26160b57cec5SDimitry Andric }
26170b57cec5SDimitry Andric
26180b57cec5SDimitry Andric /// Determine whether we can emit a reference to \p VD from the current
26190b57cec5SDimitry Andric /// context, despite not necessarily having seen an odr-use of the variable in
26200b57cec5SDimitry Andric /// this context.
canEmitSpuriousReferenceToVariable(CodeGenFunction & CGF,const DeclRefExpr * E,const VarDecl * VD,bool IsConstant)26210b57cec5SDimitry Andric static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
26220b57cec5SDimitry Andric const DeclRefExpr *E,
26230b57cec5SDimitry Andric const VarDecl *VD,
26240b57cec5SDimitry Andric bool IsConstant) {
26250b57cec5SDimitry Andric // For a variable declared in an enclosing scope, do not emit a spurious
26260b57cec5SDimitry Andric // reference even if we have a capture, as that will emit an unwarranted
26270b57cec5SDimitry Andric // reference to our capture state, and will likely generate worse code than
26280b57cec5SDimitry Andric // emitting a local copy.
26290b57cec5SDimitry Andric if (E->refersToEnclosingVariableOrCapture())
26300b57cec5SDimitry Andric return false;
26310b57cec5SDimitry Andric
26320b57cec5SDimitry Andric // For a local declaration declared in this function, we can always reference
26330b57cec5SDimitry Andric // it even if we don't have an odr-use.
26340b57cec5SDimitry Andric if (VD->hasLocalStorage()) {
26350b57cec5SDimitry Andric return VD->getDeclContext() ==
26360b57cec5SDimitry Andric dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
26370b57cec5SDimitry Andric }
26380b57cec5SDimitry Andric
26390b57cec5SDimitry Andric // For a global declaration, we can emit a reference to it if we know
26400b57cec5SDimitry Andric // for sure that we are able to emit a definition of it.
26410b57cec5SDimitry Andric VD = VD->getDefinition(CGF.getContext());
26420b57cec5SDimitry Andric if (!VD)
26430b57cec5SDimitry Andric return false;
26440b57cec5SDimitry Andric
26450b57cec5SDimitry Andric // Don't emit a spurious reference if it might be to a variable that only
26460b57cec5SDimitry Andric // exists on a different device / target.
26470b57cec5SDimitry Andric // FIXME: This is unnecessarily broad. Check whether this would actually be a
26480b57cec5SDimitry Andric // cross-target reference.
26490b57cec5SDimitry Andric if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
26500b57cec5SDimitry Andric CGF.getLangOpts().OpenCL) {
26510b57cec5SDimitry Andric return false;
26520b57cec5SDimitry Andric }
26530b57cec5SDimitry Andric
26540b57cec5SDimitry Andric // We can emit a spurious reference only if the linkage implies that we'll
26550b57cec5SDimitry Andric // be emitting a non-interposable symbol that will be retained until link
26560b57cec5SDimitry Andric // time.
26570b57cec5SDimitry Andric switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
26580b57cec5SDimitry Andric case llvm::GlobalValue::ExternalLinkage:
26590b57cec5SDimitry Andric case llvm::GlobalValue::LinkOnceODRLinkage:
26600b57cec5SDimitry Andric case llvm::GlobalValue::WeakODRLinkage:
26610b57cec5SDimitry Andric case llvm::GlobalValue::InternalLinkage:
26620b57cec5SDimitry Andric case llvm::GlobalValue::PrivateLinkage:
26630b57cec5SDimitry Andric return true;
26640b57cec5SDimitry Andric default:
26650b57cec5SDimitry Andric return false;
26660b57cec5SDimitry Andric }
26670b57cec5SDimitry Andric }
26680b57cec5SDimitry Andric
EmitDeclRefLValue(const DeclRefExpr * E)26690b57cec5SDimitry Andric LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
26700b57cec5SDimitry Andric const NamedDecl *ND = E->getDecl();
26710b57cec5SDimitry Andric QualType T = E->getType();
26720b57cec5SDimitry Andric
26730b57cec5SDimitry Andric assert(E->isNonOdrUse() != NOUR_Unevaluated &&
26740b57cec5SDimitry Andric "should not emit an unevaluated operand");
26750b57cec5SDimitry Andric
26760b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(ND)) {
26770b57cec5SDimitry Andric // Global Named registers access via intrinsics only
26780b57cec5SDimitry Andric if (VD->getStorageClass() == SC_Register &&
26790b57cec5SDimitry Andric VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
26800b57cec5SDimitry Andric return EmitGlobalNamedRegister(VD, CGM);
26810b57cec5SDimitry Andric
26820b57cec5SDimitry Andric // If this DeclRefExpr does not constitute an odr-use of the variable,
26830b57cec5SDimitry Andric // we're not permitted to emit a reference to it in general, and it might
26840b57cec5SDimitry Andric // not be captured if capture would be necessary for a use. Emit the
26850b57cec5SDimitry Andric // constant value directly instead.
26860b57cec5SDimitry Andric if (E->isNonOdrUse() == NOUR_Constant &&
26870b57cec5SDimitry Andric (VD->getType()->isReferenceType() ||
26880b57cec5SDimitry Andric !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
26890b57cec5SDimitry Andric VD->getAnyInitializer(VD);
26900b57cec5SDimitry Andric llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
26910b57cec5SDimitry Andric E->getLocation(), *VD->evaluateValue(), VD->getType());
26920b57cec5SDimitry Andric assert(Val && "failed to emit constant expression");
26930b57cec5SDimitry Andric
26940b57cec5SDimitry Andric Address Addr = Address::invalid();
26950b57cec5SDimitry Andric if (!VD->getType()->isReferenceType()) {
26960b57cec5SDimitry Andric // Spill the constant value to a global.
26970b57cec5SDimitry Andric Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
26980b57cec5SDimitry Andric getContext().getDeclAlign(VD));
2699c14a5a88SDimitry Andric llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
2700c14a5a88SDimitry Andric auto *PTy = llvm::PointerType::get(
2701c14a5a88SDimitry Andric VarTy, getContext().getTargetAddressSpace(VD->getType()));
2702c14a5a88SDimitry Andric if (PTy != Addr.getType())
2703c14a5a88SDimitry Andric Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy);
27040b57cec5SDimitry Andric } else {
27050b57cec5SDimitry Andric // Should we be using the alignment of the constant pointer we emitted?
27060b57cec5SDimitry Andric CharUnits Alignment =
27075ffd83dbSDimitry Andric CGM.getNaturalTypeAlignment(E->getType(),
27080b57cec5SDimitry Andric /* BaseInfo= */ nullptr,
27090b57cec5SDimitry Andric /* TBAAInfo= */ nullptr,
27100b57cec5SDimitry Andric /* forPointeeType= */ true);
27110b57cec5SDimitry Andric Addr = Address(Val, Alignment);
27120b57cec5SDimitry Andric }
27130b57cec5SDimitry Andric return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
27140b57cec5SDimitry Andric }
27150b57cec5SDimitry Andric
27160b57cec5SDimitry Andric // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
27170b57cec5SDimitry Andric
27180b57cec5SDimitry Andric // Check for captured variables.
27190b57cec5SDimitry Andric if (E->refersToEnclosingVariableOrCapture()) {
27200b57cec5SDimitry Andric VD = VD->getCanonicalDecl();
27210b57cec5SDimitry Andric if (auto *FD = LambdaCaptureFields.lookup(VD))
27220b57cec5SDimitry Andric return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2723480093f4SDimitry Andric if (CapturedStmtInfo) {
27240b57cec5SDimitry Andric auto I = LocalDeclMap.find(VD);
27250b57cec5SDimitry Andric if (I != LocalDeclMap.end()) {
2726480093f4SDimitry Andric LValue CapLVal;
27270b57cec5SDimitry Andric if (VD->getType()->isReferenceType())
2728480093f4SDimitry Andric CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
27290b57cec5SDimitry Andric AlignmentSource::Decl);
2730480093f4SDimitry Andric else
2731480093f4SDimitry Andric CapLVal = MakeAddrLValue(I->second, T);
2732480093f4SDimitry Andric // Mark lvalue as nontemporal if the variable is marked as nontemporal
2733480093f4SDimitry Andric // in simd context.
2734480093f4SDimitry Andric if (getLangOpts().OpenMP &&
2735480093f4SDimitry Andric CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2736480093f4SDimitry Andric CapLVal.setNontemporal(/*Value=*/true);
2737480093f4SDimitry Andric return CapLVal;
27380b57cec5SDimitry Andric }
27390b57cec5SDimitry Andric LValue CapLVal =
27400b57cec5SDimitry Andric EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
27410b57cec5SDimitry Andric CapturedStmtInfo->getContextValue());
2742480093f4SDimitry Andric CapLVal = MakeAddrLValue(
2743480093f4SDimitry Andric Address(CapLVal.getPointer(*this), getContext().getDeclAlign(VD)),
27440b57cec5SDimitry Andric CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
27450b57cec5SDimitry Andric CapLVal.getTBAAInfo());
2746480093f4SDimitry Andric // Mark lvalue as nontemporal if the variable is marked as nontemporal
2747480093f4SDimitry Andric // in simd context.
2748480093f4SDimitry Andric if (getLangOpts().OpenMP &&
2749480093f4SDimitry Andric CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2750480093f4SDimitry Andric CapLVal.setNontemporal(/*Value=*/true);
2751480093f4SDimitry Andric return CapLVal;
27520b57cec5SDimitry Andric }
27530b57cec5SDimitry Andric
27540b57cec5SDimitry Andric assert(isa<BlockDecl>(CurCodeDecl));
27550b57cec5SDimitry Andric Address addr = GetAddrOfBlockDecl(VD);
27560b57cec5SDimitry Andric return MakeAddrLValue(addr, T, AlignmentSource::Decl);
27570b57cec5SDimitry Andric }
27580b57cec5SDimitry Andric }
27590b57cec5SDimitry Andric
27600b57cec5SDimitry Andric // FIXME: We should be able to assert this for FunctionDecls as well!
27610b57cec5SDimitry Andric // FIXME: We should be able to assert this for all DeclRefExprs, not just
27620b57cec5SDimitry Andric // those with a valid source location.
27630b57cec5SDimitry Andric assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
27640b57cec5SDimitry Andric !E->getLocation().isValid()) &&
27650b57cec5SDimitry Andric "Should not use decl without marking it used!");
27660b57cec5SDimitry Andric
27670b57cec5SDimitry Andric if (ND->hasAttr<WeakRefAttr>()) {
27680b57cec5SDimitry Andric const auto *VD = cast<ValueDecl>(ND);
27690b57cec5SDimitry Andric ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
27700b57cec5SDimitry Andric return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
27710b57cec5SDimitry Andric }
27720b57cec5SDimitry Andric
27730b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(ND)) {
27740b57cec5SDimitry Andric // Check if this is a global variable.
27750b57cec5SDimitry Andric if (VD->hasLinkage() || VD->isStaticDataMember())
27760b57cec5SDimitry Andric return EmitGlobalVarDeclLValue(*this, E, VD);
27770b57cec5SDimitry Andric
27780b57cec5SDimitry Andric Address addr = Address::invalid();
27790b57cec5SDimitry Andric
27800b57cec5SDimitry Andric // The variable should generally be present in the local decl map.
27810b57cec5SDimitry Andric auto iter = LocalDeclMap.find(VD);
27820b57cec5SDimitry Andric if (iter != LocalDeclMap.end()) {
27830b57cec5SDimitry Andric addr = iter->second;
27840b57cec5SDimitry Andric
27850b57cec5SDimitry Andric // Otherwise, it might be static local we haven't emitted yet for
27860b57cec5SDimitry Andric // some reason; most likely, because it's in an outer function.
27870b57cec5SDimitry Andric } else if (VD->isStaticLocal()) {
27880b57cec5SDimitry Andric addr = Address(CGM.getOrCreateStaticVarDecl(
27890b57cec5SDimitry Andric *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false)),
27900b57cec5SDimitry Andric getContext().getDeclAlign(VD));
27910b57cec5SDimitry Andric
27920b57cec5SDimitry Andric // No other cases for now.
27930b57cec5SDimitry Andric } else {
27940b57cec5SDimitry Andric llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
27950b57cec5SDimitry Andric }
27960b57cec5SDimitry Andric
27970b57cec5SDimitry Andric
27980b57cec5SDimitry Andric // Check for OpenMP threadprivate variables.
27990b57cec5SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
28000b57cec5SDimitry Andric VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
28010b57cec5SDimitry Andric return EmitThreadPrivateVarDeclLValue(
28020b57cec5SDimitry Andric *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
28030b57cec5SDimitry Andric E->getExprLoc());
28040b57cec5SDimitry Andric }
28050b57cec5SDimitry Andric
28060b57cec5SDimitry Andric // Drill into block byref variables.
28070b57cec5SDimitry Andric bool isBlockByref = VD->isEscapingByref();
28080b57cec5SDimitry Andric if (isBlockByref) {
28090b57cec5SDimitry Andric addr = emitBlockByrefAddress(addr, VD);
28100b57cec5SDimitry Andric }
28110b57cec5SDimitry Andric
28120b57cec5SDimitry Andric // Drill into reference types.
28130b57cec5SDimitry Andric LValue LV = VD->getType()->isReferenceType() ?
28140b57cec5SDimitry Andric EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
28150b57cec5SDimitry Andric MakeAddrLValue(addr, T, AlignmentSource::Decl);
28160b57cec5SDimitry Andric
28170b57cec5SDimitry Andric bool isLocalStorage = VD->hasLocalStorage();
28180b57cec5SDimitry Andric
28190b57cec5SDimitry Andric bool NonGCable = isLocalStorage &&
28200b57cec5SDimitry Andric !VD->getType()->isReferenceType() &&
28210b57cec5SDimitry Andric !isBlockByref;
28220b57cec5SDimitry Andric if (NonGCable) {
28230b57cec5SDimitry Andric LV.getQuals().removeObjCGCAttr();
28240b57cec5SDimitry Andric LV.setNonGC(true);
28250b57cec5SDimitry Andric }
28260b57cec5SDimitry Andric
28270b57cec5SDimitry Andric bool isImpreciseLifetime =
28280b57cec5SDimitry Andric (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
28290b57cec5SDimitry Andric if (isImpreciseLifetime)
28300b57cec5SDimitry Andric LV.setARCPreciseLifetime(ARCImpreciseLifetime);
28310b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV);
28320b57cec5SDimitry Andric return LV;
28330b57cec5SDimitry Andric }
28340b57cec5SDimitry Andric
2835*5f7ddb14SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
2836*5f7ddb14SDimitry Andric LValue LV = EmitFunctionDeclLValue(*this, E, FD);
2837*5f7ddb14SDimitry Andric
2838*5f7ddb14SDimitry Andric // Emit debuginfo for the function declaration if the target wants to.
2839*5f7ddb14SDimitry Andric if (getContext().getTargetInfo().allowDebugInfoForExternalRef()) {
2840*5f7ddb14SDimitry Andric if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) {
2841*5f7ddb14SDimitry Andric auto *Fn =
2842*5f7ddb14SDimitry Andric cast<llvm::Function>(LV.getPointer(*this)->stripPointerCasts());
2843*5f7ddb14SDimitry Andric if (!Fn->getSubprogram())
2844*5f7ddb14SDimitry Andric DI->EmitFunctionDecl(FD, FD->getLocation(), T, Fn);
2845*5f7ddb14SDimitry Andric }
2846*5f7ddb14SDimitry Andric }
2847*5f7ddb14SDimitry Andric
2848*5f7ddb14SDimitry Andric return LV;
2849*5f7ddb14SDimitry Andric }
28500b57cec5SDimitry Andric
28510b57cec5SDimitry Andric // FIXME: While we're emitting a binding from an enclosing scope, all other
28520b57cec5SDimitry Andric // DeclRefExprs we see should be implicitly treated as if they also refer to
28530b57cec5SDimitry Andric // an enclosing scope.
28540b57cec5SDimitry Andric if (const auto *BD = dyn_cast<BindingDecl>(ND))
28550b57cec5SDimitry Andric return EmitLValue(BD->getBinding());
28560b57cec5SDimitry Andric
28575ffd83dbSDimitry Andric // We can form DeclRefExprs naming GUID declarations when reconstituting
28585ffd83dbSDimitry Andric // non-type template parameters into expressions.
28595ffd83dbSDimitry Andric if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
28605ffd83dbSDimitry Andric return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
28615ffd83dbSDimitry Andric AlignmentSource::Decl);
28625ffd83dbSDimitry Andric
2863af732203SDimitry Andric if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND))
2864af732203SDimitry Andric return MakeAddrLValue(CGM.GetAddrOfTemplateParamObject(TPO), T,
2865af732203SDimitry Andric AlignmentSource::Decl);
2866af732203SDimitry Andric
28670b57cec5SDimitry Andric llvm_unreachable("Unhandled DeclRefExpr");
28680b57cec5SDimitry Andric }
28690b57cec5SDimitry Andric
EmitUnaryOpLValue(const UnaryOperator * E)28700b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
28710b57cec5SDimitry Andric // __extension__ doesn't affect lvalue-ness.
28720b57cec5SDimitry Andric if (E->getOpcode() == UO_Extension)
28730b57cec5SDimitry Andric return EmitLValue(E->getSubExpr());
28740b57cec5SDimitry Andric
28750b57cec5SDimitry Andric QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
28760b57cec5SDimitry Andric switch (E->getOpcode()) {
28770b57cec5SDimitry Andric default: llvm_unreachable("Unknown unary operator lvalue!");
28780b57cec5SDimitry Andric case UO_Deref: {
28790b57cec5SDimitry Andric QualType T = E->getSubExpr()->getType()->getPointeeType();
28800b57cec5SDimitry Andric assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
28810b57cec5SDimitry Andric
28820b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
28830b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
28840b57cec5SDimitry Andric Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
28850b57cec5SDimitry Andric &TBAAInfo);
28860b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
28870b57cec5SDimitry Andric LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
28880b57cec5SDimitry Andric
28890b57cec5SDimitry Andric // We should not generate __weak write barrier on indirect reference
28900b57cec5SDimitry Andric // of a pointer to object; as in void foo (__weak id *param); *param = 0;
28910b57cec5SDimitry Andric // But, we continue to generate __strong write barrier on indirect write
28920b57cec5SDimitry Andric // into a pointer to object.
28930b57cec5SDimitry Andric if (getLangOpts().ObjC &&
28940b57cec5SDimitry Andric getLangOpts().getGC() != LangOptions::NonGC &&
28950b57cec5SDimitry Andric LV.isObjCWeak())
28960b57cec5SDimitry Andric LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
28970b57cec5SDimitry Andric return LV;
28980b57cec5SDimitry Andric }
28990b57cec5SDimitry Andric case UO_Real:
29000b57cec5SDimitry Andric case UO_Imag: {
29010b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
29020b57cec5SDimitry Andric assert(LV.isSimple() && "real/imag on non-ordinary l-value");
29030b57cec5SDimitry Andric
29040b57cec5SDimitry Andric // __real is valid on scalars. This is a faster way of testing that.
29050b57cec5SDimitry Andric // __imag can only produce an rvalue on scalars.
29060b57cec5SDimitry Andric if (E->getOpcode() == UO_Real &&
2907480093f4SDimitry Andric !LV.getAddress(*this).getElementType()->isStructTy()) {
29080b57cec5SDimitry Andric assert(E->getSubExpr()->getType()->isArithmeticType());
29090b57cec5SDimitry Andric return LV;
29100b57cec5SDimitry Andric }
29110b57cec5SDimitry Andric
29120b57cec5SDimitry Andric QualType T = ExprTy->castAs<ComplexType>()->getElementType();
29130b57cec5SDimitry Andric
29140b57cec5SDimitry Andric Address Component =
29150b57cec5SDimitry Andric (E->getOpcode() == UO_Real
2916480093f4SDimitry Andric ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
2917480093f4SDimitry Andric : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType()));
29180b57cec5SDimitry Andric LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
29190b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, T));
29200b57cec5SDimitry Andric ElemLV.getQuals().addQualifiers(LV.getQuals());
29210b57cec5SDimitry Andric return ElemLV;
29220b57cec5SDimitry Andric }
29230b57cec5SDimitry Andric case UO_PreInc:
29240b57cec5SDimitry Andric case UO_PreDec: {
29250b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
29260b57cec5SDimitry Andric bool isInc = E->getOpcode() == UO_PreInc;
29270b57cec5SDimitry Andric
29280b57cec5SDimitry Andric if (E->getType()->isAnyComplexType())
29290b57cec5SDimitry Andric EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
29300b57cec5SDimitry Andric else
29310b57cec5SDimitry Andric EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
29320b57cec5SDimitry Andric return LV;
29330b57cec5SDimitry Andric }
29340b57cec5SDimitry Andric }
29350b57cec5SDimitry Andric }
29360b57cec5SDimitry Andric
EmitStringLiteralLValue(const StringLiteral * E)29370b57cec5SDimitry Andric LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
29380b57cec5SDimitry Andric return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
29390b57cec5SDimitry Andric E->getType(), AlignmentSource::Decl);
29400b57cec5SDimitry Andric }
29410b57cec5SDimitry Andric
EmitObjCEncodeExprLValue(const ObjCEncodeExpr * E)29420b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
29430b57cec5SDimitry Andric return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
29440b57cec5SDimitry Andric E->getType(), AlignmentSource::Decl);
29450b57cec5SDimitry Andric }
29460b57cec5SDimitry Andric
EmitPredefinedLValue(const PredefinedExpr * E)29470b57cec5SDimitry Andric LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
29480b57cec5SDimitry Andric auto SL = E->getFunctionName();
29490b57cec5SDimitry Andric assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
29500b57cec5SDimitry Andric StringRef FnName = CurFn->getName();
29510b57cec5SDimitry Andric if (FnName.startswith("\01"))
29520b57cec5SDimitry Andric FnName = FnName.substr(1);
29530b57cec5SDimitry Andric StringRef NameItems[] = {
29540b57cec5SDimitry Andric PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
29550b57cec5SDimitry Andric std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
29560b57cec5SDimitry Andric if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
29575ffd83dbSDimitry Andric std::string Name = std::string(SL->getString());
29580b57cec5SDimitry Andric if (!Name.empty()) {
29590b57cec5SDimitry Andric unsigned Discriminator =
29600b57cec5SDimitry Andric CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
29610b57cec5SDimitry Andric if (Discriminator)
29620b57cec5SDimitry Andric Name += "_" + Twine(Discriminator + 1).str();
29630b57cec5SDimitry Andric auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
29640b57cec5SDimitry Andric return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
29650b57cec5SDimitry Andric } else {
29665ffd83dbSDimitry Andric auto C =
29675ffd83dbSDimitry Andric CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
29680b57cec5SDimitry Andric return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
29690b57cec5SDimitry Andric }
29700b57cec5SDimitry Andric }
29710b57cec5SDimitry Andric auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
29720b57cec5SDimitry Andric return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
29730b57cec5SDimitry Andric }
29740b57cec5SDimitry Andric
29750b57cec5SDimitry Andric /// Emit a type description suitable for use by a runtime sanitizer library. The
29760b57cec5SDimitry Andric /// format of a type descriptor is
29770b57cec5SDimitry Andric ///
29780b57cec5SDimitry Andric /// \code
29790b57cec5SDimitry Andric /// { i16 TypeKind, i16 TypeInfo }
29800b57cec5SDimitry Andric /// \endcode
29810b57cec5SDimitry Andric ///
29820b57cec5SDimitry Andric /// followed by an array of i8 containing the type name. TypeKind is 0 for an
29830b57cec5SDimitry Andric /// integer, 1 for a floating point value, and -1 for anything else.
EmitCheckTypeDescriptor(QualType T)29840b57cec5SDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
29850b57cec5SDimitry Andric // Only emit each type's descriptor once.
29860b57cec5SDimitry Andric if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
29870b57cec5SDimitry Andric return C;
29880b57cec5SDimitry Andric
29890b57cec5SDimitry Andric uint16_t TypeKind = -1;
29900b57cec5SDimitry Andric uint16_t TypeInfo = 0;
29910b57cec5SDimitry Andric
29920b57cec5SDimitry Andric if (T->isIntegerType()) {
29930b57cec5SDimitry Andric TypeKind = 0;
29940b57cec5SDimitry Andric TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
29950b57cec5SDimitry Andric (T->isSignedIntegerType() ? 1 : 0);
29960b57cec5SDimitry Andric } else if (T->isFloatingType()) {
29970b57cec5SDimitry Andric TypeKind = 1;
29980b57cec5SDimitry Andric TypeInfo = getContext().getTypeSize(T);
29990b57cec5SDimitry Andric }
30000b57cec5SDimitry Andric
30010b57cec5SDimitry Andric // Format the type name as if for a diagnostic, including quotes and
30020b57cec5SDimitry Andric // optionally an 'aka'.
30030b57cec5SDimitry Andric SmallString<32> Buffer;
30040b57cec5SDimitry Andric CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
30050b57cec5SDimitry Andric (intptr_t)T.getAsOpaquePtr(),
30060b57cec5SDimitry Andric StringRef(), StringRef(), None, Buffer,
30070b57cec5SDimitry Andric None);
30080b57cec5SDimitry Andric
30090b57cec5SDimitry Andric llvm::Constant *Components[] = {
30100b57cec5SDimitry Andric Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
30110b57cec5SDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
30120b57cec5SDimitry Andric };
30130b57cec5SDimitry Andric llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
30140b57cec5SDimitry Andric
30150b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable(
30160b57cec5SDimitry Andric CGM.getModule(), Descriptor->getType(),
30170b57cec5SDimitry Andric /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
30180b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
30190b57cec5SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
30200b57cec5SDimitry Andric
30210b57cec5SDimitry Andric // Remember the descriptor for this type.
30220b57cec5SDimitry Andric CGM.setTypeDescriptorInMap(T, GV);
30230b57cec5SDimitry Andric
30240b57cec5SDimitry Andric return GV;
30250b57cec5SDimitry Andric }
30260b57cec5SDimitry Andric
EmitCheckValue(llvm::Value * V)30270b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
30280b57cec5SDimitry Andric llvm::Type *TargetTy = IntPtrTy;
30290b57cec5SDimitry Andric
30300b57cec5SDimitry Andric if (V->getType() == TargetTy)
30310b57cec5SDimitry Andric return V;
30320b57cec5SDimitry Andric
30330b57cec5SDimitry Andric // Floating-point types which fit into intptr_t are bitcast to integers
30340b57cec5SDimitry Andric // and then passed directly (after zero-extension, if necessary).
30350b57cec5SDimitry Andric if (V->getType()->isFloatingPointTy()) {
3036af732203SDimitry Andric unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedSize();
30370b57cec5SDimitry Andric if (Bits <= TargetTy->getIntegerBitWidth())
30380b57cec5SDimitry Andric V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
30390b57cec5SDimitry Andric Bits));
30400b57cec5SDimitry Andric }
30410b57cec5SDimitry Andric
30420b57cec5SDimitry Andric // Integers which fit in intptr_t are zero-extended and passed directly.
30430b57cec5SDimitry Andric if (V->getType()->isIntegerTy() &&
30440b57cec5SDimitry Andric V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
30450b57cec5SDimitry Andric return Builder.CreateZExt(V, TargetTy);
30460b57cec5SDimitry Andric
30470b57cec5SDimitry Andric // Pointers are passed directly, everything else is passed by address.
30480b57cec5SDimitry Andric if (!V->getType()->isPointerTy()) {
30490b57cec5SDimitry Andric Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
30500b57cec5SDimitry Andric Builder.CreateStore(V, Ptr);
30510b57cec5SDimitry Andric V = Ptr.getPointer();
30520b57cec5SDimitry Andric }
30530b57cec5SDimitry Andric return Builder.CreatePtrToInt(V, TargetTy);
30540b57cec5SDimitry Andric }
30550b57cec5SDimitry Andric
30560b57cec5SDimitry Andric /// Emit a representation of a SourceLocation for passing to a handler
30570b57cec5SDimitry Andric /// in a sanitizer runtime library. The format for this data is:
30580b57cec5SDimitry Andric /// \code
30590b57cec5SDimitry Andric /// struct SourceLocation {
30600b57cec5SDimitry Andric /// const char *Filename;
30610b57cec5SDimitry Andric /// int32_t Line, Column;
30620b57cec5SDimitry Andric /// };
30630b57cec5SDimitry Andric /// \endcode
30640b57cec5SDimitry Andric /// For an invalid SourceLocation, the Filename pointer is null.
EmitCheckSourceLocation(SourceLocation Loc)30650b57cec5SDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
30660b57cec5SDimitry Andric llvm::Constant *Filename;
30670b57cec5SDimitry Andric int Line, Column;
30680b57cec5SDimitry Andric
30690b57cec5SDimitry Andric PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
30700b57cec5SDimitry Andric if (PLoc.isValid()) {
30710b57cec5SDimitry Andric StringRef FilenameString = PLoc.getFilename();
30720b57cec5SDimitry Andric
30730b57cec5SDimitry Andric int PathComponentsToStrip =
30740b57cec5SDimitry Andric CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
30750b57cec5SDimitry Andric if (PathComponentsToStrip < 0) {
30760b57cec5SDimitry Andric assert(PathComponentsToStrip != INT_MIN);
30770b57cec5SDimitry Andric int PathComponentsToKeep = -PathComponentsToStrip;
30780b57cec5SDimitry Andric auto I = llvm::sys::path::rbegin(FilenameString);
30790b57cec5SDimitry Andric auto E = llvm::sys::path::rend(FilenameString);
30800b57cec5SDimitry Andric while (I != E && --PathComponentsToKeep)
30810b57cec5SDimitry Andric ++I;
30820b57cec5SDimitry Andric
30830b57cec5SDimitry Andric FilenameString = FilenameString.substr(I - E);
30840b57cec5SDimitry Andric } else if (PathComponentsToStrip > 0) {
30850b57cec5SDimitry Andric auto I = llvm::sys::path::begin(FilenameString);
30860b57cec5SDimitry Andric auto E = llvm::sys::path::end(FilenameString);
30870b57cec5SDimitry Andric while (I != E && PathComponentsToStrip--)
30880b57cec5SDimitry Andric ++I;
30890b57cec5SDimitry Andric
30900b57cec5SDimitry Andric if (I != E)
30910b57cec5SDimitry Andric FilenameString =
30920b57cec5SDimitry Andric FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
30930b57cec5SDimitry Andric else
30940b57cec5SDimitry Andric FilenameString = llvm::sys::path::filename(FilenameString);
30950b57cec5SDimitry Andric }
30960b57cec5SDimitry Andric
30975ffd83dbSDimitry Andric auto FilenameGV =
30985ffd83dbSDimitry Andric CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
30990b57cec5SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
31000b57cec5SDimitry Andric cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
31010b57cec5SDimitry Andric Filename = FilenameGV.getPointer();
31020b57cec5SDimitry Andric Line = PLoc.getLine();
31030b57cec5SDimitry Andric Column = PLoc.getColumn();
31040b57cec5SDimitry Andric } else {
31050b57cec5SDimitry Andric Filename = llvm::Constant::getNullValue(Int8PtrTy);
31060b57cec5SDimitry Andric Line = Column = 0;
31070b57cec5SDimitry Andric }
31080b57cec5SDimitry Andric
31090b57cec5SDimitry Andric llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
31100b57cec5SDimitry Andric Builder.getInt32(Column)};
31110b57cec5SDimitry Andric
31120b57cec5SDimitry Andric return llvm::ConstantStruct::getAnon(Data);
31130b57cec5SDimitry Andric }
31140b57cec5SDimitry Andric
31150b57cec5SDimitry Andric namespace {
31160b57cec5SDimitry Andric /// Specify under what conditions this check can be recovered
31170b57cec5SDimitry Andric enum class CheckRecoverableKind {
31180b57cec5SDimitry Andric /// Always terminate program execution if this check fails.
31190b57cec5SDimitry Andric Unrecoverable,
31200b57cec5SDimitry Andric /// Check supports recovering, runtime has both fatal (noreturn) and
31210b57cec5SDimitry Andric /// non-fatal handlers for this check.
31220b57cec5SDimitry Andric Recoverable,
31230b57cec5SDimitry Andric /// Runtime conditionally aborts, always need to support recovery.
31240b57cec5SDimitry Andric AlwaysRecoverable
31250b57cec5SDimitry Andric };
31260b57cec5SDimitry Andric }
31270b57cec5SDimitry Andric
getRecoverableKind(SanitizerMask Kind)31280b57cec5SDimitry Andric static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
31290b57cec5SDimitry Andric assert(Kind.countPopulation() == 1);
31300b57cec5SDimitry Andric if (Kind == SanitizerKind::Function || Kind == SanitizerKind::Vptr)
31310b57cec5SDimitry Andric return CheckRecoverableKind::AlwaysRecoverable;
31320b57cec5SDimitry Andric else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
31330b57cec5SDimitry Andric return CheckRecoverableKind::Unrecoverable;
31340b57cec5SDimitry Andric else
31350b57cec5SDimitry Andric return CheckRecoverableKind::Recoverable;
31360b57cec5SDimitry Andric }
31370b57cec5SDimitry Andric
31380b57cec5SDimitry Andric namespace {
31390b57cec5SDimitry Andric struct SanitizerHandlerInfo {
31400b57cec5SDimitry Andric char const *const Name;
31410b57cec5SDimitry Andric unsigned Version;
31420b57cec5SDimitry Andric };
31430b57cec5SDimitry Andric }
31440b57cec5SDimitry Andric
31450b57cec5SDimitry Andric const SanitizerHandlerInfo SanitizerHandlers[] = {
31460b57cec5SDimitry Andric #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
31470b57cec5SDimitry Andric LIST_SANITIZER_CHECKS
31480b57cec5SDimitry Andric #undef SANITIZER_CHECK
31490b57cec5SDimitry Andric };
31500b57cec5SDimitry Andric
emitCheckHandlerCall(CodeGenFunction & CGF,llvm::FunctionType * FnType,ArrayRef<llvm::Value * > FnArgs,SanitizerHandler CheckHandler,CheckRecoverableKind RecoverKind,bool IsFatal,llvm::BasicBlock * ContBB)31510b57cec5SDimitry Andric static void emitCheckHandlerCall(CodeGenFunction &CGF,
31520b57cec5SDimitry Andric llvm::FunctionType *FnType,
31530b57cec5SDimitry Andric ArrayRef<llvm::Value *> FnArgs,
31540b57cec5SDimitry Andric SanitizerHandler CheckHandler,
31550b57cec5SDimitry Andric CheckRecoverableKind RecoverKind, bool IsFatal,
31560b57cec5SDimitry Andric llvm::BasicBlock *ContBB) {
31570b57cec5SDimitry Andric assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
31580b57cec5SDimitry Andric Optional<ApplyDebugLocation> DL;
31590b57cec5SDimitry Andric if (!CGF.Builder.getCurrentDebugLocation()) {
31600b57cec5SDimitry Andric // Ensure that the call has at least an artificial debug location.
31610b57cec5SDimitry Andric DL.emplace(CGF, SourceLocation());
31620b57cec5SDimitry Andric }
31630b57cec5SDimitry Andric bool NeedsAbortSuffix =
31640b57cec5SDimitry Andric IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
31650b57cec5SDimitry Andric bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
31660b57cec5SDimitry Andric const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
31670b57cec5SDimitry Andric const StringRef CheckName = CheckInfo.Name;
31680b57cec5SDimitry Andric std::string FnName = "__ubsan_handle_" + CheckName.str();
31690b57cec5SDimitry Andric if (CheckInfo.Version && !MinimalRuntime)
31700b57cec5SDimitry Andric FnName += "_v" + llvm::utostr(CheckInfo.Version);
31710b57cec5SDimitry Andric if (MinimalRuntime)
31720b57cec5SDimitry Andric FnName += "_minimal";
31730b57cec5SDimitry Andric if (NeedsAbortSuffix)
31740b57cec5SDimitry Andric FnName += "_abort";
31750b57cec5SDimitry Andric bool MayReturn =
31760b57cec5SDimitry Andric !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
31770b57cec5SDimitry Andric
31780b57cec5SDimitry Andric llvm::AttrBuilder B;
31790b57cec5SDimitry Andric if (!MayReturn) {
31800b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoReturn)
31810b57cec5SDimitry Andric .addAttribute(llvm::Attribute::NoUnwind);
31820b57cec5SDimitry Andric }
31830b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::UWTable);
31840b57cec5SDimitry Andric
31850b57cec5SDimitry Andric llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
31860b57cec5SDimitry Andric FnType, FnName,
31870b57cec5SDimitry Andric llvm::AttributeList::get(CGF.getLLVMContext(),
31880b57cec5SDimitry Andric llvm::AttributeList::FunctionIndex, B),
31890b57cec5SDimitry Andric /*Local=*/true);
31900b57cec5SDimitry Andric llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
31910b57cec5SDimitry Andric if (!MayReturn) {
31920b57cec5SDimitry Andric HandlerCall->setDoesNotReturn();
31930b57cec5SDimitry Andric CGF.Builder.CreateUnreachable();
31940b57cec5SDimitry Andric } else {
31950b57cec5SDimitry Andric CGF.Builder.CreateBr(ContBB);
31960b57cec5SDimitry Andric }
31970b57cec5SDimitry Andric }
31980b57cec5SDimitry Andric
EmitCheck(ArrayRef<std::pair<llvm::Value *,SanitizerMask>> Checked,SanitizerHandler CheckHandler,ArrayRef<llvm::Constant * > StaticArgs,ArrayRef<llvm::Value * > DynamicArgs)31990b57cec5SDimitry Andric void CodeGenFunction::EmitCheck(
32000b57cec5SDimitry Andric ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
32010b57cec5SDimitry Andric SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
32020b57cec5SDimitry Andric ArrayRef<llvm::Value *> DynamicArgs) {
32030b57cec5SDimitry Andric assert(IsSanitizerScope);
32040b57cec5SDimitry Andric assert(Checked.size() > 0);
32050b57cec5SDimitry Andric assert(CheckHandler >= 0 &&
32060b57cec5SDimitry Andric size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
32070b57cec5SDimitry Andric const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
32080b57cec5SDimitry Andric
32090b57cec5SDimitry Andric llvm::Value *FatalCond = nullptr;
32100b57cec5SDimitry Andric llvm::Value *RecoverableCond = nullptr;
32110b57cec5SDimitry Andric llvm::Value *TrapCond = nullptr;
32120b57cec5SDimitry Andric for (int i = 0, n = Checked.size(); i < n; ++i) {
32130b57cec5SDimitry Andric llvm::Value *Check = Checked[i].first;
32140b57cec5SDimitry Andric // -fsanitize-trap= overrides -fsanitize-recover=.
32150b57cec5SDimitry Andric llvm::Value *&Cond =
32160b57cec5SDimitry Andric CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
32170b57cec5SDimitry Andric ? TrapCond
32180b57cec5SDimitry Andric : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
32190b57cec5SDimitry Andric ? RecoverableCond
32200b57cec5SDimitry Andric : FatalCond;
32210b57cec5SDimitry Andric Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
32220b57cec5SDimitry Andric }
32230b57cec5SDimitry Andric
32240b57cec5SDimitry Andric if (TrapCond)
3225af732203SDimitry Andric EmitTrapCheck(TrapCond, CheckHandler);
32260b57cec5SDimitry Andric if (!FatalCond && !RecoverableCond)
32270b57cec5SDimitry Andric return;
32280b57cec5SDimitry Andric
32290b57cec5SDimitry Andric llvm::Value *JointCond;
32300b57cec5SDimitry Andric if (FatalCond && RecoverableCond)
32310b57cec5SDimitry Andric JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
32320b57cec5SDimitry Andric else
32330b57cec5SDimitry Andric JointCond = FatalCond ? FatalCond : RecoverableCond;
32340b57cec5SDimitry Andric assert(JointCond);
32350b57cec5SDimitry Andric
32360b57cec5SDimitry Andric CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
32370b57cec5SDimitry Andric assert(SanOpts.has(Checked[0].second));
32380b57cec5SDimitry Andric #ifndef NDEBUG
32390b57cec5SDimitry Andric for (int i = 1, n = Checked.size(); i < n; ++i) {
32400b57cec5SDimitry Andric assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
32410b57cec5SDimitry Andric "All recoverable kinds in a single check must be same!");
32420b57cec5SDimitry Andric assert(SanOpts.has(Checked[i].second));
32430b57cec5SDimitry Andric }
32440b57cec5SDimitry Andric #endif
32450b57cec5SDimitry Andric
32460b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cont");
32470b57cec5SDimitry Andric llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
32480b57cec5SDimitry Andric llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
32490b57cec5SDimitry Andric // Give hint that we very much don't expect to execute the handler
32500b57cec5SDimitry Andric // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
32510b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext());
32520b57cec5SDimitry Andric llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
32530b57cec5SDimitry Andric Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
32540b57cec5SDimitry Andric EmitBlock(Handlers);
32550b57cec5SDimitry Andric
32560b57cec5SDimitry Andric // Handler functions take an i8* pointing to the (handler-specific) static
32570b57cec5SDimitry Andric // information block, followed by a sequence of intptr_t arguments
32580b57cec5SDimitry Andric // representing operand values.
32590b57cec5SDimitry Andric SmallVector<llvm::Value *, 4> Args;
32600b57cec5SDimitry Andric SmallVector<llvm::Type *, 4> ArgTypes;
32610b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
32620b57cec5SDimitry Andric Args.reserve(DynamicArgs.size() + 1);
32630b57cec5SDimitry Andric ArgTypes.reserve(DynamicArgs.size() + 1);
32640b57cec5SDimitry Andric
32650b57cec5SDimitry Andric // Emit handler arguments and create handler function type.
32660b57cec5SDimitry Andric if (!StaticArgs.empty()) {
32670b57cec5SDimitry Andric llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
32680b57cec5SDimitry Andric auto *InfoPtr =
32690b57cec5SDimitry Andric new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
32700b57cec5SDimitry Andric llvm::GlobalVariable::PrivateLinkage, Info);
32710b57cec5SDimitry Andric InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
32720b57cec5SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
32730b57cec5SDimitry Andric Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
32740b57cec5SDimitry Andric ArgTypes.push_back(Int8PtrTy);
32750b57cec5SDimitry Andric }
32760b57cec5SDimitry Andric
32770b57cec5SDimitry Andric for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
32780b57cec5SDimitry Andric Args.push_back(EmitCheckValue(DynamicArgs[i]));
32790b57cec5SDimitry Andric ArgTypes.push_back(IntPtrTy);
32800b57cec5SDimitry Andric }
32810b57cec5SDimitry Andric }
32820b57cec5SDimitry Andric
32830b57cec5SDimitry Andric llvm::FunctionType *FnType =
32840b57cec5SDimitry Andric llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
32850b57cec5SDimitry Andric
32860b57cec5SDimitry Andric if (!FatalCond || !RecoverableCond) {
32870b57cec5SDimitry Andric // Simple case: we need to generate a single handler call, either
32880b57cec5SDimitry Andric // fatal, or non-fatal.
32890b57cec5SDimitry Andric emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
32900b57cec5SDimitry Andric (FatalCond != nullptr), Cont);
32910b57cec5SDimitry Andric } else {
32920b57cec5SDimitry Andric // Emit two handler calls: first one for set of unrecoverable checks,
32930b57cec5SDimitry Andric // another one for recoverable.
32940b57cec5SDimitry Andric llvm::BasicBlock *NonFatalHandlerBB =
32950b57cec5SDimitry Andric createBasicBlock("non_fatal." + CheckName);
32960b57cec5SDimitry Andric llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
32970b57cec5SDimitry Andric Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
32980b57cec5SDimitry Andric EmitBlock(FatalHandlerBB);
32990b57cec5SDimitry Andric emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
33000b57cec5SDimitry Andric NonFatalHandlerBB);
33010b57cec5SDimitry Andric EmitBlock(NonFatalHandlerBB);
33020b57cec5SDimitry Andric emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
33030b57cec5SDimitry Andric Cont);
33040b57cec5SDimitry Andric }
33050b57cec5SDimitry Andric
33060b57cec5SDimitry Andric EmitBlock(Cont);
33070b57cec5SDimitry Andric }
33080b57cec5SDimitry Andric
EmitCfiSlowPathCheck(SanitizerMask Kind,llvm::Value * Cond,llvm::ConstantInt * TypeId,llvm::Value * Ptr,ArrayRef<llvm::Constant * > StaticArgs)33090b57cec5SDimitry Andric void CodeGenFunction::EmitCfiSlowPathCheck(
33100b57cec5SDimitry Andric SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
33110b57cec5SDimitry Andric llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
33120b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
33130b57cec5SDimitry Andric
33140b57cec5SDimitry Andric llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
33150b57cec5SDimitry Andric llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
33160b57cec5SDimitry Andric
33170b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext());
33180b57cec5SDimitry Andric llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
33190b57cec5SDimitry Andric BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
33200b57cec5SDimitry Andric
33210b57cec5SDimitry Andric EmitBlock(CheckBB);
33220b57cec5SDimitry Andric
33230b57cec5SDimitry Andric bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
33240b57cec5SDimitry Andric
33250b57cec5SDimitry Andric llvm::CallInst *CheckCall;
33260b57cec5SDimitry Andric llvm::FunctionCallee SlowPathFn;
33270b57cec5SDimitry Andric if (WithDiag) {
33280b57cec5SDimitry Andric llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
33290b57cec5SDimitry Andric auto *InfoPtr =
33300b57cec5SDimitry Andric new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
33310b57cec5SDimitry Andric llvm::GlobalVariable::PrivateLinkage, Info);
33320b57cec5SDimitry Andric InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
33330b57cec5SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
33340b57cec5SDimitry Andric
33350b57cec5SDimitry Andric SlowPathFn = CGM.getModule().getOrInsertFunction(
33360b57cec5SDimitry Andric "__cfi_slowpath_diag",
33370b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
33380b57cec5SDimitry Andric false));
33390b57cec5SDimitry Andric CheckCall = Builder.CreateCall(
33400b57cec5SDimitry Andric SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
33410b57cec5SDimitry Andric } else {
33420b57cec5SDimitry Andric SlowPathFn = CGM.getModule().getOrInsertFunction(
33430b57cec5SDimitry Andric "__cfi_slowpath",
33440b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
33450b57cec5SDimitry Andric CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
33460b57cec5SDimitry Andric }
33470b57cec5SDimitry Andric
33480b57cec5SDimitry Andric CGM.setDSOLocal(
33490b57cec5SDimitry Andric cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
33500b57cec5SDimitry Andric CheckCall->setDoesNotThrow();
33510b57cec5SDimitry Andric
33520b57cec5SDimitry Andric EmitBlock(Cont);
33530b57cec5SDimitry Andric }
33540b57cec5SDimitry Andric
33550b57cec5SDimitry Andric // Emit a stub for __cfi_check function so that the linker knows about this
33560b57cec5SDimitry Andric // symbol in LTO mode.
EmitCfiCheckStub()33570b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckStub() {
33580b57cec5SDimitry Andric llvm::Module *M = &CGM.getModule();
33590b57cec5SDimitry Andric auto &Ctx = M->getContext();
33600b57cec5SDimitry Andric llvm::Function *F = llvm::Function::Create(
33610b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
33620b57cec5SDimitry Andric llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
33630b57cec5SDimitry Andric CGM.setDSOLocal(F);
33640b57cec5SDimitry Andric llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
33650b57cec5SDimitry Andric // FIXME: consider emitting an intrinsic call like
33660b57cec5SDimitry Andric // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
33670b57cec5SDimitry Andric // which can be lowered in CrossDSOCFI pass to the actual contents of
33680b57cec5SDimitry Andric // __cfi_check. This would allow inlining of __cfi_check calls.
33690b57cec5SDimitry Andric llvm::CallInst::Create(
33700b57cec5SDimitry Andric llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
33710b57cec5SDimitry Andric llvm::ReturnInst::Create(Ctx, nullptr, BB);
33720b57cec5SDimitry Andric }
33730b57cec5SDimitry Andric
33740b57cec5SDimitry Andric // This function is basically a switch over the CFI failure kind, which is
33750b57cec5SDimitry Andric // extracted from CFICheckFailData (1st function argument). Each case is either
33760b57cec5SDimitry Andric // llvm.trap or a call to one of the two runtime handlers, based on
33770b57cec5SDimitry Andric // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
33780b57cec5SDimitry Andric // failure kind) traps, but this should really never happen. CFICheckFailData
33790b57cec5SDimitry Andric // can be nullptr if the calling module has -fsanitize-trap behavior for this
33800b57cec5SDimitry Andric // check kind; in this case __cfi_check_fail traps as well.
EmitCfiCheckFail()33810b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckFail() {
33820b57cec5SDimitry Andric SanitizerScope SanScope(this);
33830b57cec5SDimitry Andric FunctionArgList Args;
33840b57cec5SDimitry Andric ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
33850b57cec5SDimitry Andric ImplicitParamDecl::Other);
33860b57cec5SDimitry Andric ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
33870b57cec5SDimitry Andric ImplicitParamDecl::Other);
33880b57cec5SDimitry Andric Args.push_back(&ArgData);
33890b57cec5SDimitry Andric Args.push_back(&ArgAddr);
33900b57cec5SDimitry Andric
33910b57cec5SDimitry Andric const CGFunctionInfo &FI =
33920b57cec5SDimitry Andric CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
33930b57cec5SDimitry Andric
33940b57cec5SDimitry Andric llvm::Function *F = llvm::Function::Create(
33950b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
33960b57cec5SDimitry Andric llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3397480093f4SDimitry Andric
3398*5f7ddb14SDimitry Andric CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3399480093f4SDimitry Andric CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
34000b57cec5SDimitry Andric F->setVisibility(llvm::GlobalValue::HiddenVisibility);
34010b57cec5SDimitry Andric
34020b57cec5SDimitry Andric StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
34030b57cec5SDimitry Andric SourceLocation());
34040b57cec5SDimitry Andric
3405*5f7ddb14SDimitry Andric // This function is not affected by NoSanitizeList. This function does
34060b57cec5SDimitry Andric // not have a source location, but "src:*" would still apply. Revert any
34070b57cec5SDimitry Andric // changes to SanOpts made in StartFunction.
34080b57cec5SDimitry Andric SanOpts = CGM.getLangOpts().Sanitize;
34090b57cec5SDimitry Andric
34100b57cec5SDimitry Andric llvm::Value *Data =
34110b57cec5SDimitry Andric EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
34120b57cec5SDimitry Andric CGM.getContext().VoidPtrTy, ArgData.getLocation());
34130b57cec5SDimitry Andric llvm::Value *Addr =
34140b57cec5SDimitry Andric EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
34150b57cec5SDimitry Andric CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
34160b57cec5SDimitry Andric
34170b57cec5SDimitry Andric // Data == nullptr means the calling module has trap behaviour for this check.
34180b57cec5SDimitry Andric llvm::Value *DataIsNotNullPtr =
34190b57cec5SDimitry Andric Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3420af732203SDimitry Andric EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
34210b57cec5SDimitry Andric
34220b57cec5SDimitry Andric llvm::StructType *SourceLocationTy =
34230b57cec5SDimitry Andric llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
34240b57cec5SDimitry Andric llvm::StructType *CfiCheckFailDataTy =
34250b57cec5SDimitry Andric llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
34260b57cec5SDimitry Andric
34270b57cec5SDimitry Andric llvm::Value *V = Builder.CreateConstGEP2_32(
34280b57cec5SDimitry Andric CfiCheckFailDataTy,
34290b57cec5SDimitry Andric Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
34300b57cec5SDimitry Andric 0);
34310b57cec5SDimitry Andric Address CheckKindAddr(V, getIntAlign());
34320b57cec5SDimitry Andric llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
34330b57cec5SDimitry Andric
34340b57cec5SDimitry Andric llvm::Value *AllVtables = llvm::MetadataAsValue::get(
34350b57cec5SDimitry Andric CGM.getLLVMContext(),
34360b57cec5SDimitry Andric llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
34370b57cec5SDimitry Andric llvm::Value *ValidVtable = Builder.CreateZExt(
34380b57cec5SDimitry Andric Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
34390b57cec5SDimitry Andric {Addr, AllVtables}),
34400b57cec5SDimitry Andric IntPtrTy);
34410b57cec5SDimitry Andric
34420b57cec5SDimitry Andric const std::pair<int, SanitizerMask> CheckKinds[] = {
34430b57cec5SDimitry Andric {CFITCK_VCall, SanitizerKind::CFIVCall},
34440b57cec5SDimitry Andric {CFITCK_NVCall, SanitizerKind::CFINVCall},
34450b57cec5SDimitry Andric {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
34460b57cec5SDimitry Andric {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
34470b57cec5SDimitry Andric {CFITCK_ICall, SanitizerKind::CFIICall}};
34480b57cec5SDimitry Andric
34490b57cec5SDimitry Andric SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
34500b57cec5SDimitry Andric for (auto CheckKindMaskPair : CheckKinds) {
34510b57cec5SDimitry Andric int Kind = CheckKindMaskPair.first;
34520b57cec5SDimitry Andric SanitizerMask Mask = CheckKindMaskPair.second;
34530b57cec5SDimitry Andric llvm::Value *Cond =
34540b57cec5SDimitry Andric Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
34550b57cec5SDimitry Andric if (CGM.getLangOpts().Sanitize.has(Mask))
34560b57cec5SDimitry Andric EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
34570b57cec5SDimitry Andric {Data, Addr, ValidVtable});
34580b57cec5SDimitry Andric else
3459af732203SDimitry Andric EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
34600b57cec5SDimitry Andric }
34610b57cec5SDimitry Andric
34620b57cec5SDimitry Andric FinishFunction();
34630b57cec5SDimitry Andric // The only reference to this function will be created during LTO link.
34640b57cec5SDimitry Andric // Make sure it survives until then.
34650b57cec5SDimitry Andric CGM.addUsedGlobal(F);
34660b57cec5SDimitry Andric }
34670b57cec5SDimitry Andric
EmitUnreachable(SourceLocation Loc)34680b57cec5SDimitry Andric void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
34690b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Unreachable)) {
34700b57cec5SDimitry Andric SanitizerScope SanScope(this);
34710b57cec5SDimitry Andric EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
34720b57cec5SDimitry Andric SanitizerKind::Unreachable),
34730b57cec5SDimitry Andric SanitizerHandler::BuiltinUnreachable,
34740b57cec5SDimitry Andric EmitCheckSourceLocation(Loc), None);
34750b57cec5SDimitry Andric }
34760b57cec5SDimitry Andric Builder.CreateUnreachable();
34770b57cec5SDimitry Andric }
34780b57cec5SDimitry Andric
EmitTrapCheck(llvm::Value * Checked,SanitizerHandler CheckHandlerID)3479af732203SDimitry Andric void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
3480af732203SDimitry Andric SanitizerHandler CheckHandlerID) {
34810b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cont");
34820b57cec5SDimitry Andric
34830b57cec5SDimitry Andric // If we're optimizing, collapse all calls to trap down to just one per
3484af732203SDimitry Andric // check-type per function to save on code size.
3485af732203SDimitry Andric if (TrapBBs.size() <= CheckHandlerID)
3486af732203SDimitry Andric TrapBBs.resize(CheckHandlerID + 1);
3487af732203SDimitry Andric llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
3488af732203SDimitry Andric
34890b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
34900b57cec5SDimitry Andric TrapBB = createBasicBlock("trap");
34910b57cec5SDimitry Andric Builder.CreateCondBr(Checked, Cont, TrapBB);
34920b57cec5SDimitry Andric EmitBlock(TrapBB);
3493af732203SDimitry Andric
3494af732203SDimitry Andric llvm::CallInst *TrapCall =
3495af732203SDimitry Andric Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
3496af732203SDimitry Andric llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
3497af732203SDimitry Andric
3498af732203SDimitry Andric if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3499af732203SDimitry Andric auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3500af732203SDimitry Andric CGM.getCodeGenOpts().TrapFuncName);
3501af732203SDimitry Andric TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
3502af732203SDimitry Andric }
35030b57cec5SDimitry Andric TrapCall->setDoesNotReturn();
35040b57cec5SDimitry Andric TrapCall->setDoesNotThrow();
35050b57cec5SDimitry Andric Builder.CreateUnreachable();
35060b57cec5SDimitry Andric } else {
3507af732203SDimitry Andric auto Call = TrapBB->begin();
3508af732203SDimitry Andric assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
3509af732203SDimitry Andric
3510af732203SDimitry Andric Call->applyMergedLocation(Call->getDebugLoc(),
3511af732203SDimitry Andric Builder.getCurrentDebugLocation());
35120b57cec5SDimitry Andric Builder.CreateCondBr(Checked, Cont, TrapBB);
35130b57cec5SDimitry Andric }
35140b57cec5SDimitry Andric
35150b57cec5SDimitry Andric EmitBlock(Cont);
35160b57cec5SDimitry Andric }
35170b57cec5SDimitry Andric
EmitTrapCall(llvm::Intrinsic::ID IntrID)35180b57cec5SDimitry Andric llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3519af732203SDimitry Andric llvm::CallInst *TrapCall =
3520af732203SDimitry Andric Builder.CreateCall(CGM.getIntrinsic(IntrID));
35210b57cec5SDimitry Andric
35220b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
35230b57cec5SDimitry Andric auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
35240b57cec5SDimitry Andric CGM.getCodeGenOpts().TrapFuncName);
35250b57cec5SDimitry Andric TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
35260b57cec5SDimitry Andric }
35270b57cec5SDimitry Andric
35280b57cec5SDimitry Andric return TrapCall;
35290b57cec5SDimitry Andric }
35300b57cec5SDimitry Andric
EmitArrayToPointerDecay(const Expr * E,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)35310b57cec5SDimitry Andric Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
35320b57cec5SDimitry Andric LValueBaseInfo *BaseInfo,
35330b57cec5SDimitry Andric TBAAAccessInfo *TBAAInfo) {
35340b57cec5SDimitry Andric assert(E->getType()->isArrayType() &&
35350b57cec5SDimitry Andric "Array to pointer decay must have array source type!");
35360b57cec5SDimitry Andric
35370b57cec5SDimitry Andric // Expressions of array type can't be bitfields or vector elements.
35380b57cec5SDimitry Andric LValue LV = EmitLValue(E);
3539480093f4SDimitry Andric Address Addr = LV.getAddress(*this);
35400b57cec5SDimitry Andric
35410b57cec5SDimitry Andric // If the array type was an incomplete type, we need to make sure
35420b57cec5SDimitry Andric // the decay ends up being the right type.
35430b57cec5SDimitry Andric llvm::Type *NewTy = ConvertType(E->getType());
35440b57cec5SDimitry Andric Addr = Builder.CreateElementBitCast(Addr, NewTy);
35450b57cec5SDimitry Andric
35460b57cec5SDimitry Andric // Note that VLA pointers are always decayed, so we don't need to do
35470b57cec5SDimitry Andric // anything here.
35480b57cec5SDimitry Andric if (!E->getType()->isVariableArrayType()) {
35490b57cec5SDimitry Andric assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
35500b57cec5SDimitry Andric "Expected pointer to array");
35510b57cec5SDimitry Andric Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
35520b57cec5SDimitry Andric }
35530b57cec5SDimitry Andric
35540b57cec5SDimitry Andric // The result of this decay conversion points to an array element within the
35550b57cec5SDimitry Andric // base lvalue. However, since TBAA currently does not support representing
35560b57cec5SDimitry Andric // accesses to elements of member arrays, we conservatively represent accesses
35570b57cec5SDimitry Andric // to the pointee object as if it had no any base lvalue specified.
35580b57cec5SDimitry Andric // TODO: Support TBAA for member arrays.
35590b57cec5SDimitry Andric QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
35600b57cec5SDimitry Andric if (BaseInfo) *BaseInfo = LV.getBaseInfo();
35610b57cec5SDimitry Andric if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
35620b57cec5SDimitry Andric
35630b57cec5SDimitry Andric return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
35640b57cec5SDimitry Andric }
35650b57cec5SDimitry Andric
35660b57cec5SDimitry Andric /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
35670b57cec5SDimitry Andric /// array to pointer, return the array subexpression.
isSimpleArrayDecayOperand(const Expr * E)35680b57cec5SDimitry Andric static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
35690b57cec5SDimitry Andric // If this isn't just an array->pointer decay, bail out.
35700b57cec5SDimitry Andric const auto *CE = dyn_cast<CastExpr>(E);
35710b57cec5SDimitry Andric if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
35720b57cec5SDimitry Andric return nullptr;
35730b57cec5SDimitry Andric
35740b57cec5SDimitry Andric // If this is a decay from variable width array, bail out.
35750b57cec5SDimitry Andric const Expr *SubExpr = CE->getSubExpr();
35760b57cec5SDimitry Andric if (SubExpr->getType()->isVariableArrayType())
35770b57cec5SDimitry Andric return nullptr;
35780b57cec5SDimitry Andric
35790b57cec5SDimitry Andric return SubExpr;
35800b57cec5SDimitry Andric }
35810b57cec5SDimitry Andric
emitArraySubscriptGEP(CodeGenFunction & CGF,llvm::Type * elemType,llvm::Value * ptr,ArrayRef<llvm::Value * > indices,bool inbounds,bool signedIndices,SourceLocation loc,const llvm::Twine & name="arrayidx")35820b57cec5SDimitry Andric static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3583*5f7ddb14SDimitry Andric llvm::Type *elemType,
35840b57cec5SDimitry Andric llvm::Value *ptr,
35850b57cec5SDimitry Andric ArrayRef<llvm::Value*> indices,
35860b57cec5SDimitry Andric bool inbounds,
35870b57cec5SDimitry Andric bool signedIndices,
35880b57cec5SDimitry Andric SourceLocation loc,
35890b57cec5SDimitry Andric const llvm::Twine &name = "arrayidx") {
35900b57cec5SDimitry Andric if (inbounds) {
35910b57cec5SDimitry Andric return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
35920b57cec5SDimitry Andric CodeGenFunction::NotSubtraction, loc,
35930b57cec5SDimitry Andric name);
35940b57cec5SDimitry Andric } else {
3595*5f7ddb14SDimitry Andric return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
35960b57cec5SDimitry Andric }
35970b57cec5SDimitry Andric }
35980b57cec5SDimitry Andric
getArrayElementAlign(CharUnits arrayAlign,llvm::Value * idx,CharUnits eltSize)35990b57cec5SDimitry Andric static CharUnits getArrayElementAlign(CharUnits arrayAlign,
36000b57cec5SDimitry Andric llvm::Value *idx,
36010b57cec5SDimitry Andric CharUnits eltSize) {
36020b57cec5SDimitry Andric // If we have a constant index, we can use the exact offset of the
36030b57cec5SDimitry Andric // element we're accessing.
36040b57cec5SDimitry Andric if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
36050b57cec5SDimitry Andric CharUnits offset = constantIdx->getZExtValue() * eltSize;
36060b57cec5SDimitry Andric return arrayAlign.alignmentAtOffset(offset);
36070b57cec5SDimitry Andric
36080b57cec5SDimitry Andric // Otherwise, use the worst-case alignment for any element.
36090b57cec5SDimitry Andric } else {
36100b57cec5SDimitry Andric return arrayAlign.alignmentOfArrayElement(eltSize);
36110b57cec5SDimitry Andric }
36120b57cec5SDimitry Andric }
36130b57cec5SDimitry Andric
getFixedSizeElementType(const ASTContext & ctx,const VariableArrayType * vla)36140b57cec5SDimitry Andric static QualType getFixedSizeElementType(const ASTContext &ctx,
36150b57cec5SDimitry Andric const VariableArrayType *vla) {
36160b57cec5SDimitry Andric QualType eltType;
36170b57cec5SDimitry Andric do {
36180b57cec5SDimitry Andric eltType = vla->getElementType();
36190b57cec5SDimitry Andric } while ((vla = ctx.getAsVariableArrayType(eltType)));
36200b57cec5SDimitry Andric return eltType;
36210b57cec5SDimitry Andric }
36220b57cec5SDimitry Andric
3623480093f4SDimitry Andric /// Given an array base, check whether its member access belongs to a record
3624480093f4SDimitry Andric /// with preserve_access_index attribute or not.
IsPreserveAIArrayBase(CodeGenFunction & CGF,const Expr * ArrayBase)3625480093f4SDimitry Andric static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3626480093f4SDimitry Andric if (!ArrayBase || !CGF.getDebugInfo())
3627480093f4SDimitry Andric return false;
3628480093f4SDimitry Andric
3629480093f4SDimitry Andric // Only support base as either a MemberExpr or DeclRefExpr.
3630480093f4SDimitry Andric // DeclRefExpr to cover cases like:
3631480093f4SDimitry Andric // struct s { int a; int b[10]; };
3632480093f4SDimitry Andric // struct s *p;
3633480093f4SDimitry Andric // p[1].a
3634480093f4SDimitry Andric // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3635480093f4SDimitry Andric // p->b[5] is a MemberExpr example.
3636480093f4SDimitry Andric const Expr *E = ArrayBase->IgnoreImpCasts();
3637480093f4SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(E))
3638480093f4SDimitry Andric return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3639480093f4SDimitry Andric
3640480093f4SDimitry Andric if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3641480093f4SDimitry Andric const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
3642480093f4SDimitry Andric if (!VarDef)
3643480093f4SDimitry Andric return false;
3644480093f4SDimitry Andric
3645480093f4SDimitry Andric const auto *PtrT = VarDef->getType()->getAs<PointerType>();
3646480093f4SDimitry Andric if (!PtrT)
3647480093f4SDimitry Andric return false;
3648480093f4SDimitry Andric
3649480093f4SDimitry Andric const auto *PointeeT = PtrT->getPointeeType()
3650480093f4SDimitry Andric ->getUnqualifiedDesugaredType();
3651480093f4SDimitry Andric if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
3652480093f4SDimitry Andric return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3653480093f4SDimitry Andric return false;
3654480093f4SDimitry Andric }
3655480093f4SDimitry Andric
3656480093f4SDimitry Andric return false;
3657480093f4SDimitry Andric }
3658480093f4SDimitry Andric
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")36590b57cec5SDimitry Andric static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
36600b57cec5SDimitry Andric ArrayRef<llvm::Value *> indices,
36610b57cec5SDimitry Andric QualType eltType, bool inbounds,
36620b57cec5SDimitry Andric bool signedIndices, SourceLocation loc,
3663a7dea167SDimitry Andric QualType *arrayType = nullptr,
3664480093f4SDimitry Andric const Expr *Base = nullptr,
36650b57cec5SDimitry Andric const llvm::Twine &name = "arrayidx") {
36660b57cec5SDimitry Andric // All the indices except that last must be zero.
36670b57cec5SDimitry Andric #ifndef NDEBUG
36680b57cec5SDimitry Andric for (auto idx : indices.drop_back())
36690b57cec5SDimitry Andric assert(isa<llvm::ConstantInt>(idx) &&
36700b57cec5SDimitry Andric cast<llvm::ConstantInt>(idx)->isZero());
36710b57cec5SDimitry Andric #endif
36720b57cec5SDimitry Andric
36730b57cec5SDimitry Andric // Determine the element size of the statically-sized base. This is
36740b57cec5SDimitry Andric // the thing that the indices are expressed in terms of.
36750b57cec5SDimitry Andric if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
36760b57cec5SDimitry Andric eltType = getFixedSizeElementType(CGF.getContext(), vla);
36770b57cec5SDimitry Andric }
36780b57cec5SDimitry Andric
36790b57cec5SDimitry Andric // We can use that to compute the best alignment of the element.
36800b57cec5SDimitry Andric CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
36810b57cec5SDimitry Andric CharUnits eltAlign =
36820b57cec5SDimitry Andric getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
36830b57cec5SDimitry Andric
36840b57cec5SDimitry Andric llvm::Value *eltPtr;
36850b57cec5SDimitry Andric auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
3686480093f4SDimitry Andric if (!LastIndex ||
3687480093f4SDimitry Andric (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
36880b57cec5SDimitry Andric eltPtr = emitArraySubscriptGEP(
3689*5f7ddb14SDimitry Andric CGF, addr.getElementType(), addr.getPointer(), indices, inbounds,
3690*5f7ddb14SDimitry Andric signedIndices, loc, name);
36910b57cec5SDimitry Andric } else {
36920b57cec5SDimitry Andric // Remember the original array subscript for bpf target
36930b57cec5SDimitry Andric unsigned idx = LastIndex->getZExtValue();
3694a7dea167SDimitry Andric llvm::DIType *DbgInfo = nullptr;
3695a7dea167SDimitry Andric if (arrayType)
3696a7dea167SDimitry Andric DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
3697480093f4SDimitry Andric eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
3698480093f4SDimitry Andric addr.getPointer(),
36990b57cec5SDimitry Andric indices.size() - 1,
3700a7dea167SDimitry Andric idx, DbgInfo);
37010b57cec5SDimitry Andric }
37020b57cec5SDimitry Andric
37030b57cec5SDimitry Andric return Address(eltPtr, eltAlign);
37040b57cec5SDimitry Andric }
37050b57cec5SDimitry Andric
EmitArraySubscriptExpr(const ArraySubscriptExpr * E,bool Accessed)37060b57cec5SDimitry Andric LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
37070b57cec5SDimitry Andric bool Accessed) {
37080b57cec5SDimitry Andric // The index must always be an integer, which is not an aggregate. Emit it
37090b57cec5SDimitry Andric // in lexical order (this complexity is, sadly, required by C++17).
37100b57cec5SDimitry Andric llvm::Value *IdxPre =
37110b57cec5SDimitry Andric (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
37120b57cec5SDimitry Andric bool SignedIndices = false;
37130b57cec5SDimitry Andric auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
37140b57cec5SDimitry Andric auto *Idx = IdxPre;
37150b57cec5SDimitry Andric if (E->getLHS() != E->getIdx()) {
37160b57cec5SDimitry Andric assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
37170b57cec5SDimitry Andric Idx = EmitScalarExpr(E->getIdx());
37180b57cec5SDimitry Andric }
37190b57cec5SDimitry Andric
37200b57cec5SDimitry Andric QualType IdxTy = E->getIdx()->getType();
37210b57cec5SDimitry Andric bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
37220b57cec5SDimitry Andric SignedIndices |= IdxSigned;
37230b57cec5SDimitry Andric
37240b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ArrayBounds))
37250b57cec5SDimitry Andric EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
37260b57cec5SDimitry Andric
37270b57cec5SDimitry Andric // Extend or truncate the index type to 32 or 64-bits.
37280b57cec5SDimitry Andric if (Promote && Idx->getType() != IntPtrTy)
37290b57cec5SDimitry Andric Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
37300b57cec5SDimitry Andric
37310b57cec5SDimitry Andric return Idx;
37320b57cec5SDimitry Andric };
37330b57cec5SDimitry Andric IdxPre = nullptr;
37340b57cec5SDimitry Andric
37350b57cec5SDimitry Andric // If the base is a vector type, then we are forming a vector element lvalue
37360b57cec5SDimitry Andric // with this subscript.
37370b57cec5SDimitry Andric if (E->getBase()->getType()->isVectorType() &&
37380b57cec5SDimitry Andric !isa<ExtVectorElementExpr>(E->getBase())) {
37390b57cec5SDimitry Andric // Emit the vector as an lvalue to get its address.
37400b57cec5SDimitry Andric LValue LHS = EmitLValue(E->getBase());
37410b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/false);
37420b57cec5SDimitry Andric assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3743480093f4SDimitry Andric return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
3744480093f4SDimitry Andric E->getBase()->getType(), LHS.getBaseInfo(),
3745480093f4SDimitry Andric TBAAAccessInfo());
37460b57cec5SDimitry Andric }
37470b57cec5SDimitry Andric
37480b57cec5SDimitry Andric // All the other cases basically behave like simple offsetting.
37490b57cec5SDimitry Andric
37500b57cec5SDimitry Andric // Handle the extvector case we ignored above.
37510b57cec5SDimitry Andric if (isa<ExtVectorElementExpr>(E->getBase())) {
37520b57cec5SDimitry Andric LValue LV = EmitLValue(E->getBase());
37530b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true);
37540b57cec5SDimitry Andric Address Addr = EmitExtVectorElementLValue(LV);
37550b57cec5SDimitry Andric
37560b57cec5SDimitry Andric QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
37570b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
37580b57cec5SDimitry Andric SignedIndices, E->getExprLoc());
37590b57cec5SDimitry Andric return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
37600b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, EltType));
37610b57cec5SDimitry Andric }
37620b57cec5SDimitry Andric
37630b57cec5SDimitry Andric LValueBaseInfo EltBaseInfo;
37640b57cec5SDimitry Andric TBAAAccessInfo EltTBAAInfo;
37650b57cec5SDimitry Andric Address Addr = Address::invalid();
37660b57cec5SDimitry Andric if (const VariableArrayType *vla =
37670b57cec5SDimitry Andric getContext().getAsVariableArrayType(E->getType())) {
37680b57cec5SDimitry Andric // The base must be a pointer, which is not an aggregate. Emit
37690b57cec5SDimitry Andric // it. It needs to be emitted first in case it's what captures
37700b57cec5SDimitry Andric // the VLA bounds.
37710b57cec5SDimitry Andric Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
37720b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true);
37730b57cec5SDimitry Andric
37740b57cec5SDimitry Andric // The element count here is the total number of non-VLA elements.
37750b57cec5SDimitry Andric llvm::Value *numElements = getVLASize(vla).NumElts;
37760b57cec5SDimitry Andric
37770b57cec5SDimitry Andric // Effectively, the multiply by the VLA size is part of the GEP.
37780b57cec5SDimitry Andric // GEP indexes are signed, and scaling an index isn't permitted to
37790b57cec5SDimitry Andric // signed-overflow, so we use the same semantics for our explicit
37800b57cec5SDimitry Andric // multiply. We suppress this if overflow is not undefined behavior.
37810b57cec5SDimitry Andric if (getLangOpts().isSignedOverflowDefined()) {
37820b57cec5SDimitry Andric Idx = Builder.CreateMul(Idx, numElements);
37830b57cec5SDimitry Andric } else {
37840b57cec5SDimitry Andric Idx = Builder.CreateNSWMul(Idx, numElements);
37850b57cec5SDimitry Andric }
37860b57cec5SDimitry Andric
37870b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
37880b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(),
37890b57cec5SDimitry Andric SignedIndices, E->getExprLoc());
37900b57cec5SDimitry Andric
37910b57cec5SDimitry Andric } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
37920b57cec5SDimitry Andric // Indexing over an interface, as in "NSString *P; P[4];"
37930b57cec5SDimitry Andric
37940b57cec5SDimitry Andric // Emit the base pointer.
37950b57cec5SDimitry Andric Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
37960b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true);
37970b57cec5SDimitry Andric
37980b57cec5SDimitry Andric CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
37990b57cec5SDimitry Andric llvm::Value *InterfaceSizeVal =
38000b57cec5SDimitry Andric llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
38010b57cec5SDimitry Andric
38020b57cec5SDimitry Andric llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
38030b57cec5SDimitry Andric
38040b57cec5SDimitry Andric // We don't necessarily build correct LLVM struct types for ObjC
38050b57cec5SDimitry Andric // interfaces, so we can't rely on GEP to do this scaling
38060b57cec5SDimitry Andric // correctly, so we need to cast to i8*. FIXME: is this actually
38070b57cec5SDimitry Andric // true? A lot of other things in the fragile ABI would break...
38080b57cec5SDimitry Andric llvm::Type *OrigBaseTy = Addr.getType();
38090b57cec5SDimitry Andric Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
38100b57cec5SDimitry Andric
38110b57cec5SDimitry Andric // Do the GEP.
38120b57cec5SDimitry Andric CharUnits EltAlign =
38130b57cec5SDimitry Andric getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
38140b57cec5SDimitry Andric llvm::Value *EltPtr =
3815*5f7ddb14SDimitry Andric emitArraySubscriptGEP(*this, Addr.getElementType(), Addr.getPointer(),
3816*5f7ddb14SDimitry Andric ScaledIdx, false, SignedIndices, E->getExprLoc());
38170b57cec5SDimitry Andric Addr = Address(EltPtr, EltAlign);
38180b57cec5SDimitry Andric
38190b57cec5SDimitry Andric // Cast back.
38200b57cec5SDimitry Andric Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
38210b57cec5SDimitry Andric } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
38220b57cec5SDimitry Andric // If this is A[i] where A is an array, the frontend will have decayed the
38230b57cec5SDimitry Andric // base to be a ArrayToPointerDecay implicit cast. While correct, it is
38240b57cec5SDimitry Andric // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
38250b57cec5SDimitry Andric // "gep x, i" here. Emit one "gep A, 0, i".
38260b57cec5SDimitry Andric assert(Array->getType()->isArrayType() &&
38270b57cec5SDimitry Andric "Array to pointer decay must have array source type!");
38280b57cec5SDimitry Andric LValue ArrayLV;
38290b57cec5SDimitry Andric // For simple multidimensional array indexing, set the 'accessed' flag for
38300b57cec5SDimitry Andric // better bounds-checking of the base expression.
38310b57cec5SDimitry Andric if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
38320b57cec5SDimitry Andric ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
38330b57cec5SDimitry Andric else
38340b57cec5SDimitry Andric ArrayLV = EmitLValue(Array);
38350b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true);
38360b57cec5SDimitry Andric
38370b57cec5SDimitry Andric // Propagate the alignment from the array itself to the result.
3838a7dea167SDimitry Andric QualType arrayType = Array->getType();
38390b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(
3840480093f4SDimitry Andric *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
38410b57cec5SDimitry Andric E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3842480093f4SDimitry Andric E->getExprLoc(), &arrayType, E->getBase());
38430b57cec5SDimitry Andric EltBaseInfo = ArrayLV.getBaseInfo();
38440b57cec5SDimitry Andric EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
38450b57cec5SDimitry Andric } else {
38460b57cec5SDimitry Andric // The base must be a pointer; emit it with an estimate of its alignment.
38470b57cec5SDimitry Andric Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
38480b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3849a7dea167SDimitry Andric QualType ptrType = E->getBase()->getType();
38500b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
38510b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(),
3852480093f4SDimitry Andric SignedIndices, E->getExprLoc(), &ptrType,
3853480093f4SDimitry Andric E->getBase());
38540b57cec5SDimitry Andric }
38550b57cec5SDimitry Andric
38560b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
38570b57cec5SDimitry Andric
38580b57cec5SDimitry Andric if (getLangOpts().ObjC &&
38590b57cec5SDimitry Andric getLangOpts().getGC() != LangOptions::NonGC) {
38600b57cec5SDimitry Andric LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
38610b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV);
38620b57cec5SDimitry Andric }
38630b57cec5SDimitry Andric return LV;
38640b57cec5SDimitry Andric }
38650b57cec5SDimitry Andric
EmitMatrixSubscriptExpr(const MatrixSubscriptExpr * E)38665ffd83dbSDimitry Andric LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
38675ffd83dbSDimitry Andric assert(
38685ffd83dbSDimitry Andric !E->isIncomplete() &&
38695ffd83dbSDimitry Andric "incomplete matrix subscript expressions should be rejected during Sema");
38705ffd83dbSDimitry Andric LValue Base = EmitLValue(E->getBase());
38715ffd83dbSDimitry Andric llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
38725ffd83dbSDimitry Andric llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
38735ffd83dbSDimitry Andric llvm::Value *NumRows = Builder.getIntN(
38745ffd83dbSDimitry Andric RowIdx->getType()->getScalarSizeInBits(),
3875af732203SDimitry Andric E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
38765ffd83dbSDimitry Andric llvm::Value *FinalIdx =
38775ffd83dbSDimitry Andric Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
38785ffd83dbSDimitry Andric return LValue::MakeMatrixElt(
38795ffd83dbSDimitry Andric MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
38805ffd83dbSDimitry Andric E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
38815ffd83dbSDimitry Andric }
38825ffd83dbSDimitry Andric
emitOMPArraySectionBase(CodeGenFunction & CGF,const Expr * Base,LValueBaseInfo & BaseInfo,TBAAAccessInfo & TBAAInfo,QualType BaseTy,QualType ElTy,bool IsLowerBound)38830b57cec5SDimitry Andric static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
38840b57cec5SDimitry Andric LValueBaseInfo &BaseInfo,
38850b57cec5SDimitry Andric TBAAAccessInfo &TBAAInfo,
38860b57cec5SDimitry Andric QualType BaseTy, QualType ElTy,
38870b57cec5SDimitry Andric bool IsLowerBound) {
38880b57cec5SDimitry Andric LValue BaseLVal;
38890b57cec5SDimitry Andric if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
38900b57cec5SDimitry Andric BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
38910b57cec5SDimitry Andric if (BaseTy->isArrayType()) {
3892480093f4SDimitry Andric Address Addr = BaseLVal.getAddress(CGF);
38930b57cec5SDimitry Andric BaseInfo = BaseLVal.getBaseInfo();
38940b57cec5SDimitry Andric
38950b57cec5SDimitry Andric // If the array type was an incomplete type, we need to make sure
38960b57cec5SDimitry Andric // the decay ends up being the right type.
38970b57cec5SDimitry Andric llvm::Type *NewTy = CGF.ConvertType(BaseTy);
38980b57cec5SDimitry Andric Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
38990b57cec5SDimitry Andric
39000b57cec5SDimitry Andric // Note that VLA pointers are always decayed, so we don't need to do
39010b57cec5SDimitry Andric // anything here.
39020b57cec5SDimitry Andric if (!BaseTy->isVariableArrayType()) {
39030b57cec5SDimitry Andric assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
39040b57cec5SDimitry Andric "Expected pointer to array");
39050b57cec5SDimitry Andric Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
39060b57cec5SDimitry Andric }
39070b57cec5SDimitry Andric
39080b57cec5SDimitry Andric return CGF.Builder.CreateElementBitCast(Addr,
39090b57cec5SDimitry Andric CGF.ConvertTypeForMem(ElTy));
39100b57cec5SDimitry Andric }
39110b57cec5SDimitry Andric LValueBaseInfo TypeBaseInfo;
39120b57cec5SDimitry Andric TBAAAccessInfo TypeTBAAInfo;
39135ffd83dbSDimitry Andric CharUnits Align =
39145ffd83dbSDimitry Andric CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
39150b57cec5SDimitry Andric BaseInfo.mergeForCast(TypeBaseInfo);
39160b57cec5SDimitry Andric TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
3917480093f4SDimitry Andric return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)), Align);
39180b57cec5SDimitry Andric }
39190b57cec5SDimitry Andric return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
39200b57cec5SDimitry Andric }
39210b57cec5SDimitry Andric
EmitOMPArraySectionExpr(const OMPArraySectionExpr * E,bool IsLowerBound)39220b57cec5SDimitry Andric LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
39230b57cec5SDimitry Andric bool IsLowerBound) {
39240b57cec5SDimitry Andric QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
39250b57cec5SDimitry Andric QualType ResultExprTy;
39260b57cec5SDimitry Andric if (auto *AT = getContext().getAsArrayType(BaseTy))
39270b57cec5SDimitry Andric ResultExprTy = AT->getElementType();
39280b57cec5SDimitry Andric else
39290b57cec5SDimitry Andric ResultExprTy = BaseTy->getPointeeType();
39300b57cec5SDimitry Andric llvm::Value *Idx = nullptr;
39315ffd83dbSDimitry Andric if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
39320b57cec5SDimitry Andric // Requesting lower bound or upper bound, but without provided length and
39330b57cec5SDimitry Andric // without ':' symbol for the default length -> length = 1.
39340b57cec5SDimitry Andric // Idx = LowerBound ?: 0;
39350b57cec5SDimitry Andric if (auto *LowerBound = E->getLowerBound()) {
39360b57cec5SDimitry Andric Idx = Builder.CreateIntCast(
39370b57cec5SDimitry Andric EmitScalarExpr(LowerBound), IntPtrTy,
39380b57cec5SDimitry Andric LowerBound->getType()->hasSignedIntegerRepresentation());
39390b57cec5SDimitry Andric } else
39400b57cec5SDimitry Andric Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
39410b57cec5SDimitry Andric } else {
39420b57cec5SDimitry Andric // Try to emit length or lower bound as constant. If this is possible, 1
39430b57cec5SDimitry Andric // is subtracted from constant length or lower bound. Otherwise, emit LLVM
39440b57cec5SDimitry Andric // IR (LB + Len) - 1.
39450b57cec5SDimitry Andric auto &C = CGM.getContext();
39460b57cec5SDimitry Andric auto *Length = E->getLength();
39470b57cec5SDimitry Andric llvm::APSInt ConstLength;
39480b57cec5SDimitry Andric if (Length) {
39490b57cec5SDimitry Andric // Idx = LowerBound + Length - 1;
3950af732203SDimitry Andric if (Optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
3951af732203SDimitry Andric ConstLength = CL->zextOrTrunc(PointerWidthInBits);
39520b57cec5SDimitry Andric Length = nullptr;
39530b57cec5SDimitry Andric }
39540b57cec5SDimitry Andric auto *LowerBound = E->getLowerBound();
39550b57cec5SDimitry Andric llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3956af732203SDimitry Andric if (LowerBound) {
3957af732203SDimitry Andric if (Optional<llvm::APSInt> LB = LowerBound->getIntegerConstantExpr(C)) {
3958af732203SDimitry Andric ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
39590b57cec5SDimitry Andric LowerBound = nullptr;
39600b57cec5SDimitry Andric }
3961af732203SDimitry Andric }
39620b57cec5SDimitry Andric if (!Length)
39630b57cec5SDimitry Andric --ConstLength;
39640b57cec5SDimitry Andric else if (!LowerBound)
39650b57cec5SDimitry Andric --ConstLowerBound;
39660b57cec5SDimitry Andric
39670b57cec5SDimitry Andric if (Length || LowerBound) {
39680b57cec5SDimitry Andric auto *LowerBoundVal =
39690b57cec5SDimitry Andric LowerBound
39700b57cec5SDimitry Andric ? Builder.CreateIntCast(
39710b57cec5SDimitry Andric EmitScalarExpr(LowerBound), IntPtrTy,
39720b57cec5SDimitry Andric LowerBound->getType()->hasSignedIntegerRepresentation())
39730b57cec5SDimitry Andric : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
39740b57cec5SDimitry Andric auto *LengthVal =
39750b57cec5SDimitry Andric Length
39760b57cec5SDimitry Andric ? Builder.CreateIntCast(
39770b57cec5SDimitry Andric EmitScalarExpr(Length), IntPtrTy,
39780b57cec5SDimitry Andric Length->getType()->hasSignedIntegerRepresentation())
39790b57cec5SDimitry Andric : llvm::ConstantInt::get(IntPtrTy, ConstLength);
39800b57cec5SDimitry Andric Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
39810b57cec5SDimitry Andric /*HasNUW=*/false,
39820b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined());
39830b57cec5SDimitry Andric if (Length && LowerBound) {
39840b57cec5SDimitry Andric Idx = Builder.CreateSub(
39850b57cec5SDimitry Andric Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
39860b57cec5SDimitry Andric /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
39870b57cec5SDimitry Andric }
39880b57cec5SDimitry Andric } else
39890b57cec5SDimitry Andric Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
39900b57cec5SDimitry Andric } else {
39910b57cec5SDimitry Andric // Idx = ArraySize - 1;
39920b57cec5SDimitry Andric QualType ArrayTy = BaseTy->isPointerType()
39930b57cec5SDimitry Andric ? E->getBase()->IgnoreParenImpCasts()->getType()
39940b57cec5SDimitry Andric : BaseTy;
39950b57cec5SDimitry Andric if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
39960b57cec5SDimitry Andric Length = VAT->getSizeExpr();
3997af732203SDimitry Andric if (Optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
3998af732203SDimitry Andric ConstLength = *L;
39990b57cec5SDimitry Andric Length = nullptr;
4000af732203SDimitry Andric }
40010b57cec5SDimitry Andric } else {
40020b57cec5SDimitry Andric auto *CAT = C.getAsConstantArrayType(ArrayTy);
40030b57cec5SDimitry Andric ConstLength = CAT->getSize();
40040b57cec5SDimitry Andric }
40050b57cec5SDimitry Andric if (Length) {
40060b57cec5SDimitry Andric auto *LengthVal = Builder.CreateIntCast(
40070b57cec5SDimitry Andric EmitScalarExpr(Length), IntPtrTy,
40080b57cec5SDimitry Andric Length->getType()->hasSignedIntegerRepresentation());
40090b57cec5SDimitry Andric Idx = Builder.CreateSub(
40100b57cec5SDimitry Andric LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
40110b57cec5SDimitry Andric /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
40120b57cec5SDimitry Andric } else {
40130b57cec5SDimitry Andric ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
40140b57cec5SDimitry Andric --ConstLength;
40150b57cec5SDimitry Andric Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
40160b57cec5SDimitry Andric }
40170b57cec5SDimitry Andric }
40180b57cec5SDimitry Andric }
40190b57cec5SDimitry Andric assert(Idx);
40200b57cec5SDimitry Andric
40210b57cec5SDimitry Andric Address EltPtr = Address::invalid();
40220b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
40230b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
40240b57cec5SDimitry Andric if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
40250b57cec5SDimitry Andric // The base must be a pointer, which is not an aggregate. Emit
40260b57cec5SDimitry Andric // it. It needs to be emitted first in case it's what captures
40270b57cec5SDimitry Andric // the VLA bounds.
40280b57cec5SDimitry Andric Address Base =
40290b57cec5SDimitry Andric emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
40300b57cec5SDimitry Andric BaseTy, VLA->getElementType(), IsLowerBound);
40310b57cec5SDimitry Andric // The element count here is the total number of non-VLA elements.
40320b57cec5SDimitry Andric llvm::Value *NumElements = getVLASize(VLA).NumElts;
40330b57cec5SDimitry Andric
40340b57cec5SDimitry Andric // Effectively, the multiply by the VLA size is part of the GEP.
40350b57cec5SDimitry Andric // GEP indexes are signed, and scaling an index isn't permitted to
40360b57cec5SDimitry Andric // signed-overflow, so we use the same semantics for our explicit
40370b57cec5SDimitry Andric // multiply. We suppress this if overflow is not undefined behavior.
40380b57cec5SDimitry Andric if (getLangOpts().isSignedOverflowDefined())
40390b57cec5SDimitry Andric Idx = Builder.CreateMul(Idx, NumElements);
40400b57cec5SDimitry Andric else
40410b57cec5SDimitry Andric Idx = Builder.CreateNSWMul(Idx, NumElements);
40420b57cec5SDimitry Andric EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
40430b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(),
40440b57cec5SDimitry Andric /*signedIndices=*/false, E->getExprLoc());
40450b57cec5SDimitry Andric } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
40460b57cec5SDimitry Andric // If this is A[i] where A is an array, the frontend will have decayed the
40470b57cec5SDimitry Andric // base to be a ArrayToPointerDecay implicit cast. While correct, it is
40480b57cec5SDimitry Andric // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
40490b57cec5SDimitry Andric // "gep x, i" here. Emit one "gep A, 0, i".
40500b57cec5SDimitry Andric assert(Array->getType()->isArrayType() &&
40510b57cec5SDimitry Andric "Array to pointer decay must have array source type!");
40520b57cec5SDimitry Andric LValue ArrayLV;
40530b57cec5SDimitry Andric // For simple multidimensional array indexing, set the 'accessed' flag for
40540b57cec5SDimitry Andric // better bounds-checking of the base expression.
40550b57cec5SDimitry Andric if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
40560b57cec5SDimitry Andric ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
40570b57cec5SDimitry Andric else
40580b57cec5SDimitry Andric ArrayLV = EmitLValue(Array);
40590b57cec5SDimitry Andric
40600b57cec5SDimitry Andric // Propagate the alignment from the array itself to the result.
40610b57cec5SDimitry Andric EltPtr = emitArraySubscriptGEP(
4062480093f4SDimitry Andric *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
40630b57cec5SDimitry Andric ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
40640b57cec5SDimitry Andric /*signedIndices=*/false, E->getExprLoc());
40650b57cec5SDimitry Andric BaseInfo = ArrayLV.getBaseInfo();
40660b57cec5SDimitry Andric TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
40670b57cec5SDimitry Andric } else {
40680b57cec5SDimitry Andric Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
40690b57cec5SDimitry Andric TBAAInfo, BaseTy, ResultExprTy,
40700b57cec5SDimitry Andric IsLowerBound);
40710b57cec5SDimitry Andric EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
40720b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(),
40730b57cec5SDimitry Andric /*signedIndices=*/false, E->getExprLoc());
40740b57cec5SDimitry Andric }
40750b57cec5SDimitry Andric
40760b57cec5SDimitry Andric return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
40770b57cec5SDimitry Andric }
40780b57cec5SDimitry Andric
40790b57cec5SDimitry Andric LValue CodeGenFunction::
EmitExtVectorElementExpr(const ExtVectorElementExpr * E)40800b57cec5SDimitry Andric EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
40810b57cec5SDimitry Andric // Emit the base vector as an l-value.
40820b57cec5SDimitry Andric LValue Base;
40830b57cec5SDimitry Andric
40840b57cec5SDimitry Andric // ExtVectorElementExpr's base can either be a vector or pointer to vector.
40850b57cec5SDimitry Andric if (E->isArrow()) {
40860b57cec5SDimitry Andric // If it is a pointer to a vector, emit the address and form an lvalue with
40870b57cec5SDimitry Andric // it.
40880b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
40890b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
40900b57cec5SDimitry Andric Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4091480093f4SDimitry Andric const auto *PT = E->getBase()->getType()->castAs<PointerType>();
40920b57cec5SDimitry Andric Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
40930b57cec5SDimitry Andric Base.getQuals().removeObjCGCAttr();
40940b57cec5SDimitry Andric } else if (E->getBase()->isGLValue()) {
40950b57cec5SDimitry Andric // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
40960b57cec5SDimitry Andric // emit the base as an lvalue.
40970b57cec5SDimitry Andric assert(E->getBase()->getType()->isVectorType());
40980b57cec5SDimitry Andric Base = EmitLValue(E->getBase());
40990b57cec5SDimitry Andric } else {
41000b57cec5SDimitry Andric // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
41010b57cec5SDimitry Andric assert(E->getBase()->getType()->isVectorType() &&
41020b57cec5SDimitry Andric "Result must be a vector");
41030b57cec5SDimitry Andric llvm::Value *Vec = EmitScalarExpr(E->getBase());
41040b57cec5SDimitry Andric
41050b57cec5SDimitry Andric // Store the vector to memory (because LValue wants an address).
41060b57cec5SDimitry Andric Address VecMem = CreateMemTemp(E->getBase()->getType());
41070b57cec5SDimitry Andric Builder.CreateStore(Vec, VecMem);
41080b57cec5SDimitry Andric Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
41090b57cec5SDimitry Andric AlignmentSource::Decl);
41100b57cec5SDimitry Andric }
41110b57cec5SDimitry Andric
41120b57cec5SDimitry Andric QualType type =
41130b57cec5SDimitry Andric E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
41140b57cec5SDimitry Andric
41150b57cec5SDimitry Andric // Encode the element access list into a vector of unsigned indices.
41160b57cec5SDimitry Andric SmallVector<uint32_t, 4> Indices;
41170b57cec5SDimitry Andric E->getEncodedElementAccess(Indices);
41180b57cec5SDimitry Andric
41190b57cec5SDimitry Andric if (Base.isSimple()) {
41200b57cec5SDimitry Andric llvm::Constant *CV =
41210b57cec5SDimitry Andric llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4122480093f4SDimitry Andric return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
41230b57cec5SDimitry Andric Base.getBaseInfo(), TBAAAccessInfo());
41240b57cec5SDimitry Andric }
41250b57cec5SDimitry Andric assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
41260b57cec5SDimitry Andric
41270b57cec5SDimitry Andric llvm::Constant *BaseElts = Base.getExtVectorElts();
41280b57cec5SDimitry Andric SmallVector<llvm::Constant *, 4> CElts;
41290b57cec5SDimitry Andric
41300b57cec5SDimitry Andric for (unsigned i = 0, e = Indices.size(); i != e; ++i)
41310b57cec5SDimitry Andric CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
41320b57cec5SDimitry Andric llvm::Constant *CV = llvm::ConstantVector::get(CElts);
41330b57cec5SDimitry Andric return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
41340b57cec5SDimitry Andric Base.getBaseInfo(), TBAAAccessInfo());
41350b57cec5SDimitry Andric }
41360b57cec5SDimitry Andric
EmitMemberExpr(const MemberExpr * E)41370b57cec5SDimitry Andric LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
41380b57cec5SDimitry Andric if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
41390b57cec5SDimitry Andric EmitIgnoredExpr(E->getBase());
41400b57cec5SDimitry Andric return EmitDeclRefLValue(DRE);
41410b57cec5SDimitry Andric }
41420b57cec5SDimitry Andric
41430b57cec5SDimitry Andric Expr *BaseExpr = E->getBase();
41440b57cec5SDimitry Andric // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
41450b57cec5SDimitry Andric LValue BaseLV;
41460b57cec5SDimitry Andric if (E->isArrow()) {
41470b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
41480b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
41490b57cec5SDimitry Andric Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
41500b57cec5SDimitry Andric QualType PtrTy = BaseExpr->getType()->getPointeeType();
41510b57cec5SDimitry Andric SanitizerSet SkippedChecks;
41520b57cec5SDimitry Andric bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
41530b57cec5SDimitry Andric if (IsBaseCXXThis)
41540b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Alignment, true);
41550b57cec5SDimitry Andric if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
41560b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Null, true);
41570b57cec5SDimitry Andric EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
41580b57cec5SDimitry Andric /*Alignment=*/CharUnits::Zero(), SkippedChecks);
41590b57cec5SDimitry Andric BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
41600b57cec5SDimitry Andric } else
41610b57cec5SDimitry Andric BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
41620b57cec5SDimitry Andric
41630b57cec5SDimitry Andric NamedDecl *ND = E->getMemberDecl();
41640b57cec5SDimitry Andric if (auto *Field = dyn_cast<FieldDecl>(ND)) {
41650b57cec5SDimitry Andric LValue LV = EmitLValueForField(BaseLV, Field);
41660b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV);
4167480093f4SDimitry Andric if (getLangOpts().OpenMP) {
4168480093f4SDimitry Andric // If the member was explicitly marked as nontemporal, mark it as
4169480093f4SDimitry Andric // nontemporal. If the base lvalue is marked as nontemporal, mark access
4170480093f4SDimitry Andric // to children as nontemporal too.
4171480093f4SDimitry Andric if ((IsWrappedCXXThis(BaseExpr) &&
4172480093f4SDimitry Andric CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
4173480093f4SDimitry Andric BaseLV.isNontemporal())
4174480093f4SDimitry Andric LV.setNontemporal(/*Value=*/true);
4175480093f4SDimitry Andric }
41760b57cec5SDimitry Andric return LV;
41770b57cec5SDimitry Andric }
41780b57cec5SDimitry Andric
41790b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND))
41800b57cec5SDimitry Andric return EmitFunctionDeclLValue(*this, E, FD);
41810b57cec5SDimitry Andric
41820b57cec5SDimitry Andric llvm_unreachable("Unhandled member declaration!");
41830b57cec5SDimitry Andric }
41840b57cec5SDimitry Andric
41850b57cec5SDimitry Andric /// Given that we are currently emitting a lambda, emit an l-value for
41860b57cec5SDimitry Andric /// one of its members.
EmitLValueForLambdaField(const FieldDecl * Field)41870b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
4188*5f7ddb14SDimitry Andric if (CurCodeDecl) {
41890b57cec5SDimitry Andric assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
41900b57cec5SDimitry Andric assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
4191*5f7ddb14SDimitry Andric }
41920b57cec5SDimitry Andric QualType LambdaTagType =
41930b57cec5SDimitry Andric getContext().getTagDeclType(Field->getParent());
41940b57cec5SDimitry Andric LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
41950b57cec5SDimitry Andric return EmitLValueForField(LambdaLV, Field);
41960b57cec5SDimitry Andric }
41970b57cec5SDimitry Andric
41980b57cec5SDimitry Andric /// Get the field index in the debug info. The debug info structure/union
41990b57cec5SDimitry Andric /// will ignore the unnamed bitfields.
getDebugInfoFIndex(const RecordDecl * Rec,unsigned FieldIndex)42000b57cec5SDimitry Andric unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
42010b57cec5SDimitry Andric unsigned FieldIndex) {
42020b57cec5SDimitry Andric unsigned I = 0, Skipped = 0;
42030b57cec5SDimitry Andric
42040b57cec5SDimitry Andric for (auto F : Rec->getDefinition()->fields()) {
42050b57cec5SDimitry Andric if (I == FieldIndex)
42060b57cec5SDimitry Andric break;
42070b57cec5SDimitry Andric if (F->isUnnamedBitfield())
42080b57cec5SDimitry Andric Skipped++;
42090b57cec5SDimitry Andric I++;
42100b57cec5SDimitry Andric }
42110b57cec5SDimitry Andric
42120b57cec5SDimitry Andric return FieldIndex - Skipped;
42130b57cec5SDimitry Andric }
42140b57cec5SDimitry Andric
42150b57cec5SDimitry Andric /// Get the address of a zero-sized field within a record. The resulting
42160b57cec5SDimitry Andric /// address doesn't necessarily have the right type.
emitAddrOfZeroSizeField(CodeGenFunction & CGF,Address Base,const FieldDecl * Field)42170b57cec5SDimitry Andric static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
42180b57cec5SDimitry Andric const FieldDecl *Field) {
42190b57cec5SDimitry Andric CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
42200b57cec5SDimitry Andric CGF.getContext().getFieldOffset(Field));
42210b57cec5SDimitry Andric if (Offset.isZero())
42220b57cec5SDimitry Andric return Base;
42230b57cec5SDimitry Andric Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
42240b57cec5SDimitry Andric return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
42250b57cec5SDimitry Andric }
42260b57cec5SDimitry Andric
42270b57cec5SDimitry Andric /// Drill down to the storage of a field without walking into
42280b57cec5SDimitry Andric /// reference types.
42290b57cec5SDimitry Andric ///
42300b57cec5SDimitry Andric /// The resulting address doesn't necessarily have the right type.
emitAddrOfFieldStorage(CodeGenFunction & CGF,Address base,const FieldDecl * field)42310b57cec5SDimitry Andric static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
42320b57cec5SDimitry Andric const FieldDecl *field) {
42330b57cec5SDimitry Andric if (field->isZeroSize(CGF.getContext()))
42340b57cec5SDimitry Andric return emitAddrOfZeroSizeField(CGF, base, field);
42350b57cec5SDimitry Andric
42360b57cec5SDimitry Andric const RecordDecl *rec = field->getParent();
42370b57cec5SDimitry Andric
42380b57cec5SDimitry Andric unsigned idx =
42390b57cec5SDimitry Andric CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
42400b57cec5SDimitry Andric
42410b57cec5SDimitry Andric return CGF.Builder.CreateStructGEP(base, idx, field->getName());
42420b57cec5SDimitry Andric }
42430b57cec5SDimitry Andric
emitPreserveStructAccess(CodeGenFunction & CGF,LValue base,Address addr,const FieldDecl * field)42445ffd83dbSDimitry Andric static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
42455ffd83dbSDimitry Andric Address addr, const FieldDecl *field) {
42460b57cec5SDimitry Andric const RecordDecl *rec = field->getParent();
42475ffd83dbSDimitry Andric llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
42485ffd83dbSDimitry Andric base.getType(), rec->getLocation());
42490b57cec5SDimitry Andric
42500b57cec5SDimitry Andric unsigned idx =
42510b57cec5SDimitry Andric CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
42520b57cec5SDimitry Andric
42530b57cec5SDimitry Andric return CGF.Builder.CreatePreserveStructAccessIndex(
42545ffd83dbSDimitry Andric addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
42550b57cec5SDimitry Andric }
42560b57cec5SDimitry Andric
hasAnyVptr(const QualType Type,const ASTContext & Context)42570b57cec5SDimitry Andric static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
42580b57cec5SDimitry Andric const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
42590b57cec5SDimitry Andric if (!RD)
42600b57cec5SDimitry Andric return false;
42610b57cec5SDimitry Andric
42620b57cec5SDimitry Andric if (RD->isDynamicClass())
42630b57cec5SDimitry Andric return true;
42640b57cec5SDimitry Andric
42650b57cec5SDimitry Andric for (const auto &Base : RD->bases())
42660b57cec5SDimitry Andric if (hasAnyVptr(Base.getType(), Context))
42670b57cec5SDimitry Andric return true;
42680b57cec5SDimitry Andric
42690b57cec5SDimitry Andric for (const FieldDecl *Field : RD->fields())
42700b57cec5SDimitry Andric if (hasAnyVptr(Field->getType(), Context))
42710b57cec5SDimitry Andric return true;
42720b57cec5SDimitry Andric
42730b57cec5SDimitry Andric return false;
42740b57cec5SDimitry Andric }
42750b57cec5SDimitry Andric
EmitLValueForField(LValue base,const FieldDecl * field)42760b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForField(LValue base,
42770b57cec5SDimitry Andric const FieldDecl *field) {
42780b57cec5SDimitry Andric LValueBaseInfo BaseInfo = base.getBaseInfo();
42790b57cec5SDimitry Andric
42800b57cec5SDimitry Andric if (field->isBitField()) {
42810b57cec5SDimitry Andric const CGRecordLayout &RL =
42820b57cec5SDimitry Andric CGM.getTypes().getCGRecordLayout(field->getParent());
42830b57cec5SDimitry Andric const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4284af732203SDimitry Andric const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
4285af732203SDimitry Andric CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
4286af732203SDimitry Andric Info.VolatileStorageSize != 0 &&
4287af732203SDimitry Andric field->getType()
4288af732203SDimitry Andric .withCVRQualifiers(base.getVRQualifiers())
4289af732203SDimitry Andric .isVolatileQualified();
4290480093f4SDimitry Andric Address Addr = base.getAddress(*this);
42910b57cec5SDimitry Andric unsigned Idx = RL.getLLVMFieldNo(field);
4292480093f4SDimitry Andric const RecordDecl *rec = field->getParent();
4293af732203SDimitry Andric if (!UseVolatile) {
4294480093f4SDimitry Andric if (!IsInPreservedAIRegion &&
4295480093f4SDimitry Andric (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
42960b57cec5SDimitry Andric if (Idx != 0)
42970b57cec5SDimitry Andric // For structs, we GEP to the field that the record layout suggests.
42980b57cec5SDimitry Andric Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4299a7dea167SDimitry Andric } else {
4300a7dea167SDimitry Andric llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4301a7dea167SDimitry Andric getContext().getRecordType(rec), rec->getLocation());
4302af732203SDimitry Andric Addr = Builder.CreatePreserveStructAccessIndex(
4303af732203SDimitry Andric Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
4304a7dea167SDimitry Andric DbgInfo);
4305a7dea167SDimitry Andric }
4306af732203SDimitry Andric }
4307af732203SDimitry Andric const unsigned SS =
4308af732203SDimitry Andric UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
43090b57cec5SDimitry Andric // Get the access type.
4310af732203SDimitry Andric llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
43110b57cec5SDimitry Andric if (Addr.getElementType() != FieldIntTy)
43120b57cec5SDimitry Andric Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
4313af732203SDimitry Andric if (UseVolatile) {
4314af732203SDimitry Andric const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
4315af732203SDimitry Andric if (VolatileOffset)
4316af732203SDimitry Andric Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
4317af732203SDimitry Andric }
43180b57cec5SDimitry Andric
43190b57cec5SDimitry Andric QualType fieldType =
43200b57cec5SDimitry Andric field->getType().withCVRQualifiers(base.getVRQualifiers());
43210b57cec5SDimitry Andric // TODO: Support TBAA for bit fields.
43220b57cec5SDimitry Andric LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
43230b57cec5SDimitry Andric return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
43240b57cec5SDimitry Andric TBAAAccessInfo());
43250b57cec5SDimitry Andric }
43260b57cec5SDimitry Andric
43270b57cec5SDimitry Andric // Fields of may-alias structures are may-alias themselves.
43280b57cec5SDimitry Andric // FIXME: this should get propagated down through anonymous structs
43290b57cec5SDimitry Andric // and unions.
43300b57cec5SDimitry Andric QualType FieldType = field->getType();
43310b57cec5SDimitry Andric const RecordDecl *rec = field->getParent();
43320b57cec5SDimitry Andric AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
43330b57cec5SDimitry Andric LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
43340b57cec5SDimitry Andric TBAAAccessInfo FieldTBAAInfo;
43350b57cec5SDimitry Andric if (base.getTBAAInfo().isMayAlias() ||
43360b57cec5SDimitry Andric rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
43370b57cec5SDimitry Andric FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
43380b57cec5SDimitry Andric } else if (rec->isUnion()) {
43390b57cec5SDimitry Andric // TODO: Support TBAA for unions.
43400b57cec5SDimitry Andric FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
43410b57cec5SDimitry Andric } else {
43420b57cec5SDimitry Andric // If no base type been assigned for the base access, then try to generate
43430b57cec5SDimitry Andric // one for this base lvalue.
43440b57cec5SDimitry Andric FieldTBAAInfo = base.getTBAAInfo();
43450b57cec5SDimitry Andric if (!FieldTBAAInfo.BaseType) {
43460b57cec5SDimitry Andric FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
43470b57cec5SDimitry Andric assert(!FieldTBAAInfo.Offset &&
43480b57cec5SDimitry Andric "Nonzero offset for an access with no base type!");
43490b57cec5SDimitry Andric }
43500b57cec5SDimitry Andric
43510b57cec5SDimitry Andric // Adjust offset to be relative to the base type.
43520b57cec5SDimitry Andric const ASTRecordLayout &Layout =
43530b57cec5SDimitry Andric getContext().getASTRecordLayout(field->getParent());
43540b57cec5SDimitry Andric unsigned CharWidth = getContext().getCharWidth();
43550b57cec5SDimitry Andric if (FieldTBAAInfo.BaseType)
43560b57cec5SDimitry Andric FieldTBAAInfo.Offset +=
43570b57cec5SDimitry Andric Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
43580b57cec5SDimitry Andric
43590b57cec5SDimitry Andric // Update the final access type and size.
43600b57cec5SDimitry Andric FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
43610b57cec5SDimitry Andric FieldTBAAInfo.Size =
43620b57cec5SDimitry Andric getContext().getTypeSizeInChars(FieldType).getQuantity();
43630b57cec5SDimitry Andric }
43640b57cec5SDimitry Andric
4365480093f4SDimitry Andric Address addr = base.getAddress(*this);
43660b57cec5SDimitry Andric if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
43670b57cec5SDimitry Andric if (CGM.getCodeGenOpts().StrictVTablePointers &&
43680b57cec5SDimitry Andric ClassDef->isDynamicClass()) {
43690b57cec5SDimitry Andric // Getting to any field of dynamic object requires stripping dynamic
43700b57cec5SDimitry Andric // information provided by invariant.group. This is because accessing
43710b57cec5SDimitry Andric // fields may leak the real address of dynamic object, which could result
43720b57cec5SDimitry Andric // in miscompilation when leaked pointer would be compared.
43730b57cec5SDimitry Andric auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
43740b57cec5SDimitry Andric addr = Address(stripped, addr.getAlignment());
43750b57cec5SDimitry Andric }
43760b57cec5SDimitry Andric }
43770b57cec5SDimitry Andric
43780b57cec5SDimitry Andric unsigned RecordCVR = base.getVRQualifiers();
43790b57cec5SDimitry Andric if (rec->isUnion()) {
43800b57cec5SDimitry Andric // For unions, there is no pointer adjustment.
43810b57cec5SDimitry Andric if (CGM.getCodeGenOpts().StrictVTablePointers &&
43820b57cec5SDimitry Andric hasAnyVptr(FieldType, getContext()))
43830b57cec5SDimitry Andric // Because unions can easily skip invariant.barriers, we need to add
43840b57cec5SDimitry Andric // a barrier every time CXXRecord field with vptr is referenced.
43850b57cec5SDimitry Andric addr = Address(Builder.CreateLaunderInvariantGroup(addr.getPointer()),
43860b57cec5SDimitry Andric addr.getAlignment());
43870b57cec5SDimitry Andric
4388480093f4SDimitry Andric if (IsInPreservedAIRegion ||
4389480093f4SDimitry Andric (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
43900b57cec5SDimitry Andric // Remember the original union field index
43915ffd83dbSDimitry Andric llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
43925ffd83dbSDimitry Andric rec->getLocation());
43930b57cec5SDimitry Andric addr = Address(
43940b57cec5SDimitry Andric Builder.CreatePreserveUnionAccessIndex(
43950b57cec5SDimitry Andric addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
43960b57cec5SDimitry Andric addr.getAlignment());
43970b57cec5SDimitry Andric }
43980b57cec5SDimitry Andric
4399a7dea167SDimitry Andric if (FieldType->isReferenceType())
4400a7dea167SDimitry Andric addr = Builder.CreateElementBitCast(
4401a7dea167SDimitry Andric addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4402a7dea167SDimitry Andric } else {
4403480093f4SDimitry Andric if (!IsInPreservedAIRegion &&
4404480093f4SDimitry Andric (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
44050b57cec5SDimitry Andric // For structs, we GEP to the field that the record layout suggests.
44060b57cec5SDimitry Andric addr = emitAddrOfFieldStorage(*this, addr, field);
44070b57cec5SDimitry Andric else
44080b57cec5SDimitry Andric // Remember the original struct field index
44095ffd83dbSDimitry Andric addr = emitPreserveStructAccess(*this, base, addr, field);
4410a7dea167SDimitry Andric }
44110b57cec5SDimitry Andric
44120b57cec5SDimitry Andric // If this is a reference field, load the reference right now.
44130b57cec5SDimitry Andric if (FieldType->isReferenceType()) {
4414a7dea167SDimitry Andric LValue RefLVal =
4415a7dea167SDimitry Andric MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
44160b57cec5SDimitry Andric if (RecordCVR & Qualifiers::Volatile)
44170b57cec5SDimitry Andric RefLVal.getQuals().addVolatile();
44180b57cec5SDimitry Andric addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
44190b57cec5SDimitry Andric
44200b57cec5SDimitry Andric // Qualifiers on the struct don't apply to the referencee.
44210b57cec5SDimitry Andric RecordCVR = 0;
44220b57cec5SDimitry Andric FieldType = FieldType->getPointeeType();
44230b57cec5SDimitry Andric }
44240b57cec5SDimitry Andric
44250b57cec5SDimitry Andric // Make sure that the address is pointing to the right type. This is critical
44260b57cec5SDimitry Andric // for both unions and structs. A union needs a bitcast, a struct element
44270b57cec5SDimitry Andric // will need a bitcast if the LLVM type laid out doesn't match the desired
44280b57cec5SDimitry Andric // type.
44290b57cec5SDimitry Andric addr = Builder.CreateElementBitCast(
44300b57cec5SDimitry Andric addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
44310b57cec5SDimitry Andric
44320b57cec5SDimitry Andric if (field->hasAttr<AnnotateAttr>())
44330b57cec5SDimitry Andric addr = EmitFieldAnnotations(field, addr);
44340b57cec5SDimitry Andric
44350b57cec5SDimitry Andric LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
44360b57cec5SDimitry Andric LV.getQuals().addCVRQualifiers(RecordCVR);
44370b57cec5SDimitry Andric
44380b57cec5SDimitry Andric // __weak attribute on a field is ignored.
44390b57cec5SDimitry Andric if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
44400b57cec5SDimitry Andric LV.getQuals().removeObjCGCAttr();
44410b57cec5SDimitry Andric
44420b57cec5SDimitry Andric return LV;
44430b57cec5SDimitry Andric }
44440b57cec5SDimitry Andric
44450b57cec5SDimitry Andric LValue
EmitLValueForFieldInitialization(LValue Base,const FieldDecl * Field)44460b57cec5SDimitry Andric CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
44470b57cec5SDimitry Andric const FieldDecl *Field) {
44480b57cec5SDimitry Andric QualType FieldType = Field->getType();
44490b57cec5SDimitry Andric
44500b57cec5SDimitry Andric if (!FieldType->isReferenceType())
44510b57cec5SDimitry Andric return EmitLValueForField(Base, Field);
44520b57cec5SDimitry Andric
4453480093f4SDimitry Andric Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
44540b57cec5SDimitry Andric
44550b57cec5SDimitry Andric // Make sure that the address is pointing to the right type.
44560b57cec5SDimitry Andric llvm::Type *llvmType = ConvertTypeForMem(FieldType);
44570b57cec5SDimitry Andric V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
44580b57cec5SDimitry Andric
44590b57cec5SDimitry Andric // TODO: Generate TBAA information that describes this access as a structure
44600b57cec5SDimitry Andric // member access and not just an access to an object of the field's type. This
44610b57cec5SDimitry Andric // should be similar to what we do in EmitLValueForField().
44620b57cec5SDimitry Andric LValueBaseInfo BaseInfo = Base.getBaseInfo();
44630b57cec5SDimitry Andric AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
44640b57cec5SDimitry Andric LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
44650b57cec5SDimitry Andric return MakeAddrLValue(V, FieldType, FieldBaseInfo,
44660b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(Base, FieldType));
44670b57cec5SDimitry Andric }
44680b57cec5SDimitry Andric
EmitCompoundLiteralLValue(const CompoundLiteralExpr * E)44690b57cec5SDimitry Andric LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
44700b57cec5SDimitry Andric if (E->isFileScope()) {
44710b57cec5SDimitry Andric ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
44720b57cec5SDimitry Andric return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
44730b57cec5SDimitry Andric }
44740b57cec5SDimitry Andric if (E->getType()->isVariablyModifiedType())
44750b57cec5SDimitry Andric // make sure to emit the VLA size.
44760b57cec5SDimitry Andric EmitVariablyModifiedType(E->getType());
44770b57cec5SDimitry Andric
44780b57cec5SDimitry Andric Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
44790b57cec5SDimitry Andric const Expr *InitExpr = E->getInitializer();
44800b57cec5SDimitry Andric LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
44810b57cec5SDimitry Andric
44820b57cec5SDimitry Andric EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
44830b57cec5SDimitry Andric /*Init*/ true);
44840b57cec5SDimitry Andric
44855ffd83dbSDimitry Andric // Block-scope compound literals are destroyed at the end of the enclosing
44865ffd83dbSDimitry Andric // scope in C.
44875ffd83dbSDimitry Andric if (!getLangOpts().CPlusPlus)
44885ffd83dbSDimitry Andric if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
44895ffd83dbSDimitry Andric pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
44905ffd83dbSDimitry Andric E->getType(), getDestroyer(DtorKind),
44915ffd83dbSDimitry Andric DtorKind & EHCleanup);
44925ffd83dbSDimitry Andric
44930b57cec5SDimitry Andric return Result;
44940b57cec5SDimitry Andric }
44950b57cec5SDimitry Andric
EmitInitListLValue(const InitListExpr * E)44960b57cec5SDimitry Andric LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
44970b57cec5SDimitry Andric if (!E->isGLValue())
44980b57cec5SDimitry Andric // Initializing an aggregate temporary in C++11: T{...}.
44990b57cec5SDimitry Andric return EmitAggExprToLValue(E);
45000b57cec5SDimitry Andric
45010b57cec5SDimitry Andric // An lvalue initializer list must be initializing a reference.
45020b57cec5SDimitry Andric assert(E->isTransparent() && "non-transparent glvalue init list");
45030b57cec5SDimitry Andric return EmitLValue(E->getInit(0));
45040b57cec5SDimitry Andric }
45050b57cec5SDimitry Andric
45060b57cec5SDimitry Andric /// Emit the operand of a glvalue conditional operator. This is either a glvalue
45070b57cec5SDimitry Andric /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
45080b57cec5SDimitry Andric /// LValue is returned and the current block has been terminated.
EmitLValueOrThrowExpression(CodeGenFunction & CGF,const Expr * Operand)45090b57cec5SDimitry Andric static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
45100b57cec5SDimitry Andric const Expr *Operand) {
45110b57cec5SDimitry Andric if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
45120b57cec5SDimitry Andric CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
45130b57cec5SDimitry Andric return None;
45140b57cec5SDimitry Andric }
45150b57cec5SDimitry Andric
45160b57cec5SDimitry Andric return CGF.EmitLValue(Operand);
45170b57cec5SDimitry Andric }
45180b57cec5SDimitry Andric
45190b57cec5SDimitry Andric LValue CodeGenFunction::
EmitConditionalOperatorLValue(const AbstractConditionalOperator * expr)45200b57cec5SDimitry Andric EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
45210b57cec5SDimitry Andric if (!expr->isGLValue()) {
45220b57cec5SDimitry Andric // ?: here should be an aggregate.
45230b57cec5SDimitry Andric assert(hasAggregateEvaluationKind(expr->getType()) &&
45240b57cec5SDimitry Andric "Unexpected conditional operator!");
45250b57cec5SDimitry Andric return EmitAggExprToLValue(expr);
45260b57cec5SDimitry Andric }
45270b57cec5SDimitry Andric
45280b57cec5SDimitry Andric OpaqueValueMapping binding(*this, expr);
45290b57cec5SDimitry Andric
45300b57cec5SDimitry Andric const Expr *condExpr = expr->getCond();
45310b57cec5SDimitry Andric bool CondExprBool;
45320b57cec5SDimitry Andric if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
45330b57cec5SDimitry Andric const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
45340b57cec5SDimitry Andric if (!CondExprBool) std::swap(live, dead);
45350b57cec5SDimitry Andric
45360b57cec5SDimitry Andric if (!ContainsLabel(dead)) {
45370b57cec5SDimitry Andric // If the true case is live, we need to track its region.
45380b57cec5SDimitry Andric if (CondExprBool)
45390b57cec5SDimitry Andric incrementProfileCounter(expr);
45405ffd83dbSDimitry Andric // If a throw expression we emit it and return an undefined lvalue
45415ffd83dbSDimitry Andric // because it can't be used.
45425ffd83dbSDimitry Andric if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(live->IgnoreParens())) {
45435ffd83dbSDimitry Andric EmitCXXThrowExpr(ThrowExpr);
45445ffd83dbSDimitry Andric llvm::Type *Ty =
45455ffd83dbSDimitry Andric llvm::PointerType::getUnqual(ConvertType(dead->getType()));
45465ffd83dbSDimitry Andric return MakeAddrLValue(
45475ffd83dbSDimitry Andric Address(llvm::UndefValue::get(Ty), CharUnits::One()),
45485ffd83dbSDimitry Andric dead->getType());
45495ffd83dbSDimitry Andric }
45500b57cec5SDimitry Andric return EmitLValue(live);
45510b57cec5SDimitry Andric }
45520b57cec5SDimitry Andric }
45530b57cec5SDimitry Andric
45540b57cec5SDimitry Andric llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
45550b57cec5SDimitry Andric llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
45560b57cec5SDimitry Andric llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
45570b57cec5SDimitry Andric
45580b57cec5SDimitry Andric ConditionalEvaluation eval(*this);
45590b57cec5SDimitry Andric EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
45600b57cec5SDimitry Andric
45610b57cec5SDimitry Andric // Any temporaries created here are conditional.
45620b57cec5SDimitry Andric EmitBlock(lhsBlock);
45630b57cec5SDimitry Andric incrementProfileCounter(expr);
45640b57cec5SDimitry Andric eval.begin(*this);
45650b57cec5SDimitry Andric Optional<LValue> lhs =
45660b57cec5SDimitry Andric EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
45670b57cec5SDimitry Andric eval.end(*this);
45680b57cec5SDimitry Andric
45690b57cec5SDimitry Andric if (lhs && !lhs->isSimple())
45700b57cec5SDimitry Andric return EmitUnsupportedLValue(expr, "conditional operator");
45710b57cec5SDimitry Andric
45720b57cec5SDimitry Andric lhsBlock = Builder.GetInsertBlock();
45730b57cec5SDimitry Andric if (lhs)
45740b57cec5SDimitry Andric Builder.CreateBr(contBlock);
45750b57cec5SDimitry Andric
45760b57cec5SDimitry Andric // Any temporaries created here are conditional.
45770b57cec5SDimitry Andric EmitBlock(rhsBlock);
45780b57cec5SDimitry Andric eval.begin(*this);
45790b57cec5SDimitry Andric Optional<LValue> rhs =
45800b57cec5SDimitry Andric EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
45810b57cec5SDimitry Andric eval.end(*this);
45820b57cec5SDimitry Andric if (rhs && !rhs->isSimple())
45830b57cec5SDimitry Andric return EmitUnsupportedLValue(expr, "conditional operator");
45840b57cec5SDimitry Andric rhsBlock = Builder.GetInsertBlock();
45850b57cec5SDimitry Andric
45860b57cec5SDimitry Andric EmitBlock(contBlock);
45870b57cec5SDimitry Andric
45880b57cec5SDimitry Andric if (lhs && rhs) {
4589480093f4SDimitry Andric llvm::PHINode *phi =
4590480093f4SDimitry Andric Builder.CreatePHI(lhs->getPointer(*this)->getType(), 2, "cond-lvalue");
4591480093f4SDimitry Andric phi->addIncoming(lhs->getPointer(*this), lhsBlock);
4592480093f4SDimitry Andric phi->addIncoming(rhs->getPointer(*this), rhsBlock);
45930b57cec5SDimitry Andric Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
45940b57cec5SDimitry Andric AlignmentSource alignSource =
45950b57cec5SDimitry Andric std::max(lhs->getBaseInfo().getAlignmentSource(),
45960b57cec5SDimitry Andric rhs->getBaseInfo().getAlignmentSource());
45970b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
45980b57cec5SDimitry Andric lhs->getTBAAInfo(), rhs->getTBAAInfo());
45990b57cec5SDimitry Andric return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
46000b57cec5SDimitry Andric TBAAInfo);
46010b57cec5SDimitry Andric } else {
46020b57cec5SDimitry Andric assert((lhs || rhs) &&
46030b57cec5SDimitry Andric "both operands of glvalue conditional are throw-expressions?");
46040b57cec5SDimitry Andric return lhs ? *lhs : *rhs;
46050b57cec5SDimitry Andric }
46060b57cec5SDimitry Andric }
46070b57cec5SDimitry Andric
46080b57cec5SDimitry Andric /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
46090b57cec5SDimitry Andric /// type. If the cast is to a reference, we can have the usual lvalue result,
46100b57cec5SDimitry Andric /// otherwise if a cast is needed by the code generator in an lvalue context,
46110b57cec5SDimitry Andric /// then it must mean that we need the address of an aggregate in order to
46120b57cec5SDimitry Andric /// access one of its members. This can happen for all the reasons that casts
46130b57cec5SDimitry Andric /// are permitted with aggregate result, including noop aggregate casts, and
46140b57cec5SDimitry Andric /// cast from scalar to union.
EmitCastLValue(const CastExpr * E)46150b57cec5SDimitry Andric LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
46160b57cec5SDimitry Andric switch (E->getCastKind()) {
46170b57cec5SDimitry Andric case CK_ToVoid:
46180b57cec5SDimitry Andric case CK_BitCast:
46190b57cec5SDimitry Andric case CK_LValueToRValueBitCast:
46200b57cec5SDimitry Andric case CK_ArrayToPointerDecay:
46210b57cec5SDimitry Andric case CK_FunctionToPointerDecay:
46220b57cec5SDimitry Andric case CK_NullToMemberPointer:
46230b57cec5SDimitry Andric case CK_NullToPointer:
46240b57cec5SDimitry Andric case CK_IntegralToPointer:
46250b57cec5SDimitry Andric case CK_PointerToIntegral:
46260b57cec5SDimitry Andric case CK_PointerToBoolean:
46270b57cec5SDimitry Andric case CK_VectorSplat:
46280b57cec5SDimitry Andric case CK_IntegralCast:
46290b57cec5SDimitry Andric case CK_BooleanToSignedIntegral:
46300b57cec5SDimitry Andric case CK_IntegralToBoolean:
46310b57cec5SDimitry Andric case CK_IntegralToFloating:
46320b57cec5SDimitry Andric case CK_FloatingToIntegral:
46330b57cec5SDimitry Andric case CK_FloatingToBoolean:
46340b57cec5SDimitry Andric case CK_FloatingCast:
46350b57cec5SDimitry Andric case CK_FloatingRealToComplex:
46360b57cec5SDimitry Andric case CK_FloatingComplexToReal:
46370b57cec5SDimitry Andric case CK_FloatingComplexToBoolean:
46380b57cec5SDimitry Andric case CK_FloatingComplexCast:
46390b57cec5SDimitry Andric case CK_FloatingComplexToIntegralComplex:
46400b57cec5SDimitry Andric case CK_IntegralRealToComplex:
46410b57cec5SDimitry Andric case CK_IntegralComplexToReal:
46420b57cec5SDimitry Andric case CK_IntegralComplexToBoolean:
46430b57cec5SDimitry Andric case CK_IntegralComplexCast:
46440b57cec5SDimitry Andric case CK_IntegralComplexToFloatingComplex:
46450b57cec5SDimitry Andric case CK_DerivedToBaseMemberPointer:
46460b57cec5SDimitry Andric case CK_BaseToDerivedMemberPointer:
46470b57cec5SDimitry Andric case CK_MemberPointerToBoolean:
46480b57cec5SDimitry Andric case CK_ReinterpretMemberPointer:
46490b57cec5SDimitry Andric case CK_AnyPointerToBlockPointerCast:
46500b57cec5SDimitry Andric case CK_ARCProduceObject:
46510b57cec5SDimitry Andric case CK_ARCConsumeObject:
46520b57cec5SDimitry Andric case CK_ARCReclaimReturnedObject:
46530b57cec5SDimitry Andric case CK_ARCExtendBlockObject:
46540b57cec5SDimitry Andric case CK_CopyAndAutoreleaseBlockObject:
46550b57cec5SDimitry Andric case CK_IntToOCLSampler:
4656af732203SDimitry Andric case CK_FloatingToFixedPoint:
4657af732203SDimitry Andric case CK_FixedPointToFloating:
46580b57cec5SDimitry Andric case CK_FixedPointCast:
46590b57cec5SDimitry Andric case CK_FixedPointToBoolean:
46600b57cec5SDimitry Andric case CK_FixedPointToIntegral:
46610b57cec5SDimitry Andric case CK_IntegralToFixedPoint:
4662*5f7ddb14SDimitry Andric case CK_MatrixCast:
46630b57cec5SDimitry Andric return EmitUnsupportedLValue(E, "unexpected cast lvalue");
46640b57cec5SDimitry Andric
46650b57cec5SDimitry Andric case CK_Dependent:
46660b57cec5SDimitry Andric llvm_unreachable("dependent cast kind in IR gen!");
46670b57cec5SDimitry Andric
46680b57cec5SDimitry Andric case CK_BuiltinFnToFnPtr:
46690b57cec5SDimitry Andric llvm_unreachable("builtin functions are handled elsewhere");
46700b57cec5SDimitry Andric
46710b57cec5SDimitry Andric // These are never l-values; just use the aggregate emission code.
46720b57cec5SDimitry Andric case CK_NonAtomicToAtomic:
46730b57cec5SDimitry Andric case CK_AtomicToNonAtomic:
46740b57cec5SDimitry Andric return EmitAggExprToLValue(E);
46750b57cec5SDimitry Andric
46760b57cec5SDimitry Andric case CK_Dynamic: {
46770b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
4678480093f4SDimitry Andric Address V = LV.getAddress(*this);
46790b57cec5SDimitry Andric const auto *DCE = cast<CXXDynamicCastExpr>(E);
46800b57cec5SDimitry Andric return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
46810b57cec5SDimitry Andric }
46820b57cec5SDimitry Andric
46830b57cec5SDimitry Andric case CK_ConstructorConversion:
46840b57cec5SDimitry Andric case CK_UserDefinedConversion:
46850b57cec5SDimitry Andric case CK_CPointerToObjCPointerCast:
46860b57cec5SDimitry Andric case CK_BlockPointerToObjCPointerCast:
46870b57cec5SDimitry Andric case CK_NoOp:
46880b57cec5SDimitry Andric case CK_LValueToRValue:
46890b57cec5SDimitry Andric return EmitLValue(E->getSubExpr());
46900b57cec5SDimitry Andric
46910b57cec5SDimitry Andric case CK_UncheckedDerivedToBase:
46920b57cec5SDimitry Andric case CK_DerivedToBase: {
4693480093f4SDimitry Andric const auto *DerivedClassTy =
4694480093f4SDimitry Andric E->getSubExpr()->getType()->castAs<RecordType>();
46950b57cec5SDimitry Andric auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
46960b57cec5SDimitry Andric
46970b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
4698480093f4SDimitry Andric Address This = LV.getAddress(*this);
46990b57cec5SDimitry Andric
47000b57cec5SDimitry Andric // Perform the derived-to-base conversion
47010b57cec5SDimitry Andric Address Base = GetAddressOfBaseClass(
47020b57cec5SDimitry Andric This, DerivedClassDecl, E->path_begin(), E->path_end(),
47030b57cec5SDimitry Andric /*NullCheckValue=*/false, E->getExprLoc());
47040b57cec5SDimitry Andric
47050b57cec5SDimitry Andric // TODO: Support accesses to members of base classes in TBAA. For now, we
47060b57cec5SDimitry Andric // conservatively pretend that the complete object is of the base class
47070b57cec5SDimitry Andric // type.
47080b57cec5SDimitry Andric return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
47090b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType()));
47100b57cec5SDimitry Andric }
47110b57cec5SDimitry Andric case CK_ToUnion:
47120b57cec5SDimitry Andric return EmitAggExprToLValue(E);
47130b57cec5SDimitry Andric case CK_BaseToDerived: {
4714480093f4SDimitry Andric const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
47150b57cec5SDimitry Andric auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
47160b57cec5SDimitry Andric
47170b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
47180b57cec5SDimitry Andric
47190b57cec5SDimitry Andric // Perform the base-to-derived conversion
4720480093f4SDimitry Andric Address Derived = GetAddressOfDerivedClass(
4721480093f4SDimitry Andric LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
47220b57cec5SDimitry Andric /*NullCheckValue=*/false);
47230b57cec5SDimitry Andric
47240b57cec5SDimitry Andric // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
47250b57cec5SDimitry Andric // performed and the object is not of the derived type.
47260b57cec5SDimitry Andric if (sanitizePerformTypeCheck())
47270b57cec5SDimitry Andric EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
47280b57cec5SDimitry Andric Derived.getPointer(), E->getType());
47290b57cec5SDimitry Andric
47300b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFIDerivedCast))
47310b57cec5SDimitry Andric EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
47320b57cec5SDimitry Andric /*MayBeNull=*/false, CFITCK_DerivedCast,
47330b57cec5SDimitry Andric E->getBeginLoc());
47340b57cec5SDimitry Andric
47350b57cec5SDimitry Andric return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
47360b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType()));
47370b57cec5SDimitry Andric }
47380b57cec5SDimitry Andric case CK_LValueBitCast: {
47390b57cec5SDimitry Andric // This must be a reinterpret_cast (or c-style equivalent).
47400b57cec5SDimitry Andric const auto *CE = cast<ExplicitCastExpr>(E);
47410b57cec5SDimitry Andric
47420b57cec5SDimitry Andric CGM.EmitExplicitCastExprType(CE, this);
47430b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
4744480093f4SDimitry Andric Address V = Builder.CreateBitCast(LV.getAddress(*this),
47450b57cec5SDimitry Andric ConvertType(CE->getTypeAsWritten()));
47460b57cec5SDimitry Andric
47470b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
47480b57cec5SDimitry Andric EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
47490b57cec5SDimitry Andric /*MayBeNull=*/false, CFITCK_UnrelatedCast,
47500b57cec5SDimitry Andric E->getBeginLoc());
47510b57cec5SDimitry Andric
47520b57cec5SDimitry Andric return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
47530b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType()));
47540b57cec5SDimitry Andric }
47550b57cec5SDimitry Andric case CK_AddressSpaceConversion: {
47560b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
47570b57cec5SDimitry Andric QualType DestTy = getContext().getPointerType(E->getType());
47580b57cec5SDimitry Andric llvm::Value *V = getTargetHooks().performAddrSpaceCast(
4759480093f4SDimitry Andric *this, LV.getPointer(*this),
4760480093f4SDimitry Andric E->getSubExpr()->getType().getAddressSpace(),
47610b57cec5SDimitry Andric E->getType().getAddressSpace(), ConvertType(DestTy));
4762480093f4SDimitry Andric return MakeAddrLValue(Address(V, LV.getAddress(*this).getAlignment()),
47630b57cec5SDimitry Andric E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
47640b57cec5SDimitry Andric }
47650b57cec5SDimitry Andric case CK_ObjCObjectLValueCast: {
47660b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
4767480093f4SDimitry Andric Address V = Builder.CreateElementBitCast(LV.getAddress(*this),
47680b57cec5SDimitry Andric ConvertType(E->getType()));
47690b57cec5SDimitry Andric return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
47700b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType()));
47710b57cec5SDimitry Andric }
47720b57cec5SDimitry Andric case CK_ZeroToOCLOpaqueType:
47730b57cec5SDimitry Andric llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
47740b57cec5SDimitry Andric }
47750b57cec5SDimitry Andric
47760b57cec5SDimitry Andric llvm_unreachable("Unhandled lvalue cast kind?");
47770b57cec5SDimitry Andric }
47780b57cec5SDimitry Andric
EmitOpaqueValueLValue(const OpaqueValueExpr * e)47790b57cec5SDimitry Andric LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
47800b57cec5SDimitry Andric assert(OpaqueValueMappingData::shouldBindAsLValue(e));
47810b57cec5SDimitry Andric return getOrCreateOpaqueLValueMapping(e);
47820b57cec5SDimitry Andric }
47830b57cec5SDimitry Andric
47840b57cec5SDimitry Andric LValue
getOrCreateOpaqueLValueMapping(const OpaqueValueExpr * e)47850b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
47860b57cec5SDimitry Andric assert(OpaqueValueMapping::shouldBindAsLValue(e));
47870b57cec5SDimitry Andric
47880b57cec5SDimitry Andric llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
47890b57cec5SDimitry Andric it = OpaqueLValues.find(e);
47900b57cec5SDimitry Andric
47910b57cec5SDimitry Andric if (it != OpaqueLValues.end())
47920b57cec5SDimitry Andric return it->second;
47930b57cec5SDimitry Andric
47940b57cec5SDimitry Andric assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
47950b57cec5SDimitry Andric return EmitLValue(e->getSourceExpr());
47960b57cec5SDimitry Andric }
47970b57cec5SDimitry Andric
47980b57cec5SDimitry Andric RValue
getOrCreateOpaqueRValueMapping(const OpaqueValueExpr * e)47990b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
48000b57cec5SDimitry Andric assert(!OpaqueValueMapping::shouldBindAsLValue(e));
48010b57cec5SDimitry Andric
48020b57cec5SDimitry Andric llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
48030b57cec5SDimitry Andric it = OpaqueRValues.find(e);
48040b57cec5SDimitry Andric
48050b57cec5SDimitry Andric if (it != OpaqueRValues.end())
48060b57cec5SDimitry Andric return it->second;
48070b57cec5SDimitry Andric
48080b57cec5SDimitry Andric assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
48090b57cec5SDimitry Andric return EmitAnyExpr(e->getSourceExpr());
48100b57cec5SDimitry Andric }
48110b57cec5SDimitry Andric
EmitRValueForField(LValue LV,const FieldDecl * FD,SourceLocation Loc)48120b57cec5SDimitry Andric RValue CodeGenFunction::EmitRValueForField(LValue LV,
48130b57cec5SDimitry Andric const FieldDecl *FD,
48140b57cec5SDimitry Andric SourceLocation Loc) {
48150b57cec5SDimitry Andric QualType FT = FD->getType();
48160b57cec5SDimitry Andric LValue FieldLV = EmitLValueForField(LV, FD);
48170b57cec5SDimitry Andric switch (getEvaluationKind(FT)) {
48180b57cec5SDimitry Andric case TEK_Complex:
48190b57cec5SDimitry Andric return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
48200b57cec5SDimitry Andric case TEK_Aggregate:
4821480093f4SDimitry Andric return FieldLV.asAggregateRValue(*this);
48220b57cec5SDimitry Andric case TEK_Scalar:
48230b57cec5SDimitry Andric // This routine is used to load fields one-by-one to perform a copy, so
48240b57cec5SDimitry Andric // don't load reference fields.
48250b57cec5SDimitry Andric if (FD->getType()->isReferenceType())
4826480093f4SDimitry Andric return RValue::get(FieldLV.getPointer(*this));
4827480093f4SDimitry Andric // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
4828480093f4SDimitry Andric // primitive load.
4829480093f4SDimitry Andric if (FieldLV.isBitField())
48300b57cec5SDimitry Andric return EmitLoadOfLValue(FieldLV, Loc);
4831480093f4SDimitry Andric return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
48320b57cec5SDimitry Andric }
48330b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
48340b57cec5SDimitry Andric }
48350b57cec5SDimitry Andric
48360b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
48370b57cec5SDimitry Andric // Expression Emission
48380b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
48390b57cec5SDimitry Andric
EmitCallExpr(const CallExpr * E,ReturnValueSlot ReturnValue)48400b57cec5SDimitry Andric RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
48410b57cec5SDimitry Andric ReturnValueSlot ReturnValue) {
48420b57cec5SDimitry Andric // Builtins never have block type.
48430b57cec5SDimitry Andric if (E->getCallee()->getType()->isBlockPointerType())
48440b57cec5SDimitry Andric return EmitBlockCallExpr(E, ReturnValue);
48450b57cec5SDimitry Andric
48460b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
48470b57cec5SDimitry Andric return EmitCXXMemberCallExpr(CE, ReturnValue);
48480b57cec5SDimitry Andric
48490b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
48500b57cec5SDimitry Andric return EmitCUDAKernelCallExpr(CE, ReturnValue);
48510b57cec5SDimitry Andric
48520b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
48530b57cec5SDimitry Andric if (const CXXMethodDecl *MD =
48540b57cec5SDimitry Andric dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
48550b57cec5SDimitry Andric return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
48560b57cec5SDimitry Andric
48570b57cec5SDimitry Andric CGCallee callee = EmitCallee(E->getCallee());
48580b57cec5SDimitry Andric
48590b57cec5SDimitry Andric if (callee.isBuiltin()) {
48600b57cec5SDimitry Andric return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
48610b57cec5SDimitry Andric E, ReturnValue);
48620b57cec5SDimitry Andric }
48630b57cec5SDimitry Andric
48640b57cec5SDimitry Andric if (callee.isPseudoDestructor()) {
48650b57cec5SDimitry Andric return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
48660b57cec5SDimitry Andric }
48670b57cec5SDimitry Andric
48680b57cec5SDimitry Andric return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
48690b57cec5SDimitry Andric }
48700b57cec5SDimitry Andric
48710b57cec5SDimitry Andric /// Emit a CallExpr without considering whether it might be a subclass.
EmitSimpleCallExpr(const CallExpr * E,ReturnValueSlot ReturnValue)48720b57cec5SDimitry Andric RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
48730b57cec5SDimitry Andric ReturnValueSlot ReturnValue) {
48740b57cec5SDimitry Andric CGCallee Callee = EmitCallee(E->getCallee());
48750b57cec5SDimitry Andric return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
48760b57cec5SDimitry Andric }
48770b57cec5SDimitry Andric
EmitDirectCallee(CodeGenFunction & CGF,GlobalDecl GD)48785ffd83dbSDimitry Andric static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
48795ffd83dbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4880480093f4SDimitry Andric
48810b57cec5SDimitry Andric if (auto builtinID = FD->getBuiltinID()) {
4882480093f4SDimitry Andric // Replaceable builtin provide their own implementation of a builtin. Unless
4883480093f4SDimitry Andric // we are in the builtin implementation itself, don't call the actual
4884480093f4SDimitry Andric // builtin. If we are in the builtin implementation, avoid trivial infinite
4885480093f4SDimitry Andric // recursion.
4886480093f4SDimitry Andric if (!FD->isInlineBuiltinDeclaration() ||
4887480093f4SDimitry Andric CGF.CurFn->getName() == FD->getName())
48880b57cec5SDimitry Andric return CGCallee::forBuiltin(builtinID, FD);
48890b57cec5SDimitry Andric }
48900b57cec5SDimitry Andric
4891*5f7ddb14SDimitry Andric llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
4892*5f7ddb14SDimitry Andric if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
4893*5f7ddb14SDimitry Andric FD->hasAttr<CUDAGlobalAttr>())
4894*5f7ddb14SDimitry Andric CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
4895*5f7ddb14SDimitry Andric cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
4896*5f7ddb14SDimitry Andric return CGCallee::forDirect(CalleePtr, GD);
48970b57cec5SDimitry Andric }
48980b57cec5SDimitry Andric
EmitCallee(const Expr * E)48990b57cec5SDimitry Andric CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
49000b57cec5SDimitry Andric E = E->IgnoreParens();
49010b57cec5SDimitry Andric
49020b57cec5SDimitry Andric // Look through function-to-pointer decay.
49030b57cec5SDimitry Andric if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
49040b57cec5SDimitry Andric if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
49050b57cec5SDimitry Andric ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
49060b57cec5SDimitry Andric return EmitCallee(ICE->getSubExpr());
49070b57cec5SDimitry Andric }
49080b57cec5SDimitry Andric
49090b57cec5SDimitry Andric // Resolve direct calls.
49100b57cec5SDimitry Andric } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
49110b57cec5SDimitry Andric if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
49120b57cec5SDimitry Andric return EmitDirectCallee(*this, FD);
49130b57cec5SDimitry Andric }
49140b57cec5SDimitry Andric } else if (auto ME = dyn_cast<MemberExpr>(E)) {
49150b57cec5SDimitry Andric if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
49160b57cec5SDimitry Andric EmitIgnoredExpr(ME->getBase());
49170b57cec5SDimitry Andric return EmitDirectCallee(*this, FD);
49180b57cec5SDimitry Andric }
49190b57cec5SDimitry Andric
49200b57cec5SDimitry Andric // Look through template substitutions.
49210b57cec5SDimitry Andric } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
49220b57cec5SDimitry Andric return EmitCallee(NTTP->getReplacement());
49230b57cec5SDimitry Andric
49240b57cec5SDimitry Andric // Treat pseudo-destructor calls differently.
49250b57cec5SDimitry Andric } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
49260b57cec5SDimitry Andric return CGCallee::forPseudoDestructor(PDE);
49270b57cec5SDimitry Andric }
49280b57cec5SDimitry Andric
49290b57cec5SDimitry Andric // Otherwise, we have an indirect reference.
49300b57cec5SDimitry Andric llvm::Value *calleePtr;
49310b57cec5SDimitry Andric QualType functionType;
49320b57cec5SDimitry Andric if (auto ptrType = E->getType()->getAs<PointerType>()) {
49330b57cec5SDimitry Andric calleePtr = EmitScalarExpr(E);
49340b57cec5SDimitry Andric functionType = ptrType->getPointeeType();
49350b57cec5SDimitry Andric } else {
49360b57cec5SDimitry Andric functionType = E->getType();
4937480093f4SDimitry Andric calleePtr = EmitLValue(E).getPointer(*this);
49380b57cec5SDimitry Andric }
49390b57cec5SDimitry Andric assert(functionType->isFunctionType());
49400b57cec5SDimitry Andric
49410b57cec5SDimitry Andric GlobalDecl GD;
49420b57cec5SDimitry Andric if (const auto *VD =
49430b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
49440b57cec5SDimitry Andric GD = GlobalDecl(VD);
49450b57cec5SDimitry Andric
49460b57cec5SDimitry Andric CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
49470b57cec5SDimitry Andric CGCallee callee(calleeInfo, calleePtr);
49480b57cec5SDimitry Andric return callee;
49490b57cec5SDimitry Andric }
49500b57cec5SDimitry Andric
EmitBinaryOperatorLValue(const BinaryOperator * E)49510b57cec5SDimitry Andric LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
49520b57cec5SDimitry Andric // Comma expressions just emit their LHS then their RHS as an l-value.
49530b57cec5SDimitry Andric if (E->getOpcode() == BO_Comma) {
49540b57cec5SDimitry Andric EmitIgnoredExpr(E->getLHS());
49550b57cec5SDimitry Andric EnsureInsertPoint();
49560b57cec5SDimitry Andric return EmitLValue(E->getRHS());
49570b57cec5SDimitry Andric }
49580b57cec5SDimitry Andric
49590b57cec5SDimitry Andric if (E->getOpcode() == BO_PtrMemD ||
49600b57cec5SDimitry Andric E->getOpcode() == BO_PtrMemI)
49610b57cec5SDimitry Andric return EmitPointerToDataMemberBinaryExpr(E);
49620b57cec5SDimitry Andric
49630b57cec5SDimitry Andric assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
49640b57cec5SDimitry Andric
49650b57cec5SDimitry Andric // Note that in all of these cases, __block variables need the RHS
49660b57cec5SDimitry Andric // evaluated first just in case the variable gets moved by the RHS.
49670b57cec5SDimitry Andric
49680b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) {
49690b57cec5SDimitry Andric case TEK_Scalar: {
49700b57cec5SDimitry Andric switch (E->getLHS()->getType().getObjCLifetime()) {
49710b57cec5SDimitry Andric case Qualifiers::OCL_Strong:
49720b57cec5SDimitry Andric return EmitARCStoreStrong(E, /*ignored*/ false).first;
49730b57cec5SDimitry Andric
49740b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing:
49750b57cec5SDimitry Andric return EmitARCStoreAutoreleasing(E).first;
49760b57cec5SDimitry Andric
49770b57cec5SDimitry Andric // No reason to do any of these differently.
49780b57cec5SDimitry Andric case Qualifiers::OCL_None:
49790b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone:
49800b57cec5SDimitry Andric case Qualifiers::OCL_Weak:
49810b57cec5SDimitry Andric break;
49820b57cec5SDimitry Andric }
49830b57cec5SDimitry Andric
49840b57cec5SDimitry Andric RValue RV = EmitAnyExpr(E->getRHS());
49850b57cec5SDimitry Andric LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
49860b57cec5SDimitry Andric if (RV.isScalar())
49870b57cec5SDimitry Andric EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
49880b57cec5SDimitry Andric EmitStoreThroughLValue(RV, LV);
4989480093f4SDimitry Andric if (getLangOpts().OpenMP)
4990480093f4SDimitry Andric CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
4991480093f4SDimitry Andric E->getLHS());
49920b57cec5SDimitry Andric return LV;
49930b57cec5SDimitry Andric }
49940b57cec5SDimitry Andric
49950b57cec5SDimitry Andric case TEK_Complex:
49960b57cec5SDimitry Andric return EmitComplexAssignmentLValue(E);
49970b57cec5SDimitry Andric
49980b57cec5SDimitry Andric case TEK_Aggregate:
49990b57cec5SDimitry Andric return EmitAggExprToLValue(E);
50000b57cec5SDimitry Andric }
50010b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
50020b57cec5SDimitry Andric }
50030b57cec5SDimitry Andric
EmitCallExprLValue(const CallExpr * E)50040b57cec5SDimitry Andric LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
50050b57cec5SDimitry Andric RValue RV = EmitCallExpr(E);
50060b57cec5SDimitry Andric
50070b57cec5SDimitry Andric if (!RV.isScalar())
50080b57cec5SDimitry Andric return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
50090b57cec5SDimitry Andric AlignmentSource::Decl);
50100b57cec5SDimitry Andric
50110b57cec5SDimitry Andric assert(E->getCallReturnType(getContext())->isReferenceType() &&
50120b57cec5SDimitry Andric "Can't have a scalar return unless the return type is a "
50130b57cec5SDimitry Andric "reference type!");
50140b57cec5SDimitry Andric
50150b57cec5SDimitry Andric return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
50160b57cec5SDimitry Andric }
50170b57cec5SDimitry Andric
EmitVAArgExprLValue(const VAArgExpr * E)50180b57cec5SDimitry Andric LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
50190b57cec5SDimitry Andric // FIXME: This shouldn't require another copy.
50200b57cec5SDimitry Andric return EmitAggExprToLValue(E);
50210b57cec5SDimitry Andric }
50220b57cec5SDimitry Andric
EmitCXXConstructLValue(const CXXConstructExpr * E)50230b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
50240b57cec5SDimitry Andric assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
50250b57cec5SDimitry Andric && "binding l-value to type which needs a temporary");
50260b57cec5SDimitry Andric AggValueSlot Slot = CreateAggTemp(E->getType());
50270b57cec5SDimitry Andric EmitCXXConstructExpr(E, Slot);
50280b57cec5SDimitry Andric return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
50290b57cec5SDimitry Andric }
50300b57cec5SDimitry Andric
50310b57cec5SDimitry Andric LValue
EmitCXXTypeidLValue(const CXXTypeidExpr * E)50320b57cec5SDimitry Andric CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
50330b57cec5SDimitry Andric return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
50340b57cec5SDimitry Andric }
50350b57cec5SDimitry Andric
EmitCXXUuidofExpr(const CXXUuidofExpr * E)50360b57cec5SDimitry Andric Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
50375ffd83dbSDimitry Andric return Builder.CreateElementBitCast(CGM.GetAddrOfMSGuidDecl(E->getGuidDecl()),
50380b57cec5SDimitry Andric ConvertType(E->getType()));
50390b57cec5SDimitry Andric }
50400b57cec5SDimitry Andric
EmitCXXUuidofLValue(const CXXUuidofExpr * E)50410b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
50420b57cec5SDimitry Andric return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
50430b57cec5SDimitry Andric AlignmentSource::Decl);
50440b57cec5SDimitry Andric }
50450b57cec5SDimitry Andric
50460b57cec5SDimitry Andric LValue
EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr * E)50470b57cec5SDimitry Andric CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
50480b57cec5SDimitry Andric AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
50490b57cec5SDimitry Andric Slot.setExternallyDestructed();
50500b57cec5SDimitry Andric EmitAggExpr(E->getSubExpr(), Slot);
50510b57cec5SDimitry Andric EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
50520b57cec5SDimitry Andric return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
50530b57cec5SDimitry Andric }
50540b57cec5SDimitry Andric
EmitObjCMessageExprLValue(const ObjCMessageExpr * E)50550b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
50560b57cec5SDimitry Andric RValue RV = EmitObjCMessageExpr(E);
50570b57cec5SDimitry Andric
50580b57cec5SDimitry Andric if (!RV.isScalar())
50590b57cec5SDimitry Andric return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
50600b57cec5SDimitry Andric AlignmentSource::Decl);
50610b57cec5SDimitry Andric
50620b57cec5SDimitry Andric assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
50630b57cec5SDimitry Andric "Can't have a scalar return unless the return type is a "
50640b57cec5SDimitry Andric "reference type!");
50650b57cec5SDimitry Andric
50660b57cec5SDimitry Andric return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
50670b57cec5SDimitry Andric }
50680b57cec5SDimitry Andric
EmitObjCSelectorLValue(const ObjCSelectorExpr * E)50690b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
50700b57cec5SDimitry Andric Address V =
50710b57cec5SDimitry Andric CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
50720b57cec5SDimitry Andric return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
50730b57cec5SDimitry Andric }
50740b57cec5SDimitry Andric
EmitIvarOffset(const ObjCInterfaceDecl * Interface,const ObjCIvarDecl * Ivar)50750b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
50760b57cec5SDimitry Andric const ObjCIvarDecl *Ivar) {
50770b57cec5SDimitry Andric return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
50780b57cec5SDimitry Andric }
50790b57cec5SDimitry Andric
EmitLValueForIvar(QualType ObjectTy,llvm::Value * BaseValue,const ObjCIvarDecl * Ivar,unsigned CVRQualifiers)50800b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
50810b57cec5SDimitry Andric llvm::Value *BaseValue,
50820b57cec5SDimitry Andric const ObjCIvarDecl *Ivar,
50830b57cec5SDimitry Andric unsigned CVRQualifiers) {
50840b57cec5SDimitry Andric return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
50850b57cec5SDimitry Andric Ivar, CVRQualifiers);
50860b57cec5SDimitry Andric }
50870b57cec5SDimitry Andric
EmitObjCIvarRefLValue(const ObjCIvarRefExpr * E)50880b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
50890b57cec5SDimitry Andric // FIXME: A lot of the code below could be shared with EmitMemberExpr.
50900b57cec5SDimitry Andric llvm::Value *BaseValue = nullptr;
50910b57cec5SDimitry Andric const Expr *BaseExpr = E->getBase();
50920b57cec5SDimitry Andric Qualifiers BaseQuals;
50930b57cec5SDimitry Andric QualType ObjectTy;
50940b57cec5SDimitry Andric if (E->isArrow()) {
50950b57cec5SDimitry Andric BaseValue = EmitScalarExpr(BaseExpr);
50960b57cec5SDimitry Andric ObjectTy = BaseExpr->getType()->getPointeeType();
50970b57cec5SDimitry Andric BaseQuals = ObjectTy.getQualifiers();
50980b57cec5SDimitry Andric } else {
50990b57cec5SDimitry Andric LValue BaseLV = EmitLValue(BaseExpr);
5100480093f4SDimitry Andric BaseValue = BaseLV.getPointer(*this);
51010b57cec5SDimitry Andric ObjectTy = BaseExpr->getType();
51020b57cec5SDimitry Andric BaseQuals = ObjectTy.getQualifiers();
51030b57cec5SDimitry Andric }
51040b57cec5SDimitry Andric
51050b57cec5SDimitry Andric LValue LV =
51060b57cec5SDimitry Andric EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
51070b57cec5SDimitry Andric BaseQuals.getCVRQualifiers());
51080b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV);
51090b57cec5SDimitry Andric return LV;
51100b57cec5SDimitry Andric }
51110b57cec5SDimitry Andric
EmitStmtExprLValue(const StmtExpr * E)51120b57cec5SDimitry Andric LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
51130b57cec5SDimitry Andric // Can only get l-value for message expression returning aggregate type
51140b57cec5SDimitry Andric RValue RV = EmitAnyExprToTemp(E);
51150b57cec5SDimitry Andric return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
51160b57cec5SDimitry Andric AlignmentSource::Decl);
51170b57cec5SDimitry Andric }
51180b57cec5SDimitry Andric
EmitCall(QualType CalleeType,const CGCallee & OrigCallee,const CallExpr * E,ReturnValueSlot ReturnValue,llvm::Value * Chain)51190b57cec5SDimitry Andric RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
51200b57cec5SDimitry Andric const CallExpr *E, ReturnValueSlot ReturnValue,
51210b57cec5SDimitry Andric llvm::Value *Chain) {
51220b57cec5SDimitry Andric // Get the actual function type. The callee type will always be a pointer to
51230b57cec5SDimitry Andric // function type or a block pointer type.
51240b57cec5SDimitry Andric assert(CalleeType->isFunctionPointerType() &&
51250b57cec5SDimitry Andric "Call must have function pointer type!");
51260b57cec5SDimitry Andric
51270b57cec5SDimitry Andric const Decl *TargetDecl =
51280b57cec5SDimitry Andric OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
51290b57cec5SDimitry Andric
51300b57cec5SDimitry Andric CalleeType = getContext().getCanonicalType(CalleeType);
51310b57cec5SDimitry Andric
51320b57cec5SDimitry Andric auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
51330b57cec5SDimitry Andric
51340b57cec5SDimitry Andric CGCallee Callee = OrigCallee;
51350b57cec5SDimitry Andric
51360b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
51370b57cec5SDimitry Andric (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
51380b57cec5SDimitry Andric if (llvm::Constant *PrefixSig =
51390b57cec5SDimitry Andric CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
51400b57cec5SDimitry Andric SanitizerScope SanScope(this);
51410b57cec5SDimitry Andric // Remove any (C++17) exception specifications, to allow calling e.g. a
51420b57cec5SDimitry Andric // noexcept function through a non-noexcept pointer.
51430b57cec5SDimitry Andric auto ProtoTy =
51440b57cec5SDimitry Andric getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
51450b57cec5SDimitry Andric llvm::Constant *FTRTTIConst =
51460b57cec5SDimitry Andric CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
5147*5f7ddb14SDimitry Andric llvm::Type *PrefixSigType = PrefixSig->getType();
51480b57cec5SDimitry Andric llvm::StructType *PrefixStructTy = llvm::StructType::get(
5149*5f7ddb14SDimitry Andric CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
51500b57cec5SDimitry Andric
51510b57cec5SDimitry Andric llvm::Value *CalleePtr = Callee.getFunctionPointer();
51520b57cec5SDimitry Andric
51530b57cec5SDimitry Andric llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
51540b57cec5SDimitry Andric CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
51550b57cec5SDimitry Andric llvm::Value *CalleeSigPtr =
51560b57cec5SDimitry Andric Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
51570b57cec5SDimitry Andric llvm::Value *CalleeSig =
5158*5f7ddb14SDimitry Andric Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
51590b57cec5SDimitry Andric llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
51600b57cec5SDimitry Andric
51610b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cont");
51620b57cec5SDimitry Andric llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
51630b57cec5SDimitry Andric Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
51640b57cec5SDimitry Andric
51650b57cec5SDimitry Andric EmitBlock(TypeCheck);
51660b57cec5SDimitry Andric llvm::Value *CalleeRTTIPtr =
51670b57cec5SDimitry Andric Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
51680b57cec5SDimitry Andric llvm::Value *CalleeRTTIEncoded =
5169*5f7ddb14SDimitry Andric Builder.CreateAlignedLoad(Int32Ty, CalleeRTTIPtr, getPointerAlign());
51700b57cec5SDimitry Andric llvm::Value *CalleeRTTI =
51710b57cec5SDimitry Andric DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
51720b57cec5SDimitry Andric llvm::Value *CalleeRTTIMatch =
51730b57cec5SDimitry Andric Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
51740b57cec5SDimitry Andric llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
51750b57cec5SDimitry Andric EmitCheckTypeDescriptor(CalleeType)};
51760b57cec5SDimitry Andric EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
51770b57cec5SDimitry Andric SanitizerHandler::FunctionTypeMismatch, StaticData,
51780b57cec5SDimitry Andric {CalleePtr, CalleeRTTI, FTRTTIConst});
51790b57cec5SDimitry Andric
51800b57cec5SDimitry Andric Builder.CreateBr(Cont);
51810b57cec5SDimitry Andric EmitBlock(Cont);
51820b57cec5SDimitry Andric }
51830b57cec5SDimitry Andric }
51840b57cec5SDimitry Andric
51850b57cec5SDimitry Andric const auto *FnType = cast<FunctionType>(PointeeType);
51860b57cec5SDimitry Andric
51870b57cec5SDimitry Andric // If we are checking indirect calls and this call is indirect, check that the
51880b57cec5SDimitry Andric // function pointer is a member of the bit set for the function type.
51890b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFIICall) &&
51900b57cec5SDimitry Andric (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
51910b57cec5SDimitry Andric SanitizerScope SanScope(this);
51920b57cec5SDimitry Andric EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
51930b57cec5SDimitry Andric
51940b57cec5SDimitry Andric llvm::Metadata *MD;
51950b57cec5SDimitry Andric if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
51960b57cec5SDimitry Andric MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
51970b57cec5SDimitry Andric else
51980b57cec5SDimitry Andric MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
51990b57cec5SDimitry Andric
52000b57cec5SDimitry Andric llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
52010b57cec5SDimitry Andric
52020b57cec5SDimitry Andric llvm::Value *CalleePtr = Callee.getFunctionPointer();
52030b57cec5SDimitry Andric llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
52040b57cec5SDimitry Andric llvm::Value *TypeTest = Builder.CreateCall(
52050b57cec5SDimitry Andric CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
52060b57cec5SDimitry Andric
52070b57cec5SDimitry Andric auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
52080b57cec5SDimitry Andric llvm::Constant *StaticData[] = {
52090b57cec5SDimitry Andric llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
52100b57cec5SDimitry Andric EmitCheckSourceLocation(E->getBeginLoc()),
52110b57cec5SDimitry Andric EmitCheckTypeDescriptor(QualType(FnType, 0)),
52120b57cec5SDimitry Andric };
52130b57cec5SDimitry Andric if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
52140b57cec5SDimitry Andric EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
52150b57cec5SDimitry Andric CastedCallee, StaticData);
52160b57cec5SDimitry Andric } else {
52170b57cec5SDimitry Andric EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
52180b57cec5SDimitry Andric SanitizerHandler::CFICheckFail, StaticData,
52190b57cec5SDimitry Andric {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
52200b57cec5SDimitry Andric }
52210b57cec5SDimitry Andric }
52220b57cec5SDimitry Andric
52230b57cec5SDimitry Andric CallArgList Args;
52240b57cec5SDimitry Andric if (Chain)
52250b57cec5SDimitry Andric Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
52260b57cec5SDimitry Andric CGM.getContext().VoidPtrTy);
52270b57cec5SDimitry Andric
52280b57cec5SDimitry Andric // C++17 requires that we evaluate arguments to a call using assignment syntax
52290b57cec5SDimitry Andric // right-to-left, and that we evaluate arguments to certain other operators
52300b57cec5SDimitry Andric // left-to-right. Note that we allow this to override the order dictated by
52310b57cec5SDimitry Andric // the calling convention on the MS ABI, which means that parameter
52320b57cec5SDimitry Andric // destruction order is not necessarily reverse construction order.
52330b57cec5SDimitry Andric // FIXME: Revisit this based on C++ committee response to unimplementability.
52340b57cec5SDimitry Andric EvaluationOrder Order = EvaluationOrder::Default;
52350b57cec5SDimitry Andric if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
52360b57cec5SDimitry Andric if (OCE->isAssignmentOp())
52370b57cec5SDimitry Andric Order = EvaluationOrder::ForceRightToLeft;
52380b57cec5SDimitry Andric else {
52390b57cec5SDimitry Andric switch (OCE->getOperator()) {
52400b57cec5SDimitry Andric case OO_LessLess:
52410b57cec5SDimitry Andric case OO_GreaterGreater:
52420b57cec5SDimitry Andric case OO_AmpAmp:
52430b57cec5SDimitry Andric case OO_PipePipe:
52440b57cec5SDimitry Andric case OO_Comma:
52450b57cec5SDimitry Andric case OO_ArrowStar:
52460b57cec5SDimitry Andric Order = EvaluationOrder::ForceLeftToRight;
52470b57cec5SDimitry Andric break;
52480b57cec5SDimitry Andric default:
52490b57cec5SDimitry Andric break;
52500b57cec5SDimitry Andric }
52510b57cec5SDimitry Andric }
52520b57cec5SDimitry Andric }
52530b57cec5SDimitry Andric
52540b57cec5SDimitry Andric EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
52550b57cec5SDimitry Andric E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
52560b57cec5SDimitry Andric
52570b57cec5SDimitry Andric const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
52580b57cec5SDimitry Andric Args, FnType, /*ChainCall=*/Chain);
52590b57cec5SDimitry Andric
52600b57cec5SDimitry Andric // C99 6.5.2.2p6:
52610b57cec5SDimitry Andric // If the expression that denotes the called function has a type
52620b57cec5SDimitry Andric // that does not include a prototype, [the default argument
52630b57cec5SDimitry Andric // promotions are performed]. If the number of arguments does not
52640b57cec5SDimitry Andric // equal the number of parameters, the behavior is undefined. If
52650b57cec5SDimitry Andric // the function is defined with a type that includes a prototype,
52660b57cec5SDimitry Andric // and either the prototype ends with an ellipsis (, ...) or the
52670b57cec5SDimitry Andric // types of the arguments after promotion are not compatible with
52680b57cec5SDimitry Andric // the types of the parameters, the behavior is undefined. If the
52690b57cec5SDimitry Andric // function is defined with a type that does not include a
52700b57cec5SDimitry Andric // prototype, and the types of the arguments after promotion are
52710b57cec5SDimitry Andric // not compatible with those of the parameters after promotion,
52720b57cec5SDimitry Andric // the behavior is undefined [except in some trivial cases].
52730b57cec5SDimitry Andric // That is, in the general case, we should assume that a call
52740b57cec5SDimitry Andric // through an unprototyped function type works like a *non-variadic*
52750b57cec5SDimitry Andric // call. The way we make this work is to cast to the exact type
52760b57cec5SDimitry Andric // of the promoted arguments.
52770b57cec5SDimitry Andric //
52780b57cec5SDimitry Andric // Chain calls use this same code path to add the invisible chain parameter
52790b57cec5SDimitry Andric // to the function type.
52800b57cec5SDimitry Andric if (isa<FunctionNoProtoType>(FnType) || Chain) {
52810b57cec5SDimitry Andric llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
52825ffd83dbSDimitry Andric int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
52835ffd83dbSDimitry Andric CalleeTy = CalleeTy->getPointerTo(AS);
52840b57cec5SDimitry Andric
52850b57cec5SDimitry Andric llvm::Value *CalleePtr = Callee.getFunctionPointer();
52860b57cec5SDimitry Andric CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
52870b57cec5SDimitry Andric Callee.setFunctionPointer(CalleePtr);
52880b57cec5SDimitry Andric }
52890b57cec5SDimitry Andric
5290*5f7ddb14SDimitry Andric // HIP function pointer contains kernel handle when it is used in triple
5291*5f7ddb14SDimitry Andric // chevron. The kernel stub needs to be loaded from kernel handle and used
5292*5f7ddb14SDimitry Andric // as callee.
5293*5f7ddb14SDimitry Andric if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
5294*5f7ddb14SDimitry Andric isa<CUDAKernelCallExpr>(E) &&
5295*5f7ddb14SDimitry Andric (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5296*5f7ddb14SDimitry Andric llvm::Value *Handle = Callee.getFunctionPointer();
5297*5f7ddb14SDimitry Andric auto *Cast =
5298*5f7ddb14SDimitry Andric Builder.CreateBitCast(Handle, Handle->getType()->getPointerTo());
5299*5f7ddb14SDimitry Andric auto *Stub = Builder.CreateLoad(Address(Cast, CGM.getPointerAlign()));
5300*5f7ddb14SDimitry Andric Callee.setFunctionPointer(Stub);
5301*5f7ddb14SDimitry Andric }
53020b57cec5SDimitry Andric llvm::CallBase *CallOrInvoke = nullptr;
53030b57cec5SDimitry Andric RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
5304*5f7ddb14SDimitry Andric E == MustTailCall, E->getExprLoc());
53050b57cec5SDimitry Andric
53060b57cec5SDimitry Andric // Generate function declaration DISuprogram in order to be used
53070b57cec5SDimitry Andric // in debug info about call sites.
53080b57cec5SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) {
53090b57cec5SDimitry Andric if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl))
53100b57cec5SDimitry Andric DI->EmitFuncDeclForCallSite(CallOrInvoke, QualType(FnType, 0),
53110b57cec5SDimitry Andric CalleeDecl);
53120b57cec5SDimitry Andric }
53130b57cec5SDimitry Andric
53140b57cec5SDimitry Andric return Call;
53150b57cec5SDimitry Andric }
53160b57cec5SDimitry Andric
53170b57cec5SDimitry Andric LValue CodeGenFunction::
EmitPointerToDataMemberBinaryExpr(const BinaryOperator * E)53180b57cec5SDimitry Andric EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
53190b57cec5SDimitry Andric Address BaseAddr = Address::invalid();
53200b57cec5SDimitry Andric if (E->getOpcode() == BO_PtrMemI) {
53210b57cec5SDimitry Andric BaseAddr = EmitPointerWithAlignment(E->getLHS());
53220b57cec5SDimitry Andric } else {
5323480093f4SDimitry Andric BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
53240b57cec5SDimitry Andric }
53250b57cec5SDimitry Andric
53260b57cec5SDimitry Andric llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
5327480093f4SDimitry Andric const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
53280b57cec5SDimitry Andric
53290b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
53300b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
53310b57cec5SDimitry Andric Address MemberAddr =
53320b57cec5SDimitry Andric EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
53330b57cec5SDimitry Andric &TBAAInfo);
53340b57cec5SDimitry Andric
53350b57cec5SDimitry Andric return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
53360b57cec5SDimitry Andric }
53370b57cec5SDimitry Andric
53380b57cec5SDimitry Andric /// Given the address of a temporary variable, produce an r-value of
53390b57cec5SDimitry Andric /// its type.
convertTempToRValue(Address addr,QualType type,SourceLocation loc)53400b57cec5SDimitry Andric RValue CodeGenFunction::convertTempToRValue(Address addr,
53410b57cec5SDimitry Andric QualType type,
53420b57cec5SDimitry Andric SourceLocation loc) {
53430b57cec5SDimitry Andric LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
53440b57cec5SDimitry Andric switch (getEvaluationKind(type)) {
53450b57cec5SDimitry Andric case TEK_Complex:
53460b57cec5SDimitry Andric return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
53470b57cec5SDimitry Andric case TEK_Aggregate:
5348480093f4SDimitry Andric return lvalue.asAggregateRValue(*this);
53490b57cec5SDimitry Andric case TEK_Scalar:
53500b57cec5SDimitry Andric return RValue::get(EmitLoadOfScalar(lvalue, loc));
53510b57cec5SDimitry Andric }
53520b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
53530b57cec5SDimitry Andric }
53540b57cec5SDimitry Andric
SetFPAccuracy(llvm::Value * Val,float Accuracy)53550b57cec5SDimitry Andric void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
53560b57cec5SDimitry Andric assert(Val->getType()->isFPOrFPVectorTy());
53570b57cec5SDimitry Andric if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
53580b57cec5SDimitry Andric return;
53590b57cec5SDimitry Andric
53600b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext());
53610b57cec5SDimitry Andric llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
53620b57cec5SDimitry Andric
53630b57cec5SDimitry Andric cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
53640b57cec5SDimitry Andric }
53650b57cec5SDimitry Andric
53660b57cec5SDimitry Andric namespace {
53670b57cec5SDimitry Andric struct LValueOrRValue {
53680b57cec5SDimitry Andric LValue LV;
53690b57cec5SDimitry Andric RValue RV;
53700b57cec5SDimitry Andric };
53710b57cec5SDimitry Andric }
53720b57cec5SDimitry Andric
emitPseudoObjectExpr(CodeGenFunction & CGF,const PseudoObjectExpr * E,bool forLValue,AggValueSlot slot)53730b57cec5SDimitry Andric static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
53740b57cec5SDimitry Andric const PseudoObjectExpr *E,
53750b57cec5SDimitry Andric bool forLValue,
53760b57cec5SDimitry Andric AggValueSlot slot) {
53770b57cec5SDimitry Andric SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
53780b57cec5SDimitry Andric
53790b57cec5SDimitry Andric // Find the result expression, if any.
53800b57cec5SDimitry Andric const Expr *resultExpr = E->getResultExpr();
53810b57cec5SDimitry Andric LValueOrRValue result;
53820b57cec5SDimitry Andric
53830b57cec5SDimitry Andric for (PseudoObjectExpr::const_semantics_iterator
53840b57cec5SDimitry Andric i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
53850b57cec5SDimitry Andric const Expr *semantic = *i;
53860b57cec5SDimitry Andric
53870b57cec5SDimitry Andric // If this semantic expression is an opaque value, bind it
53880b57cec5SDimitry Andric // to the result of its source expression.
53890b57cec5SDimitry Andric if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
53900b57cec5SDimitry Andric // Skip unique OVEs.
53910b57cec5SDimitry Andric if (ov->isUnique()) {
53920b57cec5SDimitry Andric assert(ov != resultExpr &&
53930b57cec5SDimitry Andric "A unique OVE cannot be used as the result expression");
53940b57cec5SDimitry Andric continue;
53950b57cec5SDimitry Andric }
53960b57cec5SDimitry Andric
53970b57cec5SDimitry Andric // If this is the result expression, we may need to evaluate
53980b57cec5SDimitry Andric // directly into the slot.
53990b57cec5SDimitry Andric typedef CodeGenFunction::OpaqueValueMappingData OVMA;
54000b57cec5SDimitry Andric OVMA opaqueData;
5401*5f7ddb14SDimitry Andric if (ov == resultExpr && ov->isPRValue() && !forLValue &&
54020b57cec5SDimitry Andric CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
54030b57cec5SDimitry Andric CGF.EmitAggExpr(ov->getSourceExpr(), slot);
54040b57cec5SDimitry Andric LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
54050b57cec5SDimitry Andric AlignmentSource::Decl);
54060b57cec5SDimitry Andric opaqueData = OVMA::bind(CGF, ov, LV);
54070b57cec5SDimitry Andric result.RV = slot.asRValue();
54080b57cec5SDimitry Andric
54090b57cec5SDimitry Andric // Otherwise, emit as normal.
54100b57cec5SDimitry Andric } else {
54110b57cec5SDimitry Andric opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
54120b57cec5SDimitry Andric
54130b57cec5SDimitry Andric // If this is the result, also evaluate the result now.
54140b57cec5SDimitry Andric if (ov == resultExpr) {
54150b57cec5SDimitry Andric if (forLValue)
54160b57cec5SDimitry Andric result.LV = CGF.EmitLValue(ov);
54170b57cec5SDimitry Andric else
54180b57cec5SDimitry Andric result.RV = CGF.EmitAnyExpr(ov, slot);
54190b57cec5SDimitry Andric }
54200b57cec5SDimitry Andric }
54210b57cec5SDimitry Andric
54220b57cec5SDimitry Andric opaques.push_back(opaqueData);
54230b57cec5SDimitry Andric
54240b57cec5SDimitry Andric // Otherwise, if the expression is the result, evaluate it
54250b57cec5SDimitry Andric // and remember the result.
54260b57cec5SDimitry Andric } else if (semantic == resultExpr) {
54270b57cec5SDimitry Andric if (forLValue)
54280b57cec5SDimitry Andric result.LV = CGF.EmitLValue(semantic);
54290b57cec5SDimitry Andric else
54300b57cec5SDimitry Andric result.RV = CGF.EmitAnyExpr(semantic, slot);
54310b57cec5SDimitry Andric
54320b57cec5SDimitry Andric // Otherwise, evaluate the expression in an ignored context.
54330b57cec5SDimitry Andric } else {
54340b57cec5SDimitry Andric CGF.EmitIgnoredExpr(semantic);
54350b57cec5SDimitry Andric }
54360b57cec5SDimitry Andric }
54370b57cec5SDimitry Andric
54380b57cec5SDimitry Andric // Unbind all the opaques now.
54390b57cec5SDimitry Andric for (unsigned i = 0, e = opaques.size(); i != e; ++i)
54400b57cec5SDimitry Andric opaques[i].unbind(CGF);
54410b57cec5SDimitry Andric
54420b57cec5SDimitry Andric return result;
54430b57cec5SDimitry Andric }
54440b57cec5SDimitry Andric
EmitPseudoObjectRValue(const PseudoObjectExpr * E,AggValueSlot slot)54450b57cec5SDimitry Andric RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
54460b57cec5SDimitry Andric AggValueSlot slot) {
54470b57cec5SDimitry Andric return emitPseudoObjectExpr(*this, E, false, slot).RV;
54480b57cec5SDimitry Andric }
54490b57cec5SDimitry Andric
EmitPseudoObjectLValue(const PseudoObjectExpr * E)54500b57cec5SDimitry Andric LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
54510b57cec5SDimitry Andric return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
54520b57cec5SDimitry Andric }
5453