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 
13fe6060f1SDimitry 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"
36*fe013be4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
370b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
380b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
39349cc55cSDimitry Andric #include "llvm/IR/MatrixBuilder.h"
40*fe013be4SDimitry Andric #include "llvm/Passes/OptimizationLevel.h"
410b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
420b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
430b57cec5SDimitry Andric #include "llvm/Support/Path.h"
44fe6060f1SDimitry Andric #include "llvm/Support/SaveAndRestore.h"
45*fe013be4SDimitry Andric #include "llvm/Support/xxhash.h"
460b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SanitizerStats.h"
470b57cec5SDimitry Andric 
48bdd1243dSDimitry Andric #include <optional>
490b57cec5SDimitry Andric #include <string>
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric using namespace clang;
520b57cec5SDimitry Andric using namespace CodeGen;
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
550b57cec5SDimitry Andric //                        Miscellaneous Helper Methods
560b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry
590b57cec5SDimitry Andric /// block.
600b57cec5SDimitry Andric Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
610b57cec5SDimitry Andric                                                      CharUnits Align,
620b57cec5SDimitry Andric                                                      const Twine &Name,
630b57cec5SDimitry Andric                                                      llvm::Value *ArraySize) {
640b57cec5SDimitry Andric   auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
65a7dea167SDimitry Andric   Alloca->setAlignment(Align.getAsAlign());
66*fe013be4SDimitry Andric   return Address(Alloca, Ty, Align, KnownNonNull);
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry
700b57cec5SDimitry Andric /// block. The alloca is casted to default address space if necessary.
710b57cec5SDimitry Andric Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
720b57cec5SDimitry Andric                                           const Twine &Name,
730b57cec5SDimitry Andric                                           llvm::Value *ArraySize,
740b57cec5SDimitry Andric                                           Address *AllocaAddr) {
750b57cec5SDimitry Andric   auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
760b57cec5SDimitry Andric   if (AllocaAddr)
770b57cec5SDimitry Andric     *AllocaAddr = Alloca;
780b57cec5SDimitry Andric   llvm::Value *V = Alloca.getPointer();
790b57cec5SDimitry Andric   // Alloca always returns a pointer in alloca address space, which may
800b57cec5SDimitry Andric   // be different from the type defined by the language. For example,
810b57cec5SDimitry Andric   // in C++ the auto variables are in the default address space. Therefore
820b57cec5SDimitry Andric   // cast alloca to the default address space when necessary.
830b57cec5SDimitry Andric   if (getASTAllocaAddressSpace() != LangAS::Default) {
840b57cec5SDimitry Andric     auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
850b57cec5SDimitry Andric     llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
860b57cec5SDimitry Andric     // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
870b57cec5SDimitry Andric     // otherwise alloca is inserted at the current insertion point of the
880b57cec5SDimitry Andric     // builder.
890b57cec5SDimitry Andric     if (!ArraySize)
90349cc55cSDimitry Andric       Builder.SetInsertPoint(getPostAllocaInsertPoint());
910b57cec5SDimitry Andric     V = getTargetHooks().performAddrSpaceCast(
920b57cec5SDimitry Andric         *this, V, getASTAllocaAddressSpace(), LangAS::Default,
930b57cec5SDimitry Andric         Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
940b57cec5SDimitry Andric   }
950b57cec5SDimitry Andric 
96*fe013be4SDimitry Andric   return Address(V, Ty, Align, KnownNonNull);
970b57cec5SDimitry Andric }
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric /// CreateTempAlloca - This creates an alloca and inserts it into the entry
1000b57cec5SDimitry Andric /// block if \p ArraySize is nullptr, otherwise inserts it at the current
1010b57cec5SDimitry Andric /// insertion point of the builder.
1020b57cec5SDimitry Andric llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
1030b57cec5SDimitry Andric                                                     const Twine &Name,
1040b57cec5SDimitry Andric                                                     llvm::Value *ArraySize) {
1050b57cec5SDimitry Andric   if (ArraySize)
1060b57cec5SDimitry Andric     return Builder.CreateAlloca(Ty, ArraySize, Name);
1070b57cec5SDimitry Andric   return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
1080b57cec5SDimitry Andric                               ArraySize, Name, AllocaInsertPt);
1090b57cec5SDimitry Andric }
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric /// CreateDefaultAlignTempAlloca - This creates an alloca with the
1120b57cec5SDimitry Andric /// default alignment of the corresponding LLVM type, which is *not*
1130b57cec5SDimitry Andric /// guaranteed to be related in any way to the expected alignment of
1140b57cec5SDimitry Andric /// an AST type that might have been lowered to Ty.
1150b57cec5SDimitry Andric Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1160b57cec5SDimitry Andric                                                       const Twine &Name) {
1170b57cec5SDimitry Andric   CharUnits Align =
118bdd1243dSDimitry Andric       CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(Ty));
1190b57cec5SDimitry Andric   return CreateTempAlloca(Ty, Align, Name);
1200b57cec5SDimitry Andric }
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
1230b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(Ty);
1240b57cec5SDimitry Andric   return CreateTempAlloca(ConvertType(Ty), Align, Name);
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
1280b57cec5SDimitry Andric                                        Address *Alloca) {
1290b57cec5SDimitry Andric   // FIXME: Should we prefer the preferred type alignment here?
1300b57cec5SDimitry Andric   return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
1310b57cec5SDimitry Andric }
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
1340b57cec5SDimitry Andric                                        const Twine &Name, Address *Alloca) {
1355ffd83dbSDimitry Andric   Address Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
1360b57cec5SDimitry Andric                                     /*ArraySize=*/nullptr, Alloca);
1375ffd83dbSDimitry Andric 
1385ffd83dbSDimitry Andric   if (Ty->isConstantMatrixType()) {
1390eae32dcSDimitry Andric     auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
1405ffd83dbSDimitry Andric     auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
1415ffd83dbSDimitry Andric                                                 ArrayTy->getNumElements());
1425ffd83dbSDimitry Andric 
1435ffd83dbSDimitry Andric     Result = Address(
1445ffd83dbSDimitry Andric         Builder.CreateBitCast(Result.getPointer(), VectorTy->getPointerTo()),
145*fe013be4SDimitry Andric         VectorTy, Result.getAlignment(), KnownNonNull);
1465ffd83dbSDimitry Andric   }
1475ffd83dbSDimitry Andric   return Result;
1480b57cec5SDimitry Andric }
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
1510b57cec5SDimitry Andric                                                   const Twine &Name) {
1520b57cec5SDimitry Andric   return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
1530b57cec5SDimitry Andric }
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
1560b57cec5SDimitry Andric                                                   const Twine &Name) {
1570b57cec5SDimitry Andric   return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
1580b57cec5SDimitry Andric                                   Name);
1590b57cec5SDimitry Andric }
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1620b57cec5SDimitry Andric /// expression and compare the result against zero, returning an Int1Ty value.
1630b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
1640b57cec5SDimitry Andric   PGO.setCurrentStmt(E);
1650b57cec5SDimitry Andric   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
1660b57cec5SDimitry Andric     llvm::Value *MemPtr = EmitScalarExpr(E);
1670b57cec5SDimitry Andric     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
1680b57cec5SDimitry Andric   }
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   QualType BoolTy = getContext().BoolTy;
1710b57cec5SDimitry Andric   SourceLocation Loc = E->getExprLoc();
172e8d8bef9SDimitry Andric   CGFPOptionsRAII FPOptsRAII(*this, E);
1730b57cec5SDimitry Andric   if (!E->getType()->isAnyComplexType())
1740b57cec5SDimitry Andric     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
1770b57cec5SDimitry Andric                                        Loc);
1780b57cec5SDimitry Andric }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric /// EmitIgnoredExpr - Emit code to compute the specified expression,
1810b57cec5SDimitry Andric /// ignoring the result.
1820b57cec5SDimitry Andric void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
183fe6060f1SDimitry Andric   if (E->isPRValue())
1840b57cec5SDimitry Andric     return (void)EmitAnyExpr(E, AggValueSlot::ignored(), true);
1850b57cec5SDimitry Andric 
18681ad6265SDimitry Andric   // if this is a bitfield-resulting conditional operator, we can special case
18781ad6265SDimitry Andric   // emit this. The normal 'EmitLValue' version of this is particularly
18881ad6265SDimitry Andric   // difficult to codegen for, since creating a single "LValue" for two
18981ad6265SDimitry Andric   // different sized arguments here is not particularly doable.
19081ad6265SDimitry Andric   if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
19181ad6265SDimitry Andric           E->IgnoreParenNoopCasts(getContext()))) {
19281ad6265SDimitry Andric     if (CondOp->getObjectKind() == OK_BitField)
19381ad6265SDimitry Andric       return EmitIgnoredConditionalOperator(CondOp);
19481ad6265SDimitry Andric   }
19581ad6265SDimitry Andric 
1960b57cec5SDimitry Andric   // Just emit it as an l-value and drop the result.
1970b57cec5SDimitry Andric   EmitLValue(E);
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric /// EmitAnyExpr - Emit code to compute the specified expression which
2010b57cec5SDimitry Andric /// can have any type.  The result is returned as an RValue struct.
2020b57cec5SDimitry Andric /// If this is an aggregate expression, AggSlot indicates where the
2030b57cec5SDimitry Andric /// result should be returned.
2040b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
2050b57cec5SDimitry Andric                                     AggValueSlot aggSlot,
2060b57cec5SDimitry Andric                                     bool ignoreResult) {
2070b57cec5SDimitry Andric   switch (getEvaluationKind(E->getType())) {
2080b57cec5SDimitry Andric   case TEK_Scalar:
2090b57cec5SDimitry Andric     return RValue::get(EmitScalarExpr(E, ignoreResult));
2100b57cec5SDimitry Andric   case TEK_Complex:
2110b57cec5SDimitry Andric     return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
2120b57cec5SDimitry Andric   case TEK_Aggregate:
2130b57cec5SDimitry Andric     if (!ignoreResult && aggSlot.isIgnored())
2140b57cec5SDimitry Andric       aggSlot = CreateAggTemp(E->getType(), "agg-temp");
2150b57cec5SDimitry Andric     EmitAggExpr(E, aggSlot);
2160b57cec5SDimitry Andric     return aggSlot.asRValue();
2170b57cec5SDimitry Andric   }
2180b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
2190b57cec5SDimitry Andric }
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
2220b57cec5SDimitry Andric /// always be accessible even if no aggregate location is provided.
2230b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
2240b57cec5SDimitry Andric   AggValueSlot AggSlot = AggValueSlot::ignored();
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   if (hasAggregateEvaluationKind(E->getType()))
2270b57cec5SDimitry Andric     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
2280b57cec5SDimitry Andric   return EmitAnyExpr(E, AggSlot);
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric /// EmitAnyExprToMem - Evaluate an expression into a given memory
2320b57cec5SDimitry Andric /// location.
2330b57cec5SDimitry Andric void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
2340b57cec5SDimitry Andric                                        Address Location,
2350b57cec5SDimitry Andric                                        Qualifiers Quals,
2360b57cec5SDimitry Andric                                        bool IsInit) {
2370b57cec5SDimitry Andric   // FIXME: This function should take an LValue as an argument.
2380b57cec5SDimitry Andric   switch (getEvaluationKind(E->getType())) {
2390b57cec5SDimitry Andric   case TEK_Complex:
2400b57cec5SDimitry Andric     EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
2410b57cec5SDimitry Andric                               /*isInit*/ false);
2420b57cec5SDimitry Andric     return;
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   case TEK_Aggregate: {
2450b57cec5SDimitry Andric     EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
2460b57cec5SDimitry Andric                                          AggValueSlot::IsDestructed_t(IsInit),
2470b57cec5SDimitry Andric                                          AggValueSlot::DoesNotNeedGCBarriers,
2480b57cec5SDimitry Andric                                          AggValueSlot::IsAliased_t(!IsInit),
2490b57cec5SDimitry Andric                                          AggValueSlot::MayOverlap));
2500b57cec5SDimitry Andric     return;
2510b57cec5SDimitry Andric   }
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric   case TEK_Scalar: {
2540b57cec5SDimitry Andric     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
2550b57cec5SDimitry Andric     LValue LV = MakeAddrLValue(Location, E->getType());
2560b57cec5SDimitry Andric     EmitStoreThroughLValue(RV, LV);
2570b57cec5SDimitry Andric     return;
2580b57cec5SDimitry Andric   }
2590b57cec5SDimitry Andric   }
2600b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
2610b57cec5SDimitry Andric }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric static void
2640b57cec5SDimitry Andric pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
2650b57cec5SDimitry Andric                      const Expr *E, Address ReferenceTemporary) {
2660b57cec5SDimitry Andric   // Objective-C++ ARC:
2670b57cec5SDimitry Andric   //   If we are binding a reference to a temporary that has ownership, we
2680b57cec5SDimitry Andric   //   need to perform retain/release operations on the temporary.
2690b57cec5SDimitry Andric   //
2700b57cec5SDimitry Andric   // FIXME: This should be looking at E, not M.
2710b57cec5SDimitry Andric   if (auto Lifetime = M->getType().getObjCLifetime()) {
2720b57cec5SDimitry Andric     switch (Lifetime) {
2730b57cec5SDimitry Andric     case Qualifiers::OCL_None:
2740b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
2750b57cec5SDimitry Andric       // Carry on to normal cleanup handling.
2760b57cec5SDimitry Andric       break;
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
2790b57cec5SDimitry Andric       // Nothing to do; cleaned up by an autorelease pool.
2800b57cec5SDimitry Andric       return;
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
2830b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
2840b57cec5SDimitry Andric       switch (StorageDuration Duration = M->getStorageDuration()) {
2850b57cec5SDimitry Andric       case SD_Static:
2860b57cec5SDimitry Andric         // Note: we intentionally do not register a cleanup to release
2870b57cec5SDimitry Andric         // the object on program termination.
2880b57cec5SDimitry Andric         return;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric       case SD_Thread:
2910b57cec5SDimitry Andric         // FIXME: We should probably register a cleanup in this case.
2920b57cec5SDimitry Andric         return;
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric       case SD_Automatic:
2950b57cec5SDimitry Andric       case SD_FullExpression:
2960b57cec5SDimitry Andric         CodeGenFunction::Destroyer *Destroy;
2970b57cec5SDimitry Andric         CleanupKind CleanupKind;
2980b57cec5SDimitry Andric         if (Lifetime == Qualifiers::OCL_Strong) {
2990b57cec5SDimitry Andric           const ValueDecl *VD = M->getExtendingDecl();
3000b57cec5SDimitry Andric           bool Precise =
3010b57cec5SDimitry Andric               VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
3020b57cec5SDimitry Andric           CleanupKind = CGF.getARCCleanupKind();
3030b57cec5SDimitry Andric           Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
3040b57cec5SDimitry Andric                             : &CodeGenFunction::destroyARCStrongImprecise;
3050b57cec5SDimitry Andric         } else {
3060b57cec5SDimitry Andric           // __weak objects always get EH cleanups; otherwise, exceptions
3070b57cec5SDimitry Andric           // could cause really nasty crashes instead of mere leaks.
3080b57cec5SDimitry Andric           CleanupKind = NormalAndEHCleanup;
3090b57cec5SDimitry Andric           Destroy = &CodeGenFunction::destroyARCWeak;
3100b57cec5SDimitry Andric         }
3110b57cec5SDimitry Andric         if (Duration == SD_FullExpression)
3120b57cec5SDimitry Andric           CGF.pushDestroy(CleanupKind, ReferenceTemporary,
3130b57cec5SDimitry Andric                           M->getType(), *Destroy,
3140b57cec5SDimitry Andric                           CleanupKind & EHCleanup);
3150b57cec5SDimitry Andric         else
3160b57cec5SDimitry Andric           CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
3170b57cec5SDimitry Andric                                           M->getType(),
3180b57cec5SDimitry Andric                                           *Destroy, CleanupKind & EHCleanup);
3190b57cec5SDimitry Andric         return;
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric       case SD_Dynamic:
3220b57cec5SDimitry Andric         llvm_unreachable("temporary cannot have dynamic storage duration");
3230b57cec5SDimitry Andric       }
3240b57cec5SDimitry Andric       llvm_unreachable("unknown storage duration");
3250b57cec5SDimitry Andric     }
3260b57cec5SDimitry Andric   }
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric   CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
3290b57cec5SDimitry Andric   if (const RecordType *RT =
3300b57cec5SDimitry Andric           E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
3310b57cec5SDimitry Andric     // Get the destructor for the reference temporary.
3320b57cec5SDimitry Andric     auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3330b57cec5SDimitry Andric     if (!ClassDecl->hasTrivialDestructor())
3340b57cec5SDimitry Andric       ReferenceTemporaryDtor = ClassDecl->getDestructor();
3350b57cec5SDimitry Andric   }
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   if (!ReferenceTemporaryDtor)
3380b57cec5SDimitry Andric     return;
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   // Call the destructor for the temporary.
3410b57cec5SDimitry Andric   switch (M->getStorageDuration()) {
3420b57cec5SDimitry Andric   case SD_Static:
3430b57cec5SDimitry Andric   case SD_Thread: {
3440b57cec5SDimitry Andric     llvm::FunctionCallee CleanupFn;
3450b57cec5SDimitry Andric     llvm::Constant *CleanupArg;
3460b57cec5SDimitry Andric     if (E->getType()->isArrayType()) {
3470b57cec5SDimitry Andric       CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
3480b57cec5SDimitry Andric           ReferenceTemporary, E->getType(),
3490b57cec5SDimitry Andric           CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
3500b57cec5SDimitry Andric           dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
3510b57cec5SDimitry Andric       CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
3520b57cec5SDimitry Andric     } else {
3530b57cec5SDimitry Andric       CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
3540b57cec5SDimitry Andric           GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
3550b57cec5SDimitry Andric       CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
3560b57cec5SDimitry Andric     }
3570b57cec5SDimitry Andric     CGF.CGM.getCXXABI().registerGlobalDtor(
3580b57cec5SDimitry Andric         CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
3590b57cec5SDimitry Andric     break;
3600b57cec5SDimitry Andric   }
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   case SD_FullExpression:
3630b57cec5SDimitry Andric     CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
3640b57cec5SDimitry Andric                     CodeGenFunction::destroyCXXObject,
3650b57cec5SDimitry Andric                     CGF.getLangOpts().Exceptions);
3660b57cec5SDimitry Andric     break;
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric   case SD_Automatic:
3690b57cec5SDimitry Andric     CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
3700b57cec5SDimitry Andric                                     ReferenceTemporary, E->getType(),
3710b57cec5SDimitry Andric                                     CodeGenFunction::destroyCXXObject,
3720b57cec5SDimitry Andric                                     CGF.getLangOpts().Exceptions);
3730b57cec5SDimitry Andric     break;
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   case SD_Dynamic:
3760b57cec5SDimitry Andric     llvm_unreachable("temporary cannot have dynamic storage duration");
3770b57cec5SDimitry Andric   }
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric static Address createReferenceTemporary(CodeGenFunction &CGF,
3810b57cec5SDimitry Andric                                         const MaterializeTemporaryExpr *M,
3820b57cec5SDimitry Andric                                         const Expr *Inner,
3830b57cec5SDimitry Andric                                         Address *Alloca = nullptr) {
3840b57cec5SDimitry Andric   auto &TCG = CGF.getTargetHooks();
3850b57cec5SDimitry Andric   switch (M->getStorageDuration()) {
3860b57cec5SDimitry Andric   case SD_FullExpression:
3870b57cec5SDimitry Andric   case SD_Automatic: {
3880b57cec5SDimitry Andric     // If we have a constant temporary array or record try to promote it into a
3890b57cec5SDimitry Andric     // constant global under the same rules a normal constant would've been
3900b57cec5SDimitry Andric     // promoted. This is easier on the optimizer and generally emits fewer
3910b57cec5SDimitry Andric     // instructions.
3920b57cec5SDimitry Andric     QualType Ty = Inner->getType();
3930b57cec5SDimitry Andric     if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
3940b57cec5SDimitry Andric         (Ty->isArrayType() || Ty->isRecordType()) &&
395*fe013be4SDimitry Andric         CGF.CGM.isTypeConstant(Ty, true, false))
3960b57cec5SDimitry Andric       if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
397fe6060f1SDimitry Andric         auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
3980b57cec5SDimitry Andric         auto *GV = new llvm::GlobalVariable(
3990b57cec5SDimitry Andric             CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
4000b57cec5SDimitry Andric             llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
4010b57cec5SDimitry Andric             llvm::GlobalValue::NotThreadLocal,
4020b57cec5SDimitry Andric             CGF.getContext().getTargetAddressSpace(AS));
4030b57cec5SDimitry Andric         CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
404a7dea167SDimitry Andric         GV->setAlignment(alignment.getAsAlign());
4050b57cec5SDimitry Andric         llvm::Constant *C = GV;
4060b57cec5SDimitry Andric         if (AS != LangAS::Default)
4070b57cec5SDimitry Andric           C = TCG.performAddrSpaceCast(
4080b57cec5SDimitry Andric               CGF.CGM, GV, AS, LangAS::Default,
4090b57cec5SDimitry Andric               GV->getValueType()->getPointerTo(
4100b57cec5SDimitry Andric                   CGF.getContext().getTargetAddressSpace(LangAS::Default)));
4110b57cec5SDimitry Andric         // FIXME: Should we put the new global into a COMDAT?
41281ad6265SDimitry Andric         return Address(C, GV->getValueType(), alignment);
4130b57cec5SDimitry Andric       }
4140b57cec5SDimitry Andric     return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
4150b57cec5SDimitry Andric   }
4160b57cec5SDimitry Andric   case SD_Thread:
4170b57cec5SDimitry Andric   case SD_Static:
4180b57cec5SDimitry Andric     return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   case SD_Dynamic:
4210b57cec5SDimitry Andric     llvm_unreachable("temporary can't have dynamic storage duration");
4220b57cec5SDimitry Andric   }
4230b57cec5SDimitry Andric   llvm_unreachable("unknown storage duration");
4240b57cec5SDimitry Andric }
4250b57cec5SDimitry Andric 
4265ffd83dbSDimitry Andric /// Helper method to check if the underlying ABI is AAPCS
4275ffd83dbSDimitry Andric static bool isAAPCS(const TargetInfo &TargetInfo) {
4285ffd83dbSDimitry Andric   return TargetInfo.getABI().startswith("aapcs");
4295ffd83dbSDimitry Andric }
4305ffd83dbSDimitry Andric 
4310b57cec5SDimitry Andric LValue CodeGenFunction::
4320b57cec5SDimitry Andric EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
433480093f4SDimitry Andric   const Expr *E = M->getSubExpr();
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
4360b57cec5SDimitry Andric           !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
4370b57cec5SDimitry Andric          "Reference should never be pseudo-strong!");
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric   // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
4400b57cec5SDimitry Andric   // as that will cause the lifetime adjustment to be lost for ARC
4410b57cec5SDimitry Andric   auto ownership = M->getType().getObjCLifetime();
4420b57cec5SDimitry Andric   if (ownership != Qualifiers::OCL_None &&
4430b57cec5SDimitry Andric       ownership != Qualifiers::OCL_ExplicitNone) {
4440b57cec5SDimitry Andric     Address Object = createReferenceTemporary(*this, M, E);
4450b57cec5SDimitry Andric     if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
44681ad6265SDimitry Andric       llvm::Type *Ty = ConvertTypeForMem(E->getType());
44781ad6265SDimitry Andric       Object = Address(llvm::ConstantExpr::getBitCast(
44881ad6265SDimitry Andric                            Var, Ty->getPointerTo(Object.getAddressSpace())),
44981ad6265SDimitry Andric                        Ty, Object.getAlignment());
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric       // createReferenceTemporary will promote the temporary to a global with a
4520b57cec5SDimitry Andric       // constant initializer if it can.  It can only do this to a value of
4530b57cec5SDimitry Andric       // ARC-manageable type if the value is global and therefore "immune" to
4540b57cec5SDimitry Andric       // ref-counting operations.  Therefore we have no need to emit either a
4550b57cec5SDimitry Andric       // dynamic initialization or a cleanup and we can just return the address
4560b57cec5SDimitry Andric       // of the temporary.
4570b57cec5SDimitry Andric       if (Var->hasInitializer())
4580b57cec5SDimitry Andric         return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
4610b57cec5SDimitry Andric     }
4620b57cec5SDimitry Andric     LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
4630b57cec5SDimitry Andric                                        AlignmentSource::Decl);
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric     switch (getEvaluationKind(E->getType())) {
4660b57cec5SDimitry Andric     default: llvm_unreachable("expected scalar or aggregate expression");
4670b57cec5SDimitry Andric     case TEK_Scalar:
4680b57cec5SDimitry Andric       EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
4690b57cec5SDimitry Andric       break;
4700b57cec5SDimitry Andric     case TEK_Aggregate: {
4710b57cec5SDimitry Andric       EmitAggExpr(E, AggValueSlot::forAddr(Object,
4720b57cec5SDimitry Andric                                            E->getType().getQualifiers(),
4730b57cec5SDimitry Andric                                            AggValueSlot::IsDestructed,
4740b57cec5SDimitry Andric                                            AggValueSlot::DoesNotNeedGCBarriers,
4750b57cec5SDimitry Andric                                            AggValueSlot::IsNotAliased,
4760b57cec5SDimitry Andric                                            AggValueSlot::DoesNotOverlap));
4770b57cec5SDimitry Andric       break;
4780b57cec5SDimitry Andric     }
4790b57cec5SDimitry Andric     }
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric     pushTemporaryCleanup(*this, M, E, Object);
4820b57cec5SDimitry Andric     return RefTempDst;
4830b57cec5SDimitry Andric   }
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric   SmallVector<const Expr *, 2> CommaLHSs;
4860b57cec5SDimitry Andric   SmallVector<SubobjectAdjustment, 2> Adjustments;
4870b57cec5SDimitry Andric   E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric   for (const auto &Ignored : CommaLHSs)
4900b57cec5SDimitry Andric     EmitIgnoredExpr(Ignored);
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
4930b57cec5SDimitry Andric     if (opaque->getType()->isRecordType()) {
4940b57cec5SDimitry Andric       assert(Adjustments.empty());
4950b57cec5SDimitry Andric       return EmitOpaqueValueLValue(opaque);
4960b57cec5SDimitry Andric     }
4970b57cec5SDimitry Andric   }
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric   // Create and initialize the reference temporary.
5000b57cec5SDimitry Andric   Address Alloca = Address::invalid();
5010b57cec5SDimitry Andric   Address Object = createReferenceTemporary(*this, M, E, &Alloca);
5020b57cec5SDimitry Andric   if (auto *Var = dyn_cast<llvm::GlobalVariable>(
5030b57cec5SDimitry Andric           Object.getPointer()->stripPointerCasts())) {
50481ad6265SDimitry Andric     llvm::Type *TemporaryType = ConvertTypeForMem(E->getType());
5050b57cec5SDimitry Andric     Object = Address(llvm::ConstantExpr::getBitCast(
5060b57cec5SDimitry Andric                          cast<llvm::Constant>(Object.getPointer()),
50781ad6265SDimitry Andric                          TemporaryType->getPointerTo()),
50881ad6265SDimitry Andric                      TemporaryType,
5090b57cec5SDimitry Andric                      Object.getAlignment());
5100b57cec5SDimitry Andric     // If the temporary is a global and has a constant initializer or is a
5110b57cec5SDimitry Andric     // constant temporary that we promoted to a global, we may have already
5120b57cec5SDimitry Andric     // initialized it.
5130b57cec5SDimitry Andric     if (!Var->hasInitializer()) {
5140b57cec5SDimitry Andric       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
5150b57cec5SDimitry Andric       EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
5160b57cec5SDimitry Andric     }
5170b57cec5SDimitry Andric   } else {
5180b57cec5SDimitry Andric     switch (M->getStorageDuration()) {
5190b57cec5SDimitry Andric     case SD_Automatic:
5200b57cec5SDimitry Andric       if (auto *Size = EmitLifetimeStart(
5210b57cec5SDimitry Andric               CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
5220b57cec5SDimitry Andric               Alloca.getPointer())) {
5230b57cec5SDimitry Andric         pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
5240b57cec5SDimitry Andric                                                   Alloca, Size);
5250b57cec5SDimitry Andric       }
5260b57cec5SDimitry Andric       break;
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric     case SD_FullExpression: {
5290b57cec5SDimitry Andric       if (!ShouldEmitLifetimeMarkers)
5300b57cec5SDimitry Andric         break;
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric       // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
5330b57cec5SDimitry Andric       // marker. Instead, start the lifetime of a conditional temporary earlier
534a7dea167SDimitry Andric       // so that it's unconditional. Don't do this with sanitizers which need
535*fe013be4SDimitry Andric       // more precise lifetime marks. However when inside an "await.suspend"
536*fe013be4SDimitry Andric       // block, we should always avoid conditional cleanup because it creates
537*fe013be4SDimitry Andric       // boolean marker that lives across await_suspend, which can destroy coro
538*fe013be4SDimitry Andric       // frame.
5390b57cec5SDimitry Andric       ConditionalEvaluation *OldConditional = nullptr;
5400b57cec5SDimitry Andric       CGBuilderTy::InsertPoint OldIP;
5410b57cec5SDimitry Andric       if (isInConditionalBranch() && !E->getType().isDestructedType() &&
542*fe013be4SDimitry Andric           ((!SanOpts.has(SanitizerKind::HWAddress) &&
543a7dea167SDimitry Andric             !SanOpts.has(SanitizerKind::Memory) &&
544*fe013be4SDimitry Andric             !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
545*fe013be4SDimitry Andric            inSuspendBlock())) {
5460b57cec5SDimitry Andric         OldConditional = OutermostConditional;
5470b57cec5SDimitry Andric         OutermostConditional = nullptr;
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric         OldIP = Builder.saveIP();
5500b57cec5SDimitry Andric         llvm::BasicBlock *Block = OldConditional->getStartingBlock();
5510b57cec5SDimitry Andric         Builder.restoreIP(CGBuilderTy::InsertPoint(
5520b57cec5SDimitry Andric             Block, llvm::BasicBlock::iterator(Block->back())));
5530b57cec5SDimitry Andric       }
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric       if (auto *Size = EmitLifetimeStart(
5560b57cec5SDimitry Andric               CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
5570b57cec5SDimitry Andric               Alloca.getPointer())) {
5580b57cec5SDimitry Andric         pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
5590b57cec5SDimitry Andric                                              Size);
5600b57cec5SDimitry Andric       }
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric       if (OldConditional) {
5630b57cec5SDimitry Andric         OutermostConditional = OldConditional;
5640b57cec5SDimitry Andric         Builder.restoreIP(OldIP);
5650b57cec5SDimitry Andric       }
5660b57cec5SDimitry Andric       break;
5670b57cec5SDimitry Andric     }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric     default:
5700b57cec5SDimitry Andric       break;
5710b57cec5SDimitry Andric     }
5720b57cec5SDimitry Andric     EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
5730b57cec5SDimitry Andric   }
5740b57cec5SDimitry Andric   pushTemporaryCleanup(*this, M, E, Object);
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric   // Perform derived-to-base casts and/or field accesses, to get from the
5770b57cec5SDimitry Andric   // temporary object we created (and, potentially, for which we extended
5780b57cec5SDimitry Andric   // the lifetime) to the subobject we're binding the reference to.
579349cc55cSDimitry Andric   for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
5800b57cec5SDimitry Andric     switch (Adjustment.Kind) {
5810b57cec5SDimitry Andric     case SubobjectAdjustment::DerivedToBaseAdjustment:
5820b57cec5SDimitry Andric       Object =
5830b57cec5SDimitry Andric           GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
5840b57cec5SDimitry Andric                                 Adjustment.DerivedToBase.BasePath->path_begin(),
5850b57cec5SDimitry Andric                                 Adjustment.DerivedToBase.BasePath->path_end(),
5860b57cec5SDimitry Andric                                 /*NullCheckValue=*/ false, E->getExprLoc());
5870b57cec5SDimitry Andric       break;
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric     case SubobjectAdjustment::FieldAdjustment: {
5900b57cec5SDimitry Andric       LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
5910b57cec5SDimitry Andric       LV = EmitLValueForField(LV, Adjustment.Field);
5920b57cec5SDimitry Andric       assert(LV.isSimple() &&
5930b57cec5SDimitry Andric              "materialized temporary field is not a simple lvalue");
594480093f4SDimitry Andric       Object = LV.getAddress(*this);
5950b57cec5SDimitry Andric       break;
5960b57cec5SDimitry Andric     }
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric     case SubobjectAdjustment::MemberPointerAdjustment: {
5990b57cec5SDimitry Andric       llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
6000b57cec5SDimitry Andric       Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
6010b57cec5SDimitry Andric                                                Adjustment.Ptr.MPT);
6020b57cec5SDimitry Andric       break;
6030b57cec5SDimitry Andric     }
6040b57cec5SDimitry Andric     }
6050b57cec5SDimitry Andric   }
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric   return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
6080b57cec5SDimitry Andric }
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric RValue
6110b57cec5SDimitry Andric CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
6120b57cec5SDimitry Andric   // Emit the expression as an lvalue.
6130b57cec5SDimitry Andric   LValue LV = EmitLValue(E);
6140b57cec5SDimitry Andric   assert(LV.isSimple());
615480093f4SDimitry Andric   llvm::Value *Value = LV.getPointer(*this);
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric   if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
6180b57cec5SDimitry Andric     // C++11 [dcl.ref]p5 (as amended by core issue 453):
6190b57cec5SDimitry Andric     //   If a glvalue to which a reference is directly bound designates neither
6200b57cec5SDimitry Andric     //   an existing object or function of an appropriate type nor a region of
6210b57cec5SDimitry Andric     //   storage of suitable size and alignment to contain an object of the
6220b57cec5SDimitry Andric     //   reference's type, the behavior is undefined.
6230b57cec5SDimitry Andric     QualType Ty = E->getType();
6240b57cec5SDimitry Andric     EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
6250b57cec5SDimitry Andric   }
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   return RValue::get(Value);
6280b57cec5SDimitry Andric }
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric /// getAccessedFieldNo - Given an encoded value and a result number, return the
6320b57cec5SDimitry Andric /// input field number being accessed.
6330b57cec5SDimitry Andric unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
6340b57cec5SDimitry Andric                                              const llvm::Constant *Elts) {
6350b57cec5SDimitry Andric   return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
6360b57cec5SDimitry Andric       ->getZExtValue();
6370b57cec5SDimitry Andric }
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
6400b57cec5SDimitry Andric static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
6410b57cec5SDimitry Andric                                     llvm::Value *High) {
6420b57cec5SDimitry Andric   llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
6430b57cec5SDimitry Andric   llvm::Value *K47 = Builder.getInt64(47);
6440b57cec5SDimitry Andric   llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
6450b57cec5SDimitry Andric   llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
6460b57cec5SDimitry Andric   llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
6470b57cec5SDimitry Andric   llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
6480b57cec5SDimitry Andric   return Builder.CreateMul(B1, KMul);
6490b57cec5SDimitry Andric }
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
6520b57cec5SDimitry Andric   return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
6530b57cec5SDimitry Andric          TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
6540b57cec5SDimitry Andric }
6550b57cec5SDimitry Andric 
6560b57cec5SDimitry Andric bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
6570b57cec5SDimitry Andric   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6580b57cec5SDimitry Andric   return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
6590b57cec5SDimitry Andric          (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
6600b57cec5SDimitry Andric           TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
6610b57cec5SDimitry Andric           TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
6620b57cec5SDimitry Andric }
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric bool CodeGenFunction::sanitizePerformTypeCheck() const {
665349cc55cSDimitry Andric   return SanOpts.has(SanitizerKind::Null) ||
666349cc55cSDimitry Andric          SanOpts.has(SanitizerKind::Alignment) ||
667349cc55cSDimitry Andric          SanOpts.has(SanitizerKind::ObjectSize) ||
6680b57cec5SDimitry Andric          SanOpts.has(SanitizerKind::Vptr);
6690b57cec5SDimitry Andric }
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
6720b57cec5SDimitry Andric                                     llvm::Value *Ptr, QualType Ty,
6730b57cec5SDimitry Andric                                     CharUnits Alignment,
6740b57cec5SDimitry Andric                                     SanitizerSet SkippedChecks,
6750b57cec5SDimitry Andric                                     llvm::Value *ArraySize) {
6760b57cec5SDimitry Andric   if (!sanitizePerformTypeCheck())
6770b57cec5SDimitry Andric     return;
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   // Don't check pointers outside the default address space. The null check
6800b57cec5SDimitry Andric   // isn't correct, the object-size check isn't supported by LLVM, and we can't
6810b57cec5SDimitry Andric   // communicate the addresses to the runtime handler for the vptr check.
6820b57cec5SDimitry Andric   if (Ptr->getType()->getPointerAddressSpace())
6830b57cec5SDimitry Andric     return;
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric   // Don't check pointers to volatile data. The behavior here is implementation-
6860b57cec5SDimitry Andric   // defined.
6870b57cec5SDimitry Andric   if (Ty.isVolatileQualified())
6880b57cec5SDimitry Andric     return;
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric   SanitizerScope SanScope(this);
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
6930b57cec5SDimitry Andric   llvm::BasicBlock *Done = nullptr;
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   // Quickly determine whether we have a pointer to an alloca. It's possible
6960b57cec5SDimitry Andric   // to skip null checks, and some alignment checks, for these pointers. This
6970b57cec5SDimitry Andric   // can reduce compile-time significantly.
698a7dea167SDimitry Andric   auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric   llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
7010b57cec5SDimitry Andric   llvm::Value *IsNonNull = nullptr;
7020b57cec5SDimitry Andric   bool IsGuaranteedNonNull =
7030b57cec5SDimitry Andric       SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
7040b57cec5SDimitry Andric   bool AllowNullPointers = isNullPointerAllowed(TCK);
7050b57cec5SDimitry Andric   if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
7060b57cec5SDimitry Andric       !IsGuaranteedNonNull) {
7070b57cec5SDimitry Andric     // The glvalue must not be an empty glvalue.
7080b57cec5SDimitry Andric     IsNonNull = Builder.CreateIsNotNull(Ptr);
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric     // The IR builder can constant-fold the null check if the pointer points to
7110b57cec5SDimitry Andric     // a constant.
7120b57cec5SDimitry Andric     IsGuaranteedNonNull = IsNonNull == True;
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric     // Skip the null check if the pointer is known to be non-null.
7150b57cec5SDimitry Andric     if (!IsGuaranteedNonNull) {
7160b57cec5SDimitry Andric       if (AllowNullPointers) {
7170b57cec5SDimitry Andric         // When performing pointer casts, it's OK if the value is null.
7180b57cec5SDimitry Andric         // Skip the remaining checks in that case.
7190b57cec5SDimitry Andric         Done = createBasicBlock("null");
7200b57cec5SDimitry Andric         llvm::BasicBlock *Rest = createBasicBlock("not.null");
7210b57cec5SDimitry Andric         Builder.CreateCondBr(IsNonNull, Rest, Done);
7220b57cec5SDimitry Andric         EmitBlock(Rest);
7230b57cec5SDimitry Andric       } else {
7240b57cec5SDimitry Andric         Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
7250b57cec5SDimitry Andric       }
7260b57cec5SDimitry Andric     }
7270b57cec5SDimitry Andric   }
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ObjectSize) &&
7300b57cec5SDimitry Andric       !SkippedChecks.has(SanitizerKind::ObjectSize) &&
7310b57cec5SDimitry Andric       !Ty->isIncompleteType()) {
7325ffd83dbSDimitry Andric     uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
7330b57cec5SDimitry Andric     llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
7340b57cec5SDimitry Andric     if (ArraySize)
7350b57cec5SDimitry Andric       Size = Builder.CreateMul(Size, ArraySize);
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric     // Degenerate case: new X[0] does not need an objectsize check.
7380b57cec5SDimitry Andric     llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
7390b57cec5SDimitry Andric     if (!ConstantSize || !ConstantSize->isNullValue()) {
7400b57cec5SDimitry Andric       // The glvalue must refer to a large enough storage region.
7410b57cec5SDimitry Andric       // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
7420b57cec5SDimitry Andric       //        to check this.
7430b57cec5SDimitry Andric       // FIXME: Get object address space
7440b57cec5SDimitry Andric       llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
7450b57cec5SDimitry Andric       llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
7460b57cec5SDimitry Andric       llvm::Value *Min = Builder.getFalse();
7470b57cec5SDimitry Andric       llvm::Value *NullIsUnknown = Builder.getFalse();
7480b57cec5SDimitry Andric       llvm::Value *Dynamic = Builder.getFalse();
7490b57cec5SDimitry Andric       llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
7500b57cec5SDimitry Andric       llvm::Value *LargeEnough = Builder.CreateICmpUGE(
7510b57cec5SDimitry Andric           Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
7520b57cec5SDimitry Andric       Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
7530b57cec5SDimitry Andric     }
7540b57cec5SDimitry Andric   }
7550b57cec5SDimitry Andric 
75681ad6265SDimitry Andric   llvm::MaybeAlign AlignVal;
7570b57cec5SDimitry Andric   llvm::Value *PtrAsInt = nullptr;
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Alignment) &&
7600b57cec5SDimitry Andric       !SkippedChecks.has(SanitizerKind::Alignment)) {
76181ad6265SDimitry Andric     AlignVal = Alignment.getAsMaybeAlign();
7620b57cec5SDimitry Andric     if (!Ty->isIncompleteType() && !AlignVal)
7635ffd83dbSDimitry Andric       AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
7645ffd83dbSDimitry Andric                                              /*ForPointeeType=*/true)
76581ad6265SDimitry Andric                      .getAsMaybeAlign();
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric     // The glvalue must be suitably aligned.
76881ad6265SDimitry Andric     if (AlignVal && *AlignVal > llvm::Align(1) &&
76981ad6265SDimitry Andric         (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
7700b57cec5SDimitry Andric       PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
7710b57cec5SDimitry Andric       llvm::Value *Align = Builder.CreateAnd(
77281ad6265SDimitry Andric           PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal->value() - 1));
7730b57cec5SDimitry Andric       llvm::Value *Aligned =
7740b57cec5SDimitry Andric           Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
7750b57cec5SDimitry Andric       if (Aligned != True)
7760b57cec5SDimitry Andric         Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
7770b57cec5SDimitry Andric     }
7780b57cec5SDimitry Andric   }
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric   if (Checks.size() > 0) {
7810b57cec5SDimitry Andric     llvm::Constant *StaticData[] = {
7820b57cec5SDimitry Andric         EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
78381ad6265SDimitry Andric         llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1),
7840b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, TCK)};
7850b57cec5SDimitry Andric     EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
7860b57cec5SDimitry Andric               PtrAsInt ? PtrAsInt : Ptr);
7870b57cec5SDimitry Andric   }
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric   // If possible, check that the vptr indicates that there is a subobject of
7900b57cec5SDimitry Andric   // type Ty at offset zero within this object.
7910b57cec5SDimitry Andric   //
7920b57cec5SDimitry Andric   // C++11 [basic.life]p5,6:
7930b57cec5SDimitry Andric   //   [For storage which does not refer to an object within its lifetime]
7940b57cec5SDimitry Andric   //   The program has undefined behavior if:
7950b57cec5SDimitry Andric   //    -- the [pointer or glvalue] is used to access a non-static data member
7960b57cec5SDimitry Andric   //       or call a non-static member function
7970b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Vptr) &&
7980b57cec5SDimitry Andric       !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
7990b57cec5SDimitry Andric     // Ensure that the pointer is non-null before loading it. If there is no
8000b57cec5SDimitry Andric     // compile-time guarantee, reuse the run-time null check or emit a new one.
8010b57cec5SDimitry Andric     if (!IsGuaranteedNonNull) {
8020b57cec5SDimitry Andric       if (!IsNonNull)
8030b57cec5SDimitry Andric         IsNonNull = Builder.CreateIsNotNull(Ptr);
8040b57cec5SDimitry Andric       if (!Done)
8050b57cec5SDimitry Andric         Done = createBasicBlock("vptr.null");
8060b57cec5SDimitry Andric       llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
8070b57cec5SDimitry Andric       Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
8080b57cec5SDimitry Andric       EmitBlock(VptrNotNull);
8090b57cec5SDimitry Andric     }
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric     // Compute a hash of the mangled name of the type.
8120b57cec5SDimitry Andric     //
8130b57cec5SDimitry Andric     // FIXME: This is not guaranteed to be deterministic! Move to a
8140b57cec5SDimitry Andric     //        fingerprinting mechanism once LLVM provides one. For the time
8150b57cec5SDimitry Andric     //        being the implementation happens to be deterministic.
8160b57cec5SDimitry Andric     SmallString<64> MangledName;
8170b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledName);
8180b57cec5SDimitry Andric     CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
8190b57cec5SDimitry Andric                                                      Out);
8200b57cec5SDimitry Andric 
821fe6060f1SDimitry Andric     // Contained in NoSanitizeList based on the mangled type.
822fe6060f1SDimitry Andric     if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
823fe6060f1SDimitry Andric                                                            Out.str())) {
8240b57cec5SDimitry Andric       llvm::hash_code TypeHash = hash_value(Out.str());
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric       // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
8270b57cec5SDimitry Andric       llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
8280b57cec5SDimitry Andric       llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
82981ad6265SDimitry Andric       Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), IntPtrTy,
83081ad6265SDimitry Andric                        getPointerAlign());
8310b57cec5SDimitry Andric       llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
8320b57cec5SDimitry Andric       llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric       llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
8350b57cec5SDimitry Andric       Hash = Builder.CreateTrunc(Hash, IntPtrTy);
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric       // Look the hash up in our cache.
8380b57cec5SDimitry Andric       const int CacheSize = 128;
8390b57cec5SDimitry Andric       llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
8400b57cec5SDimitry Andric       llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
8410b57cec5SDimitry Andric                                                      "__ubsan_vptr_type_cache");
8420b57cec5SDimitry Andric       llvm::Value *Slot = Builder.CreateAnd(Hash,
8430b57cec5SDimitry Andric                                             llvm::ConstantInt::get(IntPtrTy,
8440b57cec5SDimitry Andric                                                                    CacheSize-1));
8450b57cec5SDimitry Andric       llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
846fe6060f1SDimitry Andric       llvm::Value *CacheVal = Builder.CreateAlignedLoad(
847fe6060f1SDimitry Andric           IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
8480b57cec5SDimitry Andric           getPointerAlign());
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric       // If the hash isn't in the cache, call a runtime handler to perform the
8510b57cec5SDimitry Andric       // hard work of checking whether the vptr is for an object of the right
8520b57cec5SDimitry Andric       // type. This will either fill in the cache and return, or produce a
8530b57cec5SDimitry Andric       // diagnostic.
8540b57cec5SDimitry Andric       llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
8550b57cec5SDimitry Andric       llvm::Constant *StaticData[] = {
8560b57cec5SDimitry Andric         EmitCheckSourceLocation(Loc),
8570b57cec5SDimitry Andric         EmitCheckTypeDescriptor(Ty),
8580b57cec5SDimitry Andric         CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
8590b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, TCK)
8600b57cec5SDimitry Andric       };
8610b57cec5SDimitry Andric       llvm::Value *DynamicData[] = { Ptr, Hash };
8620b57cec5SDimitry Andric       EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
8630b57cec5SDimitry Andric                 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
8640b57cec5SDimitry Andric                 DynamicData);
8650b57cec5SDimitry Andric     }
8660b57cec5SDimitry Andric   }
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric   if (Done) {
8690b57cec5SDimitry Andric     Builder.CreateBr(Done);
8700b57cec5SDimitry Andric     EmitBlock(Done);
8710b57cec5SDimitry Andric   }
8720b57cec5SDimitry Andric }
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
8750b57cec5SDimitry Andric                                                    QualType EltTy) {
8760b57cec5SDimitry Andric   ASTContext &C = getContext();
8770b57cec5SDimitry Andric   uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
8780b57cec5SDimitry Andric   if (!EltSize)
8790b57cec5SDimitry Andric     return nullptr;
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric   auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
8820b57cec5SDimitry Andric   if (!ArrayDeclRef)
8830b57cec5SDimitry Andric     return nullptr;
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric   auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
8860b57cec5SDimitry Andric   if (!ParamDecl)
8870b57cec5SDimitry Andric     return nullptr;
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
8900b57cec5SDimitry Andric   if (!POSAttr)
8910b57cec5SDimitry Andric     return nullptr;
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric   // Don't load the size if it's a lower bound.
8940b57cec5SDimitry Andric   int POSType = POSAttr->getType();
8950b57cec5SDimitry Andric   if (POSType != 0 && POSType != 1)
8960b57cec5SDimitry Andric     return nullptr;
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric   // Find the implicit size parameter.
8990b57cec5SDimitry Andric   auto PassedSizeIt = SizeArguments.find(ParamDecl);
9000b57cec5SDimitry Andric   if (PassedSizeIt == SizeArguments.end())
9010b57cec5SDimitry Andric     return nullptr;
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric   const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
9040b57cec5SDimitry Andric   assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
9050b57cec5SDimitry Andric   Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
9060b57cec5SDimitry Andric   llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
9070b57cec5SDimitry Andric                                               C.getSizeType(), E->getExprLoc());
9080b57cec5SDimitry Andric   llvm::Value *SizeOfElement =
9090b57cec5SDimitry Andric       llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
9100b57cec5SDimitry Andric   return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
9110b57cec5SDimitry Andric }
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric /// If Base is known to point to the start of an array, return the length of
9140b57cec5SDimitry Andric /// that array. Return 0 if the length cannot be determined.
915fcaf7f86SDimitry Andric static llvm::Value *getArrayIndexingBound(CodeGenFunction &CGF,
916fcaf7f86SDimitry Andric                                           const Expr *Base,
917fcaf7f86SDimitry Andric                                           QualType &IndexedType,
918bdd1243dSDimitry Andric                                           LangOptions::StrictFlexArraysLevelKind
919bdd1243dSDimitry Andric                                           StrictFlexArraysLevel) {
9200b57cec5SDimitry Andric   // For the vector indexing extension, the bound is the number of elements.
9210b57cec5SDimitry Andric   if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
9220b57cec5SDimitry Andric     IndexedType = Base->getType();
9230b57cec5SDimitry Andric     return CGF.Builder.getInt32(VT->getNumElements());
9240b57cec5SDimitry Andric   }
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   Base = Base->IgnoreParens();
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CastExpr>(Base)) {
9290b57cec5SDimitry Andric     if (CE->getCastKind() == CK_ArrayToPointerDecay &&
930bdd1243dSDimitry Andric         !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.getContext(),
931bdd1243dSDimitry Andric                                                      StrictFlexArraysLevel)) {
9320b57cec5SDimitry Andric       IndexedType = CE->getSubExpr()->getType();
9330b57cec5SDimitry Andric       const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
9340b57cec5SDimitry Andric       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9350b57cec5SDimitry Andric         return CGF.Builder.getInt(CAT->getSize());
9360b57cec5SDimitry Andric       else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
9370b57cec5SDimitry Andric         return CGF.getVLASize(VAT).NumElts;
9380b57cec5SDimitry Andric       // Ignore pass_object_size here. It's not applicable on decayed pointers.
9390b57cec5SDimitry Andric     }
9400b57cec5SDimitry Andric   }
9410b57cec5SDimitry Andric 
9420b57cec5SDimitry Andric   QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
9430b57cec5SDimitry Andric   if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
9440b57cec5SDimitry Andric     IndexedType = Base->getType();
9450b57cec5SDimitry Andric     return POS;
9460b57cec5SDimitry Andric   }
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   return nullptr;
9490b57cec5SDimitry Andric }
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
9520b57cec5SDimitry Andric                                       llvm::Value *Index, QualType IndexType,
9530b57cec5SDimitry Andric                                       bool Accessed) {
9540b57cec5SDimitry Andric   assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
9550b57cec5SDimitry Andric          "should not be called unless adding bounds checks");
9560b57cec5SDimitry Andric   SanitizerScope SanScope(this);
9570b57cec5SDimitry Andric 
958bdd1243dSDimitry Andric   const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
959bdd1243dSDimitry Andric     getLangOpts().getStrictFlexArraysLevel();
960fcaf7f86SDimitry Andric 
9610b57cec5SDimitry Andric   QualType IndexedType;
962fcaf7f86SDimitry Andric   llvm::Value *Bound =
963fcaf7f86SDimitry Andric       getArrayIndexingBound(*this, Base, IndexedType, StrictFlexArraysLevel);
9640b57cec5SDimitry Andric   if (!Bound)
9650b57cec5SDimitry Andric     return;
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric   bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
9680b57cec5SDimitry Andric   llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
9690b57cec5SDimitry Andric   llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
9700b57cec5SDimitry Andric 
9710b57cec5SDimitry Andric   llvm::Constant *StaticData[] = {
9720b57cec5SDimitry Andric     EmitCheckSourceLocation(E->getExprLoc()),
9730b57cec5SDimitry Andric     EmitCheckTypeDescriptor(IndexedType),
9740b57cec5SDimitry Andric     EmitCheckTypeDescriptor(IndexType)
9750b57cec5SDimitry Andric   };
9760b57cec5SDimitry Andric   llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
9770b57cec5SDimitry Andric                                 : Builder.CreateICmpULE(IndexVal, BoundVal);
9780b57cec5SDimitry Andric   EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
9790b57cec5SDimitry Andric             SanitizerHandler::OutOfBounds, StaticData, Index);
9800b57cec5SDimitry Andric }
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric CodeGenFunction::ComplexPairTy CodeGenFunction::
9840b57cec5SDimitry Andric EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
9850b57cec5SDimitry Andric                          bool isInc, bool isPre) {
9860b57cec5SDimitry Andric   ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric   llvm::Value *NextVal;
9890b57cec5SDimitry Andric   if (isa<llvm::IntegerType>(InVal.first->getType())) {
9900b57cec5SDimitry Andric     uint64_t AmountVal = isInc ? 1 : -1;
9910b57cec5SDimitry Andric     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric     // Add the inc/dec to the real part.
9940b57cec5SDimitry Andric     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
9950b57cec5SDimitry Andric   } else {
996a7dea167SDimitry Andric     QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9970b57cec5SDimitry Andric     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
9980b57cec5SDimitry Andric     if (!isInc)
9990b57cec5SDimitry Andric       FVal.changeSign();
10000b57cec5SDimitry Andric     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric     // Add the inc/dec to the real part.
10030b57cec5SDimitry Andric     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
10040b57cec5SDimitry Andric   }
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric   ComplexPairTy IncVal(NextVal, InVal.second);
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric   // Store the updated result through the lvalue.
10090b57cec5SDimitry Andric   EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1010480093f4SDimitry Andric   if (getLangOpts().OpenMP)
1011480093f4SDimitry Andric     CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1012480093f4SDimitry Andric                                                               E->getSubExpr());
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric   // If this is a postinc, return the value read from memory, otherwise use the
10150b57cec5SDimitry Andric   // updated value.
10160b57cec5SDimitry Andric   return isPre ? IncVal : InVal;
10170b57cec5SDimitry Andric }
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
10200b57cec5SDimitry Andric                                              CodeGenFunction *CGF) {
10210b57cec5SDimitry Andric   // Bind VLAs in the cast type.
10220b57cec5SDimitry Andric   if (CGF && E->getType()->isVariablyModifiedType())
10230b57cec5SDimitry Andric     CGF->EmitVariablyModifiedType(E->getType());
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
10260b57cec5SDimitry Andric     DI->EmitExplicitCastType(E->getType());
10270b57cec5SDimitry Andric }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10300b57cec5SDimitry Andric //                         LValue Expression Emission
10310b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
10320b57cec5SDimitry Andric 
1033*fe013be4SDimitry Andric static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo,
1034*fe013be4SDimitry Andric                                         TBAAAccessInfo *TBAAInfo,
1035*fe013be4SDimitry Andric                                         KnownNonNull_t IsKnownNonNull,
1036*fe013be4SDimitry Andric                                         CodeGenFunction &CGF) {
10370b57cec5SDimitry Andric   // We allow this with ObjC object pointers because of fragile ABIs.
10380b57cec5SDimitry Andric   assert(E->getType()->isPointerType() ||
10390b57cec5SDimitry Andric          E->getType()->isObjCObjectPointerType());
10400b57cec5SDimitry Andric   E = E->IgnoreParens();
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric   // Casts:
10430b57cec5SDimitry Andric   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10440b57cec5SDimitry Andric     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1045*fe013be4SDimitry Andric       CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric     switch (CE->getCastKind()) {
10480b57cec5SDimitry Andric     // Non-converting casts (but not C's implicit conversion from void*).
10490b57cec5SDimitry Andric     case CK_BitCast:
10500b57cec5SDimitry Andric     case CK_NoOp:
10510b57cec5SDimitry Andric     case CK_AddressSpaceConversion:
10520b57cec5SDimitry Andric       if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
10530b57cec5SDimitry Andric         if (PtrTy->getPointeeType()->isVoidType())
10540b57cec5SDimitry Andric           break;
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric         LValueBaseInfo InnerBaseInfo;
10570b57cec5SDimitry Andric         TBAAAccessInfo InnerTBAAInfo;
1058*fe013be4SDimitry Andric         Address Addr = CGF.EmitPointerWithAlignment(
1059*fe013be4SDimitry Andric             CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull);
10600b57cec5SDimitry Andric         if (BaseInfo) *BaseInfo = InnerBaseInfo;
10610b57cec5SDimitry Andric         if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric         if (isa<ExplicitCastExpr>(CE)) {
10640b57cec5SDimitry Andric           LValueBaseInfo TargetTypeBaseInfo;
10650b57cec5SDimitry Andric           TBAAAccessInfo TargetTypeTBAAInfo;
1066*fe013be4SDimitry Andric           CharUnits Align = CGF.CGM.getNaturalPointeeTypeAlignment(
10675ffd83dbSDimitry Andric               E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
10680b57cec5SDimitry Andric           if (TBAAInfo)
1069*fe013be4SDimitry Andric             *TBAAInfo =
1070*fe013be4SDimitry Andric                 CGF.CGM.mergeTBAAInfoForCast(*TBAAInfo, TargetTypeTBAAInfo);
10710b57cec5SDimitry Andric           // If the source l-value is opaque, honor the alignment of the
10720b57cec5SDimitry Andric           // casted-to type.
10730b57cec5SDimitry Andric           if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
10740b57cec5SDimitry Andric             if (BaseInfo)
10750b57cec5SDimitry Andric               BaseInfo->mergeForCast(TargetTypeBaseInfo);
1076*fe013be4SDimitry Andric             Addr = Address(Addr.getPointer(), Addr.getElementType(), Align,
1077*fe013be4SDimitry Andric                            IsKnownNonNull);
10780b57cec5SDimitry Andric           }
10790b57cec5SDimitry Andric         }
10800b57cec5SDimitry Andric 
1081*fe013be4SDimitry Andric         if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
10820b57cec5SDimitry Andric             CE->getCastKind() == CK_BitCast) {
10830b57cec5SDimitry Andric           if (auto PT = E->getType()->getAs<PointerType>())
1084*fe013be4SDimitry Andric             CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr,
10850b57cec5SDimitry Andric                                           /*MayBeNull=*/true,
10860b57cec5SDimitry Andric                                           CodeGenFunction::CFITCK_UnrelatedCast,
10870b57cec5SDimitry Andric                                           CE->getBeginLoc());
10880b57cec5SDimitry Andric         }
10890eae32dcSDimitry Andric 
1090*fe013be4SDimitry Andric         llvm::Type *ElemTy =
1091*fe013be4SDimitry Andric             CGF.ConvertTypeForMem(E->getType()->getPointeeType());
1092*fe013be4SDimitry Andric         Addr = Addr.withElementType(ElemTy);
109381ad6265SDimitry Andric         if (CE->getCastKind() == CK_AddressSpaceConversion)
1094*fe013be4SDimitry Andric           Addr = CGF.Builder.CreateAddrSpaceCast(Addr,
1095*fe013be4SDimitry Andric                                                  CGF.ConvertType(E->getType()));
109681ad6265SDimitry Andric         return Addr;
10970b57cec5SDimitry Andric       }
10980b57cec5SDimitry Andric       break;
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric     // Array-to-pointer decay.
11010b57cec5SDimitry Andric     case CK_ArrayToPointerDecay:
1102*fe013be4SDimitry Andric       return CGF.EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
11030b57cec5SDimitry Andric 
11040b57cec5SDimitry Andric     // Derived-to-base conversions.
11050b57cec5SDimitry Andric     case CK_UncheckedDerivedToBase:
11060b57cec5SDimitry Andric     case CK_DerivedToBase: {
11070b57cec5SDimitry Andric       // TODO: Support accesses to members of base classes in TBAA. For now, we
11080b57cec5SDimitry Andric       // conservatively pretend that the complete object is of the base class
11090b57cec5SDimitry Andric       // type.
11100b57cec5SDimitry Andric       if (TBAAInfo)
1111*fe013be4SDimitry Andric         *TBAAInfo = CGF.CGM.getTBAAAccessInfo(E->getType());
1112*fe013be4SDimitry Andric       Address Addr = CGF.EmitPointerWithAlignment(
1113*fe013be4SDimitry Andric           CE->getSubExpr(), BaseInfo, nullptr,
1114*fe013be4SDimitry Andric           (KnownNonNull_t)(IsKnownNonNull ||
1115*fe013be4SDimitry Andric                            CE->getCastKind() == CK_UncheckedDerivedToBase));
11160b57cec5SDimitry Andric       auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1117*fe013be4SDimitry Andric       return CGF.GetAddressOfBaseClass(
1118*fe013be4SDimitry Andric           Addr, Derived, CE->path_begin(), CE->path_end(),
1119*fe013be4SDimitry Andric           CGF.ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
11200b57cec5SDimitry Andric     }
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric     // TODO: Is there any reason to treat base-to-derived conversions
11230b57cec5SDimitry Andric     // specially?
11240b57cec5SDimitry Andric     default:
11250b57cec5SDimitry Andric       break;
11260b57cec5SDimitry Andric     }
11270b57cec5SDimitry Andric   }
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric   // Unary &.
11300b57cec5SDimitry Andric   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11310b57cec5SDimitry Andric     if (UO->getOpcode() == UO_AddrOf) {
1132*fe013be4SDimitry Andric       LValue LV = CGF.EmitLValue(UO->getSubExpr(), IsKnownNonNull);
11330b57cec5SDimitry Andric       if (BaseInfo) *BaseInfo = LV.getBaseInfo();
11340b57cec5SDimitry Andric       if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1135*fe013be4SDimitry Andric       return LV.getAddress(CGF);
11360b57cec5SDimitry Andric     }
11370b57cec5SDimitry Andric   }
11380b57cec5SDimitry Andric 
113981ad6265SDimitry Andric   // std::addressof and variants.
114081ad6265SDimitry Andric   if (auto *Call = dyn_cast<CallExpr>(E)) {
114181ad6265SDimitry Andric     switch (Call->getBuiltinCallee()) {
114281ad6265SDimitry Andric     default:
114381ad6265SDimitry Andric       break;
114481ad6265SDimitry Andric     case Builtin::BIaddressof:
114581ad6265SDimitry Andric     case Builtin::BI__addressof:
114681ad6265SDimitry Andric     case Builtin::BI__builtin_addressof: {
1147*fe013be4SDimitry Andric       LValue LV = CGF.EmitLValue(Call->getArg(0), IsKnownNonNull);
114881ad6265SDimitry Andric       if (BaseInfo) *BaseInfo = LV.getBaseInfo();
114981ad6265SDimitry Andric       if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1150*fe013be4SDimitry Andric       return LV.getAddress(CGF);
115181ad6265SDimitry Andric     }
115281ad6265SDimitry Andric     }
115381ad6265SDimitry Andric   }
115481ad6265SDimitry Andric 
11550b57cec5SDimitry Andric   // TODO: conditional operators, comma.
11560b57cec5SDimitry Andric 
11570b57cec5SDimitry Andric   // Otherwise, use the alignment of the type.
11585ffd83dbSDimitry Andric   CharUnits Align =
1159*fe013be4SDimitry Andric       CGF.CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo, TBAAInfo);
1160*fe013be4SDimitry Andric   llvm::Type *ElemTy = CGF.ConvertTypeForMem(E->getType()->getPointeeType());
1161*fe013be4SDimitry Andric   return Address(CGF.EmitScalarExpr(E), ElemTy, Align, IsKnownNonNull);
1162*fe013be4SDimitry Andric }
1163*fe013be4SDimitry Andric 
1164*fe013be4SDimitry Andric /// EmitPointerWithAlignment - Given an expression of pointer type, try to
1165*fe013be4SDimitry Andric /// derive a more accurate bound on the alignment of the pointer.
1166*fe013be4SDimitry Andric Address CodeGenFunction::EmitPointerWithAlignment(
1167*fe013be4SDimitry Andric     const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo,
1168*fe013be4SDimitry Andric     KnownNonNull_t IsKnownNonNull) {
1169*fe013be4SDimitry Andric   Address Addr =
1170*fe013be4SDimitry Andric       ::EmitPointerWithAlignment(E, BaseInfo, TBAAInfo, IsKnownNonNull, *this);
1171*fe013be4SDimitry Andric   if (IsKnownNonNull && !Addr.isKnownNonNull())
1172*fe013be4SDimitry Andric     Addr.setKnownNonNull();
1173*fe013be4SDimitry Andric   return Addr;
11740b57cec5SDimitry Andric }
11750b57cec5SDimitry Andric 
1176e8d8bef9SDimitry Andric llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
1177e8d8bef9SDimitry Andric   llvm::Value *V = RV.getScalarVal();
1178e8d8bef9SDimitry Andric   if (auto MPT = T->getAs<MemberPointerType>())
1179e8d8bef9SDimitry Andric     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1180e8d8bef9SDimitry Andric   return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1181e8d8bef9SDimitry Andric }
1182e8d8bef9SDimitry Andric 
11830b57cec5SDimitry Andric RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
11840b57cec5SDimitry Andric   if (Ty->isVoidType())
11850b57cec5SDimitry Andric     return RValue::get(nullptr);
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric   switch (getEvaluationKind(Ty)) {
11880b57cec5SDimitry Andric   case TEK_Complex: {
11890b57cec5SDimitry Andric     llvm::Type *EltTy =
11900b57cec5SDimitry Andric       ConvertType(Ty->castAs<ComplexType>()->getElementType());
11910b57cec5SDimitry Andric     llvm::Value *U = llvm::UndefValue::get(EltTy);
11920b57cec5SDimitry Andric     return RValue::getComplex(std::make_pair(U, U));
11930b57cec5SDimitry Andric   }
11940b57cec5SDimitry Andric 
11950b57cec5SDimitry Andric   // If this is a use of an undefined aggregate type, the aggregate must have an
11960b57cec5SDimitry Andric   // identifiable address.  Just because the contents of the value are undefined
11970b57cec5SDimitry Andric   // doesn't mean that the address can't be taken and compared.
11980b57cec5SDimitry Andric   case TEK_Aggregate: {
11990b57cec5SDimitry Andric     Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
12000b57cec5SDimitry Andric     return RValue::getAggregate(DestPtr);
12010b57cec5SDimitry Andric   }
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   case TEK_Scalar:
12040b57cec5SDimitry Andric     return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
12050b57cec5SDimitry Andric   }
12060b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
12070b57cec5SDimitry Andric }
12080b57cec5SDimitry Andric 
12090b57cec5SDimitry Andric RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
12100b57cec5SDimitry Andric                                               const char *Name) {
12110b57cec5SDimitry Andric   ErrorUnsupported(E, Name);
12120b57cec5SDimitry Andric   return GetUndefRValue(E->getType());
12130b57cec5SDimitry Andric }
12140b57cec5SDimitry Andric 
12150b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
12160b57cec5SDimitry Andric                                               const char *Name) {
12170b57cec5SDimitry Andric   ErrorUnsupported(E, Name);
121881ad6265SDimitry Andric   llvm::Type *ElTy = ConvertType(E->getType());
121981ad6265SDimitry Andric   llvm::Type *Ty = llvm::PointerType::getUnqual(ElTy);
122081ad6265SDimitry Andric   return MakeAddrLValue(
122181ad6265SDimitry Andric       Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType());
12220b57cec5SDimitry Andric }
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
12250b57cec5SDimitry Andric   const Expr *Base = Obj;
12260b57cec5SDimitry Andric   while (!isa<CXXThisExpr>(Base)) {
12270b57cec5SDimitry Andric     // The result of a dynamic_cast can be null.
12280b57cec5SDimitry Andric     if (isa<CXXDynamicCastExpr>(Base))
12290b57cec5SDimitry Andric       return false;
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<CastExpr>(Base)) {
12320b57cec5SDimitry Andric       Base = CE->getSubExpr();
12330b57cec5SDimitry Andric     } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
12340b57cec5SDimitry Andric       Base = PE->getSubExpr();
12350b57cec5SDimitry Andric     } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
12360b57cec5SDimitry Andric       if (UO->getOpcode() == UO_Extension)
12370b57cec5SDimitry Andric         Base = UO->getSubExpr();
12380b57cec5SDimitry Andric       else
12390b57cec5SDimitry Andric         return false;
12400b57cec5SDimitry Andric     } else {
12410b57cec5SDimitry Andric       return false;
12420b57cec5SDimitry Andric     }
12430b57cec5SDimitry Andric   }
12440b57cec5SDimitry Andric   return true;
12450b57cec5SDimitry Andric }
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
12480b57cec5SDimitry Andric   LValue LV;
12490b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
12500b57cec5SDimitry Andric     LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
12510b57cec5SDimitry Andric   else
12520b57cec5SDimitry Andric     LV = EmitLValue(E);
12530b57cec5SDimitry Andric   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
12540b57cec5SDimitry Andric     SanitizerSet SkippedChecks;
12550b57cec5SDimitry Andric     if (const auto *ME = dyn_cast<MemberExpr>(E)) {
12560b57cec5SDimitry Andric       bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
12570b57cec5SDimitry Andric       if (IsBaseCXXThis)
12580b57cec5SDimitry Andric         SkippedChecks.set(SanitizerKind::Alignment, true);
12590b57cec5SDimitry Andric       if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
12600b57cec5SDimitry Andric         SkippedChecks.set(SanitizerKind::Null, true);
12610b57cec5SDimitry Andric     }
1262480093f4SDimitry Andric     EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
1263480093f4SDimitry Andric                   LV.getAlignment(), SkippedChecks);
12640b57cec5SDimitry Andric   }
12650b57cec5SDimitry Andric   return LV;
12660b57cec5SDimitry Andric }
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric /// EmitLValue - Emit code to compute a designator that specifies the location
12690b57cec5SDimitry Andric /// of the expression.
12700b57cec5SDimitry Andric ///
12710b57cec5SDimitry Andric /// This can return one of two things: a simple address or a bitfield reference.
12720b57cec5SDimitry Andric /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
12730b57cec5SDimitry Andric /// an LLVM pointer type.
12740b57cec5SDimitry Andric ///
12750b57cec5SDimitry Andric /// If this returns a bitfield reference, nothing about the pointee type of the
12760b57cec5SDimitry Andric /// LLVM value is known: For example, it may not be a pointer to an integer.
12770b57cec5SDimitry Andric ///
12780b57cec5SDimitry Andric /// If this returns a normal address, and if the lvalue's C type is fixed size,
12790b57cec5SDimitry Andric /// this method guarantees that the returned pointer type will point to an LLVM
12800b57cec5SDimitry Andric /// type of the same size of the lvalue's type.  If the lvalue has a variable
12810b57cec5SDimitry Andric /// length type, this is not possible.
12820b57cec5SDimitry Andric ///
1283*fe013be4SDimitry Andric LValue CodeGenFunction::EmitLValue(const Expr *E,
1284*fe013be4SDimitry Andric                                    KnownNonNull_t IsKnownNonNull) {
1285*fe013be4SDimitry Andric   LValue LV = EmitLValueHelper(E, IsKnownNonNull);
1286*fe013be4SDimitry Andric   if (IsKnownNonNull && !LV.isKnownNonNull())
1287*fe013be4SDimitry Andric     LV.setKnownNonNull();
1288*fe013be4SDimitry Andric   return LV;
1289*fe013be4SDimitry Andric }
1290*fe013be4SDimitry Andric 
1291*fe013be4SDimitry Andric LValue CodeGenFunction::EmitLValueHelper(const Expr *E,
1292*fe013be4SDimitry Andric                                          KnownNonNull_t IsKnownNonNull) {
12930b57cec5SDimitry Andric   ApplyDebugLocation DL(*this, E);
12940b57cec5SDimitry Andric   switch (E->getStmtClass()) {
12950b57cec5SDimitry Andric   default: return EmitUnsupportedLValue(E, "l-value expression");
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric   case Expr::ObjCPropertyRefExprClass:
12980b57cec5SDimitry Andric     llvm_unreachable("cannot emit a property reference directly");
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric   case Expr::ObjCSelectorExprClass:
13010b57cec5SDimitry Andric     return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
13020b57cec5SDimitry Andric   case Expr::ObjCIsaExprClass:
13030b57cec5SDimitry Andric     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
13040b57cec5SDimitry Andric   case Expr::BinaryOperatorClass:
13050b57cec5SDimitry Andric     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
13060b57cec5SDimitry Andric   case Expr::CompoundAssignOperatorClass: {
13070b57cec5SDimitry Andric     QualType Ty = E->getType();
13080b57cec5SDimitry Andric     if (const AtomicType *AT = Ty->getAs<AtomicType>())
13090b57cec5SDimitry Andric       Ty = AT->getValueType();
13100b57cec5SDimitry Andric     if (!Ty->isAnyComplexType())
13110b57cec5SDimitry Andric       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
13120b57cec5SDimitry Andric     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
13130b57cec5SDimitry Andric   }
13140b57cec5SDimitry Andric   case Expr::CallExprClass:
13150b57cec5SDimitry Andric   case Expr::CXXMemberCallExprClass:
13160b57cec5SDimitry Andric   case Expr::CXXOperatorCallExprClass:
13170b57cec5SDimitry Andric   case Expr::UserDefinedLiteralClass:
13180b57cec5SDimitry Andric     return EmitCallExprLValue(cast<CallExpr>(E));
1319a7dea167SDimitry Andric   case Expr::CXXRewrittenBinaryOperatorClass:
1320*fe013be4SDimitry Andric     return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
1321*fe013be4SDimitry Andric                       IsKnownNonNull);
13220b57cec5SDimitry Andric   case Expr::VAArgExprClass:
13230b57cec5SDimitry Andric     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
13240b57cec5SDimitry Andric   case Expr::DeclRefExprClass:
13250b57cec5SDimitry Andric     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
13265ffd83dbSDimitry Andric   case Expr::ConstantExprClass: {
13275ffd83dbSDimitry Andric     const ConstantExpr *CE = cast<ConstantExpr>(E);
13285ffd83dbSDimitry Andric     if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
13295ffd83dbSDimitry Andric       QualType RetType = cast<CallExpr>(CE->getSubExpr()->IgnoreImplicit())
13300eae32dcSDimitry Andric                              ->getCallReturnType(getContext())
13310eae32dcSDimitry Andric                              ->getPointeeType();
13325ffd83dbSDimitry Andric       return MakeNaturalAlignAddrLValue(Result, RetType);
13335ffd83dbSDimitry Andric     }
1334*fe013be4SDimitry Andric     return EmitLValue(cast<ConstantExpr>(E)->getSubExpr(), IsKnownNonNull);
13355ffd83dbSDimitry Andric   }
13360b57cec5SDimitry Andric   case Expr::ParenExprClass:
1337*fe013be4SDimitry Andric     return EmitLValue(cast<ParenExpr>(E)->getSubExpr(), IsKnownNonNull);
13380b57cec5SDimitry Andric   case Expr::GenericSelectionExprClass:
1339*fe013be4SDimitry Andric     return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr(),
1340*fe013be4SDimitry Andric                       IsKnownNonNull);
13410b57cec5SDimitry Andric   case Expr::PredefinedExprClass:
13420b57cec5SDimitry Andric     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
13430b57cec5SDimitry Andric   case Expr::StringLiteralClass:
13440b57cec5SDimitry Andric     return EmitStringLiteralLValue(cast<StringLiteral>(E));
13450b57cec5SDimitry Andric   case Expr::ObjCEncodeExprClass:
13460b57cec5SDimitry Andric     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
13470b57cec5SDimitry Andric   case Expr::PseudoObjectExprClass:
13480b57cec5SDimitry Andric     return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
13490b57cec5SDimitry Andric   case Expr::InitListExprClass:
13500b57cec5SDimitry Andric     return EmitInitListLValue(cast<InitListExpr>(E));
13510b57cec5SDimitry Andric   case Expr::CXXTemporaryObjectExprClass:
13520b57cec5SDimitry Andric   case Expr::CXXConstructExprClass:
13530b57cec5SDimitry Andric     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
13540b57cec5SDimitry Andric   case Expr::CXXBindTemporaryExprClass:
13550b57cec5SDimitry Andric     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
13560b57cec5SDimitry Andric   case Expr::CXXUuidofExprClass:
13570b57cec5SDimitry Andric     return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
13580b57cec5SDimitry Andric   case Expr::LambdaExprClass:
13590b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric   case Expr::ExprWithCleanupsClass: {
13620b57cec5SDimitry Andric     const auto *cleanups = cast<ExprWithCleanups>(E);
13630b57cec5SDimitry Andric     RunCleanupsScope Scope(*this);
1364*fe013be4SDimitry Andric     LValue LV = EmitLValue(cleanups->getSubExpr(), IsKnownNonNull);
13650b57cec5SDimitry Andric     if (LV.isSimple()) {
13660b57cec5SDimitry Andric       // Defend against branches out of gnu statement expressions surrounded by
13670b57cec5SDimitry Andric       // cleanups.
13680eae32dcSDimitry Andric       Address Addr = LV.getAddress(*this);
13690eae32dcSDimitry Andric       llvm::Value *V = Addr.getPointer();
13700b57cec5SDimitry Andric       Scope.ForceCleanup({&V});
1371*fe013be4SDimitry Andric       return LValue::MakeAddr(Addr.withPointer(V, Addr.isKnownNonNull()),
1372*fe013be4SDimitry Andric                               LV.getType(), getContext(), LV.getBaseInfo(),
1373*fe013be4SDimitry Andric                               LV.getTBAAInfo());
13740b57cec5SDimitry Andric     }
13750b57cec5SDimitry Andric     // FIXME: Is it possible to create an ExprWithCleanups that produces a
13760b57cec5SDimitry Andric     // bitfield lvalue or some other non-simple lvalue?
13770b57cec5SDimitry Andric     return LV;
13780b57cec5SDimitry Andric   }
13790b57cec5SDimitry Andric 
13800b57cec5SDimitry Andric   case Expr::CXXDefaultArgExprClass: {
13810b57cec5SDimitry Andric     auto *DAE = cast<CXXDefaultArgExpr>(E);
13820b57cec5SDimitry Andric     CXXDefaultArgExprScope Scope(*this, DAE);
1383*fe013be4SDimitry Andric     return EmitLValue(DAE->getExpr(), IsKnownNonNull);
13840b57cec5SDimitry Andric   }
13850b57cec5SDimitry Andric   case Expr::CXXDefaultInitExprClass: {
13860b57cec5SDimitry Andric     auto *DIE = cast<CXXDefaultInitExpr>(E);
13870b57cec5SDimitry Andric     CXXDefaultInitExprScope Scope(*this, DIE);
1388*fe013be4SDimitry Andric     return EmitLValue(DIE->getExpr(), IsKnownNonNull);
13890b57cec5SDimitry Andric   }
13900b57cec5SDimitry Andric   case Expr::CXXTypeidExprClass:
13910b57cec5SDimitry Andric     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   case Expr::ObjCMessageExprClass:
13940b57cec5SDimitry Andric     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
13950b57cec5SDimitry Andric   case Expr::ObjCIvarRefExprClass:
13960b57cec5SDimitry Andric     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
13970b57cec5SDimitry Andric   case Expr::StmtExprClass:
13980b57cec5SDimitry Andric     return EmitStmtExprLValue(cast<StmtExpr>(E));
13990b57cec5SDimitry Andric   case Expr::UnaryOperatorClass:
14000b57cec5SDimitry Andric     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
14010b57cec5SDimitry Andric   case Expr::ArraySubscriptExprClass:
14020b57cec5SDimitry Andric     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
14035ffd83dbSDimitry Andric   case Expr::MatrixSubscriptExprClass:
14045ffd83dbSDimitry Andric     return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
14050b57cec5SDimitry Andric   case Expr::OMPArraySectionExprClass:
14060b57cec5SDimitry Andric     return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
14070b57cec5SDimitry Andric   case Expr::ExtVectorElementExprClass:
14080b57cec5SDimitry Andric     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1409bdd1243dSDimitry Andric   case Expr::CXXThisExprClass:
1410bdd1243dSDimitry Andric     return MakeAddrLValue(LoadCXXThisAddress(), E->getType());
14110b57cec5SDimitry Andric   case Expr::MemberExprClass:
14120b57cec5SDimitry Andric     return EmitMemberExpr(cast<MemberExpr>(E));
14130b57cec5SDimitry Andric   case Expr::CompoundLiteralExprClass:
14140b57cec5SDimitry Andric     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
14150b57cec5SDimitry Andric   case Expr::ConditionalOperatorClass:
14160b57cec5SDimitry Andric     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
14170b57cec5SDimitry Andric   case Expr::BinaryConditionalOperatorClass:
14180b57cec5SDimitry Andric     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
14190b57cec5SDimitry Andric   case Expr::ChooseExprClass:
1420*fe013be4SDimitry Andric     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(), IsKnownNonNull);
14210b57cec5SDimitry Andric   case Expr::OpaqueValueExprClass:
14220b57cec5SDimitry Andric     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
14230b57cec5SDimitry Andric   case Expr::SubstNonTypeTemplateParmExprClass:
1424*fe013be4SDimitry Andric     return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
1425*fe013be4SDimitry Andric                       IsKnownNonNull);
14260b57cec5SDimitry Andric   case Expr::ImplicitCastExprClass:
14270b57cec5SDimitry Andric   case Expr::CStyleCastExprClass:
14280b57cec5SDimitry Andric   case Expr::CXXFunctionalCastExprClass:
14290b57cec5SDimitry Andric   case Expr::CXXStaticCastExprClass:
14300b57cec5SDimitry Andric   case Expr::CXXDynamicCastExprClass:
14310b57cec5SDimitry Andric   case Expr::CXXReinterpretCastExprClass:
14320b57cec5SDimitry Andric   case Expr::CXXConstCastExprClass:
14335ffd83dbSDimitry Andric   case Expr::CXXAddrspaceCastExprClass:
14340b57cec5SDimitry Andric   case Expr::ObjCBridgedCastExprClass:
14350b57cec5SDimitry Andric     return EmitCastLValue(cast<CastExpr>(E));
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric   case Expr::MaterializeTemporaryExprClass:
14380b57cec5SDimitry Andric     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
14390b57cec5SDimitry Andric 
14400b57cec5SDimitry Andric   case Expr::CoawaitExprClass:
14410b57cec5SDimitry Andric     return EmitCoawaitLValue(cast<CoawaitExpr>(E));
14420b57cec5SDimitry Andric   case Expr::CoyieldExprClass:
14430b57cec5SDimitry Andric     return EmitCoyieldLValue(cast<CoyieldExpr>(E));
14440b57cec5SDimitry Andric   }
14450b57cec5SDimitry Andric }
14460b57cec5SDimitry Andric 
14470b57cec5SDimitry Andric /// Given an object of the given canonical type, can we safely copy a
14480b57cec5SDimitry Andric /// value out of it based on its initializer?
14490b57cec5SDimitry Andric static bool isConstantEmittableObjectType(QualType type) {
14500b57cec5SDimitry Andric   assert(type.isCanonical());
14510b57cec5SDimitry Andric   assert(!type->isReferenceType());
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   // Must be const-qualified but non-volatile.
14540b57cec5SDimitry Andric   Qualifiers qs = type.getLocalQualifiers();
14550b57cec5SDimitry Andric   if (!qs.hasConst() || qs.hasVolatile()) return false;
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   // Otherwise, all object types satisfy this except C++ classes with
14580b57cec5SDimitry Andric   // mutable subobjects or non-trivial copy/destroy behavior.
14590b57cec5SDimitry Andric   if (const auto *RT = dyn_cast<RecordType>(type))
14600b57cec5SDimitry Andric     if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
14610b57cec5SDimitry Andric       if (RD->hasMutableFields() || !RD->isTrivial())
14620b57cec5SDimitry Andric         return false;
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric   return true;
14650b57cec5SDimitry Andric }
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric /// Can we constant-emit a load of a reference to a variable of the
14680b57cec5SDimitry Andric /// given type?  This is different from predicates like
14690b57cec5SDimitry Andric /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
14700b57cec5SDimitry Andric /// in situations that don't necessarily satisfy the language's rules
14710b57cec5SDimitry Andric /// for this (e.g. C++'s ODR-use rules).  For example, we want to able
14720b57cec5SDimitry Andric /// to do this with const float variables even if those variables
14730b57cec5SDimitry Andric /// aren't marked 'constexpr'.
14740b57cec5SDimitry Andric enum ConstantEmissionKind {
14750b57cec5SDimitry Andric   CEK_None,
14760b57cec5SDimitry Andric   CEK_AsReferenceOnly,
14770b57cec5SDimitry Andric   CEK_AsValueOrReference,
14780b57cec5SDimitry Andric   CEK_AsValueOnly
14790b57cec5SDimitry Andric };
14800b57cec5SDimitry Andric static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
14810b57cec5SDimitry Andric   type = type.getCanonicalType();
14820b57cec5SDimitry Andric   if (const auto *ref = dyn_cast<ReferenceType>(type)) {
14830b57cec5SDimitry Andric     if (isConstantEmittableObjectType(ref->getPointeeType()))
14840b57cec5SDimitry Andric       return CEK_AsValueOrReference;
14850b57cec5SDimitry Andric     return CEK_AsReferenceOnly;
14860b57cec5SDimitry Andric   }
14870b57cec5SDimitry Andric   if (isConstantEmittableObjectType(type))
14880b57cec5SDimitry Andric     return CEK_AsValueOnly;
14890b57cec5SDimitry Andric   return CEK_None;
14900b57cec5SDimitry Andric }
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric /// Try to emit a reference to the given value without producing it as
14930b57cec5SDimitry Andric /// an l-value.  This is just an optimization, but it avoids us needing
14940b57cec5SDimitry Andric /// to emit global copies of variables if they're named without triggering
14950b57cec5SDimitry Andric /// a formal use in a context where we can't emit a direct reference to them,
14960b57cec5SDimitry Andric /// for instance if a block or lambda or a member of a local class uses a
14970b57cec5SDimitry Andric /// const int variable or constexpr variable from an enclosing function.
14980b57cec5SDimitry Andric CodeGenFunction::ConstantEmission
14990b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
15000b57cec5SDimitry Andric   ValueDecl *value = refExpr->getDecl();
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric   // The value needs to be an enum constant or a constant variable.
15030b57cec5SDimitry Andric   ConstantEmissionKind CEK;
15040b57cec5SDimitry Andric   if (isa<ParmVarDecl>(value)) {
15050b57cec5SDimitry Andric     CEK = CEK_None;
15060b57cec5SDimitry Andric   } else if (auto *var = dyn_cast<VarDecl>(value)) {
15070b57cec5SDimitry Andric     CEK = checkVarTypeForConstantEmission(var->getType());
15080b57cec5SDimitry Andric   } else if (isa<EnumConstantDecl>(value)) {
15090b57cec5SDimitry Andric     CEK = CEK_AsValueOnly;
15100b57cec5SDimitry Andric   } else {
15110b57cec5SDimitry Andric     CEK = CEK_None;
15120b57cec5SDimitry Andric   }
15130b57cec5SDimitry Andric   if (CEK == CEK_None) return ConstantEmission();
15140b57cec5SDimitry Andric 
15150b57cec5SDimitry Andric   Expr::EvalResult result;
15160b57cec5SDimitry Andric   bool resultIsReference;
15170b57cec5SDimitry Andric   QualType resultType;
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric   // It's best to evaluate all the way as an r-value if that's permitted.
15200b57cec5SDimitry Andric   if (CEK != CEK_AsReferenceOnly &&
15210b57cec5SDimitry Andric       refExpr->EvaluateAsRValue(result, getContext())) {
15220b57cec5SDimitry Andric     resultIsReference = false;
15230b57cec5SDimitry Andric     resultType = refExpr->getType();
15240b57cec5SDimitry Andric 
15250b57cec5SDimitry Andric   // Otherwise, try to evaluate as an l-value.
15260b57cec5SDimitry Andric   } else if (CEK != CEK_AsValueOnly &&
15270b57cec5SDimitry Andric              refExpr->EvaluateAsLValue(result, getContext())) {
15280b57cec5SDimitry Andric     resultIsReference = true;
15290b57cec5SDimitry Andric     resultType = value->getType();
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric   // Failure.
15320b57cec5SDimitry Andric   } else {
15330b57cec5SDimitry Andric     return ConstantEmission();
15340b57cec5SDimitry Andric   }
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric   // In any case, if the initializer has side-effects, abandon ship.
15370b57cec5SDimitry Andric   if (result.HasSideEffects)
15380b57cec5SDimitry Andric     return ConstantEmission();
15390b57cec5SDimitry Andric 
1540e8d8bef9SDimitry Andric   // In CUDA/HIP device compilation, a lambda may capture a reference variable
1541e8d8bef9SDimitry Andric   // referencing a global host variable by copy. In this case the lambda should
1542e8d8bef9SDimitry Andric   // make a copy of the value of the global host variable. The DRE of the
1543e8d8bef9SDimitry Andric   // captured reference variable cannot be emitted as load from the host
1544e8d8bef9SDimitry Andric   // global variable as compile time constant, since the host variable is not
1545e8d8bef9SDimitry Andric   // accessible on device. The DRE of the captured reference variable has to be
1546e8d8bef9SDimitry Andric   // loaded from captures.
1547e8d8bef9SDimitry Andric   if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
1548e8d8bef9SDimitry Andric       refExpr->refersToEnclosingVariableOrCapture()) {
1549e8d8bef9SDimitry Andric     auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
1550e8d8bef9SDimitry Andric     if (MD && MD->getParent()->isLambda() &&
1551e8d8bef9SDimitry Andric         MD->getOverloadedOperator() == OO_Call) {
1552e8d8bef9SDimitry Andric       const APValue::LValueBase &base = result.Val.getLValueBase();
1553e8d8bef9SDimitry Andric       if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1554e8d8bef9SDimitry Andric         if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1555e8d8bef9SDimitry Andric           if (!VD->hasAttr<CUDADeviceAttr>()) {
1556e8d8bef9SDimitry Andric             return ConstantEmission();
1557e8d8bef9SDimitry Andric           }
1558e8d8bef9SDimitry Andric         }
1559e8d8bef9SDimitry Andric       }
1560e8d8bef9SDimitry Andric     }
1561e8d8bef9SDimitry Andric   }
1562e8d8bef9SDimitry Andric 
15630b57cec5SDimitry Andric   // Emit as a constant.
15640b57cec5SDimitry Andric   auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
15650b57cec5SDimitry Andric                                                result.Val, resultType);
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric   // Make sure we emit a debug reference to the global variable.
15680b57cec5SDimitry Andric   // This should probably fire even for
15690b57cec5SDimitry Andric   if (isa<VarDecl>(value)) {
15700b57cec5SDimitry Andric     if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
15710b57cec5SDimitry Andric       EmitDeclRefExprDbgValue(refExpr, result.Val);
15720b57cec5SDimitry Andric   } else {
15730b57cec5SDimitry Andric     assert(isa<EnumConstantDecl>(value));
15740b57cec5SDimitry Andric     EmitDeclRefExprDbgValue(refExpr, result.Val);
15750b57cec5SDimitry Andric   }
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric   // If we emitted a reference constant, we need to dereference that.
15780b57cec5SDimitry Andric   if (resultIsReference)
15790b57cec5SDimitry Andric     return ConstantEmission::forReference(C);
15800b57cec5SDimitry Andric 
15810b57cec5SDimitry Andric   return ConstantEmission::forValue(C);
15820b57cec5SDimitry Andric }
15830b57cec5SDimitry Andric 
15840b57cec5SDimitry Andric static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
15850b57cec5SDimitry Andric                                                         const MemberExpr *ME) {
15860b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
15870b57cec5SDimitry Andric     // Try to emit static variable member expressions as DREs.
15880b57cec5SDimitry Andric     return DeclRefExpr::Create(
15890b57cec5SDimitry Andric         CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
15900b57cec5SDimitry Andric         /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
15910b57cec5SDimitry Andric         ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
15920b57cec5SDimitry Andric   }
15930b57cec5SDimitry Andric   return nullptr;
15940b57cec5SDimitry Andric }
15950b57cec5SDimitry Andric 
15960b57cec5SDimitry Andric CodeGenFunction::ConstantEmission
15970b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
15980b57cec5SDimitry Andric   if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
15990b57cec5SDimitry Andric     return tryEmitAsConstant(DRE);
16000b57cec5SDimitry Andric   return ConstantEmission();
16010b57cec5SDimitry Andric }
16020b57cec5SDimitry Andric 
16030b57cec5SDimitry Andric llvm::Value *CodeGenFunction::emitScalarConstant(
16040b57cec5SDimitry Andric     const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
16050b57cec5SDimitry Andric   assert(Constant && "not a constant");
16060b57cec5SDimitry Andric   if (Constant.isReference())
16070b57cec5SDimitry Andric     return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
16080b57cec5SDimitry Andric                             E->getExprLoc())
16090b57cec5SDimitry Andric         .getScalarVal();
16100b57cec5SDimitry Andric   return Constant.getValue();
16110b57cec5SDimitry Andric }
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
16140b57cec5SDimitry Andric                                                SourceLocation Loc) {
1615480093f4SDimitry Andric   return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
16160b57cec5SDimitry Andric                           lvalue.getType(), Loc, lvalue.getBaseInfo(),
16170b57cec5SDimitry Andric                           lvalue.getTBAAInfo(), lvalue.isNontemporal());
16180b57cec5SDimitry Andric }
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric static bool hasBooleanRepresentation(QualType Ty) {
16210b57cec5SDimitry Andric   if (Ty->isBooleanType())
16220b57cec5SDimitry Andric     return true;
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric   if (const EnumType *ET = Ty->getAs<EnumType>())
16250b57cec5SDimitry Andric     return ET->getDecl()->getIntegerType()->isBooleanType();
16260b57cec5SDimitry Andric 
16270b57cec5SDimitry Andric   if (const AtomicType *AT = Ty->getAs<AtomicType>())
16280b57cec5SDimitry Andric     return hasBooleanRepresentation(AT->getValueType());
16290b57cec5SDimitry Andric 
16300b57cec5SDimitry Andric   return false;
16310b57cec5SDimitry Andric }
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
16340b57cec5SDimitry Andric                             llvm::APInt &Min, llvm::APInt &End,
16350b57cec5SDimitry Andric                             bool StrictEnums, bool IsBool) {
16360b57cec5SDimitry Andric   const EnumType *ET = Ty->getAs<EnumType>();
16370b57cec5SDimitry Andric   bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
16380b57cec5SDimitry Andric                                 ET && !ET->getDecl()->isFixed();
16390b57cec5SDimitry Andric   if (!IsBool && !IsRegularCPlusPlusEnum)
16400b57cec5SDimitry Andric     return false;
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric   if (IsBool) {
16430b57cec5SDimitry Andric     Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
16440b57cec5SDimitry Andric     End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
16450b57cec5SDimitry Andric   } else {
16460b57cec5SDimitry Andric     const EnumDecl *ED = ET->getDecl();
1647bdd1243dSDimitry Andric     ED->getValueRange(End, Min);
16480b57cec5SDimitry Andric   }
16490b57cec5SDimitry Andric   return true;
16500b57cec5SDimitry Andric }
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
16530b57cec5SDimitry Andric   llvm::APInt Min, End;
16540b57cec5SDimitry Andric   if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
16550b57cec5SDimitry Andric                        hasBooleanRepresentation(Ty)))
16560b57cec5SDimitry Andric     return nullptr;
16570b57cec5SDimitry Andric 
16580b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
16590b57cec5SDimitry Andric   return MDHelper.createRange(Min, End);
16600b57cec5SDimitry Andric }
16610b57cec5SDimitry Andric 
16620b57cec5SDimitry Andric bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
16630b57cec5SDimitry Andric                                            SourceLocation Loc) {
16640b57cec5SDimitry Andric   bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
16650b57cec5SDimitry Andric   bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
16660b57cec5SDimitry Andric   if (!HasBoolCheck && !HasEnumCheck)
16670b57cec5SDimitry Andric     return false;
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric   bool IsBool = hasBooleanRepresentation(Ty) ||
16700b57cec5SDimitry Andric                 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
16710b57cec5SDimitry Andric   bool NeedsBoolCheck = HasBoolCheck && IsBool;
16720b57cec5SDimitry Andric   bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
16730b57cec5SDimitry Andric   if (!NeedsBoolCheck && !NeedsEnumCheck)
16740b57cec5SDimitry Andric     return false;
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric   // Single-bit booleans don't need to be checked. Special-case this to avoid
16770b57cec5SDimitry Andric   // a bit width mismatch when handling bitfield values. This is handled by
16780b57cec5SDimitry Andric   // EmitFromMemory for the non-bitfield case.
16790b57cec5SDimitry Andric   if (IsBool &&
16800b57cec5SDimitry Andric       cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
16810b57cec5SDimitry Andric     return false;
16820b57cec5SDimitry Andric 
16830b57cec5SDimitry Andric   llvm::APInt Min, End;
16840b57cec5SDimitry Andric   if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
16850b57cec5SDimitry Andric     return true;
16860b57cec5SDimitry Andric 
16870b57cec5SDimitry Andric   auto &Ctx = getLLVMContext();
16880b57cec5SDimitry Andric   SanitizerScope SanScope(this);
16890b57cec5SDimitry Andric   llvm::Value *Check;
16900b57cec5SDimitry Andric   --End;
16910b57cec5SDimitry Andric   if (!Min) {
16920b57cec5SDimitry Andric     Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
16930b57cec5SDimitry Andric   } else {
16940b57cec5SDimitry Andric     llvm::Value *Upper =
16950b57cec5SDimitry Andric         Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
16960b57cec5SDimitry Andric     llvm::Value *Lower =
16970b57cec5SDimitry Andric         Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
16980b57cec5SDimitry Andric     Check = Builder.CreateAnd(Upper, Lower);
16990b57cec5SDimitry Andric   }
17000b57cec5SDimitry Andric   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
17010b57cec5SDimitry Andric                                   EmitCheckTypeDescriptor(Ty)};
17020b57cec5SDimitry Andric   SanitizerMask Kind =
17030b57cec5SDimitry Andric       NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
17040b57cec5SDimitry Andric   EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
17050b57cec5SDimitry Andric             StaticArgs, EmitCheckValue(Value));
17060b57cec5SDimitry Andric   return true;
17070b57cec5SDimitry Andric }
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
17100b57cec5SDimitry Andric                                                QualType Ty,
17110b57cec5SDimitry Andric                                                SourceLocation Loc,
17120b57cec5SDimitry Andric                                                LValueBaseInfo BaseInfo,
17130b57cec5SDimitry Andric                                                TBAAAccessInfo TBAAInfo,
17140b57cec5SDimitry Andric                                                bool isNontemporal) {
1715bdd1243dSDimitry Andric   if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getPointer()))
1716bdd1243dSDimitry Andric     if (GV->isThreadLocal())
1717*fe013be4SDimitry Andric       Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
1718*fe013be4SDimitry Andric                               NotKnownNonNull);
1719bdd1243dSDimitry Andric 
172081ad6265SDimitry Andric   if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
172181ad6265SDimitry Andric     // Boolean vectors use `iN` as storage type.
172281ad6265SDimitry Andric     if (ClangVecTy->isExtVectorBoolType()) {
172381ad6265SDimitry Andric       llvm::Type *ValTy = ConvertType(Ty);
172481ad6265SDimitry Andric       unsigned ValNumElems =
172581ad6265SDimitry Andric           cast<llvm::FixedVectorType>(ValTy)->getNumElements();
172681ad6265SDimitry Andric       // Load the `iP` storage object (P is the padded vector size).
172781ad6265SDimitry Andric       auto *RawIntV = Builder.CreateLoad(Addr, Volatile, "load_bits");
172881ad6265SDimitry Andric       const auto *RawIntTy = RawIntV->getType();
172981ad6265SDimitry Andric       assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors");
173081ad6265SDimitry Andric       // Bitcast iP --> <P x i1>.
173181ad6265SDimitry Andric       auto *PaddedVecTy = llvm::FixedVectorType::get(
173281ad6265SDimitry Andric           Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
173381ad6265SDimitry Andric       llvm::Value *V = Builder.CreateBitCast(RawIntV, PaddedVecTy);
173481ad6265SDimitry Andric       // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
173581ad6265SDimitry Andric       V = emitBoolVecConversion(V, ValNumElems, "extractvec");
17360b57cec5SDimitry Andric 
173781ad6265SDimitry Andric       return EmitFromMemory(V, Ty);
173881ad6265SDimitry Andric     }
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric     // Handle vectors of size 3 like size 4 for better performance.
174181ad6265SDimitry Andric     const llvm::Type *EltTy = Addr.getElementType();
174281ad6265SDimitry Andric     const auto *VTy = cast<llvm::FixedVectorType>(EltTy);
174381ad6265SDimitry Andric 
174481ad6265SDimitry Andric     if (!CGM.getCodeGenOpts().PreserveVec3Type && VTy->getNumElements() == 3) {
17450b57cec5SDimitry Andric 
174681ad6265SDimitry Andric       llvm::VectorType *vec4Ty =
174781ad6265SDimitry Andric           llvm::FixedVectorType::get(VTy->getElementType(), 4);
1748*fe013be4SDimitry Andric       Address Cast = Addr.withElementType(vec4Ty);
17490b57cec5SDimitry Andric       // Now load value.
17500b57cec5SDimitry Andric       llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
17510b57cec5SDimitry Andric 
17520b57cec5SDimitry Andric       // Shuffle vector to get vec3.
175381ad6265SDimitry Andric       V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2}, "extractVec");
17540b57cec5SDimitry Andric       return EmitFromMemory(V, Ty);
17550b57cec5SDimitry Andric     }
17560b57cec5SDimitry Andric   }
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric   // Atomic operations have to be done on integral types.
17590b57cec5SDimitry Andric   LValue AtomicLValue =
17600b57cec5SDimitry Andric       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
17610b57cec5SDimitry Andric   if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
17620b57cec5SDimitry Andric     return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
17630b57cec5SDimitry Andric   }
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric   llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
17660b57cec5SDimitry Andric   if (isNontemporal) {
17670b57cec5SDimitry Andric     llvm::MDNode *Node = llvm::MDNode::get(
17680b57cec5SDimitry Andric         Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1769*fe013be4SDimitry Andric     Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
17700b57cec5SDimitry Andric   }
17710b57cec5SDimitry Andric 
17720b57cec5SDimitry Andric   CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   if (EmitScalarRangeCheck(Load, Ty, Loc)) {
17750b57cec5SDimitry Andric     // In order to prevent the optimizer from throwing away the check, don't
17760b57cec5SDimitry Andric     // attach range metadata to the load.
17770b57cec5SDimitry Andric   } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1778bdd1243dSDimitry Andric     if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
17790b57cec5SDimitry Andric       Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1780bdd1243dSDimitry Andric       Load->setMetadata(llvm::LLVMContext::MD_noundef,
1781bdd1243dSDimitry Andric                         llvm::MDNode::get(getLLVMContext(), std::nullopt));
1782bdd1243dSDimitry Andric     }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric   return EmitFromMemory(Load, Ty);
17850b57cec5SDimitry Andric }
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
17880b57cec5SDimitry Andric   // Bool has a different representation in memory than in registers.
17890b57cec5SDimitry Andric   if (hasBooleanRepresentation(Ty)) {
17900b57cec5SDimitry Andric     // This should really always be an i1, but sometimes it's already
17910b57cec5SDimitry Andric     // an i8, and it's awkward to track those cases down.
17920b57cec5SDimitry Andric     if (Value->getType()->isIntegerTy(1))
17930b57cec5SDimitry Andric       return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
17940b57cec5SDimitry Andric     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
17950b57cec5SDimitry Andric            "wrong value rep of bool");
17960b57cec5SDimitry Andric   }
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric   return Value;
17990b57cec5SDimitry Andric }
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
18020b57cec5SDimitry Andric   // Bool has a different representation in memory than in registers.
18030b57cec5SDimitry Andric   if (hasBooleanRepresentation(Ty)) {
18040b57cec5SDimitry Andric     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
18050b57cec5SDimitry Andric            "wrong value rep of bool");
18060b57cec5SDimitry Andric     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
18070b57cec5SDimitry Andric   }
180881ad6265SDimitry Andric   if (Ty->isExtVectorBoolType()) {
180981ad6265SDimitry Andric     const auto *RawIntTy = Value->getType();
181081ad6265SDimitry Andric     // Bitcast iP --> <P x i1>.
181181ad6265SDimitry Andric     auto *PaddedVecTy = llvm::FixedVectorType::get(
181281ad6265SDimitry Andric         Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
181381ad6265SDimitry Andric     auto *V = Builder.CreateBitCast(Value, PaddedVecTy);
181481ad6265SDimitry Andric     // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
181581ad6265SDimitry Andric     llvm::Type *ValTy = ConvertType(Ty);
181681ad6265SDimitry Andric     unsigned ValNumElems = cast<llvm::FixedVectorType>(ValTy)->getNumElements();
181781ad6265SDimitry Andric     return emitBoolVecConversion(V, ValNumElems, "extractvec");
181881ad6265SDimitry Andric   }
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   return Value;
18210b57cec5SDimitry Andric }
18220b57cec5SDimitry Andric 
18235ffd83dbSDimitry Andric // Convert the pointer of \p Addr to a pointer to a vector (the value type of
18245ffd83dbSDimitry Andric // MatrixType), if it points to a array (the memory type of MatrixType).
18255ffd83dbSDimitry Andric static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF,
18265ffd83dbSDimitry Andric                                          bool IsVector = true) {
18270eae32dcSDimitry Andric   auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
18285ffd83dbSDimitry Andric   if (ArrayTy && IsVector) {
18295ffd83dbSDimitry Andric     auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
18305ffd83dbSDimitry Andric                                                 ArrayTy->getNumElements());
18315ffd83dbSDimitry Andric 
1832*fe013be4SDimitry Andric     return Addr.withElementType(VectorTy);
18335ffd83dbSDimitry Andric   }
18340eae32dcSDimitry Andric   auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
18355ffd83dbSDimitry Andric   if (VectorTy && !IsVector) {
1836e8d8bef9SDimitry Andric     auto *ArrayTy = llvm::ArrayType::get(
1837e8d8bef9SDimitry Andric         VectorTy->getElementType(),
1838e8d8bef9SDimitry Andric         cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
18395ffd83dbSDimitry Andric 
1840*fe013be4SDimitry Andric     return Addr.withElementType(ArrayTy);
18415ffd83dbSDimitry Andric   }
18425ffd83dbSDimitry Andric 
18435ffd83dbSDimitry Andric   return Addr;
18445ffd83dbSDimitry Andric }
18455ffd83dbSDimitry Andric 
18465ffd83dbSDimitry Andric // Emit a store of a matrix LValue. This may require casting the original
18475ffd83dbSDimitry Andric // pointer to memory address (ArrayType) to a pointer to the value type
18485ffd83dbSDimitry Andric // (VectorType).
18495ffd83dbSDimitry Andric static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
18505ffd83dbSDimitry Andric                                     bool isInit, CodeGenFunction &CGF) {
18515ffd83dbSDimitry Andric   Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF,
18525ffd83dbSDimitry Andric                                            value->getType()->isVectorTy());
18535ffd83dbSDimitry Andric   CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
18545ffd83dbSDimitry Andric                         lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
18555ffd83dbSDimitry Andric                         lvalue.isNontemporal());
18565ffd83dbSDimitry Andric }
18575ffd83dbSDimitry Andric 
18580b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
18590b57cec5SDimitry Andric                                         bool Volatile, QualType Ty,
18600b57cec5SDimitry Andric                                         LValueBaseInfo BaseInfo,
18610b57cec5SDimitry Andric                                         TBAAAccessInfo TBAAInfo,
18620b57cec5SDimitry Andric                                         bool isInit, bool isNontemporal) {
1863bdd1243dSDimitry Andric   if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getPointer()))
1864bdd1243dSDimitry Andric     if (GV->isThreadLocal())
1865*fe013be4SDimitry Andric       Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
1866*fe013be4SDimitry Andric                               NotKnownNonNull);
1867bdd1243dSDimitry Andric 
18680b57cec5SDimitry Andric   llvm::Type *SrcTy = Value->getType();
186981ad6265SDimitry Andric   if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
187081ad6265SDimitry Andric     auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy);
187181ad6265SDimitry Andric     if (VecTy && ClangVecTy->isExtVectorBoolType()) {
187281ad6265SDimitry Andric       auto *MemIntTy = cast<llvm::IntegerType>(Addr.getElementType());
187381ad6265SDimitry Andric       // Expand to the memory bit width.
187481ad6265SDimitry Andric       unsigned MemNumElems = MemIntTy->getPrimitiveSizeInBits();
187581ad6265SDimitry Andric       // <N x i1> --> <P x i1>.
187681ad6265SDimitry Andric       Value = emitBoolVecConversion(Value, MemNumElems, "insertvec");
187781ad6265SDimitry Andric       // <P x i1> --> iP.
187881ad6265SDimitry Andric       Value = Builder.CreateBitCast(Value, MemIntTy);
187981ad6265SDimitry Andric     } else if (!CGM.getCodeGenOpts().PreserveVec3Type) {
18800b57cec5SDimitry Andric       // Handle vec3 special.
1881e8d8bef9SDimitry Andric       if (VecTy && cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) {
18820b57cec5SDimitry Andric         // Our source is a vec3, do a shuffle vector to make it a vec4.
1883e8d8bef9SDimitry Andric         Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
18845ffd83dbSDimitry Andric                                             "extractVec");
18855ffd83dbSDimitry Andric         SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
18860b57cec5SDimitry Andric       }
18870b57cec5SDimitry Andric       if (Addr.getElementType() != SrcTy) {
1888*fe013be4SDimitry Andric         Addr = Addr.withElementType(SrcTy);
18890b57cec5SDimitry Andric       }
18900b57cec5SDimitry Andric     }
18910b57cec5SDimitry Andric   }
18920b57cec5SDimitry Andric 
18930b57cec5SDimitry Andric   Value = EmitToMemory(Value, Ty);
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric   LValue AtomicLValue =
18960b57cec5SDimitry Andric       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
18970b57cec5SDimitry Andric   if (Ty->isAtomicType() ||
18980b57cec5SDimitry Andric       (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
18990b57cec5SDimitry Andric     EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
19000b57cec5SDimitry Andric     return;
19010b57cec5SDimitry Andric   }
19020b57cec5SDimitry Andric 
19030b57cec5SDimitry Andric   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
19040b57cec5SDimitry Andric   if (isNontemporal) {
19050b57cec5SDimitry Andric     llvm::MDNode *Node =
19060b57cec5SDimitry Andric         llvm::MDNode::get(Store->getContext(),
19070b57cec5SDimitry Andric                           llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1908*fe013be4SDimitry Andric     Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
19090b57cec5SDimitry Andric   }
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric   CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
19120b57cec5SDimitry Andric }
19130b57cec5SDimitry Andric 
19140b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
19150b57cec5SDimitry Andric                                         bool isInit) {
19165ffd83dbSDimitry Andric   if (lvalue.getType()->isConstantMatrixType()) {
19175ffd83dbSDimitry Andric     EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
19185ffd83dbSDimitry Andric     return;
19195ffd83dbSDimitry Andric   }
19205ffd83dbSDimitry Andric 
1921480093f4SDimitry Andric   EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
19220b57cec5SDimitry Andric                     lvalue.getType(), lvalue.getBaseInfo(),
19230b57cec5SDimitry Andric                     lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
19240b57cec5SDimitry Andric }
19250b57cec5SDimitry Andric 
19265ffd83dbSDimitry Andric // Emit a load of a LValue of matrix type. This may require casting the pointer
19275ffd83dbSDimitry Andric // to memory address (ArrayType) to a pointer to the value type (VectorType).
19285ffd83dbSDimitry Andric static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
19295ffd83dbSDimitry Andric                                      CodeGenFunction &CGF) {
19305ffd83dbSDimitry Andric   assert(LV.getType()->isConstantMatrixType());
19315ffd83dbSDimitry Andric   Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
19325ffd83dbSDimitry Andric   LV.setAddress(Addr);
19335ffd83dbSDimitry Andric   return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
19345ffd83dbSDimitry Andric }
19355ffd83dbSDimitry Andric 
19360b57cec5SDimitry Andric /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
19370b57cec5SDimitry Andric /// method emits the address of the lvalue, then loads the result as an rvalue,
19380b57cec5SDimitry Andric /// returning the rvalue.
19390b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
19400b57cec5SDimitry Andric   if (LV.isObjCWeak()) {
19410b57cec5SDimitry Andric     // load of a __weak object.
1942480093f4SDimitry Andric     Address AddrWeakObj = LV.getAddress(*this);
19430b57cec5SDimitry Andric     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
19440b57cec5SDimitry Andric                                                              AddrWeakObj));
19450b57cec5SDimitry Andric   }
19460b57cec5SDimitry Andric   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
19470b57cec5SDimitry Andric     // In MRC mode, we do a load+autorelease.
19480b57cec5SDimitry Andric     if (!getLangOpts().ObjCAutoRefCount) {
1949480093f4SDimitry Andric       return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
19500b57cec5SDimitry Andric     }
19510b57cec5SDimitry Andric 
19520b57cec5SDimitry Andric     // In ARC mode, we load retained and then consume the value.
1953480093f4SDimitry Andric     llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
19540b57cec5SDimitry Andric     Object = EmitObjCConsumeObject(LV.getType(), Object);
19550b57cec5SDimitry Andric     return RValue::get(Object);
19560b57cec5SDimitry Andric   }
19570b57cec5SDimitry Andric 
19580b57cec5SDimitry Andric   if (LV.isSimple()) {
19590b57cec5SDimitry Andric     assert(!LV.getType()->isFunctionType());
19600b57cec5SDimitry Andric 
19615ffd83dbSDimitry Andric     if (LV.getType()->isConstantMatrixType())
19625ffd83dbSDimitry Andric       return EmitLoadOfMatrixLValue(LV, Loc, *this);
19635ffd83dbSDimitry Andric 
19640b57cec5SDimitry Andric     // Everything needs a load.
19650b57cec5SDimitry Andric     return RValue::get(EmitLoadOfScalar(LV, Loc));
19660b57cec5SDimitry Andric   }
19670b57cec5SDimitry Andric 
19680b57cec5SDimitry Andric   if (LV.isVectorElt()) {
19690b57cec5SDimitry Andric     llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
19700b57cec5SDimitry Andric                                               LV.isVolatileQualified());
19710b57cec5SDimitry Andric     return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
19720b57cec5SDimitry Andric                                                     "vecext"));
19730b57cec5SDimitry Andric   }
19740b57cec5SDimitry Andric 
19750b57cec5SDimitry Andric   // If this is a reference to a subset of the elements of a vector, either
19760b57cec5SDimitry Andric   // shuffle the input or extract/insert them as appropriate.
19775ffd83dbSDimitry Andric   if (LV.isExtVectorElt()) {
19780b57cec5SDimitry Andric     return EmitLoadOfExtVectorElementLValue(LV);
19795ffd83dbSDimitry Andric   }
19800b57cec5SDimitry Andric 
19810b57cec5SDimitry Andric   // Global Register variables always invoke intrinsics
19820b57cec5SDimitry Andric   if (LV.isGlobalReg())
19830b57cec5SDimitry Andric     return EmitLoadOfGlobalRegLValue(LV);
19840b57cec5SDimitry Andric 
19855ffd83dbSDimitry Andric   if (LV.isMatrixElt()) {
1986349cc55cSDimitry Andric     llvm::Value *Idx = LV.getMatrixIdx();
1987349cc55cSDimitry Andric     if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
198804eeddc0SDimitry Andric       const auto *const MatTy = LV.getType()->castAs<ConstantMatrixType>();
198981ad6265SDimitry Andric       llvm::MatrixBuilder MB(Builder);
1990349cc55cSDimitry Andric       MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
1991349cc55cSDimitry Andric     }
19925ffd83dbSDimitry Andric     llvm::LoadInst *Load =
19935ffd83dbSDimitry Andric         Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
1994349cc55cSDimitry Andric     return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext"));
19955ffd83dbSDimitry Andric   }
19965ffd83dbSDimitry Andric 
19970b57cec5SDimitry Andric   assert(LV.isBitField() && "Unknown LValue type!");
19980b57cec5SDimitry Andric   return EmitLoadOfBitfieldLValue(LV, Loc);
19990b57cec5SDimitry Andric }
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
20020b57cec5SDimitry Andric                                                  SourceLocation Loc) {
20030b57cec5SDimitry Andric   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric   // Get the output type.
20060b57cec5SDimitry Andric   llvm::Type *ResLTy = ConvertType(LV.getType());
20070b57cec5SDimitry Andric 
20080b57cec5SDimitry Andric   Address Ptr = LV.getBitFieldAddress();
2009e8d8bef9SDimitry Andric   llvm::Value *Val =
2010e8d8bef9SDimitry Andric       Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
20110b57cec5SDimitry Andric 
2012e8d8bef9SDimitry Andric   bool UseVolatile = LV.isVolatileQualified() &&
2013e8d8bef9SDimitry Andric                      Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2014e8d8bef9SDimitry Andric   const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2015e8d8bef9SDimitry Andric   const unsigned StorageSize =
2016e8d8bef9SDimitry Andric       UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
20170b57cec5SDimitry Andric   if (Info.IsSigned) {
2018e8d8bef9SDimitry Andric     assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2019e8d8bef9SDimitry Andric     unsigned HighBits = StorageSize - Offset - Info.Size;
20200b57cec5SDimitry Andric     if (HighBits)
20210b57cec5SDimitry Andric       Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2022e8d8bef9SDimitry Andric     if (Offset + HighBits)
2023e8d8bef9SDimitry Andric       Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
20240b57cec5SDimitry Andric   } else {
2025e8d8bef9SDimitry Andric     if (Offset)
2026e8d8bef9SDimitry Andric       Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2027e8d8bef9SDimitry Andric     if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2028e8d8bef9SDimitry Andric       Val = Builder.CreateAnd(
2029e8d8bef9SDimitry Andric           Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
20300b57cec5SDimitry Andric   }
20310b57cec5SDimitry Andric   Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
20320b57cec5SDimitry Andric   EmitScalarRangeCheck(Val, LV.getType(), Loc);
20330b57cec5SDimitry Andric   return RValue::get(Val);
20340b57cec5SDimitry Andric }
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric // If this is a reference to a subset of the elements of a vector, create an
20370b57cec5SDimitry Andric // appropriate shufflevector.
20380b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
20390b57cec5SDimitry Andric   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
20400b57cec5SDimitry Andric                                         LV.isVolatileQualified());
20410b57cec5SDimitry Andric 
20420b57cec5SDimitry Andric   const llvm::Constant *Elts = LV.getExtVectorElts();
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric   // If the result of the expression is a non-vector type, we must be extracting
20450b57cec5SDimitry Andric   // a single element.  Just codegen as an extractelement.
20460b57cec5SDimitry Andric   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
20470b57cec5SDimitry Andric   if (!ExprVT) {
20480b57cec5SDimitry Andric     unsigned InIdx = getAccessedFieldNo(0, Elts);
20490b57cec5SDimitry Andric     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
20500b57cec5SDimitry Andric     return RValue::get(Builder.CreateExtractElement(Vec, Elt));
20510b57cec5SDimitry Andric   }
20520b57cec5SDimitry Andric 
20530b57cec5SDimitry Andric   // Always use shuffle vector to try to retain the original program structure
20540b57cec5SDimitry Andric   unsigned NumResultElts = ExprVT->getNumElements();
20550b57cec5SDimitry Andric 
20565ffd83dbSDimitry Andric   SmallVector<int, 4> Mask;
20570b57cec5SDimitry Andric   for (unsigned i = 0; i != NumResultElts; ++i)
20585ffd83dbSDimitry Andric     Mask.push_back(getAccessedFieldNo(i, Elts));
20590b57cec5SDimitry Andric 
2060e8d8bef9SDimitry Andric   Vec = Builder.CreateShuffleVector(Vec, Mask);
20610b57cec5SDimitry Andric   return RValue::get(Vec);
20620b57cec5SDimitry Andric }
20630b57cec5SDimitry Andric 
20640b57cec5SDimitry Andric /// Generates lvalue for partial ext_vector access.
20650b57cec5SDimitry Andric Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
20660b57cec5SDimitry Andric   Address VectorAddress = LV.getExtVectorAddress();
2067480093f4SDimitry Andric   QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
20680b57cec5SDimitry Andric   llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
20690b57cec5SDimitry Andric 
2070*fe013be4SDimitry Andric   Address CastToPointerElement = VectorAddress.withElementType(VectorElementTy);
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric   const llvm::Constant *Elts = LV.getExtVectorElts();
20730b57cec5SDimitry Andric   unsigned ix = getAccessedFieldNo(0, Elts);
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric   Address VectorBasePtrPlusIx =
20760b57cec5SDimitry Andric     Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
20770b57cec5SDimitry Andric                                    "vector.elt");
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric   return VectorBasePtrPlusIx;
20800b57cec5SDimitry Andric }
20810b57cec5SDimitry Andric 
20820b57cec5SDimitry Andric /// Load of global gamed gegisters are always calls to intrinsics.
20830b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
20840b57cec5SDimitry Andric   assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
20850b57cec5SDimitry Andric          "Bad type for register variable");
20860b57cec5SDimitry Andric   llvm::MDNode *RegName = cast<llvm::MDNode>(
20870b57cec5SDimitry Andric       cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   // We accept integer and pointer types only
20900b57cec5SDimitry Andric   llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
20910b57cec5SDimitry Andric   llvm::Type *Ty = OrigTy;
20920b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
20930b57cec5SDimitry Andric     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
20940b57cec5SDimitry Andric   llvm::Type *Types[] = { Ty };
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
20970b57cec5SDimitry Andric   llvm::Value *Call = Builder.CreateCall(
20980b57cec5SDimitry Andric       F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
20990b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
21000b57cec5SDimitry Andric     Call = Builder.CreateIntToPtr(Call, OrigTy);
21010b57cec5SDimitry Andric   return RValue::get(Call);
21020b57cec5SDimitry Andric }
21030b57cec5SDimitry Andric 
21040b57cec5SDimitry Andric /// EmitStoreThroughLValue - Store the specified rvalue into the specified
21050b57cec5SDimitry Andric /// lvalue, where both are guaranteed to the have the same type, and that type
21060b57cec5SDimitry Andric /// is 'Ty'.
21070b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
21080b57cec5SDimitry Andric                                              bool isInit) {
21090b57cec5SDimitry Andric   if (!Dst.isSimple()) {
21100b57cec5SDimitry Andric     if (Dst.isVectorElt()) {
21110b57cec5SDimitry Andric       // Read/modify/write the vector, inserting the new element.
21120b57cec5SDimitry Andric       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
21130b57cec5SDimitry Andric                                             Dst.isVolatileQualified());
211481ad6265SDimitry Andric       auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
211581ad6265SDimitry Andric       if (IRStoreTy) {
211681ad6265SDimitry Andric         auto *IRVecTy = llvm::FixedVectorType::get(
211781ad6265SDimitry Andric             Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
211881ad6265SDimitry Andric         Vec = Builder.CreateBitCast(Vec, IRVecTy);
211981ad6265SDimitry Andric         // iN --> <N x i1>.
212081ad6265SDimitry Andric       }
21210b57cec5SDimitry Andric       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
21220b57cec5SDimitry Andric                                         Dst.getVectorIdx(), "vecins");
212381ad6265SDimitry Andric       if (IRStoreTy) {
212481ad6265SDimitry Andric         // <N x i1> --> <iN>.
212581ad6265SDimitry Andric         Vec = Builder.CreateBitCast(Vec, IRStoreTy);
212681ad6265SDimitry Andric       }
21270b57cec5SDimitry Andric       Builder.CreateStore(Vec, Dst.getVectorAddress(),
21280b57cec5SDimitry Andric                           Dst.isVolatileQualified());
21290b57cec5SDimitry Andric       return;
21300b57cec5SDimitry Andric     }
21310b57cec5SDimitry Andric 
21320b57cec5SDimitry Andric     // If this is an update of extended vector elements, insert them as
21330b57cec5SDimitry Andric     // appropriate.
21340b57cec5SDimitry Andric     if (Dst.isExtVectorElt())
21350b57cec5SDimitry Andric       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric     if (Dst.isGlobalReg())
21380b57cec5SDimitry Andric       return EmitStoreThroughGlobalRegLValue(Src, Dst);
21390b57cec5SDimitry Andric 
21405ffd83dbSDimitry Andric     if (Dst.isMatrixElt()) {
2141349cc55cSDimitry Andric       llvm::Value *Idx = Dst.getMatrixIdx();
2142349cc55cSDimitry Andric       if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
214304eeddc0SDimitry Andric         const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
214481ad6265SDimitry Andric         llvm::MatrixBuilder MB(Builder);
2145349cc55cSDimitry Andric         MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2146349cc55cSDimitry Andric       }
2147349cc55cSDimitry Andric       llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2148349cc55cSDimitry Andric       llvm::Value *Vec =
2149349cc55cSDimitry Andric           Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins");
21505ffd83dbSDimitry Andric       Builder.CreateStore(Vec, Dst.getMatrixAddress(),
21515ffd83dbSDimitry Andric                           Dst.isVolatileQualified());
21525ffd83dbSDimitry Andric       return;
21535ffd83dbSDimitry Andric     }
21545ffd83dbSDimitry Andric 
21550b57cec5SDimitry Andric     assert(Dst.isBitField() && "Unknown LValue type");
21560b57cec5SDimitry Andric     return EmitStoreThroughBitfieldLValue(Src, Dst);
21570b57cec5SDimitry Andric   }
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric   // There's special magic for assigning into an ARC-qualified l-value.
21600b57cec5SDimitry Andric   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
21610b57cec5SDimitry Andric     switch (Lifetime) {
21620b57cec5SDimitry Andric     case Qualifiers::OCL_None:
21630b57cec5SDimitry Andric       llvm_unreachable("present but none");
21640b57cec5SDimitry Andric 
21650b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
21660b57cec5SDimitry Andric       // nothing special
21670b57cec5SDimitry Andric       break;
21680b57cec5SDimitry Andric 
21690b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
21700b57cec5SDimitry Andric       if (isInit) {
21710b57cec5SDimitry Andric         Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
21720b57cec5SDimitry Andric         break;
21730b57cec5SDimitry Andric       }
21740b57cec5SDimitry Andric       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
21750b57cec5SDimitry Andric       return;
21760b57cec5SDimitry Andric 
21770b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
21780b57cec5SDimitry Andric       if (isInit)
21790b57cec5SDimitry Andric         // Initialize and then skip the primitive store.
2180480093f4SDimitry Andric         EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
21810b57cec5SDimitry Andric       else
2182480093f4SDimitry Andric         EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
2183480093f4SDimitry Andric                          /*ignore*/ true);
21840b57cec5SDimitry Andric       return;
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
21870b57cec5SDimitry Andric       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
21880b57cec5SDimitry Andric                                                      Src.getScalarVal()));
21890b57cec5SDimitry Andric       // fall into the normal path
21900b57cec5SDimitry Andric       break;
21910b57cec5SDimitry Andric     }
21920b57cec5SDimitry Andric   }
21930b57cec5SDimitry Andric 
21940b57cec5SDimitry Andric   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
21950b57cec5SDimitry Andric     // load of a __weak object.
2196480093f4SDimitry Andric     Address LvalueDst = Dst.getAddress(*this);
21970b57cec5SDimitry Andric     llvm::Value *src = Src.getScalarVal();
21980b57cec5SDimitry Andric      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
21990b57cec5SDimitry Andric     return;
22000b57cec5SDimitry Andric   }
22010b57cec5SDimitry Andric 
22020b57cec5SDimitry Andric   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
22030b57cec5SDimitry Andric     // load of a __strong object.
2204480093f4SDimitry Andric     Address LvalueDst = Dst.getAddress(*this);
22050b57cec5SDimitry Andric     llvm::Value *src = Src.getScalarVal();
22060b57cec5SDimitry Andric     if (Dst.isObjCIvar()) {
22070b57cec5SDimitry Andric       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
22080b57cec5SDimitry Andric       llvm::Type *ResultType = IntPtrTy;
22090b57cec5SDimitry Andric       Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
22100b57cec5SDimitry Andric       llvm::Value *RHS = dst.getPointer();
22110b57cec5SDimitry Andric       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
22120b57cec5SDimitry Andric       llvm::Value *LHS =
22130b57cec5SDimitry Andric         Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
22140b57cec5SDimitry Andric                                "sub.ptr.lhs.cast");
22150b57cec5SDimitry Andric       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
22160b57cec5SDimitry Andric       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
22170b57cec5SDimitry Andric                                               BytesBetween);
22180b57cec5SDimitry Andric     } else if (Dst.isGlobalObjCRef()) {
22190b57cec5SDimitry Andric       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
22200b57cec5SDimitry Andric                                                 Dst.isThreadLocalRef());
22210b57cec5SDimitry Andric     }
22220b57cec5SDimitry Andric     else
22230b57cec5SDimitry Andric       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
22240b57cec5SDimitry Andric     return;
22250b57cec5SDimitry Andric   }
22260b57cec5SDimitry Andric 
22270b57cec5SDimitry Andric   assert(Src.isScalar() && "Can't emit an agg store with this method");
22280b57cec5SDimitry Andric   EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
22290b57cec5SDimitry Andric }
22300b57cec5SDimitry Andric 
22310b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
22320b57cec5SDimitry Andric                                                      llvm::Value **Result) {
22330b57cec5SDimitry Andric   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
22340b57cec5SDimitry Andric   llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
22350b57cec5SDimitry Andric   Address Ptr = Dst.getBitFieldAddress();
22360b57cec5SDimitry Andric 
22370b57cec5SDimitry Andric   // Get the source value, truncated to the width of the bit-field.
22380b57cec5SDimitry Andric   llvm::Value *SrcVal = Src.getScalarVal();
22390b57cec5SDimitry Andric 
22400b57cec5SDimitry Andric   // Cast the source to the storage type and shift it into place.
22410b57cec5SDimitry Andric   SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
22420b57cec5SDimitry Andric                                  /*isSigned=*/false);
22430b57cec5SDimitry Andric   llvm::Value *MaskedVal = SrcVal;
22440b57cec5SDimitry Andric 
2245e8d8bef9SDimitry Andric   const bool UseVolatile =
2246e8d8bef9SDimitry Andric       CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2247e8d8bef9SDimitry Andric       Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2248e8d8bef9SDimitry Andric   const unsigned StorageSize =
2249e8d8bef9SDimitry Andric       UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2250e8d8bef9SDimitry Andric   const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
22510b57cec5SDimitry Andric   // See if there are other bits in the bitfield's storage we'll need to load
22520b57cec5SDimitry Andric   // and mask together with source before storing.
2253e8d8bef9SDimitry Andric   if (StorageSize != Info.Size) {
2254e8d8bef9SDimitry Andric     assert(StorageSize > Info.Size && "Invalid bitfield size.");
22550b57cec5SDimitry Andric     llvm::Value *Val =
22560b57cec5SDimitry Andric         Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
22570b57cec5SDimitry Andric 
22580b57cec5SDimitry Andric     // Mask the source value as needed.
22590b57cec5SDimitry Andric     if (!hasBooleanRepresentation(Dst.getType()))
2260e8d8bef9SDimitry Andric       SrcVal = Builder.CreateAnd(
2261e8d8bef9SDimitry Andric           SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
22620b57cec5SDimitry Andric           "bf.value");
22630b57cec5SDimitry Andric     MaskedVal = SrcVal;
2264e8d8bef9SDimitry Andric     if (Offset)
2265e8d8bef9SDimitry Andric       SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
22660b57cec5SDimitry Andric 
22670b57cec5SDimitry Andric     // Mask out the original value.
2268e8d8bef9SDimitry Andric     Val = Builder.CreateAnd(
2269e8d8bef9SDimitry Andric         Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
22700b57cec5SDimitry Andric         "bf.clear");
22710b57cec5SDimitry Andric 
22720b57cec5SDimitry Andric     // Or together the unchanged values and the source value.
22730b57cec5SDimitry Andric     SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
22740b57cec5SDimitry Andric   } else {
2275e8d8bef9SDimitry Andric     assert(Offset == 0);
22765ffd83dbSDimitry Andric     // According to the AACPS:
22775ffd83dbSDimitry Andric     // When a volatile bit-field is written, and its container does not overlap
2278e8d8bef9SDimitry Andric     // with any non-bit-field member, its container must be read exactly once
2279e8d8bef9SDimitry Andric     // and written exactly once using the access width appropriate to the type
2280e8d8bef9SDimitry Andric     // of the container. The two accesses are not atomic.
22815ffd83dbSDimitry Andric     if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
22825ffd83dbSDimitry Andric         CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
22835ffd83dbSDimitry Andric       Builder.CreateLoad(Ptr, true, "bf.load");
22840b57cec5SDimitry Andric   }
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric   // Write the new value back out.
22870b57cec5SDimitry Andric   Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric   // Return the new value of the bit-field, if requested.
22900b57cec5SDimitry Andric   if (Result) {
22910b57cec5SDimitry Andric     llvm::Value *ResultVal = MaskedVal;
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric     // Sign extend the value if needed.
22940b57cec5SDimitry Andric     if (Info.IsSigned) {
2295e8d8bef9SDimitry Andric       assert(Info.Size <= StorageSize);
2296e8d8bef9SDimitry Andric       unsigned HighBits = StorageSize - Info.Size;
22970b57cec5SDimitry Andric       if (HighBits) {
22980b57cec5SDimitry Andric         ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
22990b57cec5SDimitry Andric         ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
23000b57cec5SDimitry Andric       }
23010b57cec5SDimitry Andric     }
23020b57cec5SDimitry Andric 
23030b57cec5SDimitry Andric     ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
23040b57cec5SDimitry Andric                                       "bf.result.cast");
23050b57cec5SDimitry Andric     *Result = EmitFromMemory(ResultVal, Dst.getType());
23060b57cec5SDimitry Andric   }
23070b57cec5SDimitry Andric }
23080b57cec5SDimitry Andric 
23090b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
23100b57cec5SDimitry Andric                                                                LValue Dst) {
23110b57cec5SDimitry Andric   // This access turns into a read/modify/write of the vector.  Load the input
23120b57cec5SDimitry Andric   // value now.
23130b57cec5SDimitry Andric   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
23140b57cec5SDimitry Andric                                         Dst.isVolatileQualified());
23150b57cec5SDimitry Andric   const llvm::Constant *Elts = Dst.getExtVectorElts();
23160b57cec5SDimitry Andric 
23170b57cec5SDimitry Andric   llvm::Value *SrcVal = Src.getScalarVal();
23180b57cec5SDimitry Andric 
23190b57cec5SDimitry Andric   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
23200b57cec5SDimitry Andric     unsigned NumSrcElts = VTy->getNumElements();
23215ffd83dbSDimitry Andric     unsigned NumDstElts =
2322e8d8bef9SDimitry Andric         cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
23230b57cec5SDimitry Andric     if (NumDstElts == NumSrcElts) {
23240b57cec5SDimitry Andric       // Use shuffle vector is the src and destination are the same number of
23250b57cec5SDimitry Andric       // elements and restore the vector mask since it is on the side it will be
23260b57cec5SDimitry Andric       // stored.
23275ffd83dbSDimitry Andric       SmallVector<int, 4> Mask(NumDstElts);
23280b57cec5SDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
23295ffd83dbSDimitry Andric         Mask[getAccessedFieldNo(i, Elts)] = i;
23300b57cec5SDimitry Andric 
2331e8d8bef9SDimitry Andric       Vec = Builder.CreateShuffleVector(SrcVal, Mask);
23320b57cec5SDimitry Andric     } else if (NumDstElts > NumSrcElts) {
23330b57cec5SDimitry Andric       // Extended the source vector to the same length and then shuffle it
23340b57cec5SDimitry Andric       // into the destination.
23350b57cec5SDimitry Andric       // FIXME: since we're shuffling with undef, can we just use the indices
23360b57cec5SDimitry Andric       //        into that?  This could be simpler.
23375ffd83dbSDimitry Andric       SmallVector<int, 4> ExtMask;
23380b57cec5SDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
23395ffd83dbSDimitry Andric         ExtMask.push_back(i);
23405ffd83dbSDimitry Andric       ExtMask.resize(NumDstElts, -1);
2341e8d8bef9SDimitry Andric       llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
23420b57cec5SDimitry Andric       // build identity
23435ffd83dbSDimitry Andric       SmallVector<int, 4> Mask;
23440b57cec5SDimitry Andric       for (unsigned i = 0; i != NumDstElts; ++i)
23455ffd83dbSDimitry Andric         Mask.push_back(i);
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric       // When the vector size is odd and .odd or .hi is used, the last element
23480b57cec5SDimitry Andric       // of the Elts constant array will be one past the size of the vector.
23490b57cec5SDimitry Andric       // Ignore the last element here, if it is greater than the mask size.
23500b57cec5SDimitry Andric       if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
23510b57cec5SDimitry Andric         NumSrcElts--;
23520b57cec5SDimitry Andric 
23530b57cec5SDimitry Andric       // modify when what gets shuffled in
23540b57cec5SDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
23555ffd83dbSDimitry Andric         Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
23565ffd83dbSDimitry Andric       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
23570b57cec5SDimitry Andric     } else {
23580b57cec5SDimitry Andric       // We should never shorten the vector
23590b57cec5SDimitry Andric       llvm_unreachable("unexpected shorten vector length");
23600b57cec5SDimitry Andric     }
23610b57cec5SDimitry Andric   } else {
23620b57cec5SDimitry Andric     // If the Src is a scalar (not a vector) it must be updating one element.
23630b57cec5SDimitry Andric     unsigned InIdx = getAccessedFieldNo(0, Elts);
23640b57cec5SDimitry Andric     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
23650b57cec5SDimitry Andric     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
23660b57cec5SDimitry Andric   }
23670b57cec5SDimitry Andric 
23680b57cec5SDimitry Andric   Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
23690b57cec5SDimitry Andric                       Dst.isVolatileQualified());
23700b57cec5SDimitry Andric }
23710b57cec5SDimitry Andric 
23720b57cec5SDimitry Andric /// Store of global named registers are always calls to intrinsics.
23730b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
23740b57cec5SDimitry Andric   assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
23750b57cec5SDimitry Andric          "Bad type for register variable");
23760b57cec5SDimitry Andric   llvm::MDNode *RegName = cast<llvm::MDNode>(
23770b57cec5SDimitry Andric       cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
23780b57cec5SDimitry Andric   assert(RegName && "Register LValue is not metadata");
23790b57cec5SDimitry Andric 
23800b57cec5SDimitry Andric   // We accept integer and pointer types only
23810b57cec5SDimitry Andric   llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
23820b57cec5SDimitry Andric   llvm::Type *Ty = OrigTy;
23830b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
23840b57cec5SDimitry Andric     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
23850b57cec5SDimitry Andric   llvm::Type *Types[] = { Ty };
23860b57cec5SDimitry Andric 
23870b57cec5SDimitry Andric   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
23880b57cec5SDimitry Andric   llvm::Value *Value = Src.getScalarVal();
23890b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
23900b57cec5SDimitry Andric     Value = Builder.CreatePtrToInt(Value, Ty);
23910b57cec5SDimitry Andric   Builder.CreateCall(
23920b57cec5SDimitry Andric       F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
23930b57cec5SDimitry Andric }
23940b57cec5SDimitry Andric 
23950b57cec5SDimitry Andric // setObjCGCLValueClass - sets class of the lvalue for the purpose of
23960b57cec5SDimitry Andric // generating write-barries API. It is currently a global, ivar,
23970b57cec5SDimitry Andric // or neither.
23980b57cec5SDimitry Andric static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
23990b57cec5SDimitry Andric                                  LValue &LV,
24000b57cec5SDimitry Andric                                  bool IsMemberAccess=false) {
24010b57cec5SDimitry Andric   if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
24020b57cec5SDimitry Andric     return;
24030b57cec5SDimitry Andric 
24040b57cec5SDimitry Andric   if (isa<ObjCIvarRefExpr>(E)) {
24050b57cec5SDimitry Andric     QualType ExpTy = E->getType();
24060b57cec5SDimitry Andric     if (IsMemberAccess && ExpTy->isPointerType()) {
24070b57cec5SDimitry Andric       // If ivar is a structure pointer, assigning to field of
24080b57cec5SDimitry Andric       // this struct follows gcc's behavior and makes it a non-ivar
24090b57cec5SDimitry Andric       // writer-barrier conservatively.
2410a7dea167SDimitry Andric       ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
24110b57cec5SDimitry Andric       if (ExpTy->isRecordType()) {
24120b57cec5SDimitry Andric         LV.setObjCIvar(false);
24130b57cec5SDimitry Andric         return;
24140b57cec5SDimitry Andric       }
24150b57cec5SDimitry Andric     }
24160b57cec5SDimitry Andric     LV.setObjCIvar(true);
24170b57cec5SDimitry Andric     auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
24180b57cec5SDimitry Andric     LV.setBaseIvarExp(Exp->getBase());
24190b57cec5SDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
24200b57cec5SDimitry Andric     return;
24210b57cec5SDimitry Andric   }
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
24240b57cec5SDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
24250b57cec5SDimitry Andric       if (VD->hasGlobalStorage()) {
24260b57cec5SDimitry Andric         LV.setGlobalObjCRef(true);
24270b57cec5SDimitry Andric         LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
24280b57cec5SDimitry Andric       }
24290b57cec5SDimitry Andric     }
24300b57cec5SDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
24310b57cec5SDimitry Andric     return;
24320b57cec5SDimitry Andric   }
24330b57cec5SDimitry Andric 
24340b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
24350b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
24360b57cec5SDimitry Andric     return;
24370b57cec5SDimitry Andric   }
24380b57cec5SDimitry Andric 
24390b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
24400b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
24410b57cec5SDimitry Andric     if (LV.isObjCIvar()) {
24420b57cec5SDimitry Andric       // If cast is to a structure pointer, follow gcc's behavior and make it
24430b57cec5SDimitry Andric       // a non-ivar write-barrier.
24440b57cec5SDimitry Andric       QualType ExpTy = E->getType();
24450b57cec5SDimitry Andric       if (ExpTy->isPointerType())
2446a7dea167SDimitry Andric         ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
24470b57cec5SDimitry Andric       if (ExpTy->isRecordType())
24480b57cec5SDimitry Andric         LV.setObjCIvar(false);
24490b57cec5SDimitry Andric     }
24500b57cec5SDimitry Andric     return;
24510b57cec5SDimitry Andric   }
24520b57cec5SDimitry Andric 
24530b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
24540b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
24550b57cec5SDimitry Andric     return;
24560b57cec5SDimitry Andric   }
24570b57cec5SDimitry Andric 
24580b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
24590b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
24600b57cec5SDimitry Andric     return;
24610b57cec5SDimitry Andric   }
24620b57cec5SDimitry Andric 
24630b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
24640b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
24650b57cec5SDimitry Andric     return;
24660b57cec5SDimitry Andric   }
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
24690b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
24700b57cec5SDimitry Andric     return;
24710b57cec5SDimitry Andric   }
24720b57cec5SDimitry Andric 
24730b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
24740b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
24750b57cec5SDimitry Andric     if (LV.isObjCIvar() && !LV.isObjCArray())
24760b57cec5SDimitry Andric       // Using array syntax to assigning to what an ivar points to is not
24770b57cec5SDimitry Andric       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
24780b57cec5SDimitry Andric       LV.setObjCIvar(false);
24790b57cec5SDimitry Andric     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
24800b57cec5SDimitry Andric       // Using array syntax to assigning to what global points to is not
24810b57cec5SDimitry Andric       // same as assigning to the global itself. {id *G;} G[i] = 0;
24820b57cec5SDimitry Andric       LV.setGlobalObjCRef(false);
24830b57cec5SDimitry Andric     return;
24840b57cec5SDimitry Andric   }
24850b57cec5SDimitry Andric 
24860b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
24870b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
24880b57cec5SDimitry Andric     // We don't know if member is an 'ivar', but this flag is looked at
24890b57cec5SDimitry Andric     // only in the context of LV.isObjCIvar().
24900b57cec5SDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
24910b57cec5SDimitry Andric     return;
24920b57cec5SDimitry Andric   }
24930b57cec5SDimitry Andric }
24940b57cec5SDimitry Andric 
24950b57cec5SDimitry Andric static llvm::Value *
24960b57cec5SDimitry Andric EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
24970b57cec5SDimitry Andric                                 llvm::Value *V, llvm::Type *IRType,
24980b57cec5SDimitry Andric                                 StringRef Name = StringRef()) {
24990b57cec5SDimitry Andric   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
25000b57cec5SDimitry Andric   return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
25010b57cec5SDimitry Andric }
25020b57cec5SDimitry Andric 
25030b57cec5SDimitry Andric static LValue EmitThreadPrivateVarDeclLValue(
25040b57cec5SDimitry Andric     CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
25050b57cec5SDimitry Andric     llvm::Type *RealVarTy, SourceLocation Loc) {
25065ffd83dbSDimitry Andric   if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
25075ffd83dbSDimitry Andric     Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
25085ffd83dbSDimitry Andric         CGF, VD, Addr, Loc);
25095ffd83dbSDimitry Andric   else
25105ffd83dbSDimitry Andric     Addr =
25115ffd83dbSDimitry Andric         CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
25125ffd83dbSDimitry Andric 
2513*fe013be4SDimitry Andric   Addr = Addr.withElementType(RealVarTy);
25140b57cec5SDimitry Andric   return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
25150b57cec5SDimitry Andric }
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
25180b57cec5SDimitry Andric                                            const VarDecl *VD, QualType T) {
2519bdd1243dSDimitry Andric   std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
25200b57cec5SDimitry Andric       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2521bdd1243dSDimitry Andric   // Return an invalid address if variable is MT_To (or MT_Enter starting with
2522bdd1243dSDimitry Andric   // OpenMP 5.2) and unified memory is not enabled. For all other cases: MT_Link
2523bdd1243dSDimitry Andric   // and MT_To (or MT_Enter) with unified memory, return a valid address.
2524bdd1243dSDimitry Andric   if (!Res || ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
2525bdd1243dSDimitry Andric                 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
25260b57cec5SDimitry Andric                !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
25270b57cec5SDimitry Andric     return Address::invalid();
25280b57cec5SDimitry Andric   assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2529bdd1243dSDimitry Andric           ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
2530bdd1243dSDimitry Andric             *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
25310b57cec5SDimitry Andric            CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
25320b57cec5SDimitry Andric          "Expected link clause OR to clause with unified memory enabled.");
25330b57cec5SDimitry Andric   QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
25340b57cec5SDimitry Andric   Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
25350b57cec5SDimitry Andric   return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
25360b57cec5SDimitry Andric }
25370b57cec5SDimitry Andric 
25380b57cec5SDimitry Andric Address
25390b57cec5SDimitry Andric CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
25400b57cec5SDimitry Andric                                      LValueBaseInfo *PointeeBaseInfo,
25410b57cec5SDimitry Andric                                      TBAAAccessInfo *PointeeTBAAInfo) {
2542480093f4SDimitry Andric   llvm::LoadInst *Load =
2543480093f4SDimitry Andric       Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
25440b57cec5SDimitry Andric   CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
25450b57cec5SDimitry Andric 
25460eae32dcSDimitry Andric   QualType PointeeType = RefLVal.getType()->getPointeeType();
25475ffd83dbSDimitry Andric   CharUnits Align = CGM.getNaturalTypeAlignment(
25480eae32dcSDimitry Andric       PointeeType, PointeeBaseInfo, PointeeTBAAInfo,
25490b57cec5SDimitry Andric       /* forPointeeType= */ true);
25500eae32dcSDimitry Andric   return Address(Load, ConvertTypeForMem(PointeeType), Align);
25510b57cec5SDimitry Andric }
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
25540b57cec5SDimitry Andric   LValueBaseInfo PointeeBaseInfo;
25550b57cec5SDimitry Andric   TBAAAccessInfo PointeeTBAAInfo;
25560b57cec5SDimitry Andric   Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
25570b57cec5SDimitry Andric                                             &PointeeTBAAInfo);
25580b57cec5SDimitry Andric   return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
25590b57cec5SDimitry Andric                         PointeeBaseInfo, PointeeTBAAInfo);
25600b57cec5SDimitry Andric }
25610b57cec5SDimitry Andric 
25620b57cec5SDimitry Andric Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
25630b57cec5SDimitry Andric                                            const PointerType *PtrTy,
25640b57cec5SDimitry Andric                                            LValueBaseInfo *BaseInfo,
25650b57cec5SDimitry Andric                                            TBAAAccessInfo *TBAAInfo) {
25660b57cec5SDimitry Andric   llvm::Value *Addr = Builder.CreateLoad(Ptr);
256781ad6265SDimitry Andric   return Address(Addr, ConvertTypeForMem(PtrTy->getPointeeType()),
256881ad6265SDimitry Andric                  CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(), BaseInfo,
256981ad6265SDimitry Andric                                              TBAAInfo,
25700b57cec5SDimitry Andric                                              /*forPointeeType=*/true));
25710b57cec5SDimitry Andric }
25720b57cec5SDimitry Andric 
25730b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
25740b57cec5SDimitry Andric                                                 const PointerType *PtrTy) {
25750b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
25760b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
25770b57cec5SDimitry Andric   Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
25780b57cec5SDimitry Andric   return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
25790b57cec5SDimitry Andric }
25800b57cec5SDimitry Andric 
25810b57cec5SDimitry Andric static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
25820b57cec5SDimitry Andric                                       const Expr *E, const VarDecl *VD) {
25830b57cec5SDimitry Andric   QualType T = E->getType();
25840b57cec5SDimitry Andric 
25850b57cec5SDimitry Andric   // If it's thread_local, emit a call to its wrapper function instead.
25860b57cec5SDimitry Andric   if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2587a7dea167SDimitry Andric       CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
25880b57cec5SDimitry Andric     return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
25890b57cec5SDimitry Andric   // Check if the variable is marked as declare target with link clause in
25900b57cec5SDimitry Andric   // device codegen.
2591*fe013be4SDimitry Andric   if (CGF.getLangOpts().OpenMPIsTargetDevice) {
25920b57cec5SDimitry Andric     Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
25930b57cec5SDimitry Andric     if (Addr.isValid())
25940b57cec5SDimitry Andric       return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
25950b57cec5SDimitry Andric   }
25960b57cec5SDimitry Andric 
25970b57cec5SDimitry Andric   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2598bdd1243dSDimitry Andric 
2599bdd1243dSDimitry Andric   if (VD->getTLSKind() != VarDecl::TLS_None)
2600bdd1243dSDimitry Andric     V = CGF.Builder.CreateThreadLocalAddress(V);
2601bdd1243dSDimitry Andric 
26020b57cec5SDimitry Andric   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
26030b57cec5SDimitry Andric   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
26040b57cec5SDimitry Andric   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
26050eae32dcSDimitry Andric   Address Addr(V, RealVarTy, Alignment);
26060b57cec5SDimitry Andric   // Emit reference to the private copy of the variable if it is an OpenMP
26070b57cec5SDimitry Andric   // threadprivate variable.
26080b57cec5SDimitry Andric   if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
26090b57cec5SDimitry Andric       VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
26100b57cec5SDimitry Andric     return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
26110b57cec5SDimitry Andric                                           E->getExprLoc());
26120b57cec5SDimitry Andric   }
26130b57cec5SDimitry Andric   LValue LV = VD->getType()->isReferenceType() ?
26140b57cec5SDimitry Andric       CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
26150b57cec5SDimitry Andric                                     AlignmentSource::Decl) :
26160b57cec5SDimitry Andric       CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
26170b57cec5SDimitry Andric   setObjCGCLValueClass(CGF.getContext(), E, LV);
26180b57cec5SDimitry Andric   return LV;
26190b57cec5SDimitry Andric }
26200b57cec5SDimitry Andric 
26210b57cec5SDimitry Andric static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
26225ffd83dbSDimitry Andric                                                GlobalDecl GD) {
26235ffd83dbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
26240b57cec5SDimitry Andric   if (FD->hasAttr<WeakRefAttr>()) {
26250b57cec5SDimitry Andric     ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
26260b57cec5SDimitry Andric     return aliasee.getPointer();
26270b57cec5SDimitry Andric   }
26280b57cec5SDimitry Andric 
26295ffd83dbSDimitry Andric   llvm::Constant *V = CGM.GetAddrOfFunction(GD);
26300b57cec5SDimitry Andric   if (!FD->hasPrototype()) {
26310b57cec5SDimitry Andric     if (const FunctionProtoType *Proto =
26320b57cec5SDimitry Andric             FD->getType()->getAs<FunctionProtoType>()) {
26330b57cec5SDimitry Andric       // Ugly case: for a K&R-style definition, the type of the definition
26340b57cec5SDimitry Andric       // isn't the same as the type of a use.  Correct for this with a
26350b57cec5SDimitry Andric       // bitcast.
26360b57cec5SDimitry Andric       QualType NoProtoType =
26370b57cec5SDimitry Andric           CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
26380b57cec5SDimitry Andric       NoProtoType = CGM.getContext().getPointerType(NoProtoType);
26390b57cec5SDimitry Andric       V = llvm::ConstantExpr::getBitCast(V,
26400b57cec5SDimitry Andric                                       CGM.getTypes().ConvertType(NoProtoType));
26410b57cec5SDimitry Andric     }
26420b57cec5SDimitry Andric   }
26430b57cec5SDimitry Andric   return V;
26440b57cec5SDimitry Andric }
26450b57cec5SDimitry Andric 
26465ffd83dbSDimitry Andric static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
26475ffd83dbSDimitry Andric                                      GlobalDecl GD) {
26485ffd83dbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
26495ffd83dbSDimitry Andric   llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
26500b57cec5SDimitry Andric   CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
26510b57cec5SDimitry Andric   return CGF.MakeAddrLValue(V, E->getType(), Alignment,
26520b57cec5SDimitry Andric                             AlignmentSource::Decl);
26530b57cec5SDimitry Andric }
26540b57cec5SDimitry Andric 
26550b57cec5SDimitry Andric static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
26560b57cec5SDimitry Andric                                       llvm::Value *ThisValue) {
26570b57cec5SDimitry Andric   QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
26580b57cec5SDimitry Andric   LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
26590b57cec5SDimitry Andric   return CGF.EmitLValueForField(LV, FD);
26600b57cec5SDimitry Andric }
26610b57cec5SDimitry Andric 
26620b57cec5SDimitry Andric /// Named Registers are named metadata pointing to the register name
26630b57cec5SDimitry Andric /// which will be read from/written to as an argument to the intrinsic
26640b57cec5SDimitry Andric /// @llvm.read/write_register.
26650b57cec5SDimitry Andric /// So far, only the name is being passed down, but other options such as
26660b57cec5SDimitry Andric /// register type, allocation type or even optimization options could be
26670b57cec5SDimitry Andric /// passed down via the metadata node.
26680b57cec5SDimitry Andric static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
26690b57cec5SDimitry Andric   SmallString<64> Name("llvm.named.register.");
26700b57cec5SDimitry Andric   AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
26710b57cec5SDimitry Andric   assert(Asm->getLabel().size() < 64-Name.size() &&
26720b57cec5SDimitry Andric       "Register name too big");
26730b57cec5SDimitry Andric   Name.append(Asm->getLabel());
26740b57cec5SDimitry Andric   llvm::NamedMDNode *M =
26750b57cec5SDimitry Andric     CGM.getModule().getOrInsertNamedMetadata(Name);
26760b57cec5SDimitry Andric   if (M->getNumOperands() == 0) {
26770b57cec5SDimitry Andric     llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
26780b57cec5SDimitry Andric                                               Asm->getLabel());
26790b57cec5SDimitry Andric     llvm::Metadata *Ops[] = {Str};
26800b57cec5SDimitry Andric     M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
26810b57cec5SDimitry Andric   }
26820b57cec5SDimitry Andric 
26830b57cec5SDimitry Andric   CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
26840b57cec5SDimitry Andric 
26850b57cec5SDimitry Andric   llvm::Value *Ptr =
26860b57cec5SDimitry Andric     llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
26870eae32dcSDimitry Andric   return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
26880b57cec5SDimitry Andric }
26890b57cec5SDimitry Andric 
26900b57cec5SDimitry Andric /// Determine whether we can emit a reference to \p VD from the current
26910b57cec5SDimitry Andric /// context, despite not necessarily having seen an odr-use of the variable in
26920b57cec5SDimitry Andric /// this context.
26930b57cec5SDimitry Andric static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
26940b57cec5SDimitry Andric                                                const DeclRefExpr *E,
26950b57cec5SDimitry Andric                                                const VarDecl *VD,
26960b57cec5SDimitry Andric                                                bool IsConstant) {
26970b57cec5SDimitry Andric   // For a variable declared in an enclosing scope, do not emit a spurious
26980b57cec5SDimitry Andric   // reference even if we have a capture, as that will emit an unwarranted
26990b57cec5SDimitry Andric   // reference to our capture state, and will likely generate worse code than
27000b57cec5SDimitry Andric   // emitting a local copy.
27010b57cec5SDimitry Andric   if (E->refersToEnclosingVariableOrCapture())
27020b57cec5SDimitry Andric     return false;
27030b57cec5SDimitry Andric 
27040b57cec5SDimitry Andric   // For a local declaration declared in this function, we can always reference
27050b57cec5SDimitry Andric   // it even if we don't have an odr-use.
27060b57cec5SDimitry Andric   if (VD->hasLocalStorage()) {
27070b57cec5SDimitry Andric     return VD->getDeclContext() ==
27080b57cec5SDimitry Andric            dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
27090b57cec5SDimitry Andric   }
27100b57cec5SDimitry Andric 
27110b57cec5SDimitry Andric   // For a global declaration, we can emit a reference to it if we know
27120b57cec5SDimitry Andric   // for sure that we are able to emit a definition of it.
27130b57cec5SDimitry Andric   VD = VD->getDefinition(CGF.getContext());
27140b57cec5SDimitry Andric   if (!VD)
27150b57cec5SDimitry Andric     return false;
27160b57cec5SDimitry Andric 
27170b57cec5SDimitry Andric   // Don't emit a spurious reference if it might be to a variable that only
27180b57cec5SDimitry Andric   // exists on a different device / target.
27190b57cec5SDimitry Andric   // FIXME: This is unnecessarily broad. Check whether this would actually be a
27200b57cec5SDimitry Andric   // cross-target reference.
27210b57cec5SDimitry Andric   if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
27220b57cec5SDimitry Andric       CGF.getLangOpts().OpenCL) {
27230b57cec5SDimitry Andric     return false;
27240b57cec5SDimitry Andric   }
27250b57cec5SDimitry Andric 
27260b57cec5SDimitry Andric   // We can emit a spurious reference only if the linkage implies that we'll
27270b57cec5SDimitry Andric   // be emitting a non-interposable symbol that will be retained until link
27280b57cec5SDimitry Andric   // time.
27290b57cec5SDimitry Andric   switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
27300b57cec5SDimitry Andric   case llvm::GlobalValue::ExternalLinkage:
27310b57cec5SDimitry Andric   case llvm::GlobalValue::LinkOnceODRLinkage:
27320b57cec5SDimitry Andric   case llvm::GlobalValue::WeakODRLinkage:
27330b57cec5SDimitry Andric   case llvm::GlobalValue::InternalLinkage:
27340b57cec5SDimitry Andric   case llvm::GlobalValue::PrivateLinkage:
27350b57cec5SDimitry Andric     return true;
27360b57cec5SDimitry Andric   default:
27370b57cec5SDimitry Andric     return false;
27380b57cec5SDimitry Andric   }
27390b57cec5SDimitry Andric }
27400b57cec5SDimitry Andric 
27410b57cec5SDimitry Andric LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
27420b57cec5SDimitry Andric   const NamedDecl *ND = E->getDecl();
27430b57cec5SDimitry Andric   QualType T = E->getType();
27440b57cec5SDimitry Andric 
27450b57cec5SDimitry Andric   assert(E->isNonOdrUse() != NOUR_Unevaluated &&
27460b57cec5SDimitry Andric          "should not emit an unevaluated operand");
27470b57cec5SDimitry Andric 
27480b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
27490b57cec5SDimitry Andric     // Global Named registers access via intrinsics only
27500b57cec5SDimitry Andric     if (VD->getStorageClass() == SC_Register &&
27510b57cec5SDimitry Andric         VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
27520b57cec5SDimitry Andric       return EmitGlobalNamedRegister(VD, CGM);
27530b57cec5SDimitry Andric 
27540b57cec5SDimitry Andric     // If this DeclRefExpr does not constitute an odr-use of the variable,
27550b57cec5SDimitry Andric     // we're not permitted to emit a reference to it in general, and it might
27560b57cec5SDimitry Andric     // not be captured if capture would be necessary for a use. Emit the
27570b57cec5SDimitry Andric     // constant value directly instead.
27580b57cec5SDimitry Andric     if (E->isNonOdrUse() == NOUR_Constant &&
27590b57cec5SDimitry Andric         (VD->getType()->isReferenceType() ||
27600b57cec5SDimitry Andric          !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
27610b57cec5SDimitry Andric       VD->getAnyInitializer(VD);
27620b57cec5SDimitry Andric       llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
27630b57cec5SDimitry Andric           E->getLocation(), *VD->evaluateValue(), VD->getType());
27640b57cec5SDimitry Andric       assert(Val && "failed to emit constant expression");
27650b57cec5SDimitry Andric 
27660b57cec5SDimitry Andric       Address Addr = Address::invalid();
27670b57cec5SDimitry Andric       if (!VD->getType()->isReferenceType()) {
27680b57cec5SDimitry Andric         // Spill the constant value to a global.
27690b57cec5SDimitry Andric         Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
27700b57cec5SDimitry Andric                                            getContext().getDeclAlign(VD));
2771c14a5a88SDimitry Andric         llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
2772c14a5a88SDimitry Andric         auto *PTy = llvm::PointerType::get(
2773bdd1243dSDimitry Andric             VarTy, getTypes().getTargetAddressSpace(VD->getType()));
277481ad6265SDimitry Andric         Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
27750b57cec5SDimitry Andric       } else {
27760b57cec5SDimitry Andric         // Should we be using the alignment of the constant pointer we emitted?
27770b57cec5SDimitry Andric         CharUnits Alignment =
27785ffd83dbSDimitry Andric             CGM.getNaturalTypeAlignment(E->getType(),
27790b57cec5SDimitry Andric                                         /* BaseInfo= */ nullptr,
27800b57cec5SDimitry Andric                                         /* TBAAInfo= */ nullptr,
27810b57cec5SDimitry Andric                                         /* forPointeeType= */ true);
27820eae32dcSDimitry Andric         Addr = Address(Val, ConvertTypeForMem(E->getType()), Alignment);
27830b57cec5SDimitry Andric       }
27840b57cec5SDimitry Andric       return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
27850b57cec5SDimitry Andric     }
27860b57cec5SDimitry Andric 
27870b57cec5SDimitry Andric     // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric     // Check for captured variables.
27900b57cec5SDimitry Andric     if (E->refersToEnclosingVariableOrCapture()) {
27910b57cec5SDimitry Andric       VD = VD->getCanonicalDecl();
27920b57cec5SDimitry Andric       if (auto *FD = LambdaCaptureFields.lookup(VD))
27930b57cec5SDimitry Andric         return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2794480093f4SDimitry Andric       if (CapturedStmtInfo) {
27950b57cec5SDimitry Andric         auto I = LocalDeclMap.find(VD);
27960b57cec5SDimitry Andric         if (I != LocalDeclMap.end()) {
2797480093f4SDimitry Andric           LValue CapLVal;
27980b57cec5SDimitry Andric           if (VD->getType()->isReferenceType())
2799480093f4SDimitry Andric             CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
28000b57cec5SDimitry Andric                                                 AlignmentSource::Decl);
2801480093f4SDimitry Andric           else
2802480093f4SDimitry Andric             CapLVal = MakeAddrLValue(I->second, T);
2803480093f4SDimitry Andric           // Mark lvalue as nontemporal if the variable is marked as nontemporal
2804480093f4SDimitry Andric           // in simd context.
2805480093f4SDimitry Andric           if (getLangOpts().OpenMP &&
2806480093f4SDimitry Andric               CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2807480093f4SDimitry Andric             CapLVal.setNontemporal(/*Value=*/true);
2808480093f4SDimitry Andric           return CapLVal;
28090b57cec5SDimitry Andric         }
28100b57cec5SDimitry Andric         LValue CapLVal =
28110b57cec5SDimitry Andric             EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
28120b57cec5SDimitry Andric                                     CapturedStmtInfo->getContextValue());
281381ad6265SDimitry Andric         Address LValueAddress = CapLVal.getAddress(*this);
2814480093f4SDimitry Andric         CapLVal = MakeAddrLValue(
281581ad6265SDimitry Andric             Address(LValueAddress.getPointer(), LValueAddress.getElementType(),
281681ad6265SDimitry Andric                     getContext().getDeclAlign(VD)),
28170b57cec5SDimitry Andric             CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
28180b57cec5SDimitry Andric             CapLVal.getTBAAInfo());
2819480093f4SDimitry Andric         // Mark lvalue as nontemporal if the variable is marked as nontemporal
2820480093f4SDimitry Andric         // in simd context.
2821480093f4SDimitry Andric         if (getLangOpts().OpenMP &&
2822480093f4SDimitry Andric             CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2823480093f4SDimitry Andric           CapLVal.setNontemporal(/*Value=*/true);
2824480093f4SDimitry Andric         return CapLVal;
28250b57cec5SDimitry Andric       }
28260b57cec5SDimitry Andric 
28270b57cec5SDimitry Andric       assert(isa<BlockDecl>(CurCodeDecl));
28280b57cec5SDimitry Andric       Address addr = GetAddrOfBlockDecl(VD);
28290b57cec5SDimitry Andric       return MakeAddrLValue(addr, T, AlignmentSource::Decl);
28300b57cec5SDimitry Andric     }
28310b57cec5SDimitry Andric   }
28320b57cec5SDimitry Andric 
28330b57cec5SDimitry Andric   // FIXME: We should be able to assert this for FunctionDecls as well!
28340b57cec5SDimitry Andric   // FIXME: We should be able to assert this for all DeclRefExprs, not just
28350b57cec5SDimitry Andric   // those with a valid source location.
28360b57cec5SDimitry Andric   assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
28370b57cec5SDimitry Andric           !E->getLocation().isValid()) &&
28380b57cec5SDimitry Andric          "Should not use decl without marking it used!");
28390b57cec5SDimitry Andric 
28400b57cec5SDimitry Andric   if (ND->hasAttr<WeakRefAttr>()) {
28410b57cec5SDimitry Andric     const auto *VD = cast<ValueDecl>(ND);
28420b57cec5SDimitry Andric     ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
28430b57cec5SDimitry Andric     return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
28440b57cec5SDimitry Andric   }
28450b57cec5SDimitry Andric 
28460b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
28470b57cec5SDimitry Andric     // Check if this is a global variable.
28480b57cec5SDimitry Andric     if (VD->hasLinkage() || VD->isStaticDataMember())
28490b57cec5SDimitry Andric       return EmitGlobalVarDeclLValue(*this, E, VD);
28500b57cec5SDimitry Andric 
28510b57cec5SDimitry Andric     Address addr = Address::invalid();
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric     // The variable should generally be present in the local decl map.
28540b57cec5SDimitry Andric     auto iter = LocalDeclMap.find(VD);
28550b57cec5SDimitry Andric     if (iter != LocalDeclMap.end()) {
28560b57cec5SDimitry Andric       addr = iter->second;
28570b57cec5SDimitry Andric 
28580b57cec5SDimitry Andric     // Otherwise, it might be static local we haven't emitted yet for
28590b57cec5SDimitry Andric     // some reason; most likely, because it's in an outer function.
28600b57cec5SDimitry Andric     } else if (VD->isStaticLocal()) {
28610eae32dcSDimitry Andric       llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
28620eae32dcSDimitry Andric           *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
28630eae32dcSDimitry Andric       addr = Address(
28640eae32dcSDimitry Andric           var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
28650b57cec5SDimitry Andric 
28660b57cec5SDimitry Andric     // No other cases for now.
28670b57cec5SDimitry Andric     } else {
28680b57cec5SDimitry Andric       llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
28690b57cec5SDimitry Andric     }
28700b57cec5SDimitry Andric 
2871bdd1243dSDimitry Andric     // Handle threadlocal function locals.
2872bdd1243dSDimitry Andric     if (VD->getTLSKind() != VarDecl::TLS_None)
2873*fe013be4SDimitry Andric       addr = addr.withPointer(
2874*fe013be4SDimitry Andric           Builder.CreateThreadLocalAddress(addr.getPointer()), NotKnownNonNull);
28750b57cec5SDimitry Andric 
28760b57cec5SDimitry Andric     // Check for OpenMP threadprivate variables.
28770b57cec5SDimitry Andric     if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
28780b57cec5SDimitry Andric         VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
28790b57cec5SDimitry Andric       return EmitThreadPrivateVarDeclLValue(
28800b57cec5SDimitry Andric           *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
28810b57cec5SDimitry Andric           E->getExprLoc());
28820b57cec5SDimitry Andric     }
28830b57cec5SDimitry Andric 
28840b57cec5SDimitry Andric     // Drill into block byref variables.
28850b57cec5SDimitry Andric     bool isBlockByref = VD->isEscapingByref();
28860b57cec5SDimitry Andric     if (isBlockByref) {
28870b57cec5SDimitry Andric       addr = emitBlockByrefAddress(addr, VD);
28880b57cec5SDimitry Andric     }
28890b57cec5SDimitry Andric 
28900b57cec5SDimitry Andric     // Drill into reference types.
28910b57cec5SDimitry Andric     LValue LV = VD->getType()->isReferenceType() ?
28920b57cec5SDimitry Andric         EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
28930b57cec5SDimitry Andric         MakeAddrLValue(addr, T, AlignmentSource::Decl);
28940b57cec5SDimitry Andric 
28950b57cec5SDimitry Andric     bool isLocalStorage = VD->hasLocalStorage();
28960b57cec5SDimitry Andric 
28970b57cec5SDimitry Andric     bool NonGCable = isLocalStorage &&
28980b57cec5SDimitry Andric                      !VD->getType()->isReferenceType() &&
28990b57cec5SDimitry Andric                      !isBlockByref;
29000b57cec5SDimitry Andric     if (NonGCable) {
29010b57cec5SDimitry Andric       LV.getQuals().removeObjCGCAttr();
29020b57cec5SDimitry Andric       LV.setNonGC(true);
29030b57cec5SDimitry Andric     }
29040b57cec5SDimitry Andric 
29050b57cec5SDimitry Andric     bool isImpreciseLifetime =
29060b57cec5SDimitry Andric       (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
29070b57cec5SDimitry Andric     if (isImpreciseLifetime)
29080b57cec5SDimitry Andric       LV.setARCPreciseLifetime(ARCImpreciseLifetime);
29090b57cec5SDimitry Andric     setObjCGCLValueClass(getContext(), E, LV);
29100b57cec5SDimitry Andric     return LV;
29110b57cec5SDimitry Andric   }
29120b57cec5SDimitry Andric 
2913fe6060f1SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
2914fe6060f1SDimitry Andric     LValue LV = EmitFunctionDeclLValue(*this, E, FD);
2915fe6060f1SDimitry Andric 
2916fe6060f1SDimitry Andric     // Emit debuginfo for the function declaration if the target wants to.
2917fe6060f1SDimitry Andric     if (getContext().getTargetInfo().allowDebugInfoForExternalRef()) {
2918fe6060f1SDimitry Andric       if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) {
2919fe6060f1SDimitry Andric         auto *Fn =
2920fe6060f1SDimitry Andric             cast<llvm::Function>(LV.getPointer(*this)->stripPointerCasts());
2921fe6060f1SDimitry Andric         if (!Fn->getSubprogram())
2922fe6060f1SDimitry Andric           DI->EmitFunctionDecl(FD, FD->getLocation(), T, Fn);
2923fe6060f1SDimitry Andric       }
2924fe6060f1SDimitry Andric     }
2925fe6060f1SDimitry Andric 
2926fe6060f1SDimitry Andric     return LV;
2927fe6060f1SDimitry Andric   }
29280b57cec5SDimitry Andric 
29290b57cec5SDimitry Andric   // FIXME: While we're emitting a binding from an enclosing scope, all other
29300b57cec5SDimitry Andric   // DeclRefExprs we see should be implicitly treated as if they also refer to
29310b57cec5SDimitry Andric   // an enclosing scope.
2932bdd1243dSDimitry Andric   if (const auto *BD = dyn_cast<BindingDecl>(ND)) {
2933bdd1243dSDimitry Andric     if (E->refersToEnclosingVariableOrCapture()) {
2934bdd1243dSDimitry Andric       auto *FD = LambdaCaptureFields.lookup(BD);
2935bdd1243dSDimitry Andric       return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2936bdd1243dSDimitry Andric     }
29370b57cec5SDimitry Andric     return EmitLValue(BD->getBinding());
2938bdd1243dSDimitry Andric   }
29390b57cec5SDimitry Andric 
29405ffd83dbSDimitry Andric   // We can form DeclRefExprs naming GUID declarations when reconstituting
29415ffd83dbSDimitry Andric   // non-type template parameters into expressions.
29425ffd83dbSDimitry Andric   if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
29435ffd83dbSDimitry Andric     return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
29445ffd83dbSDimitry Andric                           AlignmentSource::Decl);
29455ffd83dbSDimitry Andric 
2946e8d8bef9SDimitry Andric   if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND))
2947e8d8bef9SDimitry Andric     return MakeAddrLValue(CGM.GetAddrOfTemplateParamObject(TPO), T,
2948e8d8bef9SDimitry Andric                           AlignmentSource::Decl);
2949e8d8bef9SDimitry Andric 
29500b57cec5SDimitry Andric   llvm_unreachable("Unhandled DeclRefExpr");
29510b57cec5SDimitry Andric }
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
29540b57cec5SDimitry Andric   // __extension__ doesn't affect lvalue-ness.
29550b57cec5SDimitry Andric   if (E->getOpcode() == UO_Extension)
29560b57cec5SDimitry Andric     return EmitLValue(E->getSubExpr());
29570b57cec5SDimitry Andric 
29580b57cec5SDimitry Andric   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
29590b57cec5SDimitry Andric   switch (E->getOpcode()) {
29600b57cec5SDimitry Andric   default: llvm_unreachable("Unknown unary operator lvalue!");
29610b57cec5SDimitry Andric   case UO_Deref: {
29620b57cec5SDimitry Andric     QualType T = E->getSubExpr()->getType()->getPointeeType();
29630b57cec5SDimitry Andric     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
29640b57cec5SDimitry Andric 
29650b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
29660b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
29670b57cec5SDimitry Andric     Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
29680b57cec5SDimitry Andric                                             &TBAAInfo);
29690b57cec5SDimitry Andric     LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
29700b57cec5SDimitry Andric     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
29710b57cec5SDimitry Andric 
29720b57cec5SDimitry Andric     // We should not generate __weak write barrier on indirect reference
29730b57cec5SDimitry Andric     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
29740b57cec5SDimitry Andric     // But, we continue to generate __strong write barrier on indirect write
29750b57cec5SDimitry Andric     // into a pointer to object.
29760b57cec5SDimitry Andric     if (getLangOpts().ObjC &&
29770b57cec5SDimitry Andric         getLangOpts().getGC() != LangOptions::NonGC &&
29780b57cec5SDimitry Andric         LV.isObjCWeak())
29790b57cec5SDimitry Andric       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
29800b57cec5SDimitry Andric     return LV;
29810b57cec5SDimitry Andric   }
29820b57cec5SDimitry Andric   case UO_Real:
29830b57cec5SDimitry Andric   case UO_Imag: {
29840b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
29850b57cec5SDimitry Andric     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
29860b57cec5SDimitry Andric 
29870b57cec5SDimitry Andric     // __real is valid on scalars.  This is a faster way of testing that.
29880b57cec5SDimitry Andric     // __imag can only produce an rvalue on scalars.
29890b57cec5SDimitry Andric     if (E->getOpcode() == UO_Real &&
2990480093f4SDimitry Andric         !LV.getAddress(*this).getElementType()->isStructTy()) {
29910b57cec5SDimitry Andric       assert(E->getSubExpr()->getType()->isArithmeticType());
29920b57cec5SDimitry Andric       return LV;
29930b57cec5SDimitry Andric     }
29940b57cec5SDimitry Andric 
29950b57cec5SDimitry Andric     QualType T = ExprTy->castAs<ComplexType>()->getElementType();
29960b57cec5SDimitry Andric 
29970b57cec5SDimitry Andric     Address Component =
29980b57cec5SDimitry Andric         (E->getOpcode() == UO_Real
2999480093f4SDimitry Andric              ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
3000480093f4SDimitry Andric              : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType()));
30010b57cec5SDimitry Andric     LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
30020b57cec5SDimitry Andric                                    CGM.getTBAAInfoForSubobject(LV, T));
30030b57cec5SDimitry Andric     ElemLV.getQuals().addQualifiers(LV.getQuals());
30040b57cec5SDimitry Andric     return ElemLV;
30050b57cec5SDimitry Andric   }
30060b57cec5SDimitry Andric   case UO_PreInc:
30070b57cec5SDimitry Andric   case UO_PreDec: {
30080b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
30090b57cec5SDimitry Andric     bool isInc = E->getOpcode() == UO_PreInc;
30100b57cec5SDimitry Andric 
30110b57cec5SDimitry Andric     if (E->getType()->isAnyComplexType())
30120b57cec5SDimitry Andric       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
30130b57cec5SDimitry Andric     else
30140b57cec5SDimitry Andric       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
30150b57cec5SDimitry Andric     return LV;
30160b57cec5SDimitry Andric   }
30170b57cec5SDimitry Andric   }
30180b57cec5SDimitry Andric }
30190b57cec5SDimitry Andric 
30200b57cec5SDimitry Andric LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
30210b57cec5SDimitry Andric   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
30220b57cec5SDimitry Andric                         E->getType(), AlignmentSource::Decl);
30230b57cec5SDimitry Andric }
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
30260b57cec5SDimitry Andric   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
30270b57cec5SDimitry Andric                         E->getType(), AlignmentSource::Decl);
30280b57cec5SDimitry Andric }
30290b57cec5SDimitry Andric 
30300b57cec5SDimitry Andric LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
30310b57cec5SDimitry Andric   auto SL = E->getFunctionName();
30320b57cec5SDimitry Andric   assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
30330b57cec5SDimitry Andric   StringRef FnName = CurFn->getName();
30340b57cec5SDimitry Andric   if (FnName.startswith("\01"))
30350b57cec5SDimitry Andric     FnName = FnName.substr(1);
30360b57cec5SDimitry Andric   StringRef NameItems[] = {
30370b57cec5SDimitry Andric       PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
30380b57cec5SDimitry Andric   std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
30390b57cec5SDimitry Andric   if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
30405ffd83dbSDimitry Andric     std::string Name = std::string(SL->getString());
30410b57cec5SDimitry Andric     if (!Name.empty()) {
30420b57cec5SDimitry Andric       unsigned Discriminator =
30430b57cec5SDimitry Andric           CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
30440b57cec5SDimitry Andric       if (Discriminator)
30450b57cec5SDimitry Andric         Name += "_" + Twine(Discriminator + 1).str();
30460b57cec5SDimitry Andric       auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
30470b57cec5SDimitry Andric       return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
30480b57cec5SDimitry Andric     } else {
30495ffd83dbSDimitry Andric       auto C =
30505ffd83dbSDimitry Andric           CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
30510b57cec5SDimitry Andric       return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
30520b57cec5SDimitry Andric     }
30530b57cec5SDimitry Andric   }
30540b57cec5SDimitry Andric   auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
30550b57cec5SDimitry Andric   return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
30560b57cec5SDimitry Andric }
30570b57cec5SDimitry Andric 
30580b57cec5SDimitry Andric /// Emit a type description suitable for use by a runtime sanitizer library. The
30590b57cec5SDimitry Andric /// format of a type descriptor is
30600b57cec5SDimitry Andric ///
30610b57cec5SDimitry Andric /// \code
30620b57cec5SDimitry Andric ///   { i16 TypeKind, i16 TypeInfo }
30630b57cec5SDimitry Andric /// \endcode
30640b57cec5SDimitry Andric ///
30650b57cec5SDimitry Andric /// followed by an array of i8 containing the type name. TypeKind is 0 for an
30660b57cec5SDimitry Andric /// integer, 1 for a floating point value, and -1 for anything else.
30670b57cec5SDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
30680b57cec5SDimitry Andric   // Only emit each type's descriptor once.
30690b57cec5SDimitry Andric   if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
30700b57cec5SDimitry Andric     return C;
30710b57cec5SDimitry Andric 
30720b57cec5SDimitry Andric   uint16_t TypeKind = -1;
30730b57cec5SDimitry Andric   uint16_t TypeInfo = 0;
30740b57cec5SDimitry Andric 
30750b57cec5SDimitry Andric   if (T->isIntegerType()) {
30760b57cec5SDimitry Andric     TypeKind = 0;
30770b57cec5SDimitry Andric     TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
30780b57cec5SDimitry Andric                (T->isSignedIntegerType() ? 1 : 0);
30790b57cec5SDimitry Andric   } else if (T->isFloatingType()) {
30800b57cec5SDimitry Andric     TypeKind = 1;
30810b57cec5SDimitry Andric     TypeInfo = getContext().getTypeSize(T);
30820b57cec5SDimitry Andric   }
30830b57cec5SDimitry Andric 
30840b57cec5SDimitry Andric   // Format the type name as if for a diagnostic, including quotes and
30850b57cec5SDimitry Andric   // optionally an 'aka'.
30860b57cec5SDimitry Andric   SmallString<32> Buffer;
3087bdd1243dSDimitry Andric   CGM.getDiags().ConvertArgToString(
3088bdd1243dSDimitry Andric       DiagnosticsEngine::ak_qualtype, (intptr_t)T.getAsOpaquePtr(), StringRef(),
3089bdd1243dSDimitry Andric       StringRef(), std::nullopt, Buffer, std::nullopt);
30900b57cec5SDimitry Andric 
30910b57cec5SDimitry Andric   llvm::Constant *Components[] = {
30920b57cec5SDimitry Andric     Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
30930b57cec5SDimitry Andric     llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
30940b57cec5SDimitry Andric   };
30950b57cec5SDimitry Andric   llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
30960b57cec5SDimitry Andric 
30970b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
30980b57cec5SDimitry Andric       CGM.getModule(), Descriptor->getType(),
30990b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
31000b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
31010b57cec5SDimitry Andric   CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
31020b57cec5SDimitry Andric 
31030b57cec5SDimitry Andric   // Remember the descriptor for this type.
31040b57cec5SDimitry Andric   CGM.setTypeDescriptorInMap(T, GV);
31050b57cec5SDimitry Andric 
31060b57cec5SDimitry Andric   return GV;
31070b57cec5SDimitry Andric }
31080b57cec5SDimitry Andric 
31090b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
31100b57cec5SDimitry Andric   llvm::Type *TargetTy = IntPtrTy;
31110b57cec5SDimitry Andric 
31120b57cec5SDimitry Andric   if (V->getType() == TargetTy)
31130b57cec5SDimitry Andric     return V;
31140b57cec5SDimitry Andric 
31150b57cec5SDimitry Andric   // Floating-point types which fit into intptr_t are bitcast to integers
31160b57cec5SDimitry Andric   // and then passed directly (after zero-extension, if necessary).
31170b57cec5SDimitry Andric   if (V->getType()->isFloatingPointTy()) {
3118bdd1243dSDimitry Andric     unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedValue();
31190b57cec5SDimitry Andric     if (Bits <= TargetTy->getIntegerBitWidth())
31200b57cec5SDimitry Andric       V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
31210b57cec5SDimitry Andric                                                          Bits));
31220b57cec5SDimitry Andric   }
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric   // Integers which fit in intptr_t are zero-extended and passed directly.
31250b57cec5SDimitry Andric   if (V->getType()->isIntegerTy() &&
31260b57cec5SDimitry Andric       V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
31270b57cec5SDimitry Andric     return Builder.CreateZExt(V, TargetTy);
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric   // Pointers are passed directly, everything else is passed by address.
31300b57cec5SDimitry Andric   if (!V->getType()->isPointerTy()) {
31310b57cec5SDimitry Andric     Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
31320b57cec5SDimitry Andric     Builder.CreateStore(V, Ptr);
31330b57cec5SDimitry Andric     V = Ptr.getPointer();
31340b57cec5SDimitry Andric   }
31350b57cec5SDimitry Andric   return Builder.CreatePtrToInt(V, TargetTy);
31360b57cec5SDimitry Andric }
31370b57cec5SDimitry Andric 
31380b57cec5SDimitry Andric /// Emit a representation of a SourceLocation for passing to a handler
31390b57cec5SDimitry Andric /// in a sanitizer runtime library. The format for this data is:
31400b57cec5SDimitry Andric /// \code
31410b57cec5SDimitry Andric ///   struct SourceLocation {
31420b57cec5SDimitry Andric ///     const char *Filename;
31430b57cec5SDimitry Andric ///     int32_t Line, Column;
31440b57cec5SDimitry Andric ///   };
31450b57cec5SDimitry Andric /// \endcode
31460b57cec5SDimitry Andric /// For an invalid SourceLocation, the Filename pointer is null.
31470b57cec5SDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
31480b57cec5SDimitry Andric   llvm::Constant *Filename;
31490b57cec5SDimitry Andric   int Line, Column;
31500b57cec5SDimitry Andric 
31510b57cec5SDimitry Andric   PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
31520b57cec5SDimitry Andric   if (PLoc.isValid()) {
31530b57cec5SDimitry Andric     StringRef FilenameString = PLoc.getFilename();
31540b57cec5SDimitry Andric 
31550b57cec5SDimitry Andric     int PathComponentsToStrip =
31560b57cec5SDimitry Andric         CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
31570b57cec5SDimitry Andric     if (PathComponentsToStrip < 0) {
31580b57cec5SDimitry Andric       assert(PathComponentsToStrip != INT_MIN);
31590b57cec5SDimitry Andric       int PathComponentsToKeep = -PathComponentsToStrip;
31600b57cec5SDimitry Andric       auto I = llvm::sys::path::rbegin(FilenameString);
31610b57cec5SDimitry Andric       auto E = llvm::sys::path::rend(FilenameString);
31620b57cec5SDimitry Andric       while (I != E && --PathComponentsToKeep)
31630b57cec5SDimitry Andric         ++I;
31640b57cec5SDimitry Andric 
31650b57cec5SDimitry Andric       FilenameString = FilenameString.substr(I - E);
31660b57cec5SDimitry Andric     } else if (PathComponentsToStrip > 0) {
31670b57cec5SDimitry Andric       auto I = llvm::sys::path::begin(FilenameString);
31680b57cec5SDimitry Andric       auto E = llvm::sys::path::end(FilenameString);
31690b57cec5SDimitry Andric       while (I != E && PathComponentsToStrip--)
31700b57cec5SDimitry Andric         ++I;
31710b57cec5SDimitry Andric 
31720b57cec5SDimitry Andric       if (I != E)
31730b57cec5SDimitry Andric         FilenameString =
31740b57cec5SDimitry Andric             FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
31750b57cec5SDimitry Andric       else
31760b57cec5SDimitry Andric         FilenameString = llvm::sys::path::filename(FilenameString);
31770b57cec5SDimitry Andric     }
31780b57cec5SDimitry Andric 
31795ffd83dbSDimitry Andric     auto FilenameGV =
31805ffd83dbSDimitry Andric         CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
31810b57cec5SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
3182bdd1243dSDimitry Andric         cast<llvm::GlobalVariable>(
3183bdd1243dSDimitry Andric             FilenameGV.getPointer()->stripPointerCasts()));
31840b57cec5SDimitry Andric     Filename = FilenameGV.getPointer();
31850b57cec5SDimitry Andric     Line = PLoc.getLine();
31860b57cec5SDimitry Andric     Column = PLoc.getColumn();
31870b57cec5SDimitry Andric   } else {
31880b57cec5SDimitry Andric     Filename = llvm::Constant::getNullValue(Int8PtrTy);
31890b57cec5SDimitry Andric     Line = Column = 0;
31900b57cec5SDimitry Andric   }
31910b57cec5SDimitry Andric 
31920b57cec5SDimitry Andric   llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
31930b57cec5SDimitry Andric                             Builder.getInt32(Column)};
31940b57cec5SDimitry Andric 
31950b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Data);
31960b57cec5SDimitry Andric }
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric namespace {
31990b57cec5SDimitry Andric /// Specify under what conditions this check can be recovered
32000b57cec5SDimitry Andric enum class CheckRecoverableKind {
32010b57cec5SDimitry Andric   /// Always terminate program execution if this check fails.
32020b57cec5SDimitry Andric   Unrecoverable,
32030b57cec5SDimitry Andric   /// Check supports recovering, runtime has both fatal (noreturn) and
32040b57cec5SDimitry Andric   /// non-fatal handlers for this check.
32050b57cec5SDimitry Andric   Recoverable,
32060b57cec5SDimitry Andric   /// Runtime conditionally aborts, always need to support recovery.
32070b57cec5SDimitry Andric   AlwaysRecoverable
32080b57cec5SDimitry Andric };
32090b57cec5SDimitry Andric }
32100b57cec5SDimitry Andric 
32110b57cec5SDimitry Andric static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
32120b57cec5SDimitry Andric   assert(Kind.countPopulation() == 1);
3213*fe013be4SDimitry Andric   if (Kind == SanitizerKind::Vptr)
32140b57cec5SDimitry Andric     return CheckRecoverableKind::AlwaysRecoverable;
32150b57cec5SDimitry Andric   else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
32160b57cec5SDimitry Andric     return CheckRecoverableKind::Unrecoverable;
32170b57cec5SDimitry Andric   else
32180b57cec5SDimitry Andric     return CheckRecoverableKind::Recoverable;
32190b57cec5SDimitry Andric }
32200b57cec5SDimitry Andric 
32210b57cec5SDimitry Andric namespace {
32220b57cec5SDimitry Andric struct SanitizerHandlerInfo {
32230b57cec5SDimitry Andric   char const *const Name;
32240b57cec5SDimitry Andric   unsigned Version;
32250b57cec5SDimitry Andric };
32260b57cec5SDimitry Andric }
32270b57cec5SDimitry Andric 
32280b57cec5SDimitry Andric const SanitizerHandlerInfo SanitizerHandlers[] = {
32290b57cec5SDimitry Andric #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
32300b57cec5SDimitry Andric     LIST_SANITIZER_CHECKS
32310b57cec5SDimitry Andric #undef SANITIZER_CHECK
32320b57cec5SDimitry Andric };
32330b57cec5SDimitry Andric 
32340b57cec5SDimitry Andric static void emitCheckHandlerCall(CodeGenFunction &CGF,
32350b57cec5SDimitry Andric                                  llvm::FunctionType *FnType,
32360b57cec5SDimitry Andric                                  ArrayRef<llvm::Value *> FnArgs,
32370b57cec5SDimitry Andric                                  SanitizerHandler CheckHandler,
32380b57cec5SDimitry Andric                                  CheckRecoverableKind RecoverKind, bool IsFatal,
32390b57cec5SDimitry Andric                                  llvm::BasicBlock *ContBB) {
32400b57cec5SDimitry Andric   assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
3241bdd1243dSDimitry Andric   std::optional<ApplyDebugLocation> DL;
32420b57cec5SDimitry Andric   if (!CGF.Builder.getCurrentDebugLocation()) {
32430b57cec5SDimitry Andric     // Ensure that the call has at least an artificial debug location.
32440b57cec5SDimitry Andric     DL.emplace(CGF, SourceLocation());
32450b57cec5SDimitry Andric   }
32460b57cec5SDimitry Andric   bool NeedsAbortSuffix =
32470b57cec5SDimitry Andric       IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
32480b57cec5SDimitry Andric   bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
32490b57cec5SDimitry Andric   const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
32500b57cec5SDimitry Andric   const StringRef CheckName = CheckInfo.Name;
32510b57cec5SDimitry Andric   std::string FnName = "__ubsan_handle_" + CheckName.str();
32520b57cec5SDimitry Andric   if (CheckInfo.Version && !MinimalRuntime)
32530b57cec5SDimitry Andric     FnName += "_v" + llvm::utostr(CheckInfo.Version);
32540b57cec5SDimitry Andric   if (MinimalRuntime)
32550b57cec5SDimitry Andric     FnName += "_minimal";
32560b57cec5SDimitry Andric   if (NeedsAbortSuffix)
32570b57cec5SDimitry Andric     FnName += "_abort";
32580b57cec5SDimitry Andric   bool MayReturn =
32590b57cec5SDimitry Andric       !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
32600b57cec5SDimitry Andric 
326104eeddc0SDimitry Andric   llvm::AttrBuilder B(CGF.getLLVMContext());
32620b57cec5SDimitry Andric   if (!MayReturn) {
32630b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoReturn)
32640b57cec5SDimitry Andric         .addAttribute(llvm::Attribute::NoUnwind);
32650b57cec5SDimitry Andric   }
326681ad6265SDimitry Andric   B.addUWTableAttr(llvm::UWTableKind::Default);
32670b57cec5SDimitry Andric 
32680b57cec5SDimitry Andric   llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
32690b57cec5SDimitry Andric       FnType, FnName,
32700b57cec5SDimitry Andric       llvm::AttributeList::get(CGF.getLLVMContext(),
32710b57cec5SDimitry Andric                                llvm::AttributeList::FunctionIndex, B),
32720b57cec5SDimitry Andric       /*Local=*/true);
32730b57cec5SDimitry Andric   llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
32740b57cec5SDimitry Andric   if (!MayReturn) {
32750b57cec5SDimitry Andric     HandlerCall->setDoesNotReturn();
32760b57cec5SDimitry Andric     CGF.Builder.CreateUnreachable();
32770b57cec5SDimitry Andric   } else {
32780b57cec5SDimitry Andric     CGF.Builder.CreateBr(ContBB);
32790b57cec5SDimitry Andric   }
32800b57cec5SDimitry Andric }
32810b57cec5SDimitry Andric 
32820b57cec5SDimitry Andric void CodeGenFunction::EmitCheck(
32830b57cec5SDimitry Andric     ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
32840b57cec5SDimitry Andric     SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
32850b57cec5SDimitry Andric     ArrayRef<llvm::Value *> DynamicArgs) {
32860b57cec5SDimitry Andric   assert(IsSanitizerScope);
32870b57cec5SDimitry Andric   assert(Checked.size() > 0);
32880b57cec5SDimitry Andric   assert(CheckHandler >= 0 &&
3289bdd1243dSDimitry Andric          size_t(CheckHandler) < std::size(SanitizerHandlers));
32900b57cec5SDimitry Andric   const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
32910b57cec5SDimitry Andric 
32920b57cec5SDimitry Andric   llvm::Value *FatalCond = nullptr;
32930b57cec5SDimitry Andric   llvm::Value *RecoverableCond = nullptr;
32940b57cec5SDimitry Andric   llvm::Value *TrapCond = nullptr;
32950b57cec5SDimitry Andric   for (int i = 0, n = Checked.size(); i < n; ++i) {
32960b57cec5SDimitry Andric     llvm::Value *Check = Checked[i].first;
32970b57cec5SDimitry Andric     // -fsanitize-trap= overrides -fsanitize-recover=.
32980b57cec5SDimitry Andric     llvm::Value *&Cond =
32990b57cec5SDimitry Andric         CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
33000b57cec5SDimitry Andric             ? TrapCond
33010b57cec5SDimitry Andric             : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
33020b57cec5SDimitry Andric                   ? RecoverableCond
33030b57cec5SDimitry Andric                   : FatalCond;
33040b57cec5SDimitry Andric     Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
33050b57cec5SDimitry Andric   }
33060b57cec5SDimitry Andric 
33070b57cec5SDimitry Andric   if (TrapCond)
3308e8d8bef9SDimitry Andric     EmitTrapCheck(TrapCond, CheckHandler);
33090b57cec5SDimitry Andric   if (!FatalCond && !RecoverableCond)
33100b57cec5SDimitry Andric     return;
33110b57cec5SDimitry Andric 
33120b57cec5SDimitry Andric   llvm::Value *JointCond;
33130b57cec5SDimitry Andric   if (FatalCond && RecoverableCond)
33140b57cec5SDimitry Andric     JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
33150b57cec5SDimitry Andric   else
33160b57cec5SDimitry Andric     JointCond = FatalCond ? FatalCond : RecoverableCond;
33170b57cec5SDimitry Andric   assert(JointCond);
33180b57cec5SDimitry Andric 
33190b57cec5SDimitry Andric   CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
33200b57cec5SDimitry Andric   assert(SanOpts.has(Checked[0].second));
33210b57cec5SDimitry Andric #ifndef NDEBUG
33220b57cec5SDimitry Andric   for (int i = 1, n = Checked.size(); i < n; ++i) {
33230b57cec5SDimitry Andric     assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
33240b57cec5SDimitry Andric            "All recoverable kinds in a single check must be same!");
33250b57cec5SDimitry Andric     assert(SanOpts.has(Checked[i].second));
33260b57cec5SDimitry Andric   }
33270b57cec5SDimitry Andric #endif
33280b57cec5SDimitry Andric 
33290b57cec5SDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cont");
33300b57cec5SDimitry Andric   llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
33310b57cec5SDimitry Andric   llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
33320b57cec5SDimitry Andric   // Give hint that we very much don't expect to execute the handler
33330b57cec5SDimitry Andric   // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
33340b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
33350b57cec5SDimitry Andric   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
33360b57cec5SDimitry Andric   Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
33370b57cec5SDimitry Andric   EmitBlock(Handlers);
33380b57cec5SDimitry Andric 
33390b57cec5SDimitry Andric   // Handler functions take an i8* pointing to the (handler-specific) static
33400b57cec5SDimitry Andric   // information block, followed by a sequence of intptr_t arguments
33410b57cec5SDimitry Andric   // representing operand values.
33420b57cec5SDimitry Andric   SmallVector<llvm::Value *, 4> Args;
33430b57cec5SDimitry Andric   SmallVector<llvm::Type *, 4> ArgTypes;
33440b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
33450b57cec5SDimitry Andric     Args.reserve(DynamicArgs.size() + 1);
33460b57cec5SDimitry Andric     ArgTypes.reserve(DynamicArgs.size() + 1);
33470b57cec5SDimitry Andric 
33480b57cec5SDimitry Andric     // Emit handler arguments and create handler function type.
33490b57cec5SDimitry Andric     if (!StaticArgs.empty()) {
33500b57cec5SDimitry Andric       llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3351bdd1243dSDimitry Andric       auto *InfoPtr = new llvm::GlobalVariable(
3352bdd1243dSDimitry Andric           CGM.getModule(), Info->getType(), false,
3353bdd1243dSDimitry Andric           llvm::GlobalVariable::PrivateLinkage, Info, "", nullptr,
3354bdd1243dSDimitry Andric           llvm::GlobalVariable::NotThreadLocal,
3355bdd1243dSDimitry Andric           CGM.getDataLayout().getDefaultGlobalsAddressSpace());
33560b57cec5SDimitry Andric       InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
33570b57cec5SDimitry Andric       CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3358*fe013be4SDimitry Andric       Args.push_back(InfoPtr);
3359bdd1243dSDimitry Andric       ArgTypes.push_back(Args.back()->getType());
33600b57cec5SDimitry Andric     }
33610b57cec5SDimitry Andric 
33620b57cec5SDimitry Andric     for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
33630b57cec5SDimitry Andric       Args.push_back(EmitCheckValue(DynamicArgs[i]));
33640b57cec5SDimitry Andric       ArgTypes.push_back(IntPtrTy);
33650b57cec5SDimitry Andric     }
33660b57cec5SDimitry Andric   }
33670b57cec5SDimitry Andric 
33680b57cec5SDimitry Andric   llvm::FunctionType *FnType =
33690b57cec5SDimitry Andric     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
33700b57cec5SDimitry Andric 
33710b57cec5SDimitry Andric   if (!FatalCond || !RecoverableCond) {
33720b57cec5SDimitry Andric     // Simple case: we need to generate a single handler call, either
33730b57cec5SDimitry Andric     // fatal, or non-fatal.
33740b57cec5SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
33750b57cec5SDimitry Andric                          (FatalCond != nullptr), Cont);
33760b57cec5SDimitry Andric   } else {
33770b57cec5SDimitry Andric     // Emit two handler calls: first one for set of unrecoverable checks,
33780b57cec5SDimitry Andric     // another one for recoverable.
33790b57cec5SDimitry Andric     llvm::BasicBlock *NonFatalHandlerBB =
33800b57cec5SDimitry Andric         createBasicBlock("non_fatal." + CheckName);
33810b57cec5SDimitry Andric     llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
33820b57cec5SDimitry Andric     Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
33830b57cec5SDimitry Andric     EmitBlock(FatalHandlerBB);
33840b57cec5SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
33850b57cec5SDimitry Andric                          NonFatalHandlerBB);
33860b57cec5SDimitry Andric     EmitBlock(NonFatalHandlerBB);
33870b57cec5SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
33880b57cec5SDimitry Andric                          Cont);
33890b57cec5SDimitry Andric   }
33900b57cec5SDimitry Andric 
33910b57cec5SDimitry Andric   EmitBlock(Cont);
33920b57cec5SDimitry Andric }
33930b57cec5SDimitry Andric 
33940b57cec5SDimitry Andric void CodeGenFunction::EmitCfiSlowPathCheck(
33950b57cec5SDimitry Andric     SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
33960b57cec5SDimitry Andric     llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
33970b57cec5SDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
33980b57cec5SDimitry Andric 
33990b57cec5SDimitry Andric   llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
34000b57cec5SDimitry Andric   llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
34010b57cec5SDimitry Andric 
34020b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
34030b57cec5SDimitry Andric   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
34040b57cec5SDimitry Andric   BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
34050b57cec5SDimitry Andric 
34060b57cec5SDimitry Andric   EmitBlock(CheckBB);
34070b57cec5SDimitry Andric 
34080b57cec5SDimitry Andric   bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
34090b57cec5SDimitry Andric 
34100b57cec5SDimitry Andric   llvm::CallInst *CheckCall;
34110b57cec5SDimitry Andric   llvm::FunctionCallee SlowPathFn;
34120b57cec5SDimitry Andric   if (WithDiag) {
34130b57cec5SDimitry Andric     llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
34140b57cec5SDimitry Andric     auto *InfoPtr =
34150b57cec5SDimitry Andric         new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
34160b57cec5SDimitry Andric                                  llvm::GlobalVariable::PrivateLinkage, Info);
34170b57cec5SDimitry Andric     InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
34180b57cec5SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
34190b57cec5SDimitry Andric 
34200b57cec5SDimitry Andric     SlowPathFn = CGM.getModule().getOrInsertFunction(
34210b57cec5SDimitry Andric         "__cfi_slowpath_diag",
34220b57cec5SDimitry Andric         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
34230b57cec5SDimitry Andric                                 false));
34240b57cec5SDimitry Andric     CheckCall = Builder.CreateCall(
34250b57cec5SDimitry Andric         SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
34260b57cec5SDimitry Andric   } else {
34270b57cec5SDimitry Andric     SlowPathFn = CGM.getModule().getOrInsertFunction(
34280b57cec5SDimitry Andric         "__cfi_slowpath",
34290b57cec5SDimitry Andric         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
34300b57cec5SDimitry Andric     CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
34310b57cec5SDimitry Andric   }
34320b57cec5SDimitry Andric 
34330b57cec5SDimitry Andric   CGM.setDSOLocal(
34340b57cec5SDimitry Andric       cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
34350b57cec5SDimitry Andric   CheckCall->setDoesNotThrow();
34360b57cec5SDimitry Andric 
34370b57cec5SDimitry Andric   EmitBlock(Cont);
34380b57cec5SDimitry Andric }
34390b57cec5SDimitry Andric 
34400b57cec5SDimitry Andric // Emit a stub for __cfi_check function so that the linker knows about this
34410b57cec5SDimitry Andric // symbol in LTO mode.
34420b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckStub() {
34430b57cec5SDimitry Andric   llvm::Module *M = &CGM.getModule();
34440b57cec5SDimitry Andric   auto &Ctx = M->getContext();
34450b57cec5SDimitry Andric   llvm::Function *F = llvm::Function::Create(
34460b57cec5SDimitry Andric       llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
34470b57cec5SDimitry Andric       llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
34480b57cec5SDimitry Andric   CGM.setDSOLocal(F);
34490b57cec5SDimitry Andric   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
34500b57cec5SDimitry Andric   // FIXME: consider emitting an intrinsic call like
34510b57cec5SDimitry Andric   // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
34520b57cec5SDimitry Andric   // which can be lowered in CrossDSOCFI pass to the actual contents of
34530b57cec5SDimitry Andric   // __cfi_check. This would allow inlining of __cfi_check calls.
34540b57cec5SDimitry Andric   llvm::CallInst::Create(
34550b57cec5SDimitry Andric       llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
34560b57cec5SDimitry Andric   llvm::ReturnInst::Create(Ctx, nullptr, BB);
34570b57cec5SDimitry Andric }
34580b57cec5SDimitry Andric 
34590b57cec5SDimitry Andric // This function is basically a switch over the CFI failure kind, which is
34600b57cec5SDimitry Andric // extracted from CFICheckFailData (1st function argument). Each case is either
34610b57cec5SDimitry Andric // llvm.trap or a call to one of the two runtime handlers, based on
34620b57cec5SDimitry Andric // -fsanitize-trap and -fsanitize-recover settings.  Default case (invalid
34630b57cec5SDimitry Andric // failure kind) traps, but this should really never happen.  CFICheckFailData
34640b57cec5SDimitry Andric // can be nullptr if the calling module has -fsanitize-trap behavior for this
34650b57cec5SDimitry Andric // check kind; in this case __cfi_check_fail traps as well.
34660b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckFail() {
34670b57cec5SDimitry Andric   SanitizerScope SanScope(this);
34680b57cec5SDimitry Andric   FunctionArgList Args;
34690b57cec5SDimitry Andric   ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
34700b57cec5SDimitry Andric                             ImplicitParamDecl::Other);
34710b57cec5SDimitry Andric   ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
34720b57cec5SDimitry Andric                             ImplicitParamDecl::Other);
34730b57cec5SDimitry Andric   Args.push_back(&ArgData);
34740b57cec5SDimitry Andric   Args.push_back(&ArgAddr);
34750b57cec5SDimitry Andric 
34760b57cec5SDimitry Andric   const CGFunctionInfo &FI =
34770b57cec5SDimitry Andric     CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
34780b57cec5SDimitry Andric 
34790b57cec5SDimitry Andric   llvm::Function *F = llvm::Function::Create(
34800b57cec5SDimitry Andric       llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
34810b57cec5SDimitry Andric       llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3482480093f4SDimitry Andric 
3483fe6060f1SDimitry Andric   CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3484480093f4SDimitry Andric   CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
34850b57cec5SDimitry Andric   F->setVisibility(llvm::GlobalValue::HiddenVisibility);
34860b57cec5SDimitry Andric 
34870b57cec5SDimitry Andric   StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
34880b57cec5SDimitry Andric                 SourceLocation());
34890b57cec5SDimitry Andric 
3490fe6060f1SDimitry Andric   // This function is not affected by NoSanitizeList. This function does
34910b57cec5SDimitry Andric   // not have a source location, but "src:*" would still apply. Revert any
34920b57cec5SDimitry Andric   // changes to SanOpts made in StartFunction.
34930b57cec5SDimitry Andric   SanOpts = CGM.getLangOpts().Sanitize;
34940b57cec5SDimitry Andric 
34950b57cec5SDimitry Andric   llvm::Value *Data =
34960b57cec5SDimitry Andric       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
34970b57cec5SDimitry Andric                        CGM.getContext().VoidPtrTy, ArgData.getLocation());
34980b57cec5SDimitry Andric   llvm::Value *Addr =
34990b57cec5SDimitry Andric       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
35000b57cec5SDimitry Andric                        CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
35010b57cec5SDimitry Andric 
35020b57cec5SDimitry Andric   // Data == nullptr means the calling module has trap behaviour for this check.
35030b57cec5SDimitry Andric   llvm::Value *DataIsNotNullPtr =
35040b57cec5SDimitry Andric       Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3505e8d8bef9SDimitry Andric   EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
35060b57cec5SDimitry Andric 
35070b57cec5SDimitry Andric   llvm::StructType *SourceLocationTy =
35080b57cec5SDimitry Andric       llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
35090b57cec5SDimitry Andric   llvm::StructType *CfiCheckFailDataTy =
35100b57cec5SDimitry Andric       llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
35110b57cec5SDimitry Andric 
35120b57cec5SDimitry Andric   llvm::Value *V = Builder.CreateConstGEP2_32(
35130b57cec5SDimitry Andric       CfiCheckFailDataTy,
35140b57cec5SDimitry Andric       Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
35150b57cec5SDimitry Andric       0);
351681ad6265SDimitry Andric 
351781ad6265SDimitry Andric   Address CheckKindAddr(V, Int8Ty, getIntAlign());
35180b57cec5SDimitry Andric   llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
35190b57cec5SDimitry Andric 
35200b57cec5SDimitry Andric   llvm::Value *AllVtables = llvm::MetadataAsValue::get(
35210b57cec5SDimitry Andric       CGM.getLLVMContext(),
35220b57cec5SDimitry Andric       llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
35230b57cec5SDimitry Andric   llvm::Value *ValidVtable = Builder.CreateZExt(
35240b57cec5SDimitry Andric       Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
35250b57cec5SDimitry Andric                          {Addr, AllVtables}),
35260b57cec5SDimitry Andric       IntPtrTy);
35270b57cec5SDimitry Andric 
35280b57cec5SDimitry Andric   const std::pair<int, SanitizerMask> CheckKinds[] = {
35290b57cec5SDimitry Andric       {CFITCK_VCall, SanitizerKind::CFIVCall},
35300b57cec5SDimitry Andric       {CFITCK_NVCall, SanitizerKind::CFINVCall},
35310b57cec5SDimitry Andric       {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
35320b57cec5SDimitry Andric       {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
35330b57cec5SDimitry Andric       {CFITCK_ICall, SanitizerKind::CFIICall}};
35340b57cec5SDimitry Andric 
35350b57cec5SDimitry Andric   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
35360b57cec5SDimitry Andric   for (auto CheckKindMaskPair : CheckKinds) {
35370b57cec5SDimitry Andric     int Kind = CheckKindMaskPair.first;
35380b57cec5SDimitry Andric     SanitizerMask Mask = CheckKindMaskPair.second;
35390b57cec5SDimitry Andric     llvm::Value *Cond =
35400b57cec5SDimitry Andric         Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
35410b57cec5SDimitry Andric     if (CGM.getLangOpts().Sanitize.has(Mask))
35420b57cec5SDimitry Andric       EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
35430b57cec5SDimitry Andric                 {Data, Addr, ValidVtable});
35440b57cec5SDimitry Andric     else
3545e8d8bef9SDimitry Andric       EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
35460b57cec5SDimitry Andric   }
35470b57cec5SDimitry Andric 
35480b57cec5SDimitry Andric   FinishFunction();
35490b57cec5SDimitry Andric   // The only reference to this function will be created during LTO link.
35500b57cec5SDimitry Andric   // Make sure it survives until then.
35510b57cec5SDimitry Andric   CGM.addUsedGlobal(F);
35520b57cec5SDimitry Andric }
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
35550b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Unreachable)) {
35560b57cec5SDimitry Andric     SanitizerScope SanScope(this);
35570b57cec5SDimitry Andric     EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
35580b57cec5SDimitry Andric                              SanitizerKind::Unreachable),
35590b57cec5SDimitry Andric               SanitizerHandler::BuiltinUnreachable,
3560bdd1243dSDimitry Andric               EmitCheckSourceLocation(Loc), std::nullopt);
35610b57cec5SDimitry Andric   }
35620b57cec5SDimitry Andric   Builder.CreateUnreachable();
35630b57cec5SDimitry Andric }
35640b57cec5SDimitry Andric 
3565e8d8bef9SDimitry Andric void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
3566e8d8bef9SDimitry Andric                                     SanitizerHandler CheckHandlerID) {
35670b57cec5SDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cont");
35680b57cec5SDimitry Andric 
35690b57cec5SDimitry Andric   // If we're optimizing, collapse all calls to trap down to just one per
3570e8d8bef9SDimitry Andric   // check-type per function to save on code size.
3571e8d8bef9SDimitry Andric   if (TrapBBs.size() <= CheckHandlerID)
3572e8d8bef9SDimitry Andric     TrapBBs.resize(CheckHandlerID + 1);
3573e8d8bef9SDimitry Andric   llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
3574e8d8bef9SDimitry Andric 
3575bdd1243dSDimitry Andric   if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB ||
3576bdd1243dSDimitry Andric       (CurCodeDecl && CurCodeDecl->hasAttr<OptimizeNoneAttr>())) {
35770b57cec5SDimitry Andric     TrapBB = createBasicBlock("trap");
35780b57cec5SDimitry Andric     Builder.CreateCondBr(Checked, Cont, TrapBB);
35790b57cec5SDimitry Andric     EmitBlock(TrapBB);
3580e8d8bef9SDimitry Andric 
3581e8d8bef9SDimitry Andric     llvm::CallInst *TrapCall =
3582e8d8bef9SDimitry Andric         Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
3583e8d8bef9SDimitry Andric                            llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
3584e8d8bef9SDimitry Andric 
3585e8d8bef9SDimitry Andric     if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3586e8d8bef9SDimitry Andric       auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3587e8d8bef9SDimitry Andric                                     CGM.getCodeGenOpts().TrapFuncName);
3588349cc55cSDimitry Andric       TrapCall->addFnAttr(A);
3589e8d8bef9SDimitry Andric     }
35900b57cec5SDimitry Andric     TrapCall->setDoesNotReturn();
35910b57cec5SDimitry Andric     TrapCall->setDoesNotThrow();
35920b57cec5SDimitry Andric     Builder.CreateUnreachable();
35930b57cec5SDimitry Andric   } else {
3594e8d8bef9SDimitry Andric     auto Call = TrapBB->begin();
3595e8d8bef9SDimitry Andric     assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
3596e8d8bef9SDimitry Andric 
3597e8d8bef9SDimitry Andric     Call->applyMergedLocation(Call->getDebugLoc(),
3598e8d8bef9SDimitry Andric                               Builder.getCurrentDebugLocation());
35990b57cec5SDimitry Andric     Builder.CreateCondBr(Checked, Cont, TrapBB);
36000b57cec5SDimitry Andric   }
36010b57cec5SDimitry Andric 
36020b57cec5SDimitry Andric   EmitBlock(Cont);
36030b57cec5SDimitry Andric }
36040b57cec5SDimitry Andric 
36050b57cec5SDimitry Andric llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3606e8d8bef9SDimitry Andric   llvm::CallInst *TrapCall =
3607e8d8bef9SDimitry Andric       Builder.CreateCall(CGM.getIntrinsic(IntrID));
36080b57cec5SDimitry Andric 
36090b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
36100b57cec5SDimitry Andric     auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
36110b57cec5SDimitry Andric                                   CGM.getCodeGenOpts().TrapFuncName);
3612349cc55cSDimitry Andric     TrapCall->addFnAttr(A);
36130b57cec5SDimitry Andric   }
36140b57cec5SDimitry Andric 
36150b57cec5SDimitry Andric   return TrapCall;
36160b57cec5SDimitry Andric }
36170b57cec5SDimitry Andric 
36180b57cec5SDimitry Andric Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
36190b57cec5SDimitry Andric                                                  LValueBaseInfo *BaseInfo,
36200b57cec5SDimitry Andric                                                  TBAAAccessInfo *TBAAInfo) {
36210b57cec5SDimitry Andric   assert(E->getType()->isArrayType() &&
36220b57cec5SDimitry Andric          "Array to pointer decay must have array source type!");
36230b57cec5SDimitry Andric 
36240b57cec5SDimitry Andric   // Expressions of array type can't be bitfields or vector elements.
36250b57cec5SDimitry Andric   LValue LV = EmitLValue(E);
3626480093f4SDimitry Andric   Address Addr = LV.getAddress(*this);
36270b57cec5SDimitry Andric 
36280b57cec5SDimitry Andric   // If the array type was an incomplete type, we need to make sure
36290b57cec5SDimitry Andric   // the decay ends up being the right type.
36300b57cec5SDimitry Andric   llvm::Type *NewTy = ConvertType(E->getType());
3631*fe013be4SDimitry Andric   Addr = Addr.withElementType(NewTy);
36320b57cec5SDimitry Andric 
36330b57cec5SDimitry Andric   // Note that VLA pointers are always decayed, so we don't need to do
36340b57cec5SDimitry Andric   // anything here.
36350b57cec5SDimitry Andric   if (!E->getType()->isVariableArrayType()) {
36360b57cec5SDimitry Andric     assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
36370b57cec5SDimitry Andric            "Expected pointer to array");
36380b57cec5SDimitry Andric     Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
36390b57cec5SDimitry Andric   }
36400b57cec5SDimitry Andric 
36410b57cec5SDimitry Andric   // The result of this decay conversion points to an array element within the
36420b57cec5SDimitry Andric   // base lvalue. However, since TBAA currently does not support representing
36430b57cec5SDimitry Andric   // accesses to elements of member arrays, we conservatively represent accesses
36440b57cec5SDimitry Andric   // to the pointee object as if it had no any base lvalue specified.
36450b57cec5SDimitry Andric   // TODO: Support TBAA for member arrays.
36460b57cec5SDimitry Andric   QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
36470b57cec5SDimitry Andric   if (BaseInfo) *BaseInfo = LV.getBaseInfo();
36480b57cec5SDimitry Andric   if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
36490b57cec5SDimitry Andric 
3650*fe013be4SDimitry Andric   return Addr.withElementType(ConvertTypeForMem(EltType));
36510b57cec5SDimitry Andric }
36520b57cec5SDimitry Andric 
36530b57cec5SDimitry Andric /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
36540b57cec5SDimitry Andric /// array to pointer, return the array subexpression.
36550b57cec5SDimitry Andric static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
36560b57cec5SDimitry Andric   // If this isn't just an array->pointer decay, bail out.
36570b57cec5SDimitry Andric   const auto *CE = dyn_cast<CastExpr>(E);
36580b57cec5SDimitry Andric   if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
36590b57cec5SDimitry Andric     return nullptr;
36600b57cec5SDimitry Andric 
36610b57cec5SDimitry Andric   // If this is a decay from variable width array, bail out.
36620b57cec5SDimitry Andric   const Expr *SubExpr = CE->getSubExpr();
36630b57cec5SDimitry Andric   if (SubExpr->getType()->isVariableArrayType())
36640b57cec5SDimitry Andric     return nullptr;
36650b57cec5SDimitry Andric 
36660b57cec5SDimitry Andric   return SubExpr;
36670b57cec5SDimitry Andric }
36680b57cec5SDimitry Andric 
36690b57cec5SDimitry Andric static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3670fe6060f1SDimitry Andric                                           llvm::Type *elemType,
36710b57cec5SDimitry Andric                                           llvm::Value *ptr,
36720b57cec5SDimitry Andric                                           ArrayRef<llvm::Value*> indices,
36730b57cec5SDimitry Andric                                           bool inbounds,
36740b57cec5SDimitry Andric                                           bool signedIndices,
36750b57cec5SDimitry Andric                                           SourceLocation loc,
36760b57cec5SDimitry Andric                                     const llvm::Twine &name = "arrayidx") {
36770b57cec5SDimitry Andric   if (inbounds) {
36780eae32dcSDimitry Andric     return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
36790b57cec5SDimitry Andric                                       CodeGenFunction::NotSubtraction, loc,
36800b57cec5SDimitry Andric                                       name);
36810b57cec5SDimitry Andric   } else {
3682fe6060f1SDimitry Andric     return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
36830b57cec5SDimitry Andric   }
36840b57cec5SDimitry Andric }
36850b57cec5SDimitry Andric 
36860b57cec5SDimitry Andric static CharUnits getArrayElementAlign(CharUnits arrayAlign,
36870b57cec5SDimitry Andric                                       llvm::Value *idx,
36880b57cec5SDimitry Andric                                       CharUnits eltSize) {
36890b57cec5SDimitry Andric   // If we have a constant index, we can use the exact offset of the
36900b57cec5SDimitry Andric   // element we're accessing.
36910b57cec5SDimitry Andric   if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
36920b57cec5SDimitry Andric     CharUnits offset = constantIdx->getZExtValue() * eltSize;
36930b57cec5SDimitry Andric     return arrayAlign.alignmentAtOffset(offset);
36940b57cec5SDimitry Andric 
36950b57cec5SDimitry Andric   // Otherwise, use the worst-case alignment for any element.
36960b57cec5SDimitry Andric   } else {
36970b57cec5SDimitry Andric     return arrayAlign.alignmentOfArrayElement(eltSize);
36980b57cec5SDimitry Andric   }
36990b57cec5SDimitry Andric }
37000b57cec5SDimitry Andric 
37010b57cec5SDimitry Andric static QualType getFixedSizeElementType(const ASTContext &ctx,
37020b57cec5SDimitry Andric                                         const VariableArrayType *vla) {
37030b57cec5SDimitry Andric   QualType eltType;
37040b57cec5SDimitry Andric   do {
37050b57cec5SDimitry Andric     eltType = vla->getElementType();
37060b57cec5SDimitry Andric   } while ((vla = ctx.getAsVariableArrayType(eltType)));
37070b57cec5SDimitry Andric   return eltType;
37080b57cec5SDimitry Andric }
37090b57cec5SDimitry Andric 
3710480093f4SDimitry Andric /// Given an array base, check whether its member access belongs to a record
3711480093f4SDimitry Andric /// with preserve_access_index attribute or not.
3712480093f4SDimitry Andric static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3713480093f4SDimitry Andric   if (!ArrayBase || !CGF.getDebugInfo())
3714480093f4SDimitry Andric     return false;
3715480093f4SDimitry Andric 
3716480093f4SDimitry Andric   // Only support base as either a MemberExpr or DeclRefExpr.
3717480093f4SDimitry Andric   // DeclRefExpr to cover cases like:
3718480093f4SDimitry Andric   //    struct s { int a; int b[10]; };
3719480093f4SDimitry Andric   //    struct s *p;
3720480093f4SDimitry Andric   //    p[1].a
3721480093f4SDimitry Andric   // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3722480093f4SDimitry Andric   // p->b[5] is a MemberExpr example.
3723480093f4SDimitry Andric   const Expr *E = ArrayBase->IgnoreImpCasts();
3724480093f4SDimitry Andric   if (const auto *ME = dyn_cast<MemberExpr>(E))
3725480093f4SDimitry Andric     return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3726480093f4SDimitry Andric 
3727480093f4SDimitry Andric   if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3728480093f4SDimitry Andric     const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
3729480093f4SDimitry Andric     if (!VarDef)
3730480093f4SDimitry Andric       return false;
3731480093f4SDimitry Andric 
3732480093f4SDimitry Andric     const auto *PtrT = VarDef->getType()->getAs<PointerType>();
3733480093f4SDimitry Andric     if (!PtrT)
3734480093f4SDimitry Andric       return false;
3735480093f4SDimitry Andric 
3736480093f4SDimitry Andric     const auto *PointeeT = PtrT->getPointeeType()
3737480093f4SDimitry Andric                              ->getUnqualifiedDesugaredType();
3738480093f4SDimitry Andric     if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
3739480093f4SDimitry Andric       return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3740480093f4SDimitry Andric     return false;
3741480093f4SDimitry Andric   }
3742480093f4SDimitry Andric 
3743480093f4SDimitry Andric   return false;
3744480093f4SDimitry Andric }
3745480093f4SDimitry Andric 
37460b57cec5SDimitry Andric static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
37470b57cec5SDimitry Andric                                      ArrayRef<llvm::Value *> indices,
37480b57cec5SDimitry Andric                                      QualType eltType, bool inbounds,
37490b57cec5SDimitry Andric                                      bool signedIndices, SourceLocation loc,
3750a7dea167SDimitry Andric                                      QualType *arrayType = nullptr,
3751480093f4SDimitry Andric                                      const Expr *Base = nullptr,
37520b57cec5SDimitry Andric                                      const llvm::Twine &name = "arrayidx") {
37530b57cec5SDimitry Andric   // All the indices except that last must be zero.
37540b57cec5SDimitry Andric #ifndef NDEBUG
3755bdd1243dSDimitry Andric   for (auto *idx : indices.drop_back())
37560b57cec5SDimitry Andric     assert(isa<llvm::ConstantInt>(idx) &&
37570b57cec5SDimitry Andric            cast<llvm::ConstantInt>(idx)->isZero());
37580b57cec5SDimitry Andric #endif
37590b57cec5SDimitry Andric 
37600b57cec5SDimitry Andric   // Determine the element size of the statically-sized base.  This is
37610b57cec5SDimitry Andric   // the thing that the indices are expressed in terms of.
37620b57cec5SDimitry Andric   if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
37630b57cec5SDimitry Andric     eltType = getFixedSizeElementType(CGF.getContext(), vla);
37640b57cec5SDimitry Andric   }
37650b57cec5SDimitry Andric 
37660b57cec5SDimitry Andric   // We can use that to compute the best alignment of the element.
37670b57cec5SDimitry Andric   CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
37680b57cec5SDimitry Andric   CharUnits eltAlign =
37690b57cec5SDimitry Andric     getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
37700b57cec5SDimitry Andric 
37710b57cec5SDimitry Andric   llvm::Value *eltPtr;
37720b57cec5SDimitry Andric   auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
3773480093f4SDimitry Andric   if (!LastIndex ||
3774480093f4SDimitry Andric       (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
37750b57cec5SDimitry Andric     eltPtr = emitArraySubscriptGEP(
3776fe6060f1SDimitry Andric         CGF, addr.getElementType(), addr.getPointer(), indices, inbounds,
3777fe6060f1SDimitry Andric         signedIndices, loc, name);
37780b57cec5SDimitry Andric   } else {
37790b57cec5SDimitry Andric     // Remember the original array subscript for bpf target
37800b57cec5SDimitry Andric     unsigned idx = LastIndex->getZExtValue();
3781a7dea167SDimitry Andric     llvm::DIType *DbgInfo = nullptr;
3782a7dea167SDimitry Andric     if (arrayType)
3783a7dea167SDimitry Andric       DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
3784480093f4SDimitry Andric     eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
3785480093f4SDimitry Andric                                                         addr.getPointer(),
37860b57cec5SDimitry Andric                                                         indices.size() - 1,
3787a7dea167SDimitry Andric                                                         idx, DbgInfo);
37880b57cec5SDimitry Andric   }
37890b57cec5SDimitry Andric 
37900eae32dcSDimitry Andric   return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
37910b57cec5SDimitry Andric }
37920b57cec5SDimitry Andric 
37930b57cec5SDimitry Andric LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
37940b57cec5SDimitry Andric                                                bool Accessed) {
37950b57cec5SDimitry Andric   // The index must always be an integer, which is not an aggregate.  Emit it
37960b57cec5SDimitry Andric   // in lexical order (this complexity is, sadly, required by C++17).
37970b57cec5SDimitry Andric   llvm::Value *IdxPre =
37980b57cec5SDimitry Andric       (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
37990b57cec5SDimitry Andric   bool SignedIndices = false;
38000b57cec5SDimitry Andric   auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
38010b57cec5SDimitry Andric     auto *Idx = IdxPre;
38020b57cec5SDimitry Andric     if (E->getLHS() != E->getIdx()) {
38030b57cec5SDimitry Andric       assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
38040b57cec5SDimitry Andric       Idx = EmitScalarExpr(E->getIdx());
38050b57cec5SDimitry Andric     }
38060b57cec5SDimitry Andric 
38070b57cec5SDimitry Andric     QualType IdxTy = E->getIdx()->getType();
38080b57cec5SDimitry Andric     bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
38090b57cec5SDimitry Andric     SignedIndices |= IdxSigned;
38100b57cec5SDimitry Andric 
38110b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::ArrayBounds))
38120b57cec5SDimitry Andric       EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
38130b57cec5SDimitry Andric 
38140b57cec5SDimitry Andric     // Extend or truncate the index type to 32 or 64-bits.
38150b57cec5SDimitry Andric     if (Promote && Idx->getType() != IntPtrTy)
38160b57cec5SDimitry Andric       Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
38170b57cec5SDimitry Andric 
38180b57cec5SDimitry Andric     return Idx;
38190b57cec5SDimitry Andric   };
38200b57cec5SDimitry Andric   IdxPre = nullptr;
38210b57cec5SDimitry Andric 
38220b57cec5SDimitry Andric   // If the base is a vector type, then we are forming a vector element lvalue
38230b57cec5SDimitry Andric   // with this subscript.
38240b57cec5SDimitry Andric   if (E->getBase()->getType()->isVectorType() &&
38250b57cec5SDimitry Andric       !isa<ExtVectorElementExpr>(E->getBase())) {
38260b57cec5SDimitry Andric     // Emit the vector as an lvalue to get its address.
38270b57cec5SDimitry Andric     LValue LHS = EmitLValue(E->getBase());
38280b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/false);
38290b57cec5SDimitry Andric     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3830480093f4SDimitry Andric     return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
3831480093f4SDimitry Andric                                  E->getBase()->getType(), LHS.getBaseInfo(),
3832480093f4SDimitry Andric                                  TBAAAccessInfo());
38330b57cec5SDimitry Andric   }
38340b57cec5SDimitry Andric 
38350b57cec5SDimitry Andric   // All the other cases basically behave like simple offsetting.
38360b57cec5SDimitry Andric 
38370b57cec5SDimitry Andric   // Handle the extvector case we ignored above.
38380b57cec5SDimitry Andric   if (isa<ExtVectorElementExpr>(E->getBase())) {
38390b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getBase());
38400b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
38410b57cec5SDimitry Andric     Address Addr = EmitExtVectorElementLValue(LV);
38420b57cec5SDimitry Andric 
38430b57cec5SDimitry Andric     QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
38440b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
38450b57cec5SDimitry Andric                                  SignedIndices, E->getExprLoc());
38460b57cec5SDimitry Andric     return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
38470b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, EltType));
38480b57cec5SDimitry Andric   }
38490b57cec5SDimitry Andric 
38500b57cec5SDimitry Andric   LValueBaseInfo EltBaseInfo;
38510b57cec5SDimitry Andric   TBAAAccessInfo EltTBAAInfo;
38520b57cec5SDimitry Andric   Address Addr = Address::invalid();
38530b57cec5SDimitry Andric   if (const VariableArrayType *vla =
38540b57cec5SDimitry Andric            getContext().getAsVariableArrayType(E->getType())) {
38550b57cec5SDimitry Andric     // The base must be a pointer, which is not an aggregate.  Emit
38560b57cec5SDimitry Andric     // it.  It needs to be emitted first in case it's what captures
38570b57cec5SDimitry Andric     // the VLA bounds.
38580b57cec5SDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
38590b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
38600b57cec5SDimitry Andric 
38610b57cec5SDimitry Andric     // The element count here is the total number of non-VLA elements.
38620b57cec5SDimitry Andric     llvm::Value *numElements = getVLASize(vla).NumElts;
38630b57cec5SDimitry Andric 
38640b57cec5SDimitry Andric     // Effectively, the multiply by the VLA size is part of the GEP.
38650b57cec5SDimitry Andric     // GEP indexes are signed, and scaling an index isn't permitted to
38660b57cec5SDimitry Andric     // signed-overflow, so we use the same semantics for our explicit
38670b57cec5SDimitry Andric     // multiply.  We suppress this if overflow is not undefined behavior.
38680b57cec5SDimitry Andric     if (getLangOpts().isSignedOverflowDefined()) {
38690b57cec5SDimitry Andric       Idx = Builder.CreateMul(Idx, numElements);
38700b57cec5SDimitry Andric     } else {
38710b57cec5SDimitry Andric       Idx = Builder.CreateNSWMul(Idx, numElements);
38720b57cec5SDimitry Andric     }
38730b57cec5SDimitry Andric 
38740b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
38750b57cec5SDimitry Andric                                  !getLangOpts().isSignedOverflowDefined(),
38760b57cec5SDimitry Andric                                  SignedIndices, E->getExprLoc());
38770b57cec5SDimitry Andric 
38780b57cec5SDimitry Andric   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
38790b57cec5SDimitry Andric     // Indexing over an interface, as in "NSString *P; P[4];"
38800b57cec5SDimitry Andric 
38810b57cec5SDimitry Andric     // Emit the base pointer.
38820b57cec5SDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
38830b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
38840b57cec5SDimitry Andric 
38850b57cec5SDimitry Andric     CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
38860b57cec5SDimitry Andric     llvm::Value *InterfaceSizeVal =
38870b57cec5SDimitry Andric         llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
38880b57cec5SDimitry Andric 
38890b57cec5SDimitry Andric     llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
38900b57cec5SDimitry Andric 
38910b57cec5SDimitry Andric     // We don't necessarily build correct LLVM struct types for ObjC
38920b57cec5SDimitry Andric     // interfaces, so we can't rely on GEP to do this scaling
38930b57cec5SDimitry Andric     // correctly, so we need to cast to i8*.  FIXME: is this actually
38940b57cec5SDimitry Andric     // true?  A lot of other things in the fragile ABI would break...
389581ad6265SDimitry Andric     llvm::Type *OrigBaseElemTy = Addr.getElementType();
38960b57cec5SDimitry Andric 
38970b57cec5SDimitry Andric     // Do the GEP.
38980b57cec5SDimitry Andric     CharUnits EltAlign =
38990b57cec5SDimitry Andric       getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
39000b57cec5SDimitry Andric     llvm::Value *EltPtr =
3901*fe013be4SDimitry Andric         emitArraySubscriptGEP(*this, Int8Ty, Addr.getPointer(), ScaledIdx,
3902*fe013be4SDimitry Andric                               false, SignedIndices, E->getExprLoc());
3903*fe013be4SDimitry Andric     Addr = Address(EltPtr, OrigBaseElemTy, EltAlign);
39040b57cec5SDimitry Andric   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
39050b57cec5SDimitry Andric     // If this is A[i] where A is an array, the frontend will have decayed the
39060b57cec5SDimitry Andric     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
39070b57cec5SDimitry Andric     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
39080b57cec5SDimitry Andric     // "gep x, i" here.  Emit one "gep A, 0, i".
39090b57cec5SDimitry Andric     assert(Array->getType()->isArrayType() &&
39100b57cec5SDimitry Andric            "Array to pointer decay must have array source type!");
39110b57cec5SDimitry Andric     LValue ArrayLV;
39120b57cec5SDimitry Andric     // For simple multidimensional array indexing, set the 'accessed' flag for
39130b57cec5SDimitry Andric     // better bounds-checking of the base expression.
39140b57cec5SDimitry Andric     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
39150b57cec5SDimitry Andric       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
39160b57cec5SDimitry Andric     else
39170b57cec5SDimitry Andric       ArrayLV = EmitLValue(Array);
39180b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
39190b57cec5SDimitry Andric 
39200b57cec5SDimitry Andric     // Propagate the alignment from the array itself to the result.
3921a7dea167SDimitry Andric     QualType arrayType = Array->getType();
39220b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(
3923480093f4SDimitry Andric         *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
39240b57cec5SDimitry Andric         E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3925480093f4SDimitry Andric         E->getExprLoc(), &arrayType, E->getBase());
39260b57cec5SDimitry Andric     EltBaseInfo = ArrayLV.getBaseInfo();
39270b57cec5SDimitry Andric     EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
39280b57cec5SDimitry Andric   } else {
39290b57cec5SDimitry Andric     // The base must be a pointer; emit it with an estimate of its alignment.
39300b57cec5SDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
39310b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3932a7dea167SDimitry Andric     QualType ptrType = E->getBase()->getType();
39330b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
39340b57cec5SDimitry Andric                                  !getLangOpts().isSignedOverflowDefined(),
3935480093f4SDimitry Andric                                  SignedIndices, E->getExprLoc(), &ptrType,
3936480093f4SDimitry Andric                                  E->getBase());
39370b57cec5SDimitry Andric   }
39380b57cec5SDimitry Andric 
39390b57cec5SDimitry Andric   LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
39400b57cec5SDimitry Andric 
39410b57cec5SDimitry Andric   if (getLangOpts().ObjC &&
39420b57cec5SDimitry Andric       getLangOpts().getGC() != LangOptions::NonGC) {
39430b57cec5SDimitry Andric     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
39440b57cec5SDimitry Andric     setObjCGCLValueClass(getContext(), E, LV);
39450b57cec5SDimitry Andric   }
39460b57cec5SDimitry Andric   return LV;
39470b57cec5SDimitry Andric }
39480b57cec5SDimitry Andric 
39495ffd83dbSDimitry Andric LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
39505ffd83dbSDimitry Andric   assert(
39515ffd83dbSDimitry Andric       !E->isIncomplete() &&
39525ffd83dbSDimitry Andric       "incomplete matrix subscript expressions should be rejected during Sema");
39535ffd83dbSDimitry Andric   LValue Base = EmitLValue(E->getBase());
39545ffd83dbSDimitry Andric   llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
39555ffd83dbSDimitry Andric   llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
39565ffd83dbSDimitry Andric   llvm::Value *NumRows = Builder.getIntN(
39575ffd83dbSDimitry Andric       RowIdx->getType()->getScalarSizeInBits(),
3958e8d8bef9SDimitry Andric       E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
39595ffd83dbSDimitry Andric   llvm::Value *FinalIdx =
39605ffd83dbSDimitry Andric       Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
39615ffd83dbSDimitry Andric   return LValue::MakeMatrixElt(
39625ffd83dbSDimitry Andric       MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
39635ffd83dbSDimitry Andric       E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
39645ffd83dbSDimitry Andric }
39655ffd83dbSDimitry Andric 
39660b57cec5SDimitry Andric static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
39670b57cec5SDimitry Andric                                        LValueBaseInfo &BaseInfo,
39680b57cec5SDimitry Andric                                        TBAAAccessInfo &TBAAInfo,
39690b57cec5SDimitry Andric                                        QualType BaseTy, QualType ElTy,
39700b57cec5SDimitry Andric                                        bool IsLowerBound) {
39710b57cec5SDimitry Andric   LValue BaseLVal;
39720b57cec5SDimitry Andric   if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
39730b57cec5SDimitry Andric     BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
39740b57cec5SDimitry Andric     if (BaseTy->isArrayType()) {
3975480093f4SDimitry Andric       Address Addr = BaseLVal.getAddress(CGF);
39760b57cec5SDimitry Andric       BaseInfo = BaseLVal.getBaseInfo();
39770b57cec5SDimitry Andric 
39780b57cec5SDimitry Andric       // If the array type was an incomplete type, we need to make sure
39790b57cec5SDimitry Andric       // the decay ends up being the right type.
39800b57cec5SDimitry Andric       llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3981*fe013be4SDimitry Andric       Addr = Addr.withElementType(NewTy);
39820b57cec5SDimitry Andric 
39830b57cec5SDimitry Andric       // Note that VLA pointers are always decayed, so we don't need to do
39840b57cec5SDimitry Andric       // anything here.
39850b57cec5SDimitry Andric       if (!BaseTy->isVariableArrayType()) {
39860b57cec5SDimitry Andric         assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
39870b57cec5SDimitry Andric                "Expected pointer to array");
39880b57cec5SDimitry Andric         Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
39890b57cec5SDimitry Andric       }
39900b57cec5SDimitry Andric 
3991*fe013be4SDimitry Andric       return Addr.withElementType(CGF.ConvertTypeForMem(ElTy));
39920b57cec5SDimitry Andric     }
39930b57cec5SDimitry Andric     LValueBaseInfo TypeBaseInfo;
39940b57cec5SDimitry Andric     TBAAAccessInfo TypeTBAAInfo;
39955ffd83dbSDimitry Andric     CharUnits Align =
39965ffd83dbSDimitry Andric         CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
39970b57cec5SDimitry Andric     BaseInfo.mergeForCast(TypeBaseInfo);
39980b57cec5SDimitry Andric     TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
399981ad6265SDimitry Andric     return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)),
400081ad6265SDimitry Andric                    CGF.ConvertTypeForMem(ElTy), Align);
40010b57cec5SDimitry Andric   }
40020b57cec5SDimitry Andric   return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
40030b57cec5SDimitry Andric }
40040b57cec5SDimitry Andric 
40050b57cec5SDimitry Andric LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
40060b57cec5SDimitry Andric                                                 bool IsLowerBound) {
40070b57cec5SDimitry Andric   QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
40080b57cec5SDimitry Andric   QualType ResultExprTy;
40090b57cec5SDimitry Andric   if (auto *AT = getContext().getAsArrayType(BaseTy))
40100b57cec5SDimitry Andric     ResultExprTy = AT->getElementType();
40110b57cec5SDimitry Andric   else
40120b57cec5SDimitry Andric     ResultExprTy = BaseTy->getPointeeType();
40130b57cec5SDimitry Andric   llvm::Value *Idx = nullptr;
40145ffd83dbSDimitry Andric   if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
40150b57cec5SDimitry Andric     // Requesting lower bound or upper bound, but without provided length and
40160b57cec5SDimitry Andric     // without ':' symbol for the default length -> length = 1.
40170b57cec5SDimitry Andric     // Idx = LowerBound ?: 0;
40180b57cec5SDimitry Andric     if (auto *LowerBound = E->getLowerBound()) {
40190b57cec5SDimitry Andric       Idx = Builder.CreateIntCast(
40200b57cec5SDimitry Andric           EmitScalarExpr(LowerBound), IntPtrTy,
40210b57cec5SDimitry Andric           LowerBound->getType()->hasSignedIntegerRepresentation());
40220b57cec5SDimitry Andric     } else
40230b57cec5SDimitry Andric       Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
40240b57cec5SDimitry Andric   } else {
40250b57cec5SDimitry Andric     // Try to emit length or lower bound as constant. If this is possible, 1
40260b57cec5SDimitry Andric     // is subtracted from constant length or lower bound. Otherwise, emit LLVM
40270b57cec5SDimitry Andric     // IR (LB + Len) - 1.
40280b57cec5SDimitry Andric     auto &C = CGM.getContext();
40290b57cec5SDimitry Andric     auto *Length = E->getLength();
40300b57cec5SDimitry Andric     llvm::APSInt ConstLength;
40310b57cec5SDimitry Andric     if (Length) {
40320b57cec5SDimitry Andric       // Idx = LowerBound + Length - 1;
4033bdd1243dSDimitry Andric       if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
4034e8d8bef9SDimitry Andric         ConstLength = CL->zextOrTrunc(PointerWidthInBits);
40350b57cec5SDimitry Andric         Length = nullptr;
40360b57cec5SDimitry Andric       }
40370b57cec5SDimitry Andric       auto *LowerBound = E->getLowerBound();
40380b57cec5SDimitry Andric       llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
4039e8d8bef9SDimitry Andric       if (LowerBound) {
4040bdd1243dSDimitry Andric         if (std::optional<llvm::APSInt> LB =
4041bdd1243dSDimitry Andric                 LowerBound->getIntegerConstantExpr(C)) {
4042e8d8bef9SDimitry Andric           ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
40430b57cec5SDimitry Andric           LowerBound = nullptr;
40440b57cec5SDimitry Andric         }
4045e8d8bef9SDimitry Andric       }
40460b57cec5SDimitry Andric       if (!Length)
40470b57cec5SDimitry Andric         --ConstLength;
40480b57cec5SDimitry Andric       else if (!LowerBound)
40490b57cec5SDimitry Andric         --ConstLowerBound;
40500b57cec5SDimitry Andric 
40510b57cec5SDimitry Andric       if (Length || LowerBound) {
40520b57cec5SDimitry Andric         auto *LowerBoundVal =
40530b57cec5SDimitry Andric             LowerBound
40540b57cec5SDimitry Andric                 ? Builder.CreateIntCast(
40550b57cec5SDimitry Andric                       EmitScalarExpr(LowerBound), IntPtrTy,
40560b57cec5SDimitry Andric                       LowerBound->getType()->hasSignedIntegerRepresentation())
40570b57cec5SDimitry Andric                 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
40580b57cec5SDimitry Andric         auto *LengthVal =
40590b57cec5SDimitry Andric             Length
40600b57cec5SDimitry Andric                 ? Builder.CreateIntCast(
40610b57cec5SDimitry Andric                       EmitScalarExpr(Length), IntPtrTy,
40620b57cec5SDimitry Andric                       Length->getType()->hasSignedIntegerRepresentation())
40630b57cec5SDimitry Andric                 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
40640b57cec5SDimitry Andric         Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
40650b57cec5SDimitry Andric                                 /*HasNUW=*/false,
40660b57cec5SDimitry Andric                                 !getLangOpts().isSignedOverflowDefined());
40670b57cec5SDimitry Andric         if (Length && LowerBound) {
40680b57cec5SDimitry Andric           Idx = Builder.CreateSub(
40690b57cec5SDimitry Andric               Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
40700b57cec5SDimitry Andric               /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
40710b57cec5SDimitry Andric         }
40720b57cec5SDimitry Andric       } else
40730b57cec5SDimitry Andric         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
40740b57cec5SDimitry Andric     } else {
40750b57cec5SDimitry Andric       // Idx = ArraySize - 1;
40760b57cec5SDimitry Andric       QualType ArrayTy = BaseTy->isPointerType()
40770b57cec5SDimitry Andric                              ? E->getBase()->IgnoreParenImpCasts()->getType()
40780b57cec5SDimitry Andric                              : BaseTy;
40790b57cec5SDimitry Andric       if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
40800b57cec5SDimitry Andric         Length = VAT->getSizeExpr();
4081bdd1243dSDimitry Andric         if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
4082e8d8bef9SDimitry Andric           ConstLength = *L;
40830b57cec5SDimitry Andric           Length = nullptr;
4084e8d8bef9SDimitry Andric         }
40850b57cec5SDimitry Andric       } else {
40860b57cec5SDimitry Andric         auto *CAT = C.getAsConstantArrayType(ArrayTy);
4087*fe013be4SDimitry Andric         assert(CAT && "unexpected type for array initializer");
40880b57cec5SDimitry Andric         ConstLength = CAT->getSize();
40890b57cec5SDimitry Andric       }
40900b57cec5SDimitry Andric       if (Length) {
40910b57cec5SDimitry Andric         auto *LengthVal = Builder.CreateIntCast(
40920b57cec5SDimitry Andric             EmitScalarExpr(Length), IntPtrTy,
40930b57cec5SDimitry Andric             Length->getType()->hasSignedIntegerRepresentation());
40940b57cec5SDimitry Andric         Idx = Builder.CreateSub(
40950b57cec5SDimitry Andric             LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
40960b57cec5SDimitry Andric             /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
40970b57cec5SDimitry Andric       } else {
40980b57cec5SDimitry Andric         ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
40990b57cec5SDimitry Andric         --ConstLength;
41000b57cec5SDimitry Andric         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
41010b57cec5SDimitry Andric       }
41020b57cec5SDimitry Andric     }
41030b57cec5SDimitry Andric   }
41040b57cec5SDimitry Andric   assert(Idx);
41050b57cec5SDimitry Andric 
41060b57cec5SDimitry Andric   Address EltPtr = Address::invalid();
41070b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
41080b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
41090b57cec5SDimitry Andric   if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
41100b57cec5SDimitry Andric     // The base must be a pointer, which is not an aggregate.  Emit
41110b57cec5SDimitry Andric     // it.  It needs to be emitted first in case it's what captures
41120b57cec5SDimitry Andric     // the VLA bounds.
41130b57cec5SDimitry Andric     Address Base =
41140b57cec5SDimitry Andric         emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
41150b57cec5SDimitry Andric                                 BaseTy, VLA->getElementType(), IsLowerBound);
41160b57cec5SDimitry Andric     // The element count here is the total number of non-VLA elements.
41170b57cec5SDimitry Andric     llvm::Value *NumElements = getVLASize(VLA).NumElts;
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric     // Effectively, the multiply by the VLA size is part of the GEP.
41200b57cec5SDimitry Andric     // GEP indexes are signed, and scaling an index isn't permitted to
41210b57cec5SDimitry Andric     // signed-overflow, so we use the same semantics for our explicit
41220b57cec5SDimitry Andric     // multiply.  We suppress this if overflow is not undefined behavior.
41230b57cec5SDimitry Andric     if (getLangOpts().isSignedOverflowDefined())
41240b57cec5SDimitry Andric       Idx = Builder.CreateMul(Idx, NumElements);
41250b57cec5SDimitry Andric     else
41260b57cec5SDimitry Andric       Idx = Builder.CreateNSWMul(Idx, NumElements);
41270b57cec5SDimitry Andric     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
41280b57cec5SDimitry Andric                                    !getLangOpts().isSignedOverflowDefined(),
41290b57cec5SDimitry Andric                                    /*signedIndices=*/false, E->getExprLoc());
41300b57cec5SDimitry Andric   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
41310b57cec5SDimitry Andric     // If this is A[i] where A is an array, the frontend will have decayed the
41320b57cec5SDimitry Andric     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
41330b57cec5SDimitry Andric     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
41340b57cec5SDimitry Andric     // "gep x, i" here.  Emit one "gep A, 0, i".
41350b57cec5SDimitry Andric     assert(Array->getType()->isArrayType() &&
41360b57cec5SDimitry Andric            "Array to pointer decay must have array source type!");
41370b57cec5SDimitry Andric     LValue ArrayLV;
41380b57cec5SDimitry Andric     // For simple multidimensional array indexing, set the 'accessed' flag for
41390b57cec5SDimitry Andric     // better bounds-checking of the base expression.
41400b57cec5SDimitry Andric     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
41410b57cec5SDimitry Andric       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
41420b57cec5SDimitry Andric     else
41430b57cec5SDimitry Andric       ArrayLV = EmitLValue(Array);
41440b57cec5SDimitry Andric 
41450b57cec5SDimitry Andric     // Propagate the alignment from the array itself to the result.
41460b57cec5SDimitry Andric     EltPtr = emitArraySubscriptGEP(
4147480093f4SDimitry Andric         *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
41480b57cec5SDimitry Andric         ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
41490b57cec5SDimitry Andric         /*signedIndices=*/false, E->getExprLoc());
41500b57cec5SDimitry Andric     BaseInfo = ArrayLV.getBaseInfo();
41510b57cec5SDimitry Andric     TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
41520b57cec5SDimitry Andric   } else {
41530b57cec5SDimitry Andric     Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
41540b57cec5SDimitry Andric                                            TBAAInfo, BaseTy, ResultExprTy,
41550b57cec5SDimitry Andric                                            IsLowerBound);
41560b57cec5SDimitry Andric     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
41570b57cec5SDimitry Andric                                    !getLangOpts().isSignedOverflowDefined(),
41580b57cec5SDimitry Andric                                    /*signedIndices=*/false, E->getExprLoc());
41590b57cec5SDimitry Andric   }
41600b57cec5SDimitry Andric 
41610b57cec5SDimitry Andric   return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
41620b57cec5SDimitry Andric }
41630b57cec5SDimitry Andric 
41640b57cec5SDimitry Andric LValue CodeGenFunction::
41650b57cec5SDimitry Andric EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
41660b57cec5SDimitry Andric   // Emit the base vector as an l-value.
41670b57cec5SDimitry Andric   LValue Base;
41680b57cec5SDimitry Andric 
41690b57cec5SDimitry Andric   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
41700b57cec5SDimitry Andric   if (E->isArrow()) {
41710b57cec5SDimitry Andric     // If it is a pointer to a vector, emit the address and form an lvalue with
41720b57cec5SDimitry Andric     // it.
41730b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
41740b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
41750b57cec5SDimitry Andric     Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4176480093f4SDimitry Andric     const auto *PT = E->getBase()->getType()->castAs<PointerType>();
41770b57cec5SDimitry Andric     Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
41780b57cec5SDimitry Andric     Base.getQuals().removeObjCGCAttr();
41790b57cec5SDimitry Andric   } else if (E->getBase()->isGLValue()) {
41800b57cec5SDimitry Andric     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
41810b57cec5SDimitry Andric     // emit the base as an lvalue.
41820b57cec5SDimitry Andric     assert(E->getBase()->getType()->isVectorType());
41830b57cec5SDimitry Andric     Base = EmitLValue(E->getBase());
41840b57cec5SDimitry Andric   } else {
41850b57cec5SDimitry Andric     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
41860b57cec5SDimitry Andric     assert(E->getBase()->getType()->isVectorType() &&
41870b57cec5SDimitry Andric            "Result must be a vector");
41880b57cec5SDimitry Andric     llvm::Value *Vec = EmitScalarExpr(E->getBase());
41890b57cec5SDimitry Andric 
41900b57cec5SDimitry Andric     // Store the vector to memory (because LValue wants an address).
41910b57cec5SDimitry Andric     Address VecMem = CreateMemTemp(E->getBase()->getType());
41920b57cec5SDimitry Andric     Builder.CreateStore(Vec, VecMem);
41930b57cec5SDimitry Andric     Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
41940b57cec5SDimitry Andric                           AlignmentSource::Decl);
41950b57cec5SDimitry Andric   }
41960b57cec5SDimitry Andric 
41970b57cec5SDimitry Andric   QualType type =
41980b57cec5SDimitry Andric     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
41990b57cec5SDimitry Andric 
42000b57cec5SDimitry Andric   // Encode the element access list into a vector of unsigned indices.
42010b57cec5SDimitry Andric   SmallVector<uint32_t, 4> Indices;
42020b57cec5SDimitry Andric   E->getEncodedElementAccess(Indices);
42030b57cec5SDimitry Andric 
42040b57cec5SDimitry Andric   if (Base.isSimple()) {
42050b57cec5SDimitry Andric     llvm::Constant *CV =
42060b57cec5SDimitry Andric         llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4207480093f4SDimitry Andric     return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
42080b57cec5SDimitry Andric                                     Base.getBaseInfo(), TBAAAccessInfo());
42090b57cec5SDimitry Andric   }
42100b57cec5SDimitry Andric   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
42110b57cec5SDimitry Andric 
42120b57cec5SDimitry Andric   llvm::Constant *BaseElts = Base.getExtVectorElts();
42130b57cec5SDimitry Andric   SmallVector<llvm::Constant *, 4> CElts;
42140b57cec5SDimitry Andric 
42150b57cec5SDimitry Andric   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
42160b57cec5SDimitry Andric     CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
42170b57cec5SDimitry Andric   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
42180b57cec5SDimitry Andric   return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
42190b57cec5SDimitry Andric                                   Base.getBaseInfo(), TBAAAccessInfo());
42200b57cec5SDimitry Andric }
42210b57cec5SDimitry Andric 
42220b57cec5SDimitry Andric LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
42230b57cec5SDimitry Andric   if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
42240b57cec5SDimitry Andric     EmitIgnoredExpr(E->getBase());
42250b57cec5SDimitry Andric     return EmitDeclRefLValue(DRE);
42260b57cec5SDimitry Andric   }
42270b57cec5SDimitry Andric 
42280b57cec5SDimitry Andric   Expr *BaseExpr = E->getBase();
42290b57cec5SDimitry Andric   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
42300b57cec5SDimitry Andric   LValue BaseLV;
42310b57cec5SDimitry Andric   if (E->isArrow()) {
42320b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
42330b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
42340b57cec5SDimitry Andric     Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
42350b57cec5SDimitry Andric     QualType PtrTy = BaseExpr->getType()->getPointeeType();
42360b57cec5SDimitry Andric     SanitizerSet SkippedChecks;
42370b57cec5SDimitry Andric     bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
42380b57cec5SDimitry Andric     if (IsBaseCXXThis)
42390b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::Alignment, true);
42400b57cec5SDimitry Andric     if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
42410b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::Null, true);
42420b57cec5SDimitry Andric     EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
42430b57cec5SDimitry Andric                   /*Alignment=*/CharUnits::Zero(), SkippedChecks);
42440b57cec5SDimitry Andric     BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
42450b57cec5SDimitry Andric   } else
42460b57cec5SDimitry Andric     BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
42470b57cec5SDimitry Andric 
42480b57cec5SDimitry Andric   NamedDecl *ND = E->getMemberDecl();
42490b57cec5SDimitry Andric   if (auto *Field = dyn_cast<FieldDecl>(ND)) {
42500b57cec5SDimitry Andric     LValue LV = EmitLValueForField(BaseLV, Field);
42510b57cec5SDimitry Andric     setObjCGCLValueClass(getContext(), E, LV);
4252480093f4SDimitry Andric     if (getLangOpts().OpenMP) {
4253480093f4SDimitry Andric       // If the member was explicitly marked as nontemporal, mark it as
4254480093f4SDimitry Andric       // nontemporal. If the base lvalue is marked as nontemporal, mark access
4255480093f4SDimitry Andric       // to children as nontemporal too.
4256480093f4SDimitry Andric       if ((IsWrappedCXXThis(BaseExpr) &&
4257480093f4SDimitry Andric            CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
4258480093f4SDimitry Andric           BaseLV.isNontemporal())
4259480093f4SDimitry Andric         LV.setNontemporal(/*Value=*/true);
4260480093f4SDimitry Andric     }
42610b57cec5SDimitry Andric     return LV;
42620b57cec5SDimitry Andric   }
42630b57cec5SDimitry Andric 
42640b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
42650b57cec5SDimitry Andric     return EmitFunctionDeclLValue(*this, E, FD);
42660b57cec5SDimitry Andric 
42670b57cec5SDimitry Andric   llvm_unreachable("Unhandled member declaration!");
42680b57cec5SDimitry Andric }
42690b57cec5SDimitry Andric 
42700b57cec5SDimitry Andric /// Given that we are currently emitting a lambda, emit an l-value for
42710b57cec5SDimitry Andric /// one of its members.
42720b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
4273fe6060f1SDimitry Andric   if (CurCodeDecl) {
42740b57cec5SDimitry Andric     assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
42750b57cec5SDimitry Andric     assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
4276fe6060f1SDimitry Andric   }
42770b57cec5SDimitry Andric   QualType LambdaTagType =
42780b57cec5SDimitry Andric     getContext().getTagDeclType(Field->getParent());
42790b57cec5SDimitry Andric   LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
42800b57cec5SDimitry Andric   return EmitLValueForField(LambdaLV, Field);
42810b57cec5SDimitry Andric }
42820b57cec5SDimitry Andric 
42830b57cec5SDimitry Andric /// Get the field index in the debug info. The debug info structure/union
42840b57cec5SDimitry Andric /// will ignore the unnamed bitfields.
42850b57cec5SDimitry Andric unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
42860b57cec5SDimitry Andric                                              unsigned FieldIndex) {
42870b57cec5SDimitry Andric   unsigned I = 0, Skipped = 0;
42880b57cec5SDimitry Andric 
4289bdd1243dSDimitry Andric   for (auto *F : Rec->getDefinition()->fields()) {
42900b57cec5SDimitry Andric     if (I == FieldIndex)
42910b57cec5SDimitry Andric       break;
42920b57cec5SDimitry Andric     if (F->isUnnamedBitfield())
42930b57cec5SDimitry Andric       Skipped++;
42940b57cec5SDimitry Andric     I++;
42950b57cec5SDimitry Andric   }
42960b57cec5SDimitry Andric 
42970b57cec5SDimitry Andric   return FieldIndex - Skipped;
42980b57cec5SDimitry Andric }
42990b57cec5SDimitry Andric 
43000b57cec5SDimitry Andric /// Get the address of a zero-sized field within a record. The resulting
43010b57cec5SDimitry Andric /// address doesn't necessarily have the right type.
43020b57cec5SDimitry Andric static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
43030b57cec5SDimitry Andric                                        const FieldDecl *Field) {
43040b57cec5SDimitry Andric   CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
43050b57cec5SDimitry Andric       CGF.getContext().getFieldOffset(Field));
43060b57cec5SDimitry Andric   if (Offset.isZero())
43070b57cec5SDimitry Andric     return Base;
4308*fe013be4SDimitry Andric   Base = Base.withElementType(CGF.Int8Ty);
43090b57cec5SDimitry Andric   return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
43100b57cec5SDimitry Andric }
43110b57cec5SDimitry Andric 
43120b57cec5SDimitry Andric /// Drill down to the storage of a field without walking into
43130b57cec5SDimitry Andric /// reference types.
43140b57cec5SDimitry Andric ///
43150b57cec5SDimitry Andric /// The resulting address doesn't necessarily have the right type.
43160b57cec5SDimitry Andric static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
43170b57cec5SDimitry Andric                                       const FieldDecl *field) {
43180b57cec5SDimitry Andric   if (field->isZeroSize(CGF.getContext()))
43190b57cec5SDimitry Andric     return emitAddrOfZeroSizeField(CGF, base, field);
43200b57cec5SDimitry Andric 
43210b57cec5SDimitry Andric   const RecordDecl *rec = field->getParent();
43220b57cec5SDimitry Andric 
43230b57cec5SDimitry Andric   unsigned idx =
43240b57cec5SDimitry Andric     CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
43250b57cec5SDimitry Andric 
43260b57cec5SDimitry Andric   return CGF.Builder.CreateStructGEP(base, idx, field->getName());
43270b57cec5SDimitry Andric }
43280b57cec5SDimitry Andric 
43295ffd83dbSDimitry Andric static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
43305ffd83dbSDimitry Andric                                         Address addr, const FieldDecl *field) {
43310b57cec5SDimitry Andric   const RecordDecl *rec = field->getParent();
43325ffd83dbSDimitry Andric   llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
43335ffd83dbSDimitry Andric       base.getType(), rec->getLocation());
43340b57cec5SDimitry Andric 
43350b57cec5SDimitry Andric   unsigned idx =
43360b57cec5SDimitry Andric       CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
43370b57cec5SDimitry Andric 
43380b57cec5SDimitry Andric   return CGF.Builder.CreatePreserveStructAccessIndex(
43395ffd83dbSDimitry Andric       addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
43400b57cec5SDimitry Andric }
43410b57cec5SDimitry Andric 
43420b57cec5SDimitry Andric static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
43430b57cec5SDimitry Andric   const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
43440b57cec5SDimitry Andric   if (!RD)
43450b57cec5SDimitry Andric     return false;
43460b57cec5SDimitry Andric 
43470b57cec5SDimitry Andric   if (RD->isDynamicClass())
43480b57cec5SDimitry Andric     return true;
43490b57cec5SDimitry Andric 
43500b57cec5SDimitry Andric   for (const auto &Base : RD->bases())
43510b57cec5SDimitry Andric     if (hasAnyVptr(Base.getType(), Context))
43520b57cec5SDimitry Andric       return true;
43530b57cec5SDimitry Andric 
43540b57cec5SDimitry Andric   for (const FieldDecl *Field : RD->fields())
43550b57cec5SDimitry Andric     if (hasAnyVptr(Field->getType(), Context))
43560b57cec5SDimitry Andric       return true;
43570b57cec5SDimitry Andric 
43580b57cec5SDimitry Andric   return false;
43590b57cec5SDimitry Andric }
43600b57cec5SDimitry Andric 
43610b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForField(LValue base,
43620b57cec5SDimitry Andric                                            const FieldDecl *field) {
43630b57cec5SDimitry Andric   LValueBaseInfo BaseInfo = base.getBaseInfo();
43640b57cec5SDimitry Andric 
43650b57cec5SDimitry Andric   if (field->isBitField()) {
43660b57cec5SDimitry Andric     const CGRecordLayout &RL =
43670b57cec5SDimitry Andric         CGM.getTypes().getCGRecordLayout(field->getParent());
43680b57cec5SDimitry Andric     const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4369e8d8bef9SDimitry Andric     const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
4370e8d8bef9SDimitry Andric                              CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
4371e8d8bef9SDimitry Andric                              Info.VolatileStorageSize != 0 &&
4372e8d8bef9SDimitry Andric                              field->getType()
4373e8d8bef9SDimitry Andric                                  .withCVRQualifiers(base.getVRQualifiers())
4374e8d8bef9SDimitry Andric                                  .isVolatileQualified();
4375480093f4SDimitry Andric     Address Addr = base.getAddress(*this);
43760b57cec5SDimitry Andric     unsigned Idx = RL.getLLVMFieldNo(field);
4377480093f4SDimitry Andric     const RecordDecl *rec = field->getParent();
4378e8d8bef9SDimitry Andric     if (!UseVolatile) {
4379480093f4SDimitry Andric       if (!IsInPreservedAIRegion &&
4380480093f4SDimitry Andric           (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
43810b57cec5SDimitry Andric         if (Idx != 0)
43820b57cec5SDimitry Andric           // For structs, we GEP to the field that the record layout suggests.
43830b57cec5SDimitry Andric           Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4384a7dea167SDimitry Andric       } else {
4385a7dea167SDimitry Andric         llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4386a7dea167SDimitry Andric             getContext().getRecordType(rec), rec->getLocation());
4387e8d8bef9SDimitry Andric         Addr = Builder.CreatePreserveStructAccessIndex(
4388e8d8bef9SDimitry Andric             Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
4389a7dea167SDimitry Andric             DbgInfo);
4390a7dea167SDimitry Andric       }
4391e8d8bef9SDimitry Andric     }
4392e8d8bef9SDimitry Andric     const unsigned SS =
4393e8d8bef9SDimitry Andric         UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
43940b57cec5SDimitry Andric     // Get the access type.
4395e8d8bef9SDimitry Andric     llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
4396*fe013be4SDimitry Andric     Addr = Addr.withElementType(FieldIntTy);
4397e8d8bef9SDimitry Andric     if (UseVolatile) {
4398e8d8bef9SDimitry Andric       const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
4399e8d8bef9SDimitry Andric       if (VolatileOffset)
4400e8d8bef9SDimitry Andric         Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
4401e8d8bef9SDimitry Andric     }
44020b57cec5SDimitry Andric 
44030b57cec5SDimitry Andric     QualType fieldType =
44040b57cec5SDimitry Andric         field->getType().withCVRQualifiers(base.getVRQualifiers());
44050b57cec5SDimitry Andric     // TODO: Support TBAA for bit fields.
44060b57cec5SDimitry Andric     LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
44070b57cec5SDimitry Andric     return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
44080b57cec5SDimitry Andric                                 TBAAAccessInfo());
44090b57cec5SDimitry Andric   }
44100b57cec5SDimitry Andric 
44110b57cec5SDimitry Andric   // Fields of may-alias structures are may-alias themselves.
44120b57cec5SDimitry Andric   // FIXME: this should get propagated down through anonymous structs
44130b57cec5SDimitry Andric   // and unions.
44140b57cec5SDimitry Andric   QualType FieldType = field->getType();
44150b57cec5SDimitry Andric   const RecordDecl *rec = field->getParent();
44160b57cec5SDimitry Andric   AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
44170b57cec5SDimitry Andric   LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
44180b57cec5SDimitry Andric   TBAAAccessInfo FieldTBAAInfo;
44190b57cec5SDimitry Andric   if (base.getTBAAInfo().isMayAlias() ||
44200b57cec5SDimitry Andric           rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
44210b57cec5SDimitry Andric     FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
44220b57cec5SDimitry Andric   } else if (rec->isUnion()) {
44230b57cec5SDimitry Andric     // TODO: Support TBAA for unions.
44240b57cec5SDimitry Andric     FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
44250b57cec5SDimitry Andric   } else {
44260b57cec5SDimitry Andric     // If no base type been assigned for the base access, then try to generate
44270b57cec5SDimitry Andric     // one for this base lvalue.
44280b57cec5SDimitry Andric     FieldTBAAInfo = base.getTBAAInfo();
44290b57cec5SDimitry Andric     if (!FieldTBAAInfo.BaseType) {
44300b57cec5SDimitry Andric         FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
44310b57cec5SDimitry Andric         assert(!FieldTBAAInfo.Offset &&
44320b57cec5SDimitry Andric                "Nonzero offset for an access with no base type!");
44330b57cec5SDimitry Andric     }
44340b57cec5SDimitry Andric 
44350b57cec5SDimitry Andric     // Adjust offset to be relative to the base type.
44360b57cec5SDimitry Andric     const ASTRecordLayout &Layout =
44370b57cec5SDimitry Andric         getContext().getASTRecordLayout(field->getParent());
44380b57cec5SDimitry Andric     unsigned CharWidth = getContext().getCharWidth();
44390b57cec5SDimitry Andric     if (FieldTBAAInfo.BaseType)
44400b57cec5SDimitry Andric       FieldTBAAInfo.Offset +=
44410b57cec5SDimitry Andric           Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
44420b57cec5SDimitry Andric 
44430b57cec5SDimitry Andric     // Update the final access type and size.
44440b57cec5SDimitry Andric     FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
44450b57cec5SDimitry Andric     FieldTBAAInfo.Size =
44460b57cec5SDimitry Andric         getContext().getTypeSizeInChars(FieldType).getQuantity();
44470b57cec5SDimitry Andric   }
44480b57cec5SDimitry Andric 
4449480093f4SDimitry Andric   Address addr = base.getAddress(*this);
44500b57cec5SDimitry Andric   if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
44510b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().StrictVTablePointers &&
44520b57cec5SDimitry Andric         ClassDef->isDynamicClass()) {
44530b57cec5SDimitry Andric       // Getting to any field of dynamic object requires stripping dynamic
44540b57cec5SDimitry Andric       // information provided by invariant.group.  This is because accessing
44550b57cec5SDimitry Andric       // fields may leak the real address of dynamic object, which could result
44560b57cec5SDimitry Andric       // in miscompilation when leaked pointer would be compared.
44570b57cec5SDimitry Andric       auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
445881ad6265SDimitry Andric       addr = Address(stripped, addr.getElementType(), addr.getAlignment());
44590b57cec5SDimitry Andric     }
44600b57cec5SDimitry Andric   }
44610b57cec5SDimitry Andric 
44620b57cec5SDimitry Andric   unsigned RecordCVR = base.getVRQualifiers();
44630b57cec5SDimitry Andric   if (rec->isUnion()) {
44640b57cec5SDimitry Andric     // For unions, there is no pointer adjustment.
44650b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().StrictVTablePointers &&
44660b57cec5SDimitry Andric         hasAnyVptr(FieldType, getContext()))
44670b57cec5SDimitry Andric       // Because unions can easily skip invariant.barriers, we need to add
44680b57cec5SDimitry Andric       // a barrier every time CXXRecord field with vptr is referenced.
44690eae32dcSDimitry Andric       addr = Builder.CreateLaunderInvariantGroup(addr);
44700b57cec5SDimitry Andric 
4471480093f4SDimitry Andric     if (IsInPreservedAIRegion ||
4472480093f4SDimitry Andric         (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
44730b57cec5SDimitry Andric       // Remember the original union field index
44745ffd83dbSDimitry Andric       llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
44755ffd83dbSDimitry Andric           rec->getLocation());
44760b57cec5SDimitry Andric       addr = Address(
44770b57cec5SDimitry Andric           Builder.CreatePreserveUnionAccessIndex(
44780b57cec5SDimitry Andric               addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
447981ad6265SDimitry Andric           addr.getElementType(), addr.getAlignment());
44800b57cec5SDimitry Andric     }
44810b57cec5SDimitry Andric 
4482a7dea167SDimitry Andric     if (FieldType->isReferenceType())
4483*fe013be4SDimitry Andric       addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
4484a7dea167SDimitry Andric   } else {
4485480093f4SDimitry Andric     if (!IsInPreservedAIRegion &&
4486480093f4SDimitry Andric         (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
44870b57cec5SDimitry Andric       // For structs, we GEP to the field that the record layout suggests.
44880b57cec5SDimitry Andric       addr = emitAddrOfFieldStorage(*this, addr, field);
44890b57cec5SDimitry Andric     else
44900b57cec5SDimitry Andric       // Remember the original struct field index
44915ffd83dbSDimitry Andric       addr = emitPreserveStructAccess(*this, base, addr, field);
4492a7dea167SDimitry Andric   }
44930b57cec5SDimitry Andric 
44940b57cec5SDimitry Andric   // If this is a reference field, load the reference right now.
44950b57cec5SDimitry Andric   if (FieldType->isReferenceType()) {
4496a7dea167SDimitry Andric     LValue RefLVal =
4497a7dea167SDimitry Andric         MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
44980b57cec5SDimitry Andric     if (RecordCVR & Qualifiers::Volatile)
44990b57cec5SDimitry Andric       RefLVal.getQuals().addVolatile();
45000b57cec5SDimitry Andric     addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
45010b57cec5SDimitry Andric 
45020b57cec5SDimitry Andric     // Qualifiers on the struct don't apply to the referencee.
45030b57cec5SDimitry Andric     RecordCVR = 0;
45040b57cec5SDimitry Andric     FieldType = FieldType->getPointeeType();
45050b57cec5SDimitry Andric   }
45060b57cec5SDimitry Andric 
45070b57cec5SDimitry Andric   // Make sure that the address is pointing to the right type.  This is critical
4508*fe013be4SDimitry Andric   // for both unions and structs.
4509*fe013be4SDimitry Andric   addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
45100b57cec5SDimitry Andric 
45110b57cec5SDimitry Andric   if (field->hasAttr<AnnotateAttr>())
45120b57cec5SDimitry Andric     addr = EmitFieldAnnotations(field, addr);
45130b57cec5SDimitry Andric 
45140b57cec5SDimitry Andric   LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
45150b57cec5SDimitry Andric   LV.getQuals().addCVRQualifiers(RecordCVR);
45160b57cec5SDimitry Andric 
45170b57cec5SDimitry Andric   // __weak attribute on a field is ignored.
45180b57cec5SDimitry Andric   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
45190b57cec5SDimitry Andric     LV.getQuals().removeObjCGCAttr();
45200b57cec5SDimitry Andric 
45210b57cec5SDimitry Andric   return LV;
45220b57cec5SDimitry Andric }
45230b57cec5SDimitry Andric 
45240b57cec5SDimitry Andric LValue
45250b57cec5SDimitry Andric CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
45260b57cec5SDimitry Andric                                                   const FieldDecl *Field) {
45270b57cec5SDimitry Andric   QualType FieldType = Field->getType();
45280b57cec5SDimitry Andric 
45290b57cec5SDimitry Andric   if (!FieldType->isReferenceType())
45300b57cec5SDimitry Andric     return EmitLValueForField(Base, Field);
45310b57cec5SDimitry Andric 
4532480093f4SDimitry Andric   Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
45330b57cec5SDimitry Andric 
45340b57cec5SDimitry Andric   // Make sure that the address is pointing to the right type.
45350b57cec5SDimitry Andric   llvm::Type *llvmType = ConvertTypeForMem(FieldType);
4536*fe013be4SDimitry Andric   V = V.withElementType(llvmType);
45370b57cec5SDimitry Andric 
45380b57cec5SDimitry Andric   // TODO: Generate TBAA information that describes this access as a structure
45390b57cec5SDimitry Andric   // member access and not just an access to an object of the field's type. This
45400b57cec5SDimitry Andric   // should be similar to what we do in EmitLValueForField().
45410b57cec5SDimitry Andric   LValueBaseInfo BaseInfo = Base.getBaseInfo();
45420b57cec5SDimitry Andric   AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
45430b57cec5SDimitry Andric   LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
45440b57cec5SDimitry Andric   return MakeAddrLValue(V, FieldType, FieldBaseInfo,
45450b57cec5SDimitry Andric                         CGM.getTBAAInfoForSubobject(Base, FieldType));
45460b57cec5SDimitry Andric }
45470b57cec5SDimitry Andric 
45480b57cec5SDimitry Andric LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
45490b57cec5SDimitry Andric   if (E->isFileScope()) {
45500b57cec5SDimitry Andric     ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
45510b57cec5SDimitry Andric     return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
45520b57cec5SDimitry Andric   }
45530b57cec5SDimitry Andric   if (E->getType()->isVariablyModifiedType())
45540b57cec5SDimitry Andric     // make sure to emit the VLA size.
45550b57cec5SDimitry Andric     EmitVariablyModifiedType(E->getType());
45560b57cec5SDimitry Andric 
45570b57cec5SDimitry Andric   Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
45580b57cec5SDimitry Andric   const Expr *InitExpr = E->getInitializer();
45590b57cec5SDimitry Andric   LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
45600b57cec5SDimitry Andric 
45610b57cec5SDimitry Andric   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
45620b57cec5SDimitry Andric                    /*Init*/ true);
45630b57cec5SDimitry Andric 
45645ffd83dbSDimitry Andric   // Block-scope compound literals are destroyed at the end of the enclosing
45655ffd83dbSDimitry Andric   // scope in C.
45665ffd83dbSDimitry Andric   if (!getLangOpts().CPlusPlus)
45675ffd83dbSDimitry Andric     if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
45685ffd83dbSDimitry Andric       pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
45695ffd83dbSDimitry Andric                                   E->getType(), getDestroyer(DtorKind),
45705ffd83dbSDimitry Andric                                   DtorKind & EHCleanup);
45715ffd83dbSDimitry Andric 
45720b57cec5SDimitry Andric   return Result;
45730b57cec5SDimitry Andric }
45740b57cec5SDimitry Andric 
45750b57cec5SDimitry Andric LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
45760b57cec5SDimitry Andric   if (!E->isGLValue())
45770b57cec5SDimitry Andric     // Initializing an aggregate temporary in C++11: T{...}.
45780b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
45790b57cec5SDimitry Andric 
45800b57cec5SDimitry Andric   // An lvalue initializer list must be initializing a reference.
45810b57cec5SDimitry Andric   assert(E->isTransparent() && "non-transparent glvalue init list");
45820b57cec5SDimitry Andric   return EmitLValue(E->getInit(0));
45830b57cec5SDimitry Andric }
45840b57cec5SDimitry Andric 
45850b57cec5SDimitry Andric /// Emit the operand of a glvalue conditional operator. This is either a glvalue
45860b57cec5SDimitry Andric /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
45870b57cec5SDimitry Andric /// LValue is returned and the current block has been terminated.
4588bdd1243dSDimitry Andric static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
45890b57cec5SDimitry Andric                                                          const Expr *Operand) {
45900b57cec5SDimitry Andric   if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
45910b57cec5SDimitry Andric     CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
4592bdd1243dSDimitry Andric     return std::nullopt;
45930b57cec5SDimitry Andric   }
45940b57cec5SDimitry Andric 
45950b57cec5SDimitry Andric   return CGF.EmitLValue(Operand);
45960b57cec5SDimitry Andric }
45970b57cec5SDimitry Andric 
459881ad6265SDimitry Andric namespace {
459981ad6265SDimitry Andric // Handle the case where the condition is a constant evaluatable simple integer,
460081ad6265SDimitry Andric // which means we don't have to separately handle the true/false blocks.
4601bdd1243dSDimitry Andric std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
460281ad6265SDimitry Andric     CodeGenFunction &CGF, const AbstractConditionalOperator *E) {
460381ad6265SDimitry Andric   const Expr *condExpr = E->getCond();
460481ad6265SDimitry Andric   bool CondExprBool;
460581ad6265SDimitry Andric   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
460681ad6265SDimitry Andric     const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
460781ad6265SDimitry Andric     if (!CondExprBool)
460881ad6265SDimitry Andric       std::swap(Live, Dead);
460981ad6265SDimitry Andric 
461081ad6265SDimitry Andric     if (!CGF.ContainsLabel(Dead)) {
461181ad6265SDimitry Andric       // If the true case is live, we need to track its region.
461281ad6265SDimitry Andric       if (CondExprBool)
461381ad6265SDimitry Andric         CGF.incrementProfileCounter(E);
461481ad6265SDimitry Andric       // If a throw expression we emit it and return an undefined lvalue
461581ad6265SDimitry Andric       // because it can't be used.
461681ad6265SDimitry Andric       if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) {
461781ad6265SDimitry Andric         CGF.EmitCXXThrowExpr(ThrowExpr);
461881ad6265SDimitry Andric         llvm::Type *ElemTy = CGF.ConvertType(Dead->getType());
461981ad6265SDimitry Andric         llvm::Type *Ty = llvm::PointerType::getUnqual(ElemTy);
462081ad6265SDimitry Andric         return CGF.MakeAddrLValue(
462181ad6265SDimitry Andric             Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
462281ad6265SDimitry Andric             Dead->getType());
462381ad6265SDimitry Andric       }
462481ad6265SDimitry Andric       return CGF.EmitLValue(Live);
462581ad6265SDimitry Andric     }
462681ad6265SDimitry Andric   }
4627bdd1243dSDimitry Andric   return std::nullopt;
462881ad6265SDimitry Andric }
462981ad6265SDimitry Andric struct ConditionalInfo {
463081ad6265SDimitry Andric   llvm::BasicBlock *lhsBlock, *rhsBlock;
4631bdd1243dSDimitry Andric   std::optional<LValue> LHS, RHS;
463281ad6265SDimitry Andric };
463381ad6265SDimitry Andric 
463481ad6265SDimitry Andric // Create and generate the 3 blocks for a conditional operator.
463581ad6265SDimitry Andric // Leaves the 'current block' in the continuation basic block.
463681ad6265SDimitry Andric template<typename FuncTy>
463781ad6265SDimitry Andric ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
463881ad6265SDimitry Andric                                       const AbstractConditionalOperator *E,
463981ad6265SDimitry Andric                                       const FuncTy &BranchGenFunc) {
464081ad6265SDimitry Andric   ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
4641bdd1243dSDimitry Andric                        CGF.createBasicBlock("cond.false"), std::nullopt,
4642bdd1243dSDimitry Andric                        std::nullopt};
464381ad6265SDimitry Andric   llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
464481ad6265SDimitry Andric 
464581ad6265SDimitry Andric   CodeGenFunction::ConditionalEvaluation eval(CGF);
464681ad6265SDimitry Andric   CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
464781ad6265SDimitry Andric                            CGF.getProfileCount(E));
464881ad6265SDimitry Andric 
464981ad6265SDimitry Andric   // Any temporaries created here are conditional.
465081ad6265SDimitry Andric   CGF.EmitBlock(Info.lhsBlock);
465181ad6265SDimitry Andric   CGF.incrementProfileCounter(E);
465281ad6265SDimitry Andric   eval.begin(CGF);
465381ad6265SDimitry Andric   Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
465481ad6265SDimitry Andric   eval.end(CGF);
465581ad6265SDimitry Andric   Info.lhsBlock = CGF.Builder.GetInsertBlock();
465681ad6265SDimitry Andric 
465781ad6265SDimitry Andric   if (Info.LHS)
465881ad6265SDimitry Andric     CGF.Builder.CreateBr(endBlock);
465981ad6265SDimitry Andric 
466081ad6265SDimitry Andric   // Any temporaries created here are conditional.
466181ad6265SDimitry Andric   CGF.EmitBlock(Info.rhsBlock);
466281ad6265SDimitry Andric   eval.begin(CGF);
466381ad6265SDimitry Andric   Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
466481ad6265SDimitry Andric   eval.end(CGF);
466581ad6265SDimitry Andric   Info.rhsBlock = CGF.Builder.GetInsertBlock();
466681ad6265SDimitry Andric   CGF.EmitBlock(endBlock);
466781ad6265SDimitry Andric 
466881ad6265SDimitry Andric   return Info;
466981ad6265SDimitry Andric }
467081ad6265SDimitry Andric } // namespace
467181ad6265SDimitry Andric 
467281ad6265SDimitry Andric void CodeGenFunction::EmitIgnoredConditionalOperator(
467381ad6265SDimitry Andric     const AbstractConditionalOperator *E) {
467481ad6265SDimitry Andric   if (!E->isGLValue()) {
467581ad6265SDimitry Andric     // ?: here should be an aggregate.
467681ad6265SDimitry Andric     assert(hasAggregateEvaluationKind(E->getType()) &&
467781ad6265SDimitry Andric            "Unexpected conditional operator!");
467881ad6265SDimitry Andric     return (void)EmitAggExprToLValue(E);
467981ad6265SDimitry Andric   }
468081ad6265SDimitry Andric 
468181ad6265SDimitry Andric   OpaqueValueMapping binding(*this, E);
468281ad6265SDimitry Andric   if (HandleConditionalOperatorLValueSimpleCase(*this, E))
468381ad6265SDimitry Andric     return;
468481ad6265SDimitry Andric 
468581ad6265SDimitry Andric   EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) {
468681ad6265SDimitry Andric     CGF.EmitIgnoredExpr(E);
468781ad6265SDimitry Andric     return LValue{};
468881ad6265SDimitry Andric   });
468981ad6265SDimitry Andric }
469081ad6265SDimitry Andric LValue CodeGenFunction::EmitConditionalOperatorLValue(
469181ad6265SDimitry Andric     const AbstractConditionalOperator *expr) {
46920b57cec5SDimitry Andric   if (!expr->isGLValue()) {
46930b57cec5SDimitry Andric     // ?: here should be an aggregate.
46940b57cec5SDimitry Andric     assert(hasAggregateEvaluationKind(expr->getType()) &&
46950b57cec5SDimitry Andric            "Unexpected conditional operator!");
46960b57cec5SDimitry Andric     return EmitAggExprToLValue(expr);
46970b57cec5SDimitry Andric   }
46980b57cec5SDimitry Andric 
46990b57cec5SDimitry Andric   OpaqueValueMapping binding(*this, expr);
4700bdd1243dSDimitry Andric   if (std::optional<LValue> Res =
470181ad6265SDimitry Andric           HandleConditionalOperatorLValueSimpleCase(*this, expr))
470281ad6265SDimitry Andric     return *Res;
47030b57cec5SDimitry Andric 
470481ad6265SDimitry Andric   ConditionalInfo Info = EmitConditionalBlocks(
470581ad6265SDimitry Andric       *this, expr, [](CodeGenFunction &CGF, const Expr *E) {
470681ad6265SDimitry Andric         return EmitLValueOrThrowExpression(CGF, E);
470781ad6265SDimitry Andric       });
47080b57cec5SDimitry Andric 
470981ad6265SDimitry Andric   if ((Info.LHS && !Info.LHS->isSimple()) ||
471081ad6265SDimitry Andric       (Info.RHS && !Info.RHS->isSimple()))
47110b57cec5SDimitry Andric     return EmitUnsupportedLValue(expr, "conditional operator");
47120b57cec5SDimitry Andric 
471381ad6265SDimitry Andric   if (Info.LHS && Info.RHS) {
471481ad6265SDimitry Andric     Address lhsAddr = Info.LHS->getAddress(*this);
471581ad6265SDimitry Andric     Address rhsAddr = Info.RHS->getAddress(*this);
47160eae32dcSDimitry Andric     llvm::PHINode *phi = Builder.CreatePHI(lhsAddr.getType(), 2, "cond-lvalue");
471781ad6265SDimitry Andric     phi->addIncoming(lhsAddr.getPointer(), Info.lhsBlock);
471881ad6265SDimitry Andric     phi->addIncoming(rhsAddr.getPointer(), Info.rhsBlock);
47190eae32dcSDimitry Andric     Address result(phi, lhsAddr.getElementType(),
47200eae32dcSDimitry Andric                    std::min(lhsAddr.getAlignment(), rhsAddr.getAlignment()));
47210b57cec5SDimitry Andric     AlignmentSource alignSource =
472281ad6265SDimitry Andric         std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
472381ad6265SDimitry Andric                  Info.RHS->getBaseInfo().getAlignmentSource());
47240b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
472581ad6265SDimitry Andric         Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
47260b57cec5SDimitry Andric     return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
47270b57cec5SDimitry Andric                           TBAAInfo);
47280b57cec5SDimitry Andric   } else {
472981ad6265SDimitry Andric     assert((Info.LHS || Info.RHS) &&
47300b57cec5SDimitry Andric            "both operands of glvalue conditional are throw-expressions?");
473181ad6265SDimitry Andric     return Info.LHS ? *Info.LHS : *Info.RHS;
47320b57cec5SDimitry Andric   }
47330b57cec5SDimitry Andric }
47340b57cec5SDimitry Andric 
47350b57cec5SDimitry Andric /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
47360b57cec5SDimitry Andric /// type. If the cast is to a reference, we can have the usual lvalue result,
47370b57cec5SDimitry Andric /// otherwise if a cast is needed by the code generator in an lvalue context,
47380b57cec5SDimitry Andric /// then it must mean that we need the address of an aggregate in order to
47390b57cec5SDimitry Andric /// access one of its members.  This can happen for all the reasons that casts
47400b57cec5SDimitry Andric /// are permitted with aggregate result, including noop aggregate casts, and
47410b57cec5SDimitry Andric /// cast from scalar to union.
47420b57cec5SDimitry Andric LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
47430b57cec5SDimitry Andric   switch (E->getCastKind()) {
47440b57cec5SDimitry Andric   case CK_ToVoid:
47450b57cec5SDimitry Andric   case CK_BitCast:
47460b57cec5SDimitry Andric   case CK_LValueToRValueBitCast:
47470b57cec5SDimitry Andric   case CK_ArrayToPointerDecay:
47480b57cec5SDimitry Andric   case CK_FunctionToPointerDecay:
47490b57cec5SDimitry Andric   case CK_NullToMemberPointer:
47500b57cec5SDimitry Andric   case CK_NullToPointer:
47510b57cec5SDimitry Andric   case CK_IntegralToPointer:
47520b57cec5SDimitry Andric   case CK_PointerToIntegral:
47530b57cec5SDimitry Andric   case CK_PointerToBoolean:
47540b57cec5SDimitry Andric   case CK_VectorSplat:
47550b57cec5SDimitry Andric   case CK_IntegralCast:
47560b57cec5SDimitry Andric   case CK_BooleanToSignedIntegral:
47570b57cec5SDimitry Andric   case CK_IntegralToBoolean:
47580b57cec5SDimitry Andric   case CK_IntegralToFloating:
47590b57cec5SDimitry Andric   case CK_FloatingToIntegral:
47600b57cec5SDimitry Andric   case CK_FloatingToBoolean:
47610b57cec5SDimitry Andric   case CK_FloatingCast:
47620b57cec5SDimitry Andric   case CK_FloatingRealToComplex:
47630b57cec5SDimitry Andric   case CK_FloatingComplexToReal:
47640b57cec5SDimitry Andric   case CK_FloatingComplexToBoolean:
47650b57cec5SDimitry Andric   case CK_FloatingComplexCast:
47660b57cec5SDimitry Andric   case CK_FloatingComplexToIntegralComplex:
47670b57cec5SDimitry Andric   case CK_IntegralRealToComplex:
47680b57cec5SDimitry Andric   case CK_IntegralComplexToReal:
47690b57cec5SDimitry Andric   case CK_IntegralComplexToBoolean:
47700b57cec5SDimitry Andric   case CK_IntegralComplexCast:
47710b57cec5SDimitry Andric   case CK_IntegralComplexToFloatingComplex:
47720b57cec5SDimitry Andric   case CK_DerivedToBaseMemberPointer:
47730b57cec5SDimitry Andric   case CK_BaseToDerivedMemberPointer:
47740b57cec5SDimitry Andric   case CK_MemberPointerToBoolean:
47750b57cec5SDimitry Andric   case CK_ReinterpretMemberPointer:
47760b57cec5SDimitry Andric   case CK_AnyPointerToBlockPointerCast:
47770b57cec5SDimitry Andric   case CK_ARCProduceObject:
47780b57cec5SDimitry Andric   case CK_ARCConsumeObject:
47790b57cec5SDimitry Andric   case CK_ARCReclaimReturnedObject:
47800b57cec5SDimitry Andric   case CK_ARCExtendBlockObject:
47810b57cec5SDimitry Andric   case CK_CopyAndAutoreleaseBlockObject:
47820b57cec5SDimitry Andric   case CK_IntToOCLSampler:
4783e8d8bef9SDimitry Andric   case CK_FloatingToFixedPoint:
4784e8d8bef9SDimitry Andric   case CK_FixedPointToFloating:
47850b57cec5SDimitry Andric   case CK_FixedPointCast:
47860b57cec5SDimitry Andric   case CK_FixedPointToBoolean:
47870b57cec5SDimitry Andric   case CK_FixedPointToIntegral:
47880b57cec5SDimitry Andric   case CK_IntegralToFixedPoint:
4789fe6060f1SDimitry Andric   case CK_MatrixCast:
47900b57cec5SDimitry Andric     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
47910b57cec5SDimitry Andric 
47920b57cec5SDimitry Andric   case CK_Dependent:
47930b57cec5SDimitry Andric     llvm_unreachable("dependent cast kind in IR gen!");
47940b57cec5SDimitry Andric 
47950b57cec5SDimitry Andric   case CK_BuiltinFnToFnPtr:
47960b57cec5SDimitry Andric     llvm_unreachable("builtin functions are handled elsewhere");
47970b57cec5SDimitry Andric 
47980b57cec5SDimitry Andric   // These are never l-values; just use the aggregate emission code.
47990b57cec5SDimitry Andric   case CK_NonAtomicToAtomic:
48000b57cec5SDimitry Andric   case CK_AtomicToNonAtomic:
48010b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
48020b57cec5SDimitry Andric 
48030b57cec5SDimitry Andric   case CK_Dynamic: {
48040b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4805480093f4SDimitry Andric     Address V = LV.getAddress(*this);
48060b57cec5SDimitry Andric     const auto *DCE = cast<CXXDynamicCastExpr>(E);
48070b57cec5SDimitry Andric     return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
48080b57cec5SDimitry Andric   }
48090b57cec5SDimitry Andric 
48100b57cec5SDimitry Andric   case CK_ConstructorConversion:
48110b57cec5SDimitry Andric   case CK_UserDefinedConversion:
48120b57cec5SDimitry Andric   case CK_CPointerToObjCPointerCast:
48130b57cec5SDimitry Andric   case CK_BlockPointerToObjCPointerCast:
48140b57cec5SDimitry Andric   case CK_LValueToRValue:
48150b57cec5SDimitry Andric     return EmitLValue(E->getSubExpr());
48160b57cec5SDimitry Andric 
4817349cc55cSDimitry Andric   case CK_NoOp: {
4818349cc55cSDimitry Andric     // CK_NoOp can model a qualification conversion, which can remove an array
4819349cc55cSDimitry Andric     // bound and change the IR type.
4820349cc55cSDimitry Andric     // FIXME: Once pointee types are removed from IR, remove this.
4821349cc55cSDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4822349cc55cSDimitry Andric     if (LV.isSimple()) {
4823349cc55cSDimitry Andric       Address V = LV.getAddress(*this);
4824349cc55cSDimitry Andric       if (V.isValid()) {
482504eeddc0SDimitry Andric         llvm::Type *T = ConvertTypeForMem(E->getType());
482604eeddc0SDimitry Andric         if (V.getElementType() != T)
4827*fe013be4SDimitry Andric           LV.setAddress(V.withElementType(T));
4828349cc55cSDimitry Andric       }
4829349cc55cSDimitry Andric     }
4830349cc55cSDimitry Andric     return LV;
4831349cc55cSDimitry Andric   }
4832349cc55cSDimitry Andric 
48330b57cec5SDimitry Andric   case CK_UncheckedDerivedToBase:
48340b57cec5SDimitry Andric   case CK_DerivedToBase: {
4835480093f4SDimitry Andric     const auto *DerivedClassTy =
4836480093f4SDimitry Andric         E->getSubExpr()->getType()->castAs<RecordType>();
48370b57cec5SDimitry Andric     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
48380b57cec5SDimitry Andric 
48390b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4840480093f4SDimitry Andric     Address This = LV.getAddress(*this);
48410b57cec5SDimitry Andric 
48420b57cec5SDimitry Andric     // Perform the derived-to-base conversion
48430b57cec5SDimitry Andric     Address Base = GetAddressOfBaseClass(
48440b57cec5SDimitry Andric         This, DerivedClassDecl, E->path_begin(), E->path_end(),
48450b57cec5SDimitry Andric         /*NullCheckValue=*/false, E->getExprLoc());
48460b57cec5SDimitry Andric 
48470b57cec5SDimitry Andric     // TODO: Support accesses to members of base classes in TBAA. For now, we
48480b57cec5SDimitry Andric     // conservatively pretend that the complete object is of the base class
48490b57cec5SDimitry Andric     // type.
48500b57cec5SDimitry Andric     return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
48510b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
48520b57cec5SDimitry Andric   }
48530b57cec5SDimitry Andric   case CK_ToUnion:
48540b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
48550b57cec5SDimitry Andric   case CK_BaseToDerived: {
4856480093f4SDimitry Andric     const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
48570b57cec5SDimitry Andric     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
48580b57cec5SDimitry Andric 
48590b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
48600b57cec5SDimitry Andric 
48610b57cec5SDimitry Andric     // Perform the base-to-derived conversion
4862480093f4SDimitry Andric     Address Derived = GetAddressOfDerivedClass(
4863480093f4SDimitry Andric         LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
48640b57cec5SDimitry Andric         /*NullCheckValue=*/false);
48650b57cec5SDimitry Andric 
48660b57cec5SDimitry Andric     // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
48670b57cec5SDimitry Andric     // performed and the object is not of the derived type.
48680b57cec5SDimitry Andric     if (sanitizePerformTypeCheck())
48690b57cec5SDimitry Andric       EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
48700b57cec5SDimitry Andric                     Derived.getPointer(), E->getType());
48710b57cec5SDimitry Andric 
48720b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::CFIDerivedCast))
487381ad6265SDimitry Andric       EmitVTablePtrCheckForCast(E->getType(), Derived,
48740b57cec5SDimitry Andric                                 /*MayBeNull=*/false, CFITCK_DerivedCast,
48750b57cec5SDimitry Andric                                 E->getBeginLoc());
48760b57cec5SDimitry Andric 
48770b57cec5SDimitry Andric     return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
48780b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
48790b57cec5SDimitry Andric   }
48800b57cec5SDimitry Andric   case CK_LValueBitCast: {
48810b57cec5SDimitry Andric     // This must be a reinterpret_cast (or c-style equivalent).
48820b57cec5SDimitry Andric     const auto *CE = cast<ExplicitCastExpr>(E);
48830b57cec5SDimitry Andric 
48840b57cec5SDimitry Andric     CGM.EmitExplicitCastExprType(CE, this);
48850b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4886*fe013be4SDimitry Andric     Address V = LV.getAddress(*this).withElementType(
488704eeddc0SDimitry Andric         ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
48880b57cec5SDimitry Andric 
48890b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
489081ad6265SDimitry Andric       EmitVTablePtrCheckForCast(E->getType(), V,
48910b57cec5SDimitry Andric                                 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
48920b57cec5SDimitry Andric                                 E->getBeginLoc());
48930b57cec5SDimitry Andric 
48940b57cec5SDimitry Andric     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
48950b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
48960b57cec5SDimitry Andric   }
48970b57cec5SDimitry Andric   case CK_AddressSpaceConversion: {
48980b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
48990b57cec5SDimitry Andric     QualType DestTy = getContext().getPointerType(E->getType());
49000b57cec5SDimitry Andric     llvm::Value *V = getTargetHooks().performAddrSpaceCast(
4901480093f4SDimitry Andric         *this, LV.getPointer(*this),
4902480093f4SDimitry Andric         E->getSubExpr()->getType().getAddressSpace(),
49030b57cec5SDimitry Andric         E->getType().getAddressSpace(), ConvertType(DestTy));
490481ad6265SDimitry Andric     return MakeAddrLValue(Address(V, ConvertTypeForMem(E->getType()),
490581ad6265SDimitry Andric                                   LV.getAddress(*this).getAlignment()),
49060b57cec5SDimitry Andric                           E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
49070b57cec5SDimitry Andric   }
49080b57cec5SDimitry Andric   case CK_ObjCObjectLValueCast: {
49090b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4910*fe013be4SDimitry Andric     Address V = LV.getAddress(*this).withElementType(ConvertType(E->getType()));
49110b57cec5SDimitry Andric     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
49120b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
49130b57cec5SDimitry Andric   }
49140b57cec5SDimitry Andric   case CK_ZeroToOCLOpaqueType:
49150b57cec5SDimitry Andric     llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
49160b57cec5SDimitry Andric   }
49170b57cec5SDimitry Andric 
49180b57cec5SDimitry Andric   llvm_unreachable("Unhandled lvalue cast kind?");
49190b57cec5SDimitry Andric }
49200b57cec5SDimitry Andric 
49210b57cec5SDimitry Andric LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
49220b57cec5SDimitry Andric   assert(OpaqueValueMappingData::shouldBindAsLValue(e));
49230b57cec5SDimitry Andric   return getOrCreateOpaqueLValueMapping(e);
49240b57cec5SDimitry Andric }
49250b57cec5SDimitry Andric 
49260b57cec5SDimitry Andric LValue
49270b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
49280b57cec5SDimitry Andric   assert(OpaqueValueMapping::shouldBindAsLValue(e));
49290b57cec5SDimitry Andric 
49300b57cec5SDimitry Andric   llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
49310b57cec5SDimitry Andric       it = OpaqueLValues.find(e);
49320b57cec5SDimitry Andric 
49330b57cec5SDimitry Andric   if (it != OpaqueLValues.end())
49340b57cec5SDimitry Andric     return it->second;
49350b57cec5SDimitry Andric 
49360b57cec5SDimitry Andric   assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
49370b57cec5SDimitry Andric   return EmitLValue(e->getSourceExpr());
49380b57cec5SDimitry Andric }
49390b57cec5SDimitry Andric 
49400b57cec5SDimitry Andric RValue
49410b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
49420b57cec5SDimitry Andric   assert(!OpaqueValueMapping::shouldBindAsLValue(e));
49430b57cec5SDimitry Andric 
49440b57cec5SDimitry Andric   llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
49450b57cec5SDimitry Andric       it = OpaqueRValues.find(e);
49460b57cec5SDimitry Andric 
49470b57cec5SDimitry Andric   if (it != OpaqueRValues.end())
49480b57cec5SDimitry Andric     return it->second;
49490b57cec5SDimitry Andric 
49500b57cec5SDimitry Andric   assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
49510b57cec5SDimitry Andric   return EmitAnyExpr(e->getSourceExpr());
49520b57cec5SDimitry Andric }
49530b57cec5SDimitry Andric 
49540b57cec5SDimitry Andric RValue CodeGenFunction::EmitRValueForField(LValue LV,
49550b57cec5SDimitry Andric                                            const FieldDecl *FD,
49560b57cec5SDimitry Andric                                            SourceLocation Loc) {
49570b57cec5SDimitry Andric   QualType FT = FD->getType();
49580b57cec5SDimitry Andric   LValue FieldLV = EmitLValueForField(LV, FD);
49590b57cec5SDimitry Andric   switch (getEvaluationKind(FT)) {
49600b57cec5SDimitry Andric   case TEK_Complex:
49610b57cec5SDimitry Andric     return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
49620b57cec5SDimitry Andric   case TEK_Aggregate:
4963480093f4SDimitry Andric     return FieldLV.asAggregateRValue(*this);
49640b57cec5SDimitry Andric   case TEK_Scalar:
49650b57cec5SDimitry Andric     // This routine is used to load fields one-by-one to perform a copy, so
49660b57cec5SDimitry Andric     // don't load reference fields.
49670b57cec5SDimitry Andric     if (FD->getType()->isReferenceType())
4968480093f4SDimitry Andric       return RValue::get(FieldLV.getPointer(*this));
4969480093f4SDimitry Andric     // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
4970480093f4SDimitry Andric     // primitive load.
4971480093f4SDimitry Andric     if (FieldLV.isBitField())
49720b57cec5SDimitry Andric       return EmitLoadOfLValue(FieldLV, Loc);
4973480093f4SDimitry Andric     return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
49740b57cec5SDimitry Andric   }
49750b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
49760b57cec5SDimitry Andric }
49770b57cec5SDimitry Andric 
49780b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
49790b57cec5SDimitry Andric //                             Expression Emission
49800b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
49810b57cec5SDimitry Andric 
49820b57cec5SDimitry Andric RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
49830b57cec5SDimitry Andric                                      ReturnValueSlot ReturnValue) {
49840b57cec5SDimitry Andric   // Builtins never have block type.
49850b57cec5SDimitry Andric   if (E->getCallee()->getType()->isBlockPointerType())
49860b57cec5SDimitry Andric     return EmitBlockCallExpr(E, ReturnValue);
49870b57cec5SDimitry Andric 
49880b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
49890b57cec5SDimitry Andric     return EmitCXXMemberCallExpr(CE, ReturnValue);
49900b57cec5SDimitry Andric 
49910b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
49920b57cec5SDimitry Andric     return EmitCUDAKernelCallExpr(CE, ReturnValue);
49930b57cec5SDimitry Andric 
49940b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
49950b57cec5SDimitry Andric     if (const CXXMethodDecl *MD =
49960b57cec5SDimitry Andric           dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
49970b57cec5SDimitry Andric       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
49980b57cec5SDimitry Andric 
49990b57cec5SDimitry Andric   CGCallee callee = EmitCallee(E->getCallee());
50000b57cec5SDimitry Andric 
50010b57cec5SDimitry Andric   if (callee.isBuiltin()) {
50020b57cec5SDimitry Andric     return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
50030b57cec5SDimitry Andric                            E, ReturnValue);
50040b57cec5SDimitry Andric   }
50050b57cec5SDimitry Andric 
50060b57cec5SDimitry Andric   if (callee.isPseudoDestructor()) {
50070b57cec5SDimitry Andric     return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
50080b57cec5SDimitry Andric   }
50090b57cec5SDimitry Andric 
50100b57cec5SDimitry Andric   return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
50110b57cec5SDimitry Andric }
50120b57cec5SDimitry Andric 
50130b57cec5SDimitry Andric /// Emit a CallExpr without considering whether it might be a subclass.
50140b57cec5SDimitry Andric RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
50150b57cec5SDimitry Andric                                            ReturnValueSlot ReturnValue) {
50160b57cec5SDimitry Andric   CGCallee Callee = EmitCallee(E->getCallee());
50170b57cec5SDimitry Andric   return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
50180b57cec5SDimitry Andric }
50190b57cec5SDimitry Andric 
50203a9a9c0cSDimitry Andric // Detect the unusual situation where an inline version is shadowed by a
50213a9a9c0cSDimitry Andric // non-inline version. In that case we should pick the external one
50223a9a9c0cSDimitry Andric // everywhere. That's GCC behavior too.
50233a9a9c0cSDimitry Andric static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD) {
50243a9a9c0cSDimitry Andric   for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
50253a9a9c0cSDimitry Andric     if (!PD->isInlineBuiltinDeclaration())
50263a9a9c0cSDimitry Andric       return false;
50273a9a9c0cSDimitry Andric   return true;
50283a9a9c0cSDimitry Andric }
50293a9a9c0cSDimitry Andric 
50305ffd83dbSDimitry Andric static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
50315ffd83dbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
5032480093f4SDimitry Andric 
50330b57cec5SDimitry Andric   if (auto builtinID = FD->getBuiltinID()) {
503481ad6265SDimitry Andric     std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
503581ad6265SDimitry Andric     std::string NoBuiltins = "no-builtins";
5036bdd1243dSDimitry Andric 
5037bdd1243dSDimitry Andric     StringRef Ident = CGF.CGM.getMangledName(GD);
5038bdd1243dSDimitry Andric     std::string FDInlineName = (Ident + ".inline").str();
503981ad6265SDimitry Andric 
504081ad6265SDimitry Andric     bool IsPredefinedLibFunction =
504181ad6265SDimitry Andric         CGF.getContext().BuiltinInfo.isPredefinedLibFunction(builtinID);
504281ad6265SDimitry Andric     bool HasAttributeNoBuiltin =
504381ad6265SDimitry Andric         CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
504481ad6265SDimitry Andric         CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
504581ad6265SDimitry Andric 
5046349cc55cSDimitry Andric     // When directing calling an inline builtin, call it through it's mangled
5047349cc55cSDimitry Andric     // name to make it clear it's not the actual builtin.
50483a9a9c0cSDimitry Andric     if (CGF.CurFn->getName() != FDInlineName &&
50493a9a9c0cSDimitry Andric         OnlyHasInlineBuiltinDeclaration(FD)) {
5050349cc55cSDimitry Andric       llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
5051349cc55cSDimitry Andric       llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
5052349cc55cSDimitry Andric       llvm::Module *M = Fn->getParent();
5053349cc55cSDimitry Andric       llvm::Function *Clone = M->getFunction(FDInlineName);
5054349cc55cSDimitry Andric       if (!Clone) {
5055349cc55cSDimitry Andric         Clone = llvm::Function::Create(Fn->getFunctionType(),
5056349cc55cSDimitry Andric                                        llvm::GlobalValue::InternalLinkage,
5057349cc55cSDimitry Andric                                        Fn->getAddressSpace(), FDInlineName, M);
5058349cc55cSDimitry Andric         Clone->addFnAttr(llvm::Attribute::AlwaysInline);
5059349cc55cSDimitry Andric       }
5060349cc55cSDimitry Andric       return CGCallee::forDirect(Clone, GD);
5061349cc55cSDimitry Andric     }
5062349cc55cSDimitry Andric 
5063349cc55cSDimitry Andric     // Replaceable builtins provide their own implementation of a builtin. If we
5064349cc55cSDimitry Andric     // are in an inline builtin implementation, avoid trivial infinite
506581ad6265SDimitry Andric     // recursion. Honor __attribute__((no_builtin("foo"))) or
506681ad6265SDimitry Andric     // __attribute__((no_builtin)) on the current function unless foo is
506781ad6265SDimitry Andric     // not a predefined library function which means we must generate the
506881ad6265SDimitry Andric     // builtin no matter what.
506981ad6265SDimitry Andric     else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
50700b57cec5SDimitry Andric       return CGCallee::forBuiltin(builtinID, FD);
50710b57cec5SDimitry Andric   }
50720b57cec5SDimitry Andric 
5073fe6060f1SDimitry Andric   llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
5074fe6060f1SDimitry Andric   if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
5075fe6060f1SDimitry Andric       FD->hasAttr<CUDAGlobalAttr>())
5076fe6060f1SDimitry Andric     CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
5077fe6060f1SDimitry Andric         cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
5078349cc55cSDimitry Andric 
5079fe6060f1SDimitry Andric   return CGCallee::forDirect(CalleePtr, GD);
50800b57cec5SDimitry Andric }
50810b57cec5SDimitry Andric 
50820b57cec5SDimitry Andric CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
50830b57cec5SDimitry Andric   E = E->IgnoreParens();
50840b57cec5SDimitry Andric 
50850b57cec5SDimitry Andric   // Look through function-to-pointer decay.
50860b57cec5SDimitry Andric   if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
50870b57cec5SDimitry Andric     if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
50880b57cec5SDimitry Andric         ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
50890b57cec5SDimitry Andric       return EmitCallee(ICE->getSubExpr());
50900b57cec5SDimitry Andric     }
50910b57cec5SDimitry Andric 
50920b57cec5SDimitry Andric   // Resolve direct calls.
50930b57cec5SDimitry Andric   } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
50940b57cec5SDimitry Andric     if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
50950b57cec5SDimitry Andric       return EmitDirectCallee(*this, FD);
50960b57cec5SDimitry Andric     }
50970b57cec5SDimitry Andric   } else if (auto ME = dyn_cast<MemberExpr>(E)) {
50980b57cec5SDimitry Andric     if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
50990b57cec5SDimitry Andric       EmitIgnoredExpr(ME->getBase());
51000b57cec5SDimitry Andric       return EmitDirectCallee(*this, FD);
51010b57cec5SDimitry Andric     }
51020b57cec5SDimitry Andric 
51030b57cec5SDimitry Andric   // Look through template substitutions.
51040b57cec5SDimitry Andric   } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
51050b57cec5SDimitry Andric     return EmitCallee(NTTP->getReplacement());
51060b57cec5SDimitry Andric 
51070b57cec5SDimitry Andric   // Treat pseudo-destructor calls differently.
51080b57cec5SDimitry Andric   } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
51090b57cec5SDimitry Andric     return CGCallee::forPseudoDestructor(PDE);
51100b57cec5SDimitry Andric   }
51110b57cec5SDimitry Andric 
51120b57cec5SDimitry Andric   // Otherwise, we have an indirect reference.
51130b57cec5SDimitry Andric   llvm::Value *calleePtr;
51140b57cec5SDimitry Andric   QualType functionType;
51150b57cec5SDimitry Andric   if (auto ptrType = E->getType()->getAs<PointerType>()) {
51160b57cec5SDimitry Andric     calleePtr = EmitScalarExpr(E);
51170b57cec5SDimitry Andric     functionType = ptrType->getPointeeType();
51180b57cec5SDimitry Andric   } else {
51190b57cec5SDimitry Andric     functionType = E->getType();
5120*fe013be4SDimitry Andric     calleePtr = EmitLValue(E, KnownNonNull).getPointer(*this);
51210b57cec5SDimitry Andric   }
51220b57cec5SDimitry Andric   assert(functionType->isFunctionType());
51230b57cec5SDimitry Andric 
51240b57cec5SDimitry Andric   GlobalDecl GD;
51250b57cec5SDimitry Andric   if (const auto *VD =
51260b57cec5SDimitry Andric           dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
51270b57cec5SDimitry Andric     GD = GlobalDecl(VD);
51280b57cec5SDimitry Andric 
51290b57cec5SDimitry Andric   CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
51300b57cec5SDimitry Andric   CGCallee callee(calleeInfo, calleePtr);
51310b57cec5SDimitry Andric   return callee;
51320b57cec5SDimitry Andric }
51330b57cec5SDimitry Andric 
51340b57cec5SDimitry Andric LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
51350b57cec5SDimitry Andric   // Comma expressions just emit their LHS then their RHS as an l-value.
51360b57cec5SDimitry Andric   if (E->getOpcode() == BO_Comma) {
51370b57cec5SDimitry Andric     EmitIgnoredExpr(E->getLHS());
51380b57cec5SDimitry Andric     EnsureInsertPoint();
51390b57cec5SDimitry Andric     return EmitLValue(E->getRHS());
51400b57cec5SDimitry Andric   }
51410b57cec5SDimitry Andric 
51420b57cec5SDimitry Andric   if (E->getOpcode() == BO_PtrMemD ||
51430b57cec5SDimitry Andric       E->getOpcode() == BO_PtrMemI)
51440b57cec5SDimitry Andric     return EmitPointerToDataMemberBinaryExpr(E);
51450b57cec5SDimitry Andric 
51460b57cec5SDimitry Andric   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
51470b57cec5SDimitry Andric 
51480b57cec5SDimitry Andric   // Note that in all of these cases, __block variables need the RHS
51490b57cec5SDimitry Andric   // evaluated first just in case the variable gets moved by the RHS.
51500b57cec5SDimitry Andric 
51510b57cec5SDimitry Andric   switch (getEvaluationKind(E->getType())) {
51520b57cec5SDimitry Andric   case TEK_Scalar: {
51530b57cec5SDimitry Andric     switch (E->getLHS()->getType().getObjCLifetime()) {
51540b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
51550b57cec5SDimitry Andric       return EmitARCStoreStrong(E, /*ignored*/ false).first;
51560b57cec5SDimitry Andric 
51570b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
51580b57cec5SDimitry Andric       return EmitARCStoreAutoreleasing(E).first;
51590b57cec5SDimitry Andric 
51600b57cec5SDimitry Andric     // No reason to do any of these differently.
51610b57cec5SDimitry Andric     case Qualifiers::OCL_None:
51620b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
51630b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
51640b57cec5SDimitry Andric       break;
51650b57cec5SDimitry Andric     }
51660b57cec5SDimitry Andric 
51670b57cec5SDimitry Andric     RValue RV = EmitAnyExpr(E->getRHS());
51680b57cec5SDimitry Andric     LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
51690b57cec5SDimitry Andric     if (RV.isScalar())
51700b57cec5SDimitry Andric       EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
51710b57cec5SDimitry Andric     EmitStoreThroughLValue(RV, LV);
5172480093f4SDimitry Andric     if (getLangOpts().OpenMP)
5173480093f4SDimitry Andric       CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
5174480093f4SDimitry Andric                                                                 E->getLHS());
51750b57cec5SDimitry Andric     return LV;
51760b57cec5SDimitry Andric   }
51770b57cec5SDimitry Andric 
51780b57cec5SDimitry Andric   case TEK_Complex:
51790b57cec5SDimitry Andric     return EmitComplexAssignmentLValue(E);
51800b57cec5SDimitry Andric 
51810b57cec5SDimitry Andric   case TEK_Aggregate:
51820b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
51830b57cec5SDimitry Andric   }
51840b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
51850b57cec5SDimitry Andric }
51860b57cec5SDimitry Andric 
51870b57cec5SDimitry Andric LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
51880b57cec5SDimitry Andric   RValue RV = EmitCallExpr(E);
51890b57cec5SDimitry Andric 
51900b57cec5SDimitry Andric   if (!RV.isScalar())
51910b57cec5SDimitry Andric     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
51920b57cec5SDimitry Andric                           AlignmentSource::Decl);
51930b57cec5SDimitry Andric 
51940b57cec5SDimitry Andric   assert(E->getCallReturnType(getContext())->isReferenceType() &&
51950b57cec5SDimitry Andric          "Can't have a scalar return unless the return type is a "
51960b57cec5SDimitry Andric          "reference type!");
51970b57cec5SDimitry Andric 
51980b57cec5SDimitry Andric   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
51990b57cec5SDimitry Andric }
52000b57cec5SDimitry Andric 
52010b57cec5SDimitry Andric LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
52020b57cec5SDimitry Andric   // FIXME: This shouldn't require another copy.
52030b57cec5SDimitry Andric   return EmitAggExprToLValue(E);
52040b57cec5SDimitry Andric }
52050b57cec5SDimitry Andric 
52060b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
52070b57cec5SDimitry Andric   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
52080b57cec5SDimitry Andric          && "binding l-value to type which needs a temporary");
52090b57cec5SDimitry Andric   AggValueSlot Slot = CreateAggTemp(E->getType());
52100b57cec5SDimitry Andric   EmitCXXConstructExpr(E, Slot);
52110b57cec5SDimitry Andric   return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
52120b57cec5SDimitry Andric }
52130b57cec5SDimitry Andric 
52140b57cec5SDimitry Andric LValue
52150b57cec5SDimitry Andric CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
52160b57cec5SDimitry Andric   return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
52170b57cec5SDimitry Andric }
52180b57cec5SDimitry Andric 
52190b57cec5SDimitry Andric Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
5220*fe013be4SDimitry Andric   return CGM.GetAddrOfMSGuidDecl(E->getGuidDecl())
5221*fe013be4SDimitry Andric       .withElementType(ConvertType(E->getType()));
52220b57cec5SDimitry Andric }
52230b57cec5SDimitry Andric 
52240b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
52250b57cec5SDimitry Andric   return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
52260b57cec5SDimitry Andric                         AlignmentSource::Decl);
52270b57cec5SDimitry Andric }
52280b57cec5SDimitry Andric 
52290b57cec5SDimitry Andric LValue
52300b57cec5SDimitry Andric CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
52310b57cec5SDimitry Andric   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
52320b57cec5SDimitry Andric   Slot.setExternallyDestructed();
52330b57cec5SDimitry Andric   EmitAggExpr(E->getSubExpr(), Slot);
52340b57cec5SDimitry Andric   EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
52350b57cec5SDimitry Andric   return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
52360b57cec5SDimitry Andric }
52370b57cec5SDimitry Andric 
52380b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
52390b57cec5SDimitry Andric   RValue RV = EmitObjCMessageExpr(E);
52400b57cec5SDimitry Andric 
52410b57cec5SDimitry Andric   if (!RV.isScalar())
52420b57cec5SDimitry Andric     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
52430b57cec5SDimitry Andric                           AlignmentSource::Decl);
52440b57cec5SDimitry Andric 
52450b57cec5SDimitry Andric   assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
52460b57cec5SDimitry Andric          "Can't have a scalar return unless the return type is a "
52470b57cec5SDimitry Andric          "reference type!");
52480b57cec5SDimitry Andric 
52490b57cec5SDimitry Andric   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
52500b57cec5SDimitry Andric }
52510b57cec5SDimitry Andric 
52520b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
52530b57cec5SDimitry Andric   Address V =
52540b57cec5SDimitry Andric     CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
52550b57cec5SDimitry Andric   return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
52560b57cec5SDimitry Andric }
52570b57cec5SDimitry Andric 
52580b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
52590b57cec5SDimitry Andric                                              const ObjCIvarDecl *Ivar) {
52600b57cec5SDimitry Andric   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
52610b57cec5SDimitry Andric }
52620b57cec5SDimitry Andric 
5263bdd1243dSDimitry Andric llvm::Value *
5264bdd1243dSDimitry Andric CodeGenFunction::EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface,
5265bdd1243dSDimitry Andric                                              const ObjCIvarDecl *Ivar) {
5266bdd1243dSDimitry Andric   llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar);
5267bdd1243dSDimitry Andric   QualType PointerDiffType = getContext().getPointerDiffType();
5268bdd1243dSDimitry Andric   return Builder.CreateZExtOrTrunc(OffsetValue,
5269bdd1243dSDimitry Andric                                    getTypes().ConvertType(PointerDiffType));
5270bdd1243dSDimitry Andric }
5271bdd1243dSDimitry Andric 
52720b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
52730b57cec5SDimitry Andric                                           llvm::Value *BaseValue,
52740b57cec5SDimitry Andric                                           const ObjCIvarDecl *Ivar,
52750b57cec5SDimitry Andric                                           unsigned CVRQualifiers) {
52760b57cec5SDimitry Andric   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
52770b57cec5SDimitry Andric                                                    Ivar, CVRQualifiers);
52780b57cec5SDimitry Andric }
52790b57cec5SDimitry Andric 
52800b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
52810b57cec5SDimitry Andric   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
52820b57cec5SDimitry Andric   llvm::Value *BaseValue = nullptr;
52830b57cec5SDimitry Andric   const Expr *BaseExpr = E->getBase();
52840b57cec5SDimitry Andric   Qualifiers BaseQuals;
52850b57cec5SDimitry Andric   QualType ObjectTy;
52860b57cec5SDimitry Andric   if (E->isArrow()) {
52870b57cec5SDimitry Andric     BaseValue = EmitScalarExpr(BaseExpr);
52880b57cec5SDimitry Andric     ObjectTy = BaseExpr->getType()->getPointeeType();
52890b57cec5SDimitry Andric     BaseQuals = ObjectTy.getQualifiers();
52900b57cec5SDimitry Andric   } else {
52910b57cec5SDimitry Andric     LValue BaseLV = EmitLValue(BaseExpr);
5292480093f4SDimitry Andric     BaseValue = BaseLV.getPointer(*this);
52930b57cec5SDimitry Andric     ObjectTy = BaseExpr->getType();
52940b57cec5SDimitry Andric     BaseQuals = ObjectTy.getQualifiers();
52950b57cec5SDimitry Andric   }
52960b57cec5SDimitry Andric 
52970b57cec5SDimitry Andric   LValue LV =
52980b57cec5SDimitry Andric     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
52990b57cec5SDimitry Andric                       BaseQuals.getCVRQualifiers());
53000b57cec5SDimitry Andric   setObjCGCLValueClass(getContext(), E, LV);
53010b57cec5SDimitry Andric   return LV;
53020b57cec5SDimitry Andric }
53030b57cec5SDimitry Andric 
53040b57cec5SDimitry Andric LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
53050b57cec5SDimitry Andric   // Can only get l-value for message expression returning aggregate type
53060b57cec5SDimitry Andric   RValue RV = EmitAnyExprToTemp(E);
53070b57cec5SDimitry Andric   return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
53080b57cec5SDimitry Andric                         AlignmentSource::Decl);
53090b57cec5SDimitry Andric }
53100b57cec5SDimitry Andric 
53110b57cec5SDimitry Andric RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
53120b57cec5SDimitry Andric                                  const CallExpr *E, ReturnValueSlot ReturnValue,
53130b57cec5SDimitry Andric                                  llvm::Value *Chain) {
53140b57cec5SDimitry Andric   // Get the actual function type. The callee type will always be a pointer to
53150b57cec5SDimitry Andric   // function type or a block pointer type.
53160b57cec5SDimitry Andric   assert(CalleeType->isFunctionPointerType() &&
53170b57cec5SDimitry Andric          "Call must have function pointer type!");
53180b57cec5SDimitry Andric 
53190b57cec5SDimitry Andric   const Decl *TargetDecl =
53200b57cec5SDimitry Andric       OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
53210b57cec5SDimitry Andric 
5322*fe013be4SDimitry Andric   assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
5323*fe013be4SDimitry Andric           !cast<FunctionDecl>(TargetDecl)->isImmediateFunction()) &&
5324*fe013be4SDimitry Andric          "trying to emit a call to an immediate function");
5325*fe013be4SDimitry Andric 
53260b57cec5SDimitry Andric   CalleeType = getContext().getCanonicalType(CalleeType);
53270b57cec5SDimitry Andric 
53280b57cec5SDimitry Andric   auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
53290b57cec5SDimitry Andric 
53300b57cec5SDimitry Andric   CGCallee Callee = OrigCallee;
53310b57cec5SDimitry Andric 
5332*fe013be4SDimitry Andric   if (SanOpts.has(SanitizerKind::Function) &&
5333*fe013be4SDimitry Andric       (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) &&
5334*fe013be4SDimitry Andric       !isa<FunctionNoProtoType>(PointeeType)) {
53350b57cec5SDimitry Andric     if (llvm::Constant *PrefixSig =
53360b57cec5SDimitry Andric             CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
53370b57cec5SDimitry Andric       SanitizerScope SanScope(this);
5338*fe013be4SDimitry Andric       auto *TypeHash = getUBSanFunctionTypeHash(PointeeType);
5339*fe013be4SDimitry Andric 
5340fe6060f1SDimitry Andric       llvm::Type *PrefixSigType = PrefixSig->getType();
53410b57cec5SDimitry Andric       llvm::StructType *PrefixStructTy = llvm::StructType::get(
5342fe6060f1SDimitry Andric           CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
53430b57cec5SDimitry Andric 
53440b57cec5SDimitry Andric       llvm::Value *CalleePtr = Callee.getFunctionPointer();
53450b57cec5SDimitry Andric 
5346*fe013be4SDimitry Andric       // On 32-bit Arm, the low bit of a function pointer indicates whether
5347*fe013be4SDimitry Andric       // it's using the Arm or Thumb instruction set. The actual first
5348*fe013be4SDimitry Andric       // instruction lives at the same address either way, so we must clear
5349*fe013be4SDimitry Andric       // that low bit before using the function address to find the prefix
5350*fe013be4SDimitry Andric       // structure.
5351*fe013be4SDimitry Andric       //
5352*fe013be4SDimitry Andric       // This applies to both Arm and Thumb target triples, because
5353*fe013be4SDimitry Andric       // either one could be used in an interworking context where it
5354*fe013be4SDimitry Andric       // might be passed function pointers of both types.
5355*fe013be4SDimitry Andric       llvm::Value *AlignedCalleePtr;
5356*fe013be4SDimitry Andric       if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) {
5357*fe013be4SDimitry Andric         llvm::Value *CalleeAddress =
5358*fe013be4SDimitry Andric             Builder.CreatePtrToInt(CalleePtr, IntPtrTy);
5359*fe013be4SDimitry Andric         llvm::Value *Mask = llvm::ConstantInt::get(IntPtrTy, ~1);
5360*fe013be4SDimitry Andric         llvm::Value *AlignedCalleeAddress =
5361*fe013be4SDimitry Andric             Builder.CreateAnd(CalleeAddress, Mask);
5362*fe013be4SDimitry Andric         AlignedCalleePtr =
5363*fe013be4SDimitry Andric             Builder.CreateIntToPtr(AlignedCalleeAddress, CalleePtr->getType());
5364*fe013be4SDimitry Andric       } else {
5365*fe013be4SDimitry Andric         AlignedCalleePtr = CalleePtr;
5366*fe013be4SDimitry Andric       }
5367*fe013be4SDimitry Andric 
53680b57cec5SDimitry Andric       llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
5369*fe013be4SDimitry Andric           AlignedCalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
53700b57cec5SDimitry Andric       llvm::Value *CalleeSigPtr =
5371*fe013be4SDimitry Andric           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
53720b57cec5SDimitry Andric       llvm::Value *CalleeSig =
5373fe6060f1SDimitry Andric           Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
53740b57cec5SDimitry Andric       llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
53750b57cec5SDimitry Andric 
53760b57cec5SDimitry Andric       llvm::BasicBlock *Cont = createBasicBlock("cont");
53770b57cec5SDimitry Andric       llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
53780b57cec5SDimitry Andric       Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
53790b57cec5SDimitry Andric 
53800b57cec5SDimitry Andric       EmitBlock(TypeCheck);
5381*fe013be4SDimitry Andric       llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad(
5382*fe013be4SDimitry Andric           Int32Ty,
5383*fe013be4SDimitry Andric           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
5384*fe013be4SDimitry Andric           getPointerAlign());
5385*fe013be4SDimitry Andric       llvm::Value *CalleeTypeHashMatch =
5386*fe013be4SDimitry Andric           Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
53870b57cec5SDimitry Andric       llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
53880b57cec5SDimitry Andric                                       EmitCheckTypeDescriptor(CalleeType)};
5389*fe013be4SDimitry Andric       EmitCheck(std::make_pair(CalleeTypeHashMatch, SanitizerKind::Function),
53900b57cec5SDimitry Andric                 SanitizerHandler::FunctionTypeMismatch, StaticData,
5391*fe013be4SDimitry Andric                 {CalleePtr});
53920b57cec5SDimitry Andric 
53930b57cec5SDimitry Andric       Builder.CreateBr(Cont);
53940b57cec5SDimitry Andric       EmitBlock(Cont);
53950b57cec5SDimitry Andric     }
53960b57cec5SDimitry Andric   }
53970b57cec5SDimitry Andric 
53980b57cec5SDimitry Andric   const auto *FnType = cast<FunctionType>(PointeeType);
53990b57cec5SDimitry Andric 
54000b57cec5SDimitry Andric   // If we are checking indirect calls and this call is indirect, check that the
54010b57cec5SDimitry Andric   // function pointer is a member of the bit set for the function type.
54020b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::CFIICall) &&
54030b57cec5SDimitry Andric       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
54040b57cec5SDimitry Andric     SanitizerScope SanScope(this);
54050b57cec5SDimitry Andric     EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
54060b57cec5SDimitry Andric 
54070b57cec5SDimitry Andric     llvm::Metadata *MD;
54080b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
54090b57cec5SDimitry Andric       MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
54100b57cec5SDimitry Andric     else
54110b57cec5SDimitry Andric       MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
54120b57cec5SDimitry Andric 
54130b57cec5SDimitry Andric     llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
54140b57cec5SDimitry Andric 
54150b57cec5SDimitry Andric     llvm::Value *CalleePtr = Callee.getFunctionPointer();
54160b57cec5SDimitry Andric     llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
54170b57cec5SDimitry Andric     llvm::Value *TypeTest = Builder.CreateCall(
54180b57cec5SDimitry Andric         CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
54190b57cec5SDimitry Andric 
54200b57cec5SDimitry Andric     auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
54210b57cec5SDimitry Andric     llvm::Constant *StaticData[] = {
54220b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
54230b57cec5SDimitry Andric         EmitCheckSourceLocation(E->getBeginLoc()),
54240b57cec5SDimitry Andric         EmitCheckTypeDescriptor(QualType(FnType, 0)),
54250b57cec5SDimitry Andric     };
54260b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
54270b57cec5SDimitry Andric       EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
54280b57cec5SDimitry Andric                            CastedCallee, StaticData);
54290b57cec5SDimitry Andric     } else {
54300b57cec5SDimitry Andric       EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
54310b57cec5SDimitry Andric                 SanitizerHandler::CFICheckFail, StaticData,
54320b57cec5SDimitry Andric                 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
54330b57cec5SDimitry Andric     }
54340b57cec5SDimitry Andric   }
54350b57cec5SDimitry Andric 
54360b57cec5SDimitry Andric   CallArgList Args;
54370b57cec5SDimitry Andric   if (Chain)
54380b57cec5SDimitry Andric     Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
54390b57cec5SDimitry Andric              CGM.getContext().VoidPtrTy);
54400b57cec5SDimitry Andric 
54410b57cec5SDimitry Andric   // C++17 requires that we evaluate arguments to a call using assignment syntax
54420b57cec5SDimitry Andric   // right-to-left, and that we evaluate arguments to certain other operators
54430b57cec5SDimitry Andric   // left-to-right. Note that we allow this to override the order dictated by
54440b57cec5SDimitry Andric   // the calling convention on the MS ABI, which means that parameter
54450b57cec5SDimitry Andric   // destruction order is not necessarily reverse construction order.
54460b57cec5SDimitry Andric   // FIXME: Revisit this based on C++ committee response to unimplementability.
54470b57cec5SDimitry Andric   EvaluationOrder Order = EvaluationOrder::Default;
54480b57cec5SDimitry Andric   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
54490b57cec5SDimitry Andric     if (OCE->isAssignmentOp())
54500b57cec5SDimitry Andric       Order = EvaluationOrder::ForceRightToLeft;
54510b57cec5SDimitry Andric     else {
54520b57cec5SDimitry Andric       switch (OCE->getOperator()) {
54530b57cec5SDimitry Andric       case OO_LessLess:
54540b57cec5SDimitry Andric       case OO_GreaterGreater:
54550b57cec5SDimitry Andric       case OO_AmpAmp:
54560b57cec5SDimitry Andric       case OO_PipePipe:
54570b57cec5SDimitry Andric       case OO_Comma:
54580b57cec5SDimitry Andric       case OO_ArrowStar:
54590b57cec5SDimitry Andric         Order = EvaluationOrder::ForceLeftToRight;
54600b57cec5SDimitry Andric         break;
54610b57cec5SDimitry Andric       default:
54620b57cec5SDimitry Andric         break;
54630b57cec5SDimitry Andric       }
54640b57cec5SDimitry Andric     }
54650b57cec5SDimitry Andric   }
54660b57cec5SDimitry Andric 
54670b57cec5SDimitry Andric   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
54680b57cec5SDimitry Andric                E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
54690b57cec5SDimitry Andric 
54700b57cec5SDimitry Andric   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
54710b57cec5SDimitry Andric       Args, FnType, /*ChainCall=*/Chain);
54720b57cec5SDimitry Andric 
54730b57cec5SDimitry Andric   // C99 6.5.2.2p6:
54740b57cec5SDimitry Andric   //   If the expression that denotes the called function has a type
54750b57cec5SDimitry Andric   //   that does not include a prototype, [the default argument
54760b57cec5SDimitry Andric   //   promotions are performed]. If the number of arguments does not
54770b57cec5SDimitry Andric   //   equal the number of parameters, the behavior is undefined. If
54780b57cec5SDimitry Andric   //   the function is defined with a type that includes a prototype,
54790b57cec5SDimitry Andric   //   and either the prototype ends with an ellipsis (, ...) or the
54800b57cec5SDimitry Andric   //   types of the arguments after promotion are not compatible with
54810b57cec5SDimitry Andric   //   the types of the parameters, the behavior is undefined. If the
54820b57cec5SDimitry Andric   //   function is defined with a type that does not include a
54830b57cec5SDimitry Andric   //   prototype, and the types of the arguments after promotion are
54840b57cec5SDimitry Andric   //   not compatible with those of the parameters after promotion,
54850b57cec5SDimitry Andric   //   the behavior is undefined [except in some trivial cases].
54860b57cec5SDimitry Andric   // That is, in the general case, we should assume that a call
54870b57cec5SDimitry Andric   // through an unprototyped function type works like a *non-variadic*
54880b57cec5SDimitry Andric   // call.  The way we make this work is to cast to the exact type
54890b57cec5SDimitry Andric   // of the promoted arguments.
54900b57cec5SDimitry Andric   //
54910b57cec5SDimitry Andric   // Chain calls use this same code path to add the invisible chain parameter
54920b57cec5SDimitry Andric   // to the function type.
54930b57cec5SDimitry Andric   if (isa<FunctionNoProtoType>(FnType) || Chain) {
54940b57cec5SDimitry Andric     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
54955ffd83dbSDimitry Andric     int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
54965ffd83dbSDimitry Andric     CalleeTy = CalleeTy->getPointerTo(AS);
54970b57cec5SDimitry Andric 
54980b57cec5SDimitry Andric     llvm::Value *CalleePtr = Callee.getFunctionPointer();
54990b57cec5SDimitry Andric     CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
55000b57cec5SDimitry Andric     Callee.setFunctionPointer(CalleePtr);
55010b57cec5SDimitry Andric   }
55020b57cec5SDimitry Andric 
5503fe6060f1SDimitry Andric   // HIP function pointer contains kernel handle when it is used in triple
5504fe6060f1SDimitry Andric   // chevron. The kernel stub needs to be loaded from kernel handle and used
5505fe6060f1SDimitry Andric   // as callee.
5506fe6060f1SDimitry Andric   if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
5507fe6060f1SDimitry Andric       isa<CUDAKernelCallExpr>(E) &&
5508fe6060f1SDimitry Andric       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5509fe6060f1SDimitry Andric     llvm::Value *Handle = Callee.getFunctionPointer();
5510fe6060f1SDimitry Andric     auto *Cast =
5511fe6060f1SDimitry Andric         Builder.CreateBitCast(Handle, Handle->getType()->getPointerTo());
551281ad6265SDimitry Andric     auto *Stub = Builder.CreateLoad(
551381ad6265SDimitry Andric         Address(Cast, Handle->getType(), CGM.getPointerAlign()));
5514fe6060f1SDimitry Andric     Callee.setFunctionPointer(Stub);
5515fe6060f1SDimitry Andric   }
55160b57cec5SDimitry Andric   llvm::CallBase *CallOrInvoke = nullptr;
55170b57cec5SDimitry Andric   RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
5518fe6060f1SDimitry Andric                          E == MustTailCall, E->getExprLoc());
55190b57cec5SDimitry Andric 
55200b57cec5SDimitry Andric   // Generate function declaration DISuprogram in order to be used
55210b57cec5SDimitry Andric   // in debug info about call sites.
55220b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
5523349cc55cSDimitry Andric     if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5524349cc55cSDimitry Andric       FunctionArgList Args;
5525349cc55cSDimitry Andric       QualType ResTy = BuildFunctionArgList(CalleeDecl, Args);
5526349cc55cSDimitry Andric       DI->EmitFuncDeclForCallSite(CallOrInvoke,
5527349cc55cSDimitry Andric                                   DI->getFunctionType(CalleeDecl, ResTy, Args),
55280b57cec5SDimitry Andric                                   CalleeDecl);
55290b57cec5SDimitry Andric     }
5530349cc55cSDimitry Andric   }
55310b57cec5SDimitry Andric 
55320b57cec5SDimitry Andric   return Call;
55330b57cec5SDimitry Andric }
55340b57cec5SDimitry Andric 
55350b57cec5SDimitry Andric LValue CodeGenFunction::
55360b57cec5SDimitry Andric EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
55370b57cec5SDimitry Andric   Address BaseAddr = Address::invalid();
55380b57cec5SDimitry Andric   if (E->getOpcode() == BO_PtrMemI) {
55390b57cec5SDimitry Andric     BaseAddr = EmitPointerWithAlignment(E->getLHS());
55400b57cec5SDimitry Andric   } else {
5541480093f4SDimitry Andric     BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
55420b57cec5SDimitry Andric   }
55430b57cec5SDimitry Andric 
55440b57cec5SDimitry Andric   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
5545480093f4SDimitry Andric   const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
55460b57cec5SDimitry Andric 
55470b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
55480b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
55490b57cec5SDimitry Andric   Address MemberAddr =
55500b57cec5SDimitry Andric     EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
55510b57cec5SDimitry Andric                                     &TBAAInfo);
55520b57cec5SDimitry Andric 
55530b57cec5SDimitry Andric   return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
55540b57cec5SDimitry Andric }
55550b57cec5SDimitry Andric 
55560b57cec5SDimitry Andric /// Given the address of a temporary variable, produce an r-value of
55570b57cec5SDimitry Andric /// its type.
55580b57cec5SDimitry Andric RValue CodeGenFunction::convertTempToRValue(Address addr,
55590b57cec5SDimitry Andric                                             QualType type,
55600b57cec5SDimitry Andric                                             SourceLocation loc) {
55610b57cec5SDimitry Andric   LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
55620b57cec5SDimitry Andric   switch (getEvaluationKind(type)) {
55630b57cec5SDimitry Andric   case TEK_Complex:
55640b57cec5SDimitry Andric     return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
55650b57cec5SDimitry Andric   case TEK_Aggregate:
5566480093f4SDimitry Andric     return lvalue.asAggregateRValue(*this);
55670b57cec5SDimitry Andric   case TEK_Scalar:
55680b57cec5SDimitry Andric     return RValue::get(EmitLoadOfScalar(lvalue, loc));
55690b57cec5SDimitry Andric   }
55700b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
55710b57cec5SDimitry Andric }
55720b57cec5SDimitry Andric 
55730b57cec5SDimitry Andric void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
55740b57cec5SDimitry Andric   assert(Val->getType()->isFPOrFPVectorTy());
55750b57cec5SDimitry Andric   if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
55760b57cec5SDimitry Andric     return;
55770b57cec5SDimitry Andric 
55780b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
55790b57cec5SDimitry Andric   llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
55800b57cec5SDimitry Andric 
55810b57cec5SDimitry Andric   cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
55820b57cec5SDimitry Andric }
55830b57cec5SDimitry Andric 
5584*fe013be4SDimitry Andric void CodeGenFunction::SetSqrtFPAccuracy(llvm::Value *Val) {
5585*fe013be4SDimitry Andric   llvm::Type *EltTy = Val->getType()->getScalarType();
5586*fe013be4SDimitry Andric   if (!EltTy->isFloatTy())
5587*fe013be4SDimitry Andric     return;
5588*fe013be4SDimitry Andric 
5589*fe013be4SDimitry Andric   if ((getLangOpts().OpenCL &&
5590*fe013be4SDimitry Andric        !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
5591*fe013be4SDimitry Andric       (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
5592*fe013be4SDimitry Andric        !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
5593*fe013be4SDimitry Andric     // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 3ulp
5594*fe013be4SDimitry Andric     //
5595*fe013be4SDimitry Andric     // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
5596*fe013be4SDimitry Andric     // build option allows an application to specify that single precision
5597*fe013be4SDimitry Andric     // floating-point divide (x/y and 1/x) and sqrt used in the program
5598*fe013be4SDimitry Andric     // source are correctly rounded.
5599*fe013be4SDimitry Andric     //
5600*fe013be4SDimitry Andric     // TODO: CUDA has a prec-sqrt flag
5601*fe013be4SDimitry Andric     SetFPAccuracy(Val, 3.0f);
5602*fe013be4SDimitry Andric   }
5603*fe013be4SDimitry Andric }
5604*fe013be4SDimitry Andric 
5605*fe013be4SDimitry Andric void CodeGenFunction::SetDivFPAccuracy(llvm::Value *Val) {
5606*fe013be4SDimitry Andric   llvm::Type *EltTy = Val->getType()->getScalarType();
5607*fe013be4SDimitry Andric   if (!EltTy->isFloatTy())
5608*fe013be4SDimitry Andric     return;
5609*fe013be4SDimitry Andric 
5610*fe013be4SDimitry Andric   if ((getLangOpts().OpenCL &&
5611*fe013be4SDimitry Andric        !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
5612*fe013be4SDimitry Andric       (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
5613*fe013be4SDimitry Andric        !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
5614*fe013be4SDimitry Andric     // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
5615*fe013be4SDimitry Andric     //
5616*fe013be4SDimitry Andric     // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
5617*fe013be4SDimitry Andric     // build option allows an application to specify that single precision
5618*fe013be4SDimitry Andric     // floating-point divide (x/y and 1/x) and sqrt used in the program
5619*fe013be4SDimitry Andric     // source are correctly rounded.
5620*fe013be4SDimitry Andric     //
5621*fe013be4SDimitry Andric     // TODO: CUDA has a prec-div flag
5622*fe013be4SDimitry Andric     SetFPAccuracy(Val, 2.5f);
5623*fe013be4SDimitry Andric   }
5624*fe013be4SDimitry Andric }
5625*fe013be4SDimitry Andric 
56260b57cec5SDimitry Andric namespace {
56270b57cec5SDimitry Andric   struct LValueOrRValue {
56280b57cec5SDimitry Andric     LValue LV;
56290b57cec5SDimitry Andric     RValue RV;
56300b57cec5SDimitry Andric   };
56310b57cec5SDimitry Andric }
56320b57cec5SDimitry Andric 
56330b57cec5SDimitry Andric static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
56340b57cec5SDimitry Andric                                            const PseudoObjectExpr *E,
56350b57cec5SDimitry Andric                                            bool forLValue,
56360b57cec5SDimitry Andric                                            AggValueSlot slot) {
56370b57cec5SDimitry Andric   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
56380b57cec5SDimitry Andric 
56390b57cec5SDimitry Andric   // Find the result expression, if any.
56400b57cec5SDimitry Andric   const Expr *resultExpr = E->getResultExpr();
56410b57cec5SDimitry Andric   LValueOrRValue result;
56420b57cec5SDimitry Andric 
56430b57cec5SDimitry Andric   for (PseudoObjectExpr::const_semantics_iterator
56440b57cec5SDimitry Andric          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
56450b57cec5SDimitry Andric     const Expr *semantic = *i;
56460b57cec5SDimitry Andric 
56470b57cec5SDimitry Andric     // If this semantic expression is an opaque value, bind it
56480b57cec5SDimitry Andric     // to the result of its source expression.
56490b57cec5SDimitry Andric     if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
56500b57cec5SDimitry Andric       // Skip unique OVEs.
56510b57cec5SDimitry Andric       if (ov->isUnique()) {
56520b57cec5SDimitry Andric         assert(ov != resultExpr &&
56530b57cec5SDimitry Andric                "A unique OVE cannot be used as the result expression");
56540b57cec5SDimitry Andric         continue;
56550b57cec5SDimitry Andric       }
56560b57cec5SDimitry Andric 
56570b57cec5SDimitry Andric       // If this is the result expression, we may need to evaluate
56580b57cec5SDimitry Andric       // directly into the slot.
56590b57cec5SDimitry Andric       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
56600b57cec5SDimitry Andric       OVMA opaqueData;
5661fe6060f1SDimitry Andric       if (ov == resultExpr && ov->isPRValue() && !forLValue &&
56620b57cec5SDimitry Andric           CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
56630b57cec5SDimitry Andric         CGF.EmitAggExpr(ov->getSourceExpr(), slot);
56640b57cec5SDimitry Andric         LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
56650b57cec5SDimitry Andric                                        AlignmentSource::Decl);
56660b57cec5SDimitry Andric         opaqueData = OVMA::bind(CGF, ov, LV);
56670b57cec5SDimitry Andric         result.RV = slot.asRValue();
56680b57cec5SDimitry Andric 
56690b57cec5SDimitry Andric       // Otherwise, emit as normal.
56700b57cec5SDimitry Andric       } else {
56710b57cec5SDimitry Andric         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
56720b57cec5SDimitry Andric 
56730b57cec5SDimitry Andric         // If this is the result, also evaluate the result now.
56740b57cec5SDimitry Andric         if (ov == resultExpr) {
56750b57cec5SDimitry Andric           if (forLValue)
56760b57cec5SDimitry Andric             result.LV = CGF.EmitLValue(ov);
56770b57cec5SDimitry Andric           else
56780b57cec5SDimitry Andric             result.RV = CGF.EmitAnyExpr(ov, slot);
56790b57cec5SDimitry Andric         }
56800b57cec5SDimitry Andric       }
56810b57cec5SDimitry Andric 
56820b57cec5SDimitry Andric       opaques.push_back(opaqueData);
56830b57cec5SDimitry Andric 
56840b57cec5SDimitry Andric     // Otherwise, if the expression is the result, evaluate it
56850b57cec5SDimitry Andric     // and remember the result.
56860b57cec5SDimitry Andric     } else if (semantic == resultExpr) {
56870b57cec5SDimitry Andric       if (forLValue)
56880b57cec5SDimitry Andric         result.LV = CGF.EmitLValue(semantic);
56890b57cec5SDimitry Andric       else
56900b57cec5SDimitry Andric         result.RV = CGF.EmitAnyExpr(semantic, slot);
56910b57cec5SDimitry Andric 
56920b57cec5SDimitry Andric     // Otherwise, evaluate the expression in an ignored context.
56930b57cec5SDimitry Andric     } else {
56940b57cec5SDimitry Andric       CGF.EmitIgnoredExpr(semantic);
56950b57cec5SDimitry Andric     }
56960b57cec5SDimitry Andric   }
56970b57cec5SDimitry Andric 
56980b57cec5SDimitry Andric   // Unbind all the opaques now.
56990b57cec5SDimitry Andric   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
57000b57cec5SDimitry Andric     opaques[i].unbind(CGF);
57010b57cec5SDimitry Andric 
57020b57cec5SDimitry Andric   return result;
57030b57cec5SDimitry Andric }
57040b57cec5SDimitry Andric 
57050b57cec5SDimitry Andric RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
57060b57cec5SDimitry Andric                                                AggValueSlot slot) {
57070b57cec5SDimitry Andric   return emitPseudoObjectExpr(*this, E, false, slot).RV;
57080b57cec5SDimitry Andric }
57090b57cec5SDimitry Andric 
57100b57cec5SDimitry Andric LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
57110b57cec5SDimitry Andric   return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
57120b57cec5SDimitry Andric }
5713