1*0b57cec5SDimitry Andric //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This contains code to emit Expr nodes as LLVM code.
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "CGCXXABI.h"
14*0b57cec5SDimitry Andric #include "CGCall.h"
15*0b57cec5SDimitry Andric #include "CGCleanup.h"
16*0b57cec5SDimitry Andric #include "CGDebugInfo.h"
17*0b57cec5SDimitry Andric #include "CGObjCRuntime.h"
18*0b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
19*0b57cec5SDimitry Andric #include "CGRecordLayout.h"
20*0b57cec5SDimitry Andric #include "CodeGenFunction.h"
21*0b57cec5SDimitry Andric #include "CodeGenModule.h"
22*0b57cec5SDimitry Andric #include "ConstantEmitter.h"
23*0b57cec5SDimitry Andric #include "TargetInfo.h"
24*0b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
25*0b57cec5SDimitry Andric #include "clang/AST/Attr.h"
26*0b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
27*0b57cec5SDimitry Andric #include "clang/AST/NSAPI.h"
28*0b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
29*0b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
305ffd83dbSDimitry Andric #include "clang/Basic/SourceManager.h"
31*0b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
32*0b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
34*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
35*0b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
37*0b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
38*0b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
39*0b57cec5SDimitry Andric #include "llvm/Support/Path.h"
40*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SanitizerStats.h"
41*0b57cec5SDimitry Andric 
42*0b57cec5SDimitry Andric #include <string>
43*0b57cec5SDimitry Andric 
44*0b57cec5SDimitry Andric using namespace clang;
45*0b57cec5SDimitry Andric using namespace CodeGen;
46*0b57cec5SDimitry Andric 
47*0b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
48*0b57cec5SDimitry Andric //                        Miscellaneous Helper Methods
49*0b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
50*0b57cec5SDimitry Andric 
51*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
52*0b57cec5SDimitry Andric   unsigned addressSpace =
53*0b57cec5SDimitry Andric       cast<llvm::PointerType>(value->getType())->getAddressSpace();
54*0b57cec5SDimitry Andric 
55*0b57cec5SDimitry Andric   llvm::PointerType *destType = Int8PtrTy;
56*0b57cec5SDimitry Andric   if (addressSpace)
57*0b57cec5SDimitry Andric     destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
58*0b57cec5SDimitry Andric 
59*0b57cec5SDimitry Andric   if (value->getType() == destType) return value;
60*0b57cec5SDimitry Andric   return Builder.CreateBitCast(value, destType);
61*0b57cec5SDimitry Andric }
62*0b57cec5SDimitry Andric 
63*0b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry
64*0b57cec5SDimitry Andric /// block.
65*0b57cec5SDimitry Andric Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
66*0b57cec5SDimitry Andric                                                      CharUnits Align,
67*0b57cec5SDimitry Andric                                                      const Twine &Name,
68*0b57cec5SDimitry Andric                                                      llvm::Value *ArraySize) {
69*0b57cec5SDimitry Andric   auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
70a7dea167SDimitry Andric   Alloca->setAlignment(Align.getAsAlign());
71*0b57cec5SDimitry Andric   return Address(Alloca, Align);
72*0b57cec5SDimitry Andric }
73*0b57cec5SDimitry Andric 
74*0b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry
75*0b57cec5SDimitry Andric /// block. The alloca is casted to default address space if necessary.
76*0b57cec5SDimitry Andric Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
77*0b57cec5SDimitry Andric                                           const Twine &Name,
78*0b57cec5SDimitry Andric                                           llvm::Value *ArraySize,
79*0b57cec5SDimitry Andric                                           Address *AllocaAddr) {
80*0b57cec5SDimitry Andric   auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
81*0b57cec5SDimitry Andric   if (AllocaAddr)
82*0b57cec5SDimitry Andric     *AllocaAddr = Alloca;
83*0b57cec5SDimitry Andric   llvm::Value *V = Alloca.getPointer();
84*0b57cec5SDimitry Andric   // Alloca always returns a pointer in alloca address space, which may
85*0b57cec5SDimitry Andric   // be different from the type defined by the language. For example,
86*0b57cec5SDimitry Andric   // in C++ the auto variables are in the default address space. Therefore
87*0b57cec5SDimitry Andric   // cast alloca to the default address space when necessary.
88*0b57cec5SDimitry Andric   if (getASTAllocaAddressSpace() != LangAS::Default) {
89*0b57cec5SDimitry Andric     auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
90*0b57cec5SDimitry Andric     llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
91*0b57cec5SDimitry Andric     // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
92*0b57cec5SDimitry Andric     // otherwise alloca is inserted at the current insertion point of the
93*0b57cec5SDimitry Andric     // builder.
94*0b57cec5SDimitry Andric     if (!ArraySize)
95*0b57cec5SDimitry Andric       Builder.SetInsertPoint(AllocaInsertPt);
96*0b57cec5SDimitry Andric     V = getTargetHooks().performAddrSpaceCast(
97*0b57cec5SDimitry Andric         *this, V, getASTAllocaAddressSpace(), LangAS::Default,
98*0b57cec5SDimitry Andric         Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
99*0b57cec5SDimitry Andric   }
100*0b57cec5SDimitry Andric 
101*0b57cec5SDimitry Andric   return Address(V, Align);
102*0b57cec5SDimitry Andric }
103*0b57cec5SDimitry Andric 
104*0b57cec5SDimitry Andric /// CreateTempAlloca - This creates an alloca and inserts it into the entry
105*0b57cec5SDimitry Andric /// block if \p ArraySize is nullptr, otherwise inserts it at the current
106*0b57cec5SDimitry Andric /// insertion point of the builder.
107*0b57cec5SDimitry Andric llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
108*0b57cec5SDimitry Andric                                                     const Twine &Name,
109*0b57cec5SDimitry Andric                                                     llvm::Value *ArraySize) {
110*0b57cec5SDimitry Andric   if (ArraySize)
111*0b57cec5SDimitry Andric     return Builder.CreateAlloca(Ty, ArraySize, Name);
112*0b57cec5SDimitry Andric   return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
113*0b57cec5SDimitry Andric                               ArraySize, Name, AllocaInsertPt);
114*0b57cec5SDimitry Andric }
115*0b57cec5SDimitry Andric 
116*0b57cec5SDimitry Andric /// CreateDefaultAlignTempAlloca - This creates an alloca with the
117*0b57cec5SDimitry Andric /// default alignment of the corresponding LLVM type, which is *not*
118*0b57cec5SDimitry Andric /// guaranteed to be related in any way to the expected alignment of
119*0b57cec5SDimitry Andric /// an AST type that might have been lowered to Ty.
120*0b57cec5SDimitry Andric Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
121*0b57cec5SDimitry Andric                                                       const Twine &Name) {
122*0b57cec5SDimitry Andric   CharUnits Align =
123*0b57cec5SDimitry Andric     CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
124*0b57cec5SDimitry Andric   return CreateTempAlloca(Ty, Align, Name);
125*0b57cec5SDimitry Andric }
126*0b57cec5SDimitry Andric 
127*0b57cec5SDimitry Andric void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
128*0b57cec5SDimitry Andric   assert(isa<llvm::AllocaInst>(Var.getPointer()));
1295ffd83dbSDimitry Andric   auto *Store = new llvm::StoreInst(Init, Var.getPointer(), /*volatile*/ false,
1305ffd83dbSDimitry Andric                                     Var.getAlignment().getAsAlign());
131*0b57cec5SDimitry Andric   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
132*0b57cec5SDimitry Andric   Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
133*0b57cec5SDimitry Andric }
134*0b57cec5SDimitry Andric 
135*0b57cec5SDimitry Andric Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
136*0b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(Ty);
137*0b57cec5SDimitry Andric   return CreateTempAlloca(ConvertType(Ty), Align, Name);
138*0b57cec5SDimitry Andric }
139*0b57cec5SDimitry Andric 
140*0b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
141*0b57cec5SDimitry Andric                                        Address *Alloca) {
142*0b57cec5SDimitry Andric   // FIXME: Should we prefer the preferred type alignment here?
143*0b57cec5SDimitry Andric   return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
144*0b57cec5SDimitry Andric }
145*0b57cec5SDimitry Andric 
146*0b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
147*0b57cec5SDimitry Andric                                        const Twine &Name, Address *Alloca) {
1485ffd83dbSDimitry Andric   Address Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
149*0b57cec5SDimitry Andric                                     /*ArraySize=*/nullptr, Alloca);
1505ffd83dbSDimitry Andric 
1515ffd83dbSDimitry Andric   if (Ty->isConstantMatrixType()) {
1525ffd83dbSDimitry Andric     auto *ArrayTy = cast<llvm::ArrayType>(Result.getType()->getElementType());
1535ffd83dbSDimitry Andric     auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
1545ffd83dbSDimitry Andric                                                 ArrayTy->getNumElements());
1555ffd83dbSDimitry Andric 
1565ffd83dbSDimitry Andric     Result = Address(
1575ffd83dbSDimitry Andric         Builder.CreateBitCast(Result.getPointer(), VectorTy->getPointerTo()),
1585ffd83dbSDimitry Andric         Result.getAlignment());
1595ffd83dbSDimitry Andric   }
1605ffd83dbSDimitry Andric   return Result;
161*0b57cec5SDimitry Andric }
162*0b57cec5SDimitry Andric 
163*0b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
164*0b57cec5SDimitry Andric                                                   const Twine &Name) {
165*0b57cec5SDimitry Andric   return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
166*0b57cec5SDimitry Andric }
167*0b57cec5SDimitry Andric 
168*0b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
169*0b57cec5SDimitry Andric                                                   const Twine &Name) {
170*0b57cec5SDimitry Andric   return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
171*0b57cec5SDimitry Andric                                   Name);
172*0b57cec5SDimitry Andric }
173*0b57cec5SDimitry Andric 
174*0b57cec5SDimitry Andric /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
175*0b57cec5SDimitry Andric /// expression and compare the result against zero, returning an Int1Ty value.
176*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
177*0b57cec5SDimitry Andric   PGO.setCurrentStmt(E);
178*0b57cec5SDimitry Andric   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
179*0b57cec5SDimitry Andric     llvm::Value *MemPtr = EmitScalarExpr(E);
180*0b57cec5SDimitry Andric     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
181*0b57cec5SDimitry Andric   }
182*0b57cec5SDimitry Andric 
183*0b57cec5SDimitry Andric   QualType BoolTy = getContext().BoolTy;
184*0b57cec5SDimitry Andric   SourceLocation Loc = E->getExprLoc();
185*0b57cec5SDimitry Andric   if (!E->getType()->isAnyComplexType())
186*0b57cec5SDimitry Andric     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
187*0b57cec5SDimitry Andric 
188*0b57cec5SDimitry Andric   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
189*0b57cec5SDimitry Andric                                        Loc);
190*0b57cec5SDimitry Andric }
191*0b57cec5SDimitry Andric 
192*0b57cec5SDimitry Andric /// EmitIgnoredExpr - Emit code to compute the specified expression,
193*0b57cec5SDimitry Andric /// ignoring the result.
194*0b57cec5SDimitry Andric void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
195*0b57cec5SDimitry Andric   if (E->isRValue())
196*0b57cec5SDimitry Andric     return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
197*0b57cec5SDimitry Andric 
198*0b57cec5SDimitry Andric   // Just emit it as an l-value and drop the result.
199*0b57cec5SDimitry Andric   EmitLValue(E);
200*0b57cec5SDimitry Andric }
201*0b57cec5SDimitry Andric 
202*0b57cec5SDimitry Andric /// EmitAnyExpr - Emit code to compute the specified expression which
203*0b57cec5SDimitry Andric /// can have any type.  The result is returned as an RValue struct.
204*0b57cec5SDimitry Andric /// If this is an aggregate expression, AggSlot indicates where the
205*0b57cec5SDimitry Andric /// result should be returned.
206*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
207*0b57cec5SDimitry Andric                                     AggValueSlot aggSlot,
208*0b57cec5SDimitry Andric                                     bool ignoreResult) {
209*0b57cec5SDimitry Andric   switch (getEvaluationKind(E->getType())) {
210*0b57cec5SDimitry Andric   case TEK_Scalar:
211*0b57cec5SDimitry Andric     return RValue::get(EmitScalarExpr(E, ignoreResult));
212*0b57cec5SDimitry Andric   case TEK_Complex:
213*0b57cec5SDimitry Andric     return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
214*0b57cec5SDimitry Andric   case TEK_Aggregate:
215*0b57cec5SDimitry Andric     if (!ignoreResult && aggSlot.isIgnored())
216*0b57cec5SDimitry Andric       aggSlot = CreateAggTemp(E->getType(), "agg-temp");
217*0b57cec5SDimitry Andric     EmitAggExpr(E, aggSlot);
218*0b57cec5SDimitry Andric     return aggSlot.asRValue();
219*0b57cec5SDimitry Andric   }
220*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
221*0b57cec5SDimitry Andric }
222*0b57cec5SDimitry Andric 
223*0b57cec5SDimitry Andric /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
224*0b57cec5SDimitry Andric /// always be accessible even if no aggregate location is provided.
225*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
226*0b57cec5SDimitry Andric   AggValueSlot AggSlot = AggValueSlot::ignored();
227*0b57cec5SDimitry Andric 
228*0b57cec5SDimitry Andric   if (hasAggregateEvaluationKind(E->getType()))
229*0b57cec5SDimitry Andric     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
230*0b57cec5SDimitry Andric   return EmitAnyExpr(E, AggSlot);
231*0b57cec5SDimitry Andric }
232*0b57cec5SDimitry Andric 
233*0b57cec5SDimitry Andric /// EmitAnyExprToMem - Evaluate an expression into a given memory
234*0b57cec5SDimitry Andric /// location.
235*0b57cec5SDimitry Andric void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
236*0b57cec5SDimitry Andric                                        Address Location,
237*0b57cec5SDimitry Andric                                        Qualifiers Quals,
238*0b57cec5SDimitry Andric                                        bool IsInit) {
239*0b57cec5SDimitry Andric   // FIXME: This function should take an LValue as an argument.
240*0b57cec5SDimitry Andric   switch (getEvaluationKind(E->getType())) {
241*0b57cec5SDimitry Andric   case TEK_Complex:
242*0b57cec5SDimitry Andric     EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
243*0b57cec5SDimitry Andric                               /*isInit*/ false);
244*0b57cec5SDimitry Andric     return;
245*0b57cec5SDimitry Andric 
246*0b57cec5SDimitry Andric   case TEK_Aggregate: {
247*0b57cec5SDimitry Andric     EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
248*0b57cec5SDimitry Andric                                          AggValueSlot::IsDestructed_t(IsInit),
249*0b57cec5SDimitry Andric                                          AggValueSlot::DoesNotNeedGCBarriers,
250*0b57cec5SDimitry Andric                                          AggValueSlot::IsAliased_t(!IsInit),
251*0b57cec5SDimitry Andric                                          AggValueSlot::MayOverlap));
252*0b57cec5SDimitry Andric     return;
253*0b57cec5SDimitry Andric   }
254*0b57cec5SDimitry Andric 
255*0b57cec5SDimitry Andric   case TEK_Scalar: {
256*0b57cec5SDimitry Andric     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
257*0b57cec5SDimitry Andric     LValue LV = MakeAddrLValue(Location, E->getType());
258*0b57cec5SDimitry Andric     EmitStoreThroughLValue(RV, LV);
259*0b57cec5SDimitry Andric     return;
260*0b57cec5SDimitry Andric   }
261*0b57cec5SDimitry Andric   }
262*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
263*0b57cec5SDimitry Andric }
264*0b57cec5SDimitry Andric 
265*0b57cec5SDimitry Andric static void
266*0b57cec5SDimitry Andric pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
267*0b57cec5SDimitry Andric                      const Expr *E, Address ReferenceTemporary) {
268*0b57cec5SDimitry Andric   // Objective-C++ ARC:
269*0b57cec5SDimitry Andric   //   If we are binding a reference to a temporary that has ownership, we
270*0b57cec5SDimitry Andric   //   need to perform retain/release operations on the temporary.
271*0b57cec5SDimitry Andric   //
272*0b57cec5SDimitry Andric   // FIXME: This should be looking at E, not M.
273*0b57cec5SDimitry Andric   if (auto Lifetime = M->getType().getObjCLifetime()) {
274*0b57cec5SDimitry Andric     switch (Lifetime) {
275*0b57cec5SDimitry Andric     case Qualifiers::OCL_None:
276*0b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
277*0b57cec5SDimitry Andric       // Carry on to normal cleanup handling.
278*0b57cec5SDimitry Andric       break;
279*0b57cec5SDimitry Andric 
280*0b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
281*0b57cec5SDimitry Andric       // Nothing to do; cleaned up by an autorelease pool.
282*0b57cec5SDimitry Andric       return;
283*0b57cec5SDimitry Andric 
284*0b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
285*0b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
286*0b57cec5SDimitry Andric       switch (StorageDuration Duration = M->getStorageDuration()) {
287*0b57cec5SDimitry Andric       case SD_Static:
288*0b57cec5SDimitry Andric         // Note: we intentionally do not register a cleanup to release
289*0b57cec5SDimitry Andric         // the object on program termination.
290*0b57cec5SDimitry Andric         return;
291*0b57cec5SDimitry Andric 
292*0b57cec5SDimitry Andric       case SD_Thread:
293*0b57cec5SDimitry Andric         // FIXME: We should probably register a cleanup in this case.
294*0b57cec5SDimitry Andric         return;
295*0b57cec5SDimitry Andric 
296*0b57cec5SDimitry Andric       case SD_Automatic:
297*0b57cec5SDimitry Andric       case SD_FullExpression:
298*0b57cec5SDimitry Andric         CodeGenFunction::Destroyer *Destroy;
299*0b57cec5SDimitry Andric         CleanupKind CleanupKind;
300*0b57cec5SDimitry Andric         if (Lifetime == Qualifiers::OCL_Strong) {
301*0b57cec5SDimitry Andric           const ValueDecl *VD = M->getExtendingDecl();
302*0b57cec5SDimitry Andric           bool Precise =
303*0b57cec5SDimitry Andric               VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
304*0b57cec5SDimitry Andric           CleanupKind = CGF.getARCCleanupKind();
305*0b57cec5SDimitry Andric           Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
306*0b57cec5SDimitry Andric                             : &CodeGenFunction::destroyARCStrongImprecise;
307*0b57cec5SDimitry Andric         } else {
308*0b57cec5SDimitry Andric           // __weak objects always get EH cleanups; otherwise, exceptions
309*0b57cec5SDimitry Andric           // could cause really nasty crashes instead of mere leaks.
310*0b57cec5SDimitry Andric           CleanupKind = NormalAndEHCleanup;
311*0b57cec5SDimitry Andric           Destroy = &CodeGenFunction::destroyARCWeak;
312*0b57cec5SDimitry Andric         }
313*0b57cec5SDimitry Andric         if (Duration == SD_FullExpression)
314*0b57cec5SDimitry Andric           CGF.pushDestroy(CleanupKind, ReferenceTemporary,
315*0b57cec5SDimitry Andric                           M->getType(), *Destroy,
316*0b57cec5SDimitry Andric                           CleanupKind & EHCleanup);
317*0b57cec5SDimitry Andric         else
318*0b57cec5SDimitry Andric           CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
319*0b57cec5SDimitry Andric                                           M->getType(),
320*0b57cec5SDimitry Andric                                           *Destroy, CleanupKind & EHCleanup);
321*0b57cec5SDimitry Andric         return;
322*0b57cec5SDimitry Andric 
323*0b57cec5SDimitry Andric       case SD_Dynamic:
324*0b57cec5SDimitry Andric         llvm_unreachable("temporary cannot have dynamic storage duration");
325*0b57cec5SDimitry Andric       }
326*0b57cec5SDimitry Andric       llvm_unreachable("unknown storage duration");
327*0b57cec5SDimitry Andric     }
328*0b57cec5SDimitry Andric   }
329*0b57cec5SDimitry Andric 
330*0b57cec5SDimitry Andric   CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
331*0b57cec5SDimitry Andric   if (const RecordType *RT =
332*0b57cec5SDimitry Andric           E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
333*0b57cec5SDimitry Andric     // Get the destructor for the reference temporary.
334*0b57cec5SDimitry Andric     auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
335*0b57cec5SDimitry Andric     if (!ClassDecl->hasTrivialDestructor())
336*0b57cec5SDimitry Andric       ReferenceTemporaryDtor = ClassDecl->getDestructor();
337*0b57cec5SDimitry Andric   }
338*0b57cec5SDimitry Andric 
339*0b57cec5SDimitry Andric   if (!ReferenceTemporaryDtor)
340*0b57cec5SDimitry Andric     return;
341*0b57cec5SDimitry Andric 
342*0b57cec5SDimitry Andric   // Call the destructor for the temporary.
343*0b57cec5SDimitry Andric   switch (M->getStorageDuration()) {
344*0b57cec5SDimitry Andric   case SD_Static:
345*0b57cec5SDimitry Andric   case SD_Thread: {
346*0b57cec5SDimitry Andric     llvm::FunctionCallee CleanupFn;
347*0b57cec5SDimitry Andric     llvm::Constant *CleanupArg;
348*0b57cec5SDimitry Andric     if (E->getType()->isArrayType()) {
349*0b57cec5SDimitry Andric       CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
350*0b57cec5SDimitry Andric           ReferenceTemporary, E->getType(),
351*0b57cec5SDimitry Andric           CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
352*0b57cec5SDimitry Andric           dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
353*0b57cec5SDimitry Andric       CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
354*0b57cec5SDimitry Andric     } else {
355*0b57cec5SDimitry Andric       CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
356*0b57cec5SDimitry Andric           GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
357*0b57cec5SDimitry Andric       CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
358*0b57cec5SDimitry Andric     }
359*0b57cec5SDimitry Andric     CGF.CGM.getCXXABI().registerGlobalDtor(
360*0b57cec5SDimitry Andric         CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
361*0b57cec5SDimitry Andric     break;
362*0b57cec5SDimitry Andric   }
363*0b57cec5SDimitry Andric 
364*0b57cec5SDimitry Andric   case SD_FullExpression:
365*0b57cec5SDimitry Andric     CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
366*0b57cec5SDimitry Andric                     CodeGenFunction::destroyCXXObject,
367*0b57cec5SDimitry Andric                     CGF.getLangOpts().Exceptions);
368*0b57cec5SDimitry Andric     break;
369*0b57cec5SDimitry Andric 
370*0b57cec5SDimitry Andric   case SD_Automatic:
371*0b57cec5SDimitry Andric     CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
372*0b57cec5SDimitry Andric                                     ReferenceTemporary, E->getType(),
373*0b57cec5SDimitry Andric                                     CodeGenFunction::destroyCXXObject,
374*0b57cec5SDimitry Andric                                     CGF.getLangOpts().Exceptions);
375*0b57cec5SDimitry Andric     break;
376*0b57cec5SDimitry Andric 
377*0b57cec5SDimitry Andric   case SD_Dynamic:
378*0b57cec5SDimitry Andric     llvm_unreachable("temporary cannot have dynamic storage duration");
379*0b57cec5SDimitry Andric   }
380*0b57cec5SDimitry Andric }
381*0b57cec5SDimitry Andric 
382*0b57cec5SDimitry Andric static Address createReferenceTemporary(CodeGenFunction &CGF,
383*0b57cec5SDimitry Andric                                         const MaterializeTemporaryExpr *M,
384*0b57cec5SDimitry Andric                                         const Expr *Inner,
385*0b57cec5SDimitry Andric                                         Address *Alloca = nullptr) {
386*0b57cec5SDimitry Andric   auto &TCG = CGF.getTargetHooks();
387*0b57cec5SDimitry Andric   switch (M->getStorageDuration()) {
388*0b57cec5SDimitry Andric   case SD_FullExpression:
389*0b57cec5SDimitry Andric   case SD_Automatic: {
390*0b57cec5SDimitry Andric     // If we have a constant temporary array or record try to promote it into a
391*0b57cec5SDimitry Andric     // constant global under the same rules a normal constant would've been
392*0b57cec5SDimitry Andric     // promoted. This is easier on the optimizer and generally emits fewer
393*0b57cec5SDimitry Andric     // instructions.
394*0b57cec5SDimitry Andric     QualType Ty = Inner->getType();
395*0b57cec5SDimitry Andric     if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
396*0b57cec5SDimitry Andric         (Ty->isArrayType() || Ty->isRecordType()) &&
397*0b57cec5SDimitry Andric         CGF.CGM.isTypeConstant(Ty, true))
398*0b57cec5SDimitry Andric       if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
399*0b57cec5SDimitry Andric         if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
400*0b57cec5SDimitry Andric           auto AS = AddrSpace.getValue();
401*0b57cec5SDimitry Andric           auto *GV = new llvm::GlobalVariable(
402*0b57cec5SDimitry Andric               CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
403*0b57cec5SDimitry Andric               llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
404*0b57cec5SDimitry Andric               llvm::GlobalValue::NotThreadLocal,
405*0b57cec5SDimitry Andric               CGF.getContext().getTargetAddressSpace(AS));
406*0b57cec5SDimitry Andric           CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
407a7dea167SDimitry Andric           GV->setAlignment(alignment.getAsAlign());
408*0b57cec5SDimitry Andric           llvm::Constant *C = GV;
409*0b57cec5SDimitry Andric           if (AS != LangAS::Default)
410*0b57cec5SDimitry Andric             C = TCG.performAddrSpaceCast(
411*0b57cec5SDimitry Andric                 CGF.CGM, GV, AS, LangAS::Default,
412*0b57cec5SDimitry Andric                 GV->getValueType()->getPointerTo(
413*0b57cec5SDimitry Andric                     CGF.getContext().getTargetAddressSpace(LangAS::Default)));
414*0b57cec5SDimitry Andric           // FIXME: Should we put the new global into a COMDAT?
415*0b57cec5SDimitry Andric           return Address(C, alignment);
416*0b57cec5SDimitry Andric         }
417*0b57cec5SDimitry Andric       }
418*0b57cec5SDimitry Andric     return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
419*0b57cec5SDimitry Andric   }
420*0b57cec5SDimitry Andric   case SD_Thread:
421*0b57cec5SDimitry Andric   case SD_Static:
422*0b57cec5SDimitry Andric     return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
423*0b57cec5SDimitry Andric 
424*0b57cec5SDimitry Andric   case SD_Dynamic:
425*0b57cec5SDimitry Andric     llvm_unreachable("temporary can't have dynamic storage duration");
426*0b57cec5SDimitry Andric   }
427*0b57cec5SDimitry Andric   llvm_unreachable("unknown storage duration");
428*0b57cec5SDimitry Andric }
429*0b57cec5SDimitry Andric 
4305ffd83dbSDimitry Andric /// Helper method to check if the underlying ABI is AAPCS
4315ffd83dbSDimitry Andric static bool isAAPCS(const TargetInfo &TargetInfo) {
4325ffd83dbSDimitry Andric   return TargetInfo.getABI().startswith("aapcs");
4335ffd83dbSDimitry Andric }
4345ffd83dbSDimitry Andric 
435*0b57cec5SDimitry Andric LValue CodeGenFunction::
436*0b57cec5SDimitry Andric EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
437480093f4SDimitry Andric   const Expr *E = M->getSubExpr();
438*0b57cec5SDimitry Andric 
439*0b57cec5SDimitry Andric   assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
440*0b57cec5SDimitry Andric           !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
441*0b57cec5SDimitry Andric          "Reference should never be pseudo-strong!");
442*0b57cec5SDimitry Andric 
443*0b57cec5SDimitry Andric   // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
444*0b57cec5SDimitry Andric   // as that will cause the lifetime adjustment to be lost for ARC
445*0b57cec5SDimitry Andric   auto ownership = M->getType().getObjCLifetime();
446*0b57cec5SDimitry Andric   if (ownership != Qualifiers::OCL_None &&
447*0b57cec5SDimitry Andric       ownership != Qualifiers::OCL_ExplicitNone) {
448*0b57cec5SDimitry Andric     Address Object = createReferenceTemporary(*this, M, E);
449*0b57cec5SDimitry Andric     if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
450*0b57cec5SDimitry Andric       Object = Address(llvm::ConstantExpr::getBitCast(Var,
451*0b57cec5SDimitry Andric                            ConvertTypeForMem(E->getType())
452*0b57cec5SDimitry Andric                              ->getPointerTo(Object.getAddressSpace())),
453*0b57cec5SDimitry Andric                        Object.getAlignment());
454*0b57cec5SDimitry Andric 
455*0b57cec5SDimitry Andric       // createReferenceTemporary will promote the temporary to a global with a
456*0b57cec5SDimitry Andric       // constant initializer if it can.  It can only do this to a value of
457*0b57cec5SDimitry Andric       // ARC-manageable type if the value is global and therefore "immune" to
458*0b57cec5SDimitry Andric       // ref-counting operations.  Therefore we have no need to emit either a
459*0b57cec5SDimitry Andric       // dynamic initialization or a cleanup and we can just return the address
460*0b57cec5SDimitry Andric       // of the temporary.
461*0b57cec5SDimitry Andric       if (Var->hasInitializer())
462*0b57cec5SDimitry Andric         return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
463*0b57cec5SDimitry Andric 
464*0b57cec5SDimitry Andric       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
465*0b57cec5SDimitry Andric     }
466*0b57cec5SDimitry Andric     LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
467*0b57cec5SDimitry Andric                                        AlignmentSource::Decl);
468*0b57cec5SDimitry Andric 
469*0b57cec5SDimitry Andric     switch (getEvaluationKind(E->getType())) {
470*0b57cec5SDimitry Andric     default: llvm_unreachable("expected scalar or aggregate expression");
471*0b57cec5SDimitry Andric     case TEK_Scalar:
472*0b57cec5SDimitry Andric       EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
473*0b57cec5SDimitry Andric       break;
474*0b57cec5SDimitry Andric     case TEK_Aggregate: {
475*0b57cec5SDimitry Andric       EmitAggExpr(E, AggValueSlot::forAddr(Object,
476*0b57cec5SDimitry Andric                                            E->getType().getQualifiers(),
477*0b57cec5SDimitry Andric                                            AggValueSlot::IsDestructed,
478*0b57cec5SDimitry Andric                                            AggValueSlot::DoesNotNeedGCBarriers,
479*0b57cec5SDimitry Andric                                            AggValueSlot::IsNotAliased,
480*0b57cec5SDimitry Andric                                            AggValueSlot::DoesNotOverlap));
481*0b57cec5SDimitry Andric       break;
482*0b57cec5SDimitry Andric     }
483*0b57cec5SDimitry Andric     }
484*0b57cec5SDimitry Andric 
485*0b57cec5SDimitry Andric     pushTemporaryCleanup(*this, M, E, Object);
486*0b57cec5SDimitry Andric     return RefTempDst;
487*0b57cec5SDimitry Andric   }
488*0b57cec5SDimitry Andric 
489*0b57cec5SDimitry Andric   SmallVector<const Expr *, 2> CommaLHSs;
490*0b57cec5SDimitry Andric   SmallVector<SubobjectAdjustment, 2> Adjustments;
491*0b57cec5SDimitry Andric   E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
492*0b57cec5SDimitry Andric 
493*0b57cec5SDimitry Andric   for (const auto &Ignored : CommaLHSs)
494*0b57cec5SDimitry Andric     EmitIgnoredExpr(Ignored);
495*0b57cec5SDimitry Andric 
496*0b57cec5SDimitry Andric   if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
497*0b57cec5SDimitry Andric     if (opaque->getType()->isRecordType()) {
498*0b57cec5SDimitry Andric       assert(Adjustments.empty());
499*0b57cec5SDimitry Andric       return EmitOpaqueValueLValue(opaque);
500*0b57cec5SDimitry Andric     }
501*0b57cec5SDimitry Andric   }
502*0b57cec5SDimitry Andric 
503*0b57cec5SDimitry Andric   // Create and initialize the reference temporary.
504*0b57cec5SDimitry Andric   Address Alloca = Address::invalid();
505*0b57cec5SDimitry Andric   Address Object = createReferenceTemporary(*this, M, E, &Alloca);
506*0b57cec5SDimitry Andric   if (auto *Var = dyn_cast<llvm::GlobalVariable>(
507*0b57cec5SDimitry Andric           Object.getPointer()->stripPointerCasts())) {
508*0b57cec5SDimitry Andric     Object = Address(llvm::ConstantExpr::getBitCast(
509*0b57cec5SDimitry Andric                          cast<llvm::Constant>(Object.getPointer()),
510*0b57cec5SDimitry Andric                          ConvertTypeForMem(E->getType())->getPointerTo()),
511*0b57cec5SDimitry Andric                      Object.getAlignment());
512*0b57cec5SDimitry Andric     // If the temporary is a global and has a constant initializer or is a
513*0b57cec5SDimitry Andric     // constant temporary that we promoted to a global, we may have already
514*0b57cec5SDimitry Andric     // initialized it.
515*0b57cec5SDimitry Andric     if (!Var->hasInitializer()) {
516*0b57cec5SDimitry Andric       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
517*0b57cec5SDimitry Andric       EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
518*0b57cec5SDimitry Andric     }
519*0b57cec5SDimitry Andric   } else {
520*0b57cec5SDimitry Andric     switch (M->getStorageDuration()) {
521*0b57cec5SDimitry Andric     case SD_Automatic:
522*0b57cec5SDimitry Andric       if (auto *Size = EmitLifetimeStart(
523*0b57cec5SDimitry Andric               CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
524*0b57cec5SDimitry Andric               Alloca.getPointer())) {
525*0b57cec5SDimitry Andric         pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
526*0b57cec5SDimitry Andric                                                   Alloca, Size);
527*0b57cec5SDimitry Andric       }
528*0b57cec5SDimitry Andric       break;
529*0b57cec5SDimitry Andric 
530*0b57cec5SDimitry Andric     case SD_FullExpression: {
531*0b57cec5SDimitry Andric       if (!ShouldEmitLifetimeMarkers)
532*0b57cec5SDimitry Andric         break;
533*0b57cec5SDimitry Andric 
534*0b57cec5SDimitry Andric       // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
535*0b57cec5SDimitry Andric       // marker. Instead, start the lifetime of a conditional temporary earlier
536a7dea167SDimitry Andric       // so that it's unconditional. Don't do this with sanitizers which need
537a7dea167SDimitry Andric       // more precise lifetime marks.
538*0b57cec5SDimitry Andric       ConditionalEvaluation *OldConditional = nullptr;
539*0b57cec5SDimitry Andric       CGBuilderTy::InsertPoint OldIP;
540*0b57cec5SDimitry Andric       if (isInConditionalBranch() && !E->getType().isDestructedType() &&
541a7dea167SDimitry Andric           !SanOpts.has(SanitizerKind::HWAddress) &&
542a7dea167SDimitry Andric           !SanOpts.has(SanitizerKind::Memory) &&
543*0b57cec5SDimitry Andric           !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) {
544*0b57cec5SDimitry Andric         OldConditional = OutermostConditional;
545*0b57cec5SDimitry Andric         OutermostConditional = nullptr;
546*0b57cec5SDimitry Andric 
547*0b57cec5SDimitry Andric         OldIP = Builder.saveIP();
548*0b57cec5SDimitry Andric         llvm::BasicBlock *Block = OldConditional->getStartingBlock();
549*0b57cec5SDimitry Andric         Builder.restoreIP(CGBuilderTy::InsertPoint(
550*0b57cec5SDimitry Andric             Block, llvm::BasicBlock::iterator(Block->back())));
551*0b57cec5SDimitry Andric       }
552*0b57cec5SDimitry Andric 
553*0b57cec5SDimitry Andric       if (auto *Size = EmitLifetimeStart(
554*0b57cec5SDimitry Andric               CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
555*0b57cec5SDimitry Andric               Alloca.getPointer())) {
556*0b57cec5SDimitry Andric         pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
557*0b57cec5SDimitry Andric                                              Size);
558*0b57cec5SDimitry Andric       }
559*0b57cec5SDimitry Andric 
560*0b57cec5SDimitry Andric       if (OldConditional) {
561*0b57cec5SDimitry Andric         OutermostConditional = OldConditional;
562*0b57cec5SDimitry Andric         Builder.restoreIP(OldIP);
563*0b57cec5SDimitry Andric       }
564*0b57cec5SDimitry Andric       break;
565*0b57cec5SDimitry Andric     }
566*0b57cec5SDimitry Andric 
567*0b57cec5SDimitry Andric     default:
568*0b57cec5SDimitry Andric       break;
569*0b57cec5SDimitry Andric     }
570*0b57cec5SDimitry Andric     EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
571*0b57cec5SDimitry Andric   }
572*0b57cec5SDimitry Andric   pushTemporaryCleanup(*this, M, E, Object);
573*0b57cec5SDimitry Andric 
574*0b57cec5SDimitry Andric   // Perform derived-to-base casts and/or field accesses, to get from the
575*0b57cec5SDimitry Andric   // temporary object we created (and, potentially, for which we extended
576*0b57cec5SDimitry Andric   // the lifetime) to the subobject we're binding the reference to.
577*0b57cec5SDimitry Andric   for (unsigned I = Adjustments.size(); I != 0; --I) {
578*0b57cec5SDimitry Andric     SubobjectAdjustment &Adjustment = Adjustments[I-1];
579*0b57cec5SDimitry Andric     switch (Adjustment.Kind) {
580*0b57cec5SDimitry Andric     case SubobjectAdjustment::DerivedToBaseAdjustment:
581*0b57cec5SDimitry Andric       Object =
582*0b57cec5SDimitry Andric           GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
583*0b57cec5SDimitry Andric                                 Adjustment.DerivedToBase.BasePath->path_begin(),
584*0b57cec5SDimitry Andric                                 Adjustment.DerivedToBase.BasePath->path_end(),
585*0b57cec5SDimitry Andric                                 /*NullCheckValue=*/ false, E->getExprLoc());
586*0b57cec5SDimitry Andric       break;
587*0b57cec5SDimitry Andric 
588*0b57cec5SDimitry Andric     case SubobjectAdjustment::FieldAdjustment: {
589*0b57cec5SDimitry Andric       LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
590*0b57cec5SDimitry Andric       LV = EmitLValueForField(LV, Adjustment.Field);
591*0b57cec5SDimitry Andric       assert(LV.isSimple() &&
592*0b57cec5SDimitry Andric              "materialized temporary field is not a simple lvalue");
593480093f4SDimitry Andric       Object = LV.getAddress(*this);
594*0b57cec5SDimitry Andric       break;
595*0b57cec5SDimitry Andric     }
596*0b57cec5SDimitry Andric 
597*0b57cec5SDimitry Andric     case SubobjectAdjustment::MemberPointerAdjustment: {
598*0b57cec5SDimitry Andric       llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
599*0b57cec5SDimitry Andric       Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
600*0b57cec5SDimitry Andric                                                Adjustment.Ptr.MPT);
601*0b57cec5SDimitry Andric       break;
602*0b57cec5SDimitry Andric     }
603*0b57cec5SDimitry Andric     }
604*0b57cec5SDimitry Andric   }
605*0b57cec5SDimitry Andric 
606*0b57cec5SDimitry Andric   return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
607*0b57cec5SDimitry Andric }
608*0b57cec5SDimitry Andric 
609*0b57cec5SDimitry Andric RValue
610*0b57cec5SDimitry Andric CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
611*0b57cec5SDimitry Andric   // Emit the expression as an lvalue.
612*0b57cec5SDimitry Andric   LValue LV = EmitLValue(E);
613*0b57cec5SDimitry Andric   assert(LV.isSimple());
614480093f4SDimitry Andric   llvm::Value *Value = LV.getPointer(*this);
615*0b57cec5SDimitry Andric 
616*0b57cec5SDimitry Andric   if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
617*0b57cec5SDimitry Andric     // C++11 [dcl.ref]p5 (as amended by core issue 453):
618*0b57cec5SDimitry Andric     //   If a glvalue to which a reference is directly bound designates neither
619*0b57cec5SDimitry Andric     //   an existing object or function of an appropriate type nor a region of
620*0b57cec5SDimitry Andric     //   storage of suitable size and alignment to contain an object of the
621*0b57cec5SDimitry Andric     //   reference's type, the behavior is undefined.
622*0b57cec5SDimitry Andric     QualType Ty = E->getType();
623*0b57cec5SDimitry Andric     EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
624*0b57cec5SDimitry Andric   }
625*0b57cec5SDimitry Andric 
626*0b57cec5SDimitry Andric   return RValue::get(Value);
627*0b57cec5SDimitry Andric }
628*0b57cec5SDimitry Andric 
629*0b57cec5SDimitry Andric 
630*0b57cec5SDimitry Andric /// getAccessedFieldNo - Given an encoded value and a result number, return the
631*0b57cec5SDimitry Andric /// input field number being accessed.
632*0b57cec5SDimitry Andric unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
633*0b57cec5SDimitry Andric                                              const llvm::Constant *Elts) {
634*0b57cec5SDimitry Andric   return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
635*0b57cec5SDimitry Andric       ->getZExtValue();
636*0b57cec5SDimitry Andric }
637*0b57cec5SDimitry Andric 
638*0b57cec5SDimitry Andric /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
639*0b57cec5SDimitry Andric static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
640*0b57cec5SDimitry Andric                                     llvm::Value *High) {
641*0b57cec5SDimitry Andric   llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
642*0b57cec5SDimitry Andric   llvm::Value *K47 = Builder.getInt64(47);
643*0b57cec5SDimitry Andric   llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
644*0b57cec5SDimitry Andric   llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
645*0b57cec5SDimitry Andric   llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
646*0b57cec5SDimitry Andric   llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
647*0b57cec5SDimitry Andric   return Builder.CreateMul(B1, KMul);
648*0b57cec5SDimitry Andric }
649*0b57cec5SDimitry Andric 
650*0b57cec5SDimitry Andric bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
651*0b57cec5SDimitry Andric   return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
652*0b57cec5SDimitry Andric          TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
653*0b57cec5SDimitry Andric }
654*0b57cec5SDimitry Andric 
655*0b57cec5SDimitry Andric bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
656*0b57cec5SDimitry Andric   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
657*0b57cec5SDimitry Andric   return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
658*0b57cec5SDimitry Andric          (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
659*0b57cec5SDimitry Andric           TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
660*0b57cec5SDimitry Andric           TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
661*0b57cec5SDimitry Andric }
662*0b57cec5SDimitry Andric 
663*0b57cec5SDimitry Andric bool CodeGenFunction::sanitizePerformTypeCheck() const {
664*0b57cec5SDimitry Andric   return SanOpts.has(SanitizerKind::Null) |
665*0b57cec5SDimitry Andric          SanOpts.has(SanitizerKind::Alignment) |
666*0b57cec5SDimitry Andric          SanOpts.has(SanitizerKind::ObjectSize) |
667*0b57cec5SDimitry Andric          SanOpts.has(SanitizerKind::Vptr);
668*0b57cec5SDimitry Andric }
669*0b57cec5SDimitry Andric 
670*0b57cec5SDimitry Andric void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
671*0b57cec5SDimitry Andric                                     llvm::Value *Ptr, QualType Ty,
672*0b57cec5SDimitry Andric                                     CharUnits Alignment,
673*0b57cec5SDimitry Andric                                     SanitizerSet SkippedChecks,
674*0b57cec5SDimitry Andric                                     llvm::Value *ArraySize) {
675*0b57cec5SDimitry Andric   if (!sanitizePerformTypeCheck())
676*0b57cec5SDimitry Andric     return;
677*0b57cec5SDimitry Andric 
678*0b57cec5SDimitry Andric   // Don't check pointers outside the default address space. The null check
679*0b57cec5SDimitry Andric   // isn't correct, the object-size check isn't supported by LLVM, and we can't
680*0b57cec5SDimitry Andric   // communicate the addresses to the runtime handler for the vptr check.
681*0b57cec5SDimitry Andric   if (Ptr->getType()->getPointerAddressSpace())
682*0b57cec5SDimitry Andric     return;
683*0b57cec5SDimitry Andric 
684*0b57cec5SDimitry Andric   // Don't check pointers to volatile data. The behavior here is implementation-
685*0b57cec5SDimitry Andric   // defined.
686*0b57cec5SDimitry Andric   if (Ty.isVolatileQualified())
687*0b57cec5SDimitry Andric     return;
688*0b57cec5SDimitry Andric 
689*0b57cec5SDimitry Andric   SanitizerScope SanScope(this);
690*0b57cec5SDimitry Andric 
691*0b57cec5SDimitry Andric   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
692*0b57cec5SDimitry Andric   llvm::BasicBlock *Done = nullptr;
693*0b57cec5SDimitry Andric 
694*0b57cec5SDimitry Andric   // Quickly determine whether we have a pointer to an alloca. It's possible
695*0b57cec5SDimitry Andric   // to skip null checks, and some alignment checks, for these pointers. This
696*0b57cec5SDimitry Andric   // can reduce compile-time significantly.
697a7dea167SDimitry Andric   auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
698*0b57cec5SDimitry Andric 
699*0b57cec5SDimitry Andric   llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
700*0b57cec5SDimitry Andric   llvm::Value *IsNonNull = nullptr;
701*0b57cec5SDimitry Andric   bool IsGuaranteedNonNull =
702*0b57cec5SDimitry Andric       SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
703*0b57cec5SDimitry Andric   bool AllowNullPointers = isNullPointerAllowed(TCK);
704*0b57cec5SDimitry Andric   if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
705*0b57cec5SDimitry Andric       !IsGuaranteedNonNull) {
706*0b57cec5SDimitry Andric     // The glvalue must not be an empty glvalue.
707*0b57cec5SDimitry Andric     IsNonNull = Builder.CreateIsNotNull(Ptr);
708*0b57cec5SDimitry Andric 
709*0b57cec5SDimitry Andric     // The IR builder can constant-fold the null check if the pointer points to
710*0b57cec5SDimitry Andric     // a constant.
711*0b57cec5SDimitry Andric     IsGuaranteedNonNull = IsNonNull == True;
712*0b57cec5SDimitry Andric 
713*0b57cec5SDimitry Andric     // Skip the null check if the pointer is known to be non-null.
714*0b57cec5SDimitry Andric     if (!IsGuaranteedNonNull) {
715*0b57cec5SDimitry Andric       if (AllowNullPointers) {
716*0b57cec5SDimitry Andric         // When performing pointer casts, it's OK if the value is null.
717*0b57cec5SDimitry Andric         // Skip the remaining checks in that case.
718*0b57cec5SDimitry Andric         Done = createBasicBlock("null");
719*0b57cec5SDimitry Andric         llvm::BasicBlock *Rest = createBasicBlock("not.null");
720*0b57cec5SDimitry Andric         Builder.CreateCondBr(IsNonNull, Rest, Done);
721*0b57cec5SDimitry Andric         EmitBlock(Rest);
722*0b57cec5SDimitry Andric       } else {
723*0b57cec5SDimitry Andric         Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
724*0b57cec5SDimitry Andric       }
725*0b57cec5SDimitry Andric     }
726*0b57cec5SDimitry Andric   }
727*0b57cec5SDimitry Andric 
728*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ObjectSize) &&
729*0b57cec5SDimitry Andric       !SkippedChecks.has(SanitizerKind::ObjectSize) &&
730*0b57cec5SDimitry Andric       !Ty->isIncompleteType()) {
7315ffd83dbSDimitry Andric     uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
732*0b57cec5SDimitry Andric     llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
733*0b57cec5SDimitry Andric     if (ArraySize)
734*0b57cec5SDimitry Andric       Size = Builder.CreateMul(Size, ArraySize);
735*0b57cec5SDimitry Andric 
736*0b57cec5SDimitry Andric     // Degenerate case: new X[0] does not need an objectsize check.
737*0b57cec5SDimitry Andric     llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
738*0b57cec5SDimitry Andric     if (!ConstantSize || !ConstantSize->isNullValue()) {
739*0b57cec5SDimitry Andric       // The glvalue must refer to a large enough storage region.
740*0b57cec5SDimitry Andric       // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
741*0b57cec5SDimitry Andric       //        to check this.
742*0b57cec5SDimitry Andric       // FIXME: Get object address space
743*0b57cec5SDimitry Andric       llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
744*0b57cec5SDimitry Andric       llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
745*0b57cec5SDimitry Andric       llvm::Value *Min = Builder.getFalse();
746*0b57cec5SDimitry Andric       llvm::Value *NullIsUnknown = Builder.getFalse();
747*0b57cec5SDimitry Andric       llvm::Value *Dynamic = Builder.getFalse();
748*0b57cec5SDimitry Andric       llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
749*0b57cec5SDimitry Andric       llvm::Value *LargeEnough = Builder.CreateICmpUGE(
750*0b57cec5SDimitry Andric           Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
751*0b57cec5SDimitry Andric       Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
752*0b57cec5SDimitry Andric     }
753*0b57cec5SDimitry Andric   }
754*0b57cec5SDimitry Andric 
755*0b57cec5SDimitry Andric   uint64_t AlignVal = 0;
756*0b57cec5SDimitry Andric   llvm::Value *PtrAsInt = nullptr;
757*0b57cec5SDimitry Andric 
758*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Alignment) &&
759*0b57cec5SDimitry Andric       !SkippedChecks.has(SanitizerKind::Alignment)) {
760*0b57cec5SDimitry Andric     AlignVal = Alignment.getQuantity();
761*0b57cec5SDimitry Andric     if (!Ty->isIncompleteType() && !AlignVal)
7625ffd83dbSDimitry Andric       AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
7635ffd83dbSDimitry Andric                                              /*ForPointeeType=*/true)
7645ffd83dbSDimitry Andric                      .getQuantity();
765*0b57cec5SDimitry Andric 
766*0b57cec5SDimitry Andric     // The glvalue must be suitably aligned.
767*0b57cec5SDimitry Andric     if (AlignVal > 1 &&
768*0b57cec5SDimitry Andric         (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
769*0b57cec5SDimitry Andric       PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
770*0b57cec5SDimitry Andric       llvm::Value *Align = Builder.CreateAnd(
771*0b57cec5SDimitry Andric           PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
772*0b57cec5SDimitry Andric       llvm::Value *Aligned =
773*0b57cec5SDimitry Andric           Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
774*0b57cec5SDimitry Andric       if (Aligned != True)
775*0b57cec5SDimitry Andric         Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
776*0b57cec5SDimitry Andric     }
777*0b57cec5SDimitry Andric   }
778*0b57cec5SDimitry Andric 
779*0b57cec5SDimitry Andric   if (Checks.size() > 0) {
780*0b57cec5SDimitry Andric     // Make sure we're not losing information. Alignment needs to be a power of
781*0b57cec5SDimitry Andric     // 2
782*0b57cec5SDimitry Andric     assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
783*0b57cec5SDimitry Andric     llvm::Constant *StaticData[] = {
784*0b57cec5SDimitry Andric         EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
785*0b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
786*0b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, TCK)};
787*0b57cec5SDimitry Andric     EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
788*0b57cec5SDimitry Andric               PtrAsInt ? PtrAsInt : Ptr);
789*0b57cec5SDimitry Andric   }
790*0b57cec5SDimitry Andric 
791*0b57cec5SDimitry Andric   // If possible, check that the vptr indicates that there is a subobject of
792*0b57cec5SDimitry Andric   // type Ty at offset zero within this object.
793*0b57cec5SDimitry Andric   //
794*0b57cec5SDimitry Andric   // C++11 [basic.life]p5,6:
795*0b57cec5SDimitry Andric   //   [For storage which does not refer to an object within its lifetime]
796*0b57cec5SDimitry Andric   //   The program has undefined behavior if:
797*0b57cec5SDimitry Andric   //    -- the [pointer or glvalue] is used to access a non-static data member
798*0b57cec5SDimitry Andric   //       or call a non-static member function
799*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Vptr) &&
800*0b57cec5SDimitry Andric       !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
801*0b57cec5SDimitry Andric     // Ensure that the pointer is non-null before loading it. If there is no
802*0b57cec5SDimitry Andric     // compile-time guarantee, reuse the run-time null check or emit a new one.
803*0b57cec5SDimitry Andric     if (!IsGuaranteedNonNull) {
804*0b57cec5SDimitry Andric       if (!IsNonNull)
805*0b57cec5SDimitry Andric         IsNonNull = Builder.CreateIsNotNull(Ptr);
806*0b57cec5SDimitry Andric       if (!Done)
807*0b57cec5SDimitry Andric         Done = createBasicBlock("vptr.null");
808*0b57cec5SDimitry Andric       llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
809*0b57cec5SDimitry Andric       Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
810*0b57cec5SDimitry Andric       EmitBlock(VptrNotNull);
811*0b57cec5SDimitry Andric     }
812*0b57cec5SDimitry Andric 
813*0b57cec5SDimitry Andric     // Compute a hash of the mangled name of the type.
814*0b57cec5SDimitry Andric     //
815*0b57cec5SDimitry Andric     // FIXME: This is not guaranteed to be deterministic! Move to a
816*0b57cec5SDimitry Andric     //        fingerprinting mechanism once LLVM provides one. For the time
817*0b57cec5SDimitry Andric     //        being the implementation happens to be deterministic.
818*0b57cec5SDimitry Andric     SmallString<64> MangledName;
819*0b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledName);
820*0b57cec5SDimitry Andric     CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
821*0b57cec5SDimitry Andric                                                      Out);
822*0b57cec5SDimitry Andric 
823*0b57cec5SDimitry Andric     // Blacklist based on the mangled type.
824*0b57cec5SDimitry Andric     if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
825*0b57cec5SDimitry Andric             SanitizerKind::Vptr, Out.str())) {
826*0b57cec5SDimitry Andric       llvm::hash_code TypeHash = hash_value(Out.str());
827*0b57cec5SDimitry Andric 
828*0b57cec5SDimitry Andric       // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
829*0b57cec5SDimitry Andric       llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
830*0b57cec5SDimitry Andric       llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
831*0b57cec5SDimitry Andric       Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
832*0b57cec5SDimitry Andric       llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
833*0b57cec5SDimitry Andric       llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
834*0b57cec5SDimitry Andric 
835*0b57cec5SDimitry Andric       llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
836*0b57cec5SDimitry Andric       Hash = Builder.CreateTrunc(Hash, IntPtrTy);
837*0b57cec5SDimitry Andric 
838*0b57cec5SDimitry Andric       // Look the hash up in our cache.
839*0b57cec5SDimitry Andric       const int CacheSize = 128;
840*0b57cec5SDimitry Andric       llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
841*0b57cec5SDimitry Andric       llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
842*0b57cec5SDimitry Andric                                                      "__ubsan_vptr_type_cache");
843*0b57cec5SDimitry Andric       llvm::Value *Slot = Builder.CreateAnd(Hash,
844*0b57cec5SDimitry Andric                                             llvm::ConstantInt::get(IntPtrTy,
845*0b57cec5SDimitry Andric                                                                    CacheSize-1));
846*0b57cec5SDimitry Andric       llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
847*0b57cec5SDimitry Andric       llvm::Value *CacheVal =
848*0b57cec5SDimitry Andric         Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
849*0b57cec5SDimitry Andric                                   getPointerAlign());
850*0b57cec5SDimitry Andric 
851*0b57cec5SDimitry Andric       // If the hash isn't in the cache, call a runtime handler to perform the
852*0b57cec5SDimitry Andric       // hard work of checking whether the vptr is for an object of the right
853*0b57cec5SDimitry Andric       // type. This will either fill in the cache and return, or produce a
854*0b57cec5SDimitry Andric       // diagnostic.
855*0b57cec5SDimitry Andric       llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
856*0b57cec5SDimitry Andric       llvm::Constant *StaticData[] = {
857*0b57cec5SDimitry Andric         EmitCheckSourceLocation(Loc),
858*0b57cec5SDimitry Andric         EmitCheckTypeDescriptor(Ty),
859*0b57cec5SDimitry Andric         CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
860*0b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, TCK)
861*0b57cec5SDimitry Andric       };
862*0b57cec5SDimitry Andric       llvm::Value *DynamicData[] = { Ptr, Hash };
863*0b57cec5SDimitry Andric       EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
864*0b57cec5SDimitry Andric                 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
865*0b57cec5SDimitry Andric                 DynamicData);
866*0b57cec5SDimitry Andric     }
867*0b57cec5SDimitry Andric   }
868*0b57cec5SDimitry Andric 
869*0b57cec5SDimitry Andric   if (Done) {
870*0b57cec5SDimitry Andric     Builder.CreateBr(Done);
871*0b57cec5SDimitry Andric     EmitBlock(Done);
872*0b57cec5SDimitry Andric   }
873*0b57cec5SDimitry Andric }
874*0b57cec5SDimitry Andric 
875*0b57cec5SDimitry Andric /// Determine whether this expression refers to a flexible array member in a
876*0b57cec5SDimitry Andric /// struct. We disable array bounds checks for such members.
877*0b57cec5SDimitry Andric static bool isFlexibleArrayMemberExpr(const Expr *E) {
878*0b57cec5SDimitry Andric   // For compatibility with existing code, we treat arrays of length 0 or
879*0b57cec5SDimitry Andric   // 1 as flexible array members.
8805ffd83dbSDimitry Andric   // FIXME: This is inconsistent with the warning code in SemaChecking. Unify
8815ffd83dbSDimitry Andric   // the two mechanisms.
882*0b57cec5SDimitry Andric   const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
883*0b57cec5SDimitry Andric   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
8845ffd83dbSDimitry Andric     // FIXME: Sema doesn't treat [1] as a flexible array member if the bound
8855ffd83dbSDimitry Andric     // was produced by macro expansion.
886*0b57cec5SDimitry Andric     if (CAT->getSize().ugt(1))
887*0b57cec5SDimitry Andric       return false;
888*0b57cec5SDimitry Andric   } else if (!isa<IncompleteArrayType>(AT))
889*0b57cec5SDimitry Andric     return false;
890*0b57cec5SDimitry Andric 
891*0b57cec5SDimitry Andric   E = E->IgnoreParens();
892*0b57cec5SDimitry Andric 
893*0b57cec5SDimitry Andric   // A flexible array member must be the last member in the class.
894*0b57cec5SDimitry Andric   if (const auto *ME = dyn_cast<MemberExpr>(E)) {
895*0b57cec5SDimitry Andric     // FIXME: If the base type of the member expr is not FD->getParent(),
896*0b57cec5SDimitry Andric     // this should not be treated as a flexible array member access.
897*0b57cec5SDimitry Andric     if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
8985ffd83dbSDimitry Andric       // FIXME: Sema doesn't treat a T[1] union member as a flexible array
8995ffd83dbSDimitry Andric       // member, only a T[0] or T[] member gets that treatment.
9005ffd83dbSDimitry Andric       if (FD->getParent()->isUnion())
9015ffd83dbSDimitry Andric         return true;
902*0b57cec5SDimitry Andric       RecordDecl::field_iterator FI(
903*0b57cec5SDimitry Andric           DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
904*0b57cec5SDimitry Andric       return ++FI == FD->getParent()->field_end();
905*0b57cec5SDimitry Andric     }
906*0b57cec5SDimitry Andric   } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
907*0b57cec5SDimitry Andric     return IRE->getDecl()->getNextIvar() == nullptr;
908*0b57cec5SDimitry Andric   }
909*0b57cec5SDimitry Andric 
910*0b57cec5SDimitry Andric   return false;
911*0b57cec5SDimitry Andric }
912*0b57cec5SDimitry Andric 
913*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
914*0b57cec5SDimitry Andric                                                    QualType EltTy) {
915*0b57cec5SDimitry Andric   ASTContext &C = getContext();
916*0b57cec5SDimitry Andric   uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
917*0b57cec5SDimitry Andric   if (!EltSize)
918*0b57cec5SDimitry Andric     return nullptr;
919*0b57cec5SDimitry Andric 
920*0b57cec5SDimitry Andric   auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
921*0b57cec5SDimitry Andric   if (!ArrayDeclRef)
922*0b57cec5SDimitry Andric     return nullptr;
923*0b57cec5SDimitry Andric 
924*0b57cec5SDimitry Andric   auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
925*0b57cec5SDimitry Andric   if (!ParamDecl)
926*0b57cec5SDimitry Andric     return nullptr;
927*0b57cec5SDimitry Andric 
928*0b57cec5SDimitry Andric   auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
929*0b57cec5SDimitry Andric   if (!POSAttr)
930*0b57cec5SDimitry Andric     return nullptr;
931*0b57cec5SDimitry Andric 
932*0b57cec5SDimitry Andric   // Don't load the size if it's a lower bound.
933*0b57cec5SDimitry Andric   int POSType = POSAttr->getType();
934*0b57cec5SDimitry Andric   if (POSType != 0 && POSType != 1)
935*0b57cec5SDimitry Andric     return nullptr;
936*0b57cec5SDimitry Andric 
937*0b57cec5SDimitry Andric   // Find the implicit size parameter.
938*0b57cec5SDimitry Andric   auto PassedSizeIt = SizeArguments.find(ParamDecl);
939*0b57cec5SDimitry Andric   if (PassedSizeIt == SizeArguments.end())
940*0b57cec5SDimitry Andric     return nullptr;
941*0b57cec5SDimitry Andric 
942*0b57cec5SDimitry Andric   const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
943*0b57cec5SDimitry Andric   assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
944*0b57cec5SDimitry Andric   Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
945*0b57cec5SDimitry Andric   llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
946*0b57cec5SDimitry Andric                                               C.getSizeType(), E->getExprLoc());
947*0b57cec5SDimitry Andric   llvm::Value *SizeOfElement =
948*0b57cec5SDimitry Andric       llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
949*0b57cec5SDimitry Andric   return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
950*0b57cec5SDimitry Andric }
951*0b57cec5SDimitry Andric 
952*0b57cec5SDimitry Andric /// If Base is known to point to the start of an array, return the length of
953*0b57cec5SDimitry Andric /// that array. Return 0 if the length cannot be determined.
954*0b57cec5SDimitry Andric static llvm::Value *getArrayIndexingBound(
955*0b57cec5SDimitry Andric     CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
956*0b57cec5SDimitry Andric   // For the vector indexing extension, the bound is the number of elements.
957*0b57cec5SDimitry Andric   if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
958*0b57cec5SDimitry Andric     IndexedType = Base->getType();
959*0b57cec5SDimitry Andric     return CGF.Builder.getInt32(VT->getNumElements());
960*0b57cec5SDimitry Andric   }
961*0b57cec5SDimitry Andric 
962*0b57cec5SDimitry Andric   Base = Base->IgnoreParens();
963*0b57cec5SDimitry Andric 
964*0b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CastExpr>(Base)) {
965*0b57cec5SDimitry Andric     if (CE->getCastKind() == CK_ArrayToPointerDecay &&
966*0b57cec5SDimitry Andric         !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
967*0b57cec5SDimitry Andric       IndexedType = CE->getSubExpr()->getType();
968*0b57cec5SDimitry Andric       const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
969*0b57cec5SDimitry Andric       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
970*0b57cec5SDimitry Andric         return CGF.Builder.getInt(CAT->getSize());
971*0b57cec5SDimitry Andric       else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
972*0b57cec5SDimitry Andric         return CGF.getVLASize(VAT).NumElts;
973*0b57cec5SDimitry Andric       // Ignore pass_object_size here. It's not applicable on decayed pointers.
974*0b57cec5SDimitry Andric     }
975*0b57cec5SDimitry Andric   }
976*0b57cec5SDimitry Andric 
977*0b57cec5SDimitry Andric   QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
978*0b57cec5SDimitry Andric   if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
979*0b57cec5SDimitry Andric     IndexedType = Base->getType();
980*0b57cec5SDimitry Andric     return POS;
981*0b57cec5SDimitry Andric   }
982*0b57cec5SDimitry Andric 
983*0b57cec5SDimitry Andric   return nullptr;
984*0b57cec5SDimitry Andric }
985*0b57cec5SDimitry Andric 
986*0b57cec5SDimitry Andric void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
987*0b57cec5SDimitry Andric                                       llvm::Value *Index, QualType IndexType,
988*0b57cec5SDimitry Andric                                       bool Accessed) {
989*0b57cec5SDimitry Andric   assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
990*0b57cec5SDimitry Andric          "should not be called unless adding bounds checks");
991*0b57cec5SDimitry Andric   SanitizerScope SanScope(this);
992*0b57cec5SDimitry Andric 
993*0b57cec5SDimitry Andric   QualType IndexedType;
994*0b57cec5SDimitry Andric   llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
995*0b57cec5SDimitry Andric   if (!Bound)
996*0b57cec5SDimitry Andric     return;
997*0b57cec5SDimitry Andric 
998*0b57cec5SDimitry Andric   bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
999*0b57cec5SDimitry Andric   llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
1000*0b57cec5SDimitry Andric   llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
1001*0b57cec5SDimitry Andric 
1002*0b57cec5SDimitry Andric   llvm::Constant *StaticData[] = {
1003*0b57cec5SDimitry Andric     EmitCheckSourceLocation(E->getExprLoc()),
1004*0b57cec5SDimitry Andric     EmitCheckTypeDescriptor(IndexedType),
1005*0b57cec5SDimitry Andric     EmitCheckTypeDescriptor(IndexType)
1006*0b57cec5SDimitry Andric   };
1007*0b57cec5SDimitry Andric   llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
1008*0b57cec5SDimitry Andric                                 : Builder.CreateICmpULE(IndexVal, BoundVal);
1009*0b57cec5SDimitry Andric   EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
1010*0b57cec5SDimitry Andric             SanitizerHandler::OutOfBounds, StaticData, Index);
1011*0b57cec5SDimitry Andric }
1012*0b57cec5SDimitry Andric 
1013*0b57cec5SDimitry Andric 
1014*0b57cec5SDimitry Andric CodeGenFunction::ComplexPairTy CodeGenFunction::
1015*0b57cec5SDimitry Andric EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1016*0b57cec5SDimitry Andric                          bool isInc, bool isPre) {
1017*0b57cec5SDimitry Andric   ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
1018*0b57cec5SDimitry Andric 
1019*0b57cec5SDimitry Andric   llvm::Value *NextVal;
1020*0b57cec5SDimitry Andric   if (isa<llvm::IntegerType>(InVal.first->getType())) {
1021*0b57cec5SDimitry Andric     uint64_t AmountVal = isInc ? 1 : -1;
1022*0b57cec5SDimitry Andric     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
1023*0b57cec5SDimitry Andric 
1024*0b57cec5SDimitry Andric     // Add the inc/dec to the real part.
1025*0b57cec5SDimitry Andric     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1026*0b57cec5SDimitry Andric   } else {
1027a7dea167SDimitry Andric     QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
1028*0b57cec5SDimitry Andric     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
1029*0b57cec5SDimitry Andric     if (!isInc)
1030*0b57cec5SDimitry Andric       FVal.changeSign();
1031*0b57cec5SDimitry Andric     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
1032*0b57cec5SDimitry Andric 
1033*0b57cec5SDimitry Andric     // Add the inc/dec to the real part.
1034*0b57cec5SDimitry Andric     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1035*0b57cec5SDimitry Andric   }
1036*0b57cec5SDimitry Andric 
1037*0b57cec5SDimitry Andric   ComplexPairTy IncVal(NextVal, InVal.second);
1038*0b57cec5SDimitry Andric 
1039*0b57cec5SDimitry Andric   // Store the updated result through the lvalue.
1040*0b57cec5SDimitry Andric   EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1041480093f4SDimitry Andric   if (getLangOpts().OpenMP)
1042480093f4SDimitry Andric     CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1043480093f4SDimitry Andric                                                               E->getSubExpr());
1044*0b57cec5SDimitry Andric 
1045*0b57cec5SDimitry Andric   // If this is a postinc, return the value read from memory, otherwise use the
1046*0b57cec5SDimitry Andric   // updated value.
1047*0b57cec5SDimitry Andric   return isPre ? IncVal : InVal;
1048*0b57cec5SDimitry Andric }
1049*0b57cec5SDimitry Andric 
1050*0b57cec5SDimitry Andric void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
1051*0b57cec5SDimitry Andric                                              CodeGenFunction *CGF) {
1052*0b57cec5SDimitry Andric   // Bind VLAs in the cast type.
1053*0b57cec5SDimitry Andric   if (CGF && E->getType()->isVariablyModifiedType())
1054*0b57cec5SDimitry Andric     CGF->EmitVariablyModifiedType(E->getType());
1055*0b57cec5SDimitry Andric 
1056*0b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
1057*0b57cec5SDimitry Andric     DI->EmitExplicitCastType(E->getType());
1058*0b57cec5SDimitry Andric }
1059*0b57cec5SDimitry Andric 
1060*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1061*0b57cec5SDimitry Andric //                         LValue Expression Emission
1062*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1063*0b57cec5SDimitry Andric 
1064*0b57cec5SDimitry Andric /// EmitPointerWithAlignment - Given an expression of pointer type, try to
1065*0b57cec5SDimitry Andric /// derive a more accurate bound on the alignment of the pointer.
1066*0b57cec5SDimitry Andric Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
1067*0b57cec5SDimitry Andric                                                   LValueBaseInfo *BaseInfo,
1068*0b57cec5SDimitry Andric                                                   TBAAAccessInfo *TBAAInfo) {
1069*0b57cec5SDimitry Andric   // We allow this with ObjC object pointers because of fragile ABIs.
1070*0b57cec5SDimitry Andric   assert(E->getType()->isPointerType() ||
1071*0b57cec5SDimitry Andric          E->getType()->isObjCObjectPointerType());
1072*0b57cec5SDimitry Andric   E = E->IgnoreParens();
1073*0b57cec5SDimitry Andric 
1074*0b57cec5SDimitry Andric   // Casts:
1075*0b57cec5SDimitry Andric   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1076*0b57cec5SDimitry Andric     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1077*0b57cec5SDimitry Andric       CGM.EmitExplicitCastExprType(ECE, this);
1078*0b57cec5SDimitry Andric 
1079*0b57cec5SDimitry Andric     switch (CE->getCastKind()) {
1080*0b57cec5SDimitry Andric     // Non-converting casts (but not C's implicit conversion from void*).
1081*0b57cec5SDimitry Andric     case CK_BitCast:
1082*0b57cec5SDimitry Andric     case CK_NoOp:
1083*0b57cec5SDimitry Andric     case CK_AddressSpaceConversion:
1084*0b57cec5SDimitry Andric       if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1085*0b57cec5SDimitry Andric         if (PtrTy->getPointeeType()->isVoidType())
1086*0b57cec5SDimitry Andric           break;
1087*0b57cec5SDimitry Andric 
1088*0b57cec5SDimitry Andric         LValueBaseInfo InnerBaseInfo;
1089*0b57cec5SDimitry Andric         TBAAAccessInfo InnerTBAAInfo;
1090*0b57cec5SDimitry Andric         Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
1091*0b57cec5SDimitry Andric                                                 &InnerBaseInfo,
1092*0b57cec5SDimitry Andric                                                 &InnerTBAAInfo);
1093*0b57cec5SDimitry Andric         if (BaseInfo) *BaseInfo = InnerBaseInfo;
1094*0b57cec5SDimitry Andric         if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1095*0b57cec5SDimitry Andric 
1096*0b57cec5SDimitry Andric         if (isa<ExplicitCastExpr>(CE)) {
1097*0b57cec5SDimitry Andric           LValueBaseInfo TargetTypeBaseInfo;
1098*0b57cec5SDimitry Andric           TBAAAccessInfo TargetTypeTBAAInfo;
10995ffd83dbSDimitry Andric           CharUnits Align = CGM.getNaturalPointeeTypeAlignment(
11005ffd83dbSDimitry Andric               E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1101*0b57cec5SDimitry Andric           if (TBAAInfo)
1102*0b57cec5SDimitry Andric             *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
1103*0b57cec5SDimitry Andric                                                  TargetTypeTBAAInfo);
1104*0b57cec5SDimitry Andric           // If the source l-value is opaque, honor the alignment of the
1105*0b57cec5SDimitry Andric           // casted-to type.
1106*0b57cec5SDimitry Andric           if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1107*0b57cec5SDimitry Andric             if (BaseInfo)
1108*0b57cec5SDimitry Andric               BaseInfo->mergeForCast(TargetTypeBaseInfo);
1109*0b57cec5SDimitry Andric             Addr = Address(Addr.getPointer(), Align);
1110*0b57cec5SDimitry Andric           }
1111*0b57cec5SDimitry Andric         }
1112*0b57cec5SDimitry Andric 
1113*0b57cec5SDimitry Andric         if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1114*0b57cec5SDimitry Andric             CE->getCastKind() == CK_BitCast) {
1115*0b57cec5SDimitry Andric           if (auto PT = E->getType()->getAs<PointerType>())
1116*0b57cec5SDimitry Andric             EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
1117*0b57cec5SDimitry Andric                                       /*MayBeNull=*/true,
1118*0b57cec5SDimitry Andric                                       CodeGenFunction::CFITCK_UnrelatedCast,
1119*0b57cec5SDimitry Andric                                       CE->getBeginLoc());
1120*0b57cec5SDimitry Andric         }
1121*0b57cec5SDimitry Andric         return CE->getCastKind() != CK_AddressSpaceConversion
1122*0b57cec5SDimitry Andric                    ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
1123*0b57cec5SDimitry Andric                    : Builder.CreateAddrSpaceCast(Addr,
1124*0b57cec5SDimitry Andric                                                  ConvertType(E->getType()));
1125*0b57cec5SDimitry Andric       }
1126*0b57cec5SDimitry Andric       break;
1127*0b57cec5SDimitry Andric 
1128*0b57cec5SDimitry Andric     // Array-to-pointer decay.
1129*0b57cec5SDimitry Andric     case CK_ArrayToPointerDecay:
1130*0b57cec5SDimitry Andric       return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1131*0b57cec5SDimitry Andric 
1132*0b57cec5SDimitry Andric     // Derived-to-base conversions.
1133*0b57cec5SDimitry Andric     case CK_UncheckedDerivedToBase:
1134*0b57cec5SDimitry Andric     case CK_DerivedToBase: {
1135*0b57cec5SDimitry Andric       // TODO: Support accesses to members of base classes in TBAA. For now, we
1136*0b57cec5SDimitry Andric       // conservatively pretend that the complete object is of the base class
1137*0b57cec5SDimitry Andric       // type.
1138*0b57cec5SDimitry Andric       if (TBAAInfo)
1139*0b57cec5SDimitry Andric         *TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
1140*0b57cec5SDimitry Andric       Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
1141*0b57cec5SDimitry Andric       auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1142*0b57cec5SDimitry Andric       return GetAddressOfBaseClass(Addr, Derived,
1143*0b57cec5SDimitry Andric                                    CE->path_begin(), CE->path_end(),
1144*0b57cec5SDimitry Andric                                    ShouldNullCheckClassCastValue(CE),
1145*0b57cec5SDimitry Andric                                    CE->getExprLoc());
1146*0b57cec5SDimitry Andric     }
1147*0b57cec5SDimitry Andric 
1148*0b57cec5SDimitry Andric     // TODO: Is there any reason to treat base-to-derived conversions
1149*0b57cec5SDimitry Andric     // specially?
1150*0b57cec5SDimitry Andric     default:
1151*0b57cec5SDimitry Andric       break;
1152*0b57cec5SDimitry Andric     }
1153*0b57cec5SDimitry Andric   }
1154*0b57cec5SDimitry Andric 
1155*0b57cec5SDimitry Andric   // Unary &.
1156*0b57cec5SDimitry Andric   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1157*0b57cec5SDimitry Andric     if (UO->getOpcode() == UO_AddrOf) {
1158*0b57cec5SDimitry Andric       LValue LV = EmitLValue(UO->getSubExpr());
1159*0b57cec5SDimitry Andric       if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1160*0b57cec5SDimitry Andric       if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1161480093f4SDimitry Andric       return LV.getAddress(*this);
1162*0b57cec5SDimitry Andric     }
1163*0b57cec5SDimitry Andric   }
1164*0b57cec5SDimitry Andric 
1165*0b57cec5SDimitry Andric   // TODO: conditional operators, comma.
1166*0b57cec5SDimitry Andric 
1167*0b57cec5SDimitry Andric   // Otherwise, use the alignment of the type.
11685ffd83dbSDimitry Andric   CharUnits Align =
11695ffd83dbSDimitry Andric       CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo, TBAAInfo);
1170*0b57cec5SDimitry Andric   return Address(EmitScalarExpr(E), Align);
1171*0b57cec5SDimitry Andric }
1172*0b57cec5SDimitry Andric 
1173*0b57cec5SDimitry Andric RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
1174*0b57cec5SDimitry Andric   if (Ty->isVoidType())
1175*0b57cec5SDimitry Andric     return RValue::get(nullptr);
1176*0b57cec5SDimitry Andric 
1177*0b57cec5SDimitry Andric   switch (getEvaluationKind(Ty)) {
1178*0b57cec5SDimitry Andric   case TEK_Complex: {
1179*0b57cec5SDimitry Andric     llvm::Type *EltTy =
1180*0b57cec5SDimitry Andric       ConvertType(Ty->castAs<ComplexType>()->getElementType());
1181*0b57cec5SDimitry Andric     llvm::Value *U = llvm::UndefValue::get(EltTy);
1182*0b57cec5SDimitry Andric     return RValue::getComplex(std::make_pair(U, U));
1183*0b57cec5SDimitry Andric   }
1184*0b57cec5SDimitry Andric 
1185*0b57cec5SDimitry Andric   // If this is a use of an undefined aggregate type, the aggregate must have an
1186*0b57cec5SDimitry Andric   // identifiable address.  Just because the contents of the value are undefined
1187*0b57cec5SDimitry Andric   // doesn't mean that the address can't be taken and compared.
1188*0b57cec5SDimitry Andric   case TEK_Aggregate: {
1189*0b57cec5SDimitry Andric     Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1190*0b57cec5SDimitry Andric     return RValue::getAggregate(DestPtr);
1191*0b57cec5SDimitry Andric   }
1192*0b57cec5SDimitry Andric 
1193*0b57cec5SDimitry Andric   case TEK_Scalar:
1194*0b57cec5SDimitry Andric     return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1195*0b57cec5SDimitry Andric   }
1196*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
1197*0b57cec5SDimitry Andric }
1198*0b57cec5SDimitry Andric 
1199*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1200*0b57cec5SDimitry Andric                                               const char *Name) {
1201*0b57cec5SDimitry Andric   ErrorUnsupported(E, Name);
1202*0b57cec5SDimitry Andric   return GetUndefRValue(E->getType());
1203*0b57cec5SDimitry Andric }
1204*0b57cec5SDimitry Andric 
1205*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1206*0b57cec5SDimitry Andric                                               const char *Name) {
1207*0b57cec5SDimitry Andric   ErrorUnsupported(E, Name);
1208*0b57cec5SDimitry Andric   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
1209*0b57cec5SDimitry Andric   return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1210*0b57cec5SDimitry Andric                         E->getType());
1211*0b57cec5SDimitry Andric }
1212*0b57cec5SDimitry Andric 
1213*0b57cec5SDimitry Andric bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
1214*0b57cec5SDimitry Andric   const Expr *Base = Obj;
1215*0b57cec5SDimitry Andric   while (!isa<CXXThisExpr>(Base)) {
1216*0b57cec5SDimitry Andric     // The result of a dynamic_cast can be null.
1217*0b57cec5SDimitry Andric     if (isa<CXXDynamicCastExpr>(Base))
1218*0b57cec5SDimitry Andric       return false;
1219*0b57cec5SDimitry Andric 
1220*0b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1221*0b57cec5SDimitry Andric       Base = CE->getSubExpr();
1222*0b57cec5SDimitry Andric     } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1223*0b57cec5SDimitry Andric       Base = PE->getSubExpr();
1224*0b57cec5SDimitry Andric     } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1225*0b57cec5SDimitry Andric       if (UO->getOpcode() == UO_Extension)
1226*0b57cec5SDimitry Andric         Base = UO->getSubExpr();
1227*0b57cec5SDimitry Andric       else
1228*0b57cec5SDimitry Andric         return false;
1229*0b57cec5SDimitry Andric     } else {
1230*0b57cec5SDimitry Andric       return false;
1231*0b57cec5SDimitry Andric     }
1232*0b57cec5SDimitry Andric   }
1233*0b57cec5SDimitry Andric   return true;
1234*0b57cec5SDimitry Andric }
1235*0b57cec5SDimitry Andric 
1236*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1237*0b57cec5SDimitry Andric   LValue LV;
1238*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1239*0b57cec5SDimitry Andric     LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1240*0b57cec5SDimitry Andric   else
1241*0b57cec5SDimitry Andric     LV = EmitLValue(E);
1242*0b57cec5SDimitry Andric   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1243*0b57cec5SDimitry Andric     SanitizerSet SkippedChecks;
1244*0b57cec5SDimitry Andric     if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1245*0b57cec5SDimitry Andric       bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1246*0b57cec5SDimitry Andric       if (IsBaseCXXThis)
1247*0b57cec5SDimitry Andric         SkippedChecks.set(SanitizerKind::Alignment, true);
1248*0b57cec5SDimitry Andric       if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1249*0b57cec5SDimitry Andric         SkippedChecks.set(SanitizerKind::Null, true);
1250*0b57cec5SDimitry Andric     }
1251480093f4SDimitry Andric     EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
1252480093f4SDimitry Andric                   LV.getAlignment(), SkippedChecks);
1253*0b57cec5SDimitry Andric   }
1254*0b57cec5SDimitry Andric   return LV;
1255*0b57cec5SDimitry Andric }
1256*0b57cec5SDimitry Andric 
1257*0b57cec5SDimitry Andric /// EmitLValue - Emit code to compute a designator that specifies the location
1258*0b57cec5SDimitry Andric /// of the expression.
1259*0b57cec5SDimitry Andric ///
1260*0b57cec5SDimitry Andric /// This can return one of two things: a simple address or a bitfield reference.
1261*0b57cec5SDimitry Andric /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1262*0b57cec5SDimitry Andric /// an LLVM pointer type.
1263*0b57cec5SDimitry Andric ///
1264*0b57cec5SDimitry Andric /// If this returns a bitfield reference, nothing about the pointee type of the
1265*0b57cec5SDimitry Andric /// LLVM value is known: For example, it may not be a pointer to an integer.
1266*0b57cec5SDimitry Andric ///
1267*0b57cec5SDimitry Andric /// If this returns a normal address, and if the lvalue's C type is fixed size,
1268*0b57cec5SDimitry Andric /// this method guarantees that the returned pointer type will point to an LLVM
1269*0b57cec5SDimitry Andric /// type of the same size of the lvalue's type.  If the lvalue has a variable
1270*0b57cec5SDimitry Andric /// length type, this is not possible.
1271*0b57cec5SDimitry Andric ///
1272*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValue(const Expr *E) {
1273*0b57cec5SDimitry Andric   ApplyDebugLocation DL(*this, E);
1274*0b57cec5SDimitry Andric   switch (E->getStmtClass()) {
1275*0b57cec5SDimitry Andric   default: return EmitUnsupportedLValue(E, "l-value expression");
1276*0b57cec5SDimitry Andric 
1277*0b57cec5SDimitry Andric   case Expr::ObjCPropertyRefExprClass:
1278*0b57cec5SDimitry Andric     llvm_unreachable("cannot emit a property reference directly");
1279*0b57cec5SDimitry Andric 
1280*0b57cec5SDimitry Andric   case Expr::ObjCSelectorExprClass:
1281*0b57cec5SDimitry Andric     return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1282*0b57cec5SDimitry Andric   case Expr::ObjCIsaExprClass:
1283*0b57cec5SDimitry Andric     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1284*0b57cec5SDimitry Andric   case Expr::BinaryOperatorClass:
1285*0b57cec5SDimitry Andric     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1286*0b57cec5SDimitry Andric   case Expr::CompoundAssignOperatorClass: {
1287*0b57cec5SDimitry Andric     QualType Ty = E->getType();
1288*0b57cec5SDimitry Andric     if (const AtomicType *AT = Ty->getAs<AtomicType>())
1289*0b57cec5SDimitry Andric       Ty = AT->getValueType();
1290*0b57cec5SDimitry Andric     if (!Ty->isAnyComplexType())
1291*0b57cec5SDimitry Andric       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1292*0b57cec5SDimitry Andric     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1293*0b57cec5SDimitry Andric   }
1294*0b57cec5SDimitry Andric   case Expr::CallExprClass:
1295*0b57cec5SDimitry Andric   case Expr::CXXMemberCallExprClass:
1296*0b57cec5SDimitry Andric   case Expr::CXXOperatorCallExprClass:
1297*0b57cec5SDimitry Andric   case Expr::UserDefinedLiteralClass:
1298*0b57cec5SDimitry Andric     return EmitCallExprLValue(cast<CallExpr>(E));
1299a7dea167SDimitry Andric   case Expr::CXXRewrittenBinaryOperatorClass:
1300a7dea167SDimitry Andric     return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm());
1301*0b57cec5SDimitry Andric   case Expr::VAArgExprClass:
1302*0b57cec5SDimitry Andric     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1303*0b57cec5SDimitry Andric   case Expr::DeclRefExprClass:
1304*0b57cec5SDimitry Andric     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
13055ffd83dbSDimitry Andric   case Expr::ConstantExprClass: {
13065ffd83dbSDimitry Andric     const ConstantExpr *CE = cast<ConstantExpr>(E);
13075ffd83dbSDimitry Andric     if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
13085ffd83dbSDimitry Andric       QualType RetType = cast<CallExpr>(CE->getSubExpr()->IgnoreImplicit())
13095ffd83dbSDimitry Andric                              ->getCallReturnType(getContext());
13105ffd83dbSDimitry Andric       return MakeNaturalAlignAddrLValue(Result, RetType);
13115ffd83dbSDimitry Andric     }
1312*0b57cec5SDimitry Andric     return EmitLValue(cast<ConstantExpr>(E)->getSubExpr());
13135ffd83dbSDimitry Andric   }
1314*0b57cec5SDimitry Andric   case Expr::ParenExprClass:
1315*0b57cec5SDimitry Andric     return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1316*0b57cec5SDimitry Andric   case Expr::GenericSelectionExprClass:
1317*0b57cec5SDimitry Andric     return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1318*0b57cec5SDimitry Andric   case Expr::PredefinedExprClass:
1319*0b57cec5SDimitry Andric     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1320*0b57cec5SDimitry Andric   case Expr::StringLiteralClass:
1321*0b57cec5SDimitry Andric     return EmitStringLiteralLValue(cast<StringLiteral>(E));
1322*0b57cec5SDimitry Andric   case Expr::ObjCEncodeExprClass:
1323*0b57cec5SDimitry Andric     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1324*0b57cec5SDimitry Andric   case Expr::PseudoObjectExprClass:
1325*0b57cec5SDimitry Andric     return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1326*0b57cec5SDimitry Andric   case Expr::InitListExprClass:
1327*0b57cec5SDimitry Andric     return EmitInitListLValue(cast<InitListExpr>(E));
1328*0b57cec5SDimitry Andric   case Expr::CXXTemporaryObjectExprClass:
1329*0b57cec5SDimitry Andric   case Expr::CXXConstructExprClass:
1330*0b57cec5SDimitry Andric     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1331*0b57cec5SDimitry Andric   case Expr::CXXBindTemporaryExprClass:
1332*0b57cec5SDimitry Andric     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1333*0b57cec5SDimitry Andric   case Expr::CXXUuidofExprClass:
1334*0b57cec5SDimitry Andric     return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1335*0b57cec5SDimitry Andric   case Expr::LambdaExprClass:
1336*0b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
1337*0b57cec5SDimitry Andric 
1338*0b57cec5SDimitry Andric   case Expr::ExprWithCleanupsClass: {
1339*0b57cec5SDimitry Andric     const auto *cleanups = cast<ExprWithCleanups>(E);
1340*0b57cec5SDimitry Andric     RunCleanupsScope Scope(*this);
1341*0b57cec5SDimitry Andric     LValue LV = EmitLValue(cleanups->getSubExpr());
1342*0b57cec5SDimitry Andric     if (LV.isSimple()) {
1343*0b57cec5SDimitry Andric       // Defend against branches out of gnu statement expressions surrounded by
1344*0b57cec5SDimitry Andric       // cleanups.
1345480093f4SDimitry Andric       llvm::Value *V = LV.getPointer(*this);
1346*0b57cec5SDimitry Andric       Scope.ForceCleanup({&V});
1347*0b57cec5SDimitry Andric       return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1348*0b57cec5SDimitry Andric                               getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
1349*0b57cec5SDimitry Andric     }
1350*0b57cec5SDimitry Andric     // FIXME: Is it possible to create an ExprWithCleanups that produces a
1351*0b57cec5SDimitry Andric     // bitfield lvalue or some other non-simple lvalue?
1352*0b57cec5SDimitry Andric     return LV;
1353*0b57cec5SDimitry Andric   }
1354*0b57cec5SDimitry Andric 
1355*0b57cec5SDimitry Andric   case Expr::CXXDefaultArgExprClass: {
1356*0b57cec5SDimitry Andric     auto *DAE = cast<CXXDefaultArgExpr>(E);
1357*0b57cec5SDimitry Andric     CXXDefaultArgExprScope Scope(*this, DAE);
1358*0b57cec5SDimitry Andric     return EmitLValue(DAE->getExpr());
1359*0b57cec5SDimitry Andric   }
1360*0b57cec5SDimitry Andric   case Expr::CXXDefaultInitExprClass: {
1361*0b57cec5SDimitry Andric     auto *DIE = cast<CXXDefaultInitExpr>(E);
1362*0b57cec5SDimitry Andric     CXXDefaultInitExprScope Scope(*this, DIE);
1363*0b57cec5SDimitry Andric     return EmitLValue(DIE->getExpr());
1364*0b57cec5SDimitry Andric   }
1365*0b57cec5SDimitry Andric   case Expr::CXXTypeidExprClass:
1366*0b57cec5SDimitry Andric     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1367*0b57cec5SDimitry Andric 
1368*0b57cec5SDimitry Andric   case Expr::ObjCMessageExprClass:
1369*0b57cec5SDimitry Andric     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1370*0b57cec5SDimitry Andric   case Expr::ObjCIvarRefExprClass:
1371*0b57cec5SDimitry Andric     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1372*0b57cec5SDimitry Andric   case Expr::StmtExprClass:
1373*0b57cec5SDimitry Andric     return EmitStmtExprLValue(cast<StmtExpr>(E));
1374*0b57cec5SDimitry Andric   case Expr::UnaryOperatorClass:
1375*0b57cec5SDimitry Andric     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1376*0b57cec5SDimitry Andric   case Expr::ArraySubscriptExprClass:
1377*0b57cec5SDimitry Andric     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
13785ffd83dbSDimitry Andric   case Expr::MatrixSubscriptExprClass:
13795ffd83dbSDimitry Andric     return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
1380*0b57cec5SDimitry Andric   case Expr::OMPArraySectionExprClass:
1381*0b57cec5SDimitry Andric     return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1382*0b57cec5SDimitry Andric   case Expr::ExtVectorElementExprClass:
1383*0b57cec5SDimitry Andric     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1384*0b57cec5SDimitry Andric   case Expr::MemberExprClass:
1385*0b57cec5SDimitry Andric     return EmitMemberExpr(cast<MemberExpr>(E));
1386*0b57cec5SDimitry Andric   case Expr::CompoundLiteralExprClass:
1387*0b57cec5SDimitry Andric     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1388*0b57cec5SDimitry Andric   case Expr::ConditionalOperatorClass:
1389*0b57cec5SDimitry Andric     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1390*0b57cec5SDimitry Andric   case Expr::BinaryConditionalOperatorClass:
1391*0b57cec5SDimitry Andric     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1392*0b57cec5SDimitry Andric   case Expr::ChooseExprClass:
1393*0b57cec5SDimitry Andric     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1394*0b57cec5SDimitry Andric   case Expr::OpaqueValueExprClass:
1395*0b57cec5SDimitry Andric     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1396*0b57cec5SDimitry Andric   case Expr::SubstNonTypeTemplateParmExprClass:
1397*0b57cec5SDimitry Andric     return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1398*0b57cec5SDimitry Andric   case Expr::ImplicitCastExprClass:
1399*0b57cec5SDimitry Andric   case Expr::CStyleCastExprClass:
1400*0b57cec5SDimitry Andric   case Expr::CXXFunctionalCastExprClass:
1401*0b57cec5SDimitry Andric   case Expr::CXXStaticCastExprClass:
1402*0b57cec5SDimitry Andric   case Expr::CXXDynamicCastExprClass:
1403*0b57cec5SDimitry Andric   case Expr::CXXReinterpretCastExprClass:
1404*0b57cec5SDimitry Andric   case Expr::CXXConstCastExprClass:
14055ffd83dbSDimitry Andric   case Expr::CXXAddrspaceCastExprClass:
1406*0b57cec5SDimitry Andric   case Expr::ObjCBridgedCastExprClass:
1407*0b57cec5SDimitry Andric     return EmitCastLValue(cast<CastExpr>(E));
1408*0b57cec5SDimitry Andric 
1409*0b57cec5SDimitry Andric   case Expr::MaterializeTemporaryExprClass:
1410*0b57cec5SDimitry Andric     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1411*0b57cec5SDimitry Andric 
1412*0b57cec5SDimitry Andric   case Expr::CoawaitExprClass:
1413*0b57cec5SDimitry Andric     return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1414*0b57cec5SDimitry Andric   case Expr::CoyieldExprClass:
1415*0b57cec5SDimitry Andric     return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1416*0b57cec5SDimitry Andric   }
1417*0b57cec5SDimitry Andric }
1418*0b57cec5SDimitry Andric 
1419*0b57cec5SDimitry Andric /// Given an object of the given canonical type, can we safely copy a
1420*0b57cec5SDimitry Andric /// value out of it based on its initializer?
1421*0b57cec5SDimitry Andric static bool isConstantEmittableObjectType(QualType type) {
1422*0b57cec5SDimitry Andric   assert(type.isCanonical());
1423*0b57cec5SDimitry Andric   assert(!type->isReferenceType());
1424*0b57cec5SDimitry Andric 
1425*0b57cec5SDimitry Andric   // Must be const-qualified but non-volatile.
1426*0b57cec5SDimitry Andric   Qualifiers qs = type.getLocalQualifiers();
1427*0b57cec5SDimitry Andric   if (!qs.hasConst() || qs.hasVolatile()) return false;
1428*0b57cec5SDimitry Andric 
1429*0b57cec5SDimitry Andric   // Otherwise, all object types satisfy this except C++ classes with
1430*0b57cec5SDimitry Andric   // mutable subobjects or non-trivial copy/destroy behavior.
1431*0b57cec5SDimitry Andric   if (const auto *RT = dyn_cast<RecordType>(type))
1432*0b57cec5SDimitry Andric     if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1433*0b57cec5SDimitry Andric       if (RD->hasMutableFields() || !RD->isTrivial())
1434*0b57cec5SDimitry Andric         return false;
1435*0b57cec5SDimitry Andric 
1436*0b57cec5SDimitry Andric   return true;
1437*0b57cec5SDimitry Andric }
1438*0b57cec5SDimitry Andric 
1439*0b57cec5SDimitry Andric /// Can we constant-emit a load of a reference to a variable of the
1440*0b57cec5SDimitry Andric /// given type?  This is different from predicates like
1441*0b57cec5SDimitry Andric /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
1442*0b57cec5SDimitry Andric /// in situations that don't necessarily satisfy the language's rules
1443*0b57cec5SDimitry Andric /// for this (e.g. C++'s ODR-use rules).  For example, we want to able
1444*0b57cec5SDimitry Andric /// to do this with const float variables even if those variables
1445*0b57cec5SDimitry Andric /// aren't marked 'constexpr'.
1446*0b57cec5SDimitry Andric enum ConstantEmissionKind {
1447*0b57cec5SDimitry Andric   CEK_None,
1448*0b57cec5SDimitry Andric   CEK_AsReferenceOnly,
1449*0b57cec5SDimitry Andric   CEK_AsValueOrReference,
1450*0b57cec5SDimitry Andric   CEK_AsValueOnly
1451*0b57cec5SDimitry Andric };
1452*0b57cec5SDimitry Andric static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1453*0b57cec5SDimitry Andric   type = type.getCanonicalType();
1454*0b57cec5SDimitry Andric   if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1455*0b57cec5SDimitry Andric     if (isConstantEmittableObjectType(ref->getPointeeType()))
1456*0b57cec5SDimitry Andric       return CEK_AsValueOrReference;
1457*0b57cec5SDimitry Andric     return CEK_AsReferenceOnly;
1458*0b57cec5SDimitry Andric   }
1459*0b57cec5SDimitry Andric   if (isConstantEmittableObjectType(type))
1460*0b57cec5SDimitry Andric     return CEK_AsValueOnly;
1461*0b57cec5SDimitry Andric   return CEK_None;
1462*0b57cec5SDimitry Andric }
1463*0b57cec5SDimitry Andric 
1464*0b57cec5SDimitry Andric /// Try to emit a reference to the given value without producing it as
1465*0b57cec5SDimitry Andric /// an l-value.  This is just an optimization, but it avoids us needing
1466*0b57cec5SDimitry Andric /// to emit global copies of variables if they're named without triggering
1467*0b57cec5SDimitry Andric /// a formal use in a context where we can't emit a direct reference to them,
1468*0b57cec5SDimitry Andric /// for instance if a block or lambda or a member of a local class uses a
1469*0b57cec5SDimitry Andric /// const int variable or constexpr variable from an enclosing function.
1470*0b57cec5SDimitry Andric CodeGenFunction::ConstantEmission
1471*0b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1472*0b57cec5SDimitry Andric   ValueDecl *value = refExpr->getDecl();
1473*0b57cec5SDimitry Andric 
1474*0b57cec5SDimitry Andric   // The value needs to be an enum constant or a constant variable.
1475*0b57cec5SDimitry Andric   ConstantEmissionKind CEK;
1476*0b57cec5SDimitry Andric   if (isa<ParmVarDecl>(value)) {
1477*0b57cec5SDimitry Andric     CEK = CEK_None;
1478*0b57cec5SDimitry Andric   } else if (auto *var = dyn_cast<VarDecl>(value)) {
1479*0b57cec5SDimitry Andric     CEK = checkVarTypeForConstantEmission(var->getType());
1480*0b57cec5SDimitry Andric   } else if (isa<EnumConstantDecl>(value)) {
1481*0b57cec5SDimitry Andric     CEK = CEK_AsValueOnly;
1482*0b57cec5SDimitry Andric   } else {
1483*0b57cec5SDimitry Andric     CEK = CEK_None;
1484*0b57cec5SDimitry Andric   }
1485*0b57cec5SDimitry Andric   if (CEK == CEK_None) return ConstantEmission();
1486*0b57cec5SDimitry Andric 
1487*0b57cec5SDimitry Andric   Expr::EvalResult result;
1488*0b57cec5SDimitry Andric   bool resultIsReference;
1489*0b57cec5SDimitry Andric   QualType resultType;
1490*0b57cec5SDimitry Andric 
1491*0b57cec5SDimitry Andric   // It's best to evaluate all the way as an r-value if that's permitted.
1492*0b57cec5SDimitry Andric   if (CEK != CEK_AsReferenceOnly &&
1493*0b57cec5SDimitry Andric       refExpr->EvaluateAsRValue(result, getContext())) {
1494*0b57cec5SDimitry Andric     resultIsReference = false;
1495*0b57cec5SDimitry Andric     resultType = refExpr->getType();
1496*0b57cec5SDimitry Andric 
1497*0b57cec5SDimitry Andric   // Otherwise, try to evaluate as an l-value.
1498*0b57cec5SDimitry Andric   } else if (CEK != CEK_AsValueOnly &&
1499*0b57cec5SDimitry Andric              refExpr->EvaluateAsLValue(result, getContext())) {
1500*0b57cec5SDimitry Andric     resultIsReference = true;
1501*0b57cec5SDimitry Andric     resultType = value->getType();
1502*0b57cec5SDimitry Andric 
1503*0b57cec5SDimitry Andric   // Failure.
1504*0b57cec5SDimitry Andric   } else {
1505*0b57cec5SDimitry Andric     return ConstantEmission();
1506*0b57cec5SDimitry Andric   }
1507*0b57cec5SDimitry Andric 
1508*0b57cec5SDimitry Andric   // In any case, if the initializer has side-effects, abandon ship.
1509*0b57cec5SDimitry Andric   if (result.HasSideEffects)
1510*0b57cec5SDimitry Andric     return ConstantEmission();
1511*0b57cec5SDimitry Andric 
1512*0b57cec5SDimitry Andric   // Emit as a constant.
1513*0b57cec5SDimitry Andric   auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1514*0b57cec5SDimitry Andric                                                result.Val, resultType);
1515*0b57cec5SDimitry Andric 
1516*0b57cec5SDimitry Andric   // Make sure we emit a debug reference to the global variable.
1517*0b57cec5SDimitry Andric   // This should probably fire even for
1518*0b57cec5SDimitry Andric   if (isa<VarDecl>(value)) {
1519*0b57cec5SDimitry Andric     if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1520*0b57cec5SDimitry Andric       EmitDeclRefExprDbgValue(refExpr, result.Val);
1521*0b57cec5SDimitry Andric   } else {
1522*0b57cec5SDimitry Andric     assert(isa<EnumConstantDecl>(value));
1523*0b57cec5SDimitry Andric     EmitDeclRefExprDbgValue(refExpr, result.Val);
1524*0b57cec5SDimitry Andric   }
1525*0b57cec5SDimitry Andric 
1526*0b57cec5SDimitry Andric   // If we emitted a reference constant, we need to dereference that.
1527*0b57cec5SDimitry Andric   if (resultIsReference)
1528*0b57cec5SDimitry Andric     return ConstantEmission::forReference(C);
1529*0b57cec5SDimitry Andric 
1530*0b57cec5SDimitry Andric   return ConstantEmission::forValue(C);
1531*0b57cec5SDimitry Andric }
1532*0b57cec5SDimitry Andric 
1533*0b57cec5SDimitry Andric static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1534*0b57cec5SDimitry Andric                                                         const MemberExpr *ME) {
1535*0b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1536*0b57cec5SDimitry Andric     // Try to emit static variable member expressions as DREs.
1537*0b57cec5SDimitry Andric     return DeclRefExpr::Create(
1538*0b57cec5SDimitry Andric         CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1539*0b57cec5SDimitry Andric         /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1540*0b57cec5SDimitry Andric         ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
1541*0b57cec5SDimitry Andric   }
1542*0b57cec5SDimitry Andric   return nullptr;
1543*0b57cec5SDimitry Andric }
1544*0b57cec5SDimitry Andric 
1545*0b57cec5SDimitry Andric CodeGenFunction::ConstantEmission
1546*0b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1547*0b57cec5SDimitry Andric   if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1548*0b57cec5SDimitry Andric     return tryEmitAsConstant(DRE);
1549*0b57cec5SDimitry Andric   return ConstantEmission();
1550*0b57cec5SDimitry Andric }
1551*0b57cec5SDimitry Andric 
1552*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::emitScalarConstant(
1553*0b57cec5SDimitry Andric     const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
1554*0b57cec5SDimitry Andric   assert(Constant && "not a constant");
1555*0b57cec5SDimitry Andric   if (Constant.isReference())
1556*0b57cec5SDimitry Andric     return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
1557*0b57cec5SDimitry Andric                             E->getExprLoc())
1558*0b57cec5SDimitry Andric         .getScalarVal();
1559*0b57cec5SDimitry Andric   return Constant.getValue();
1560*0b57cec5SDimitry Andric }
1561*0b57cec5SDimitry Andric 
1562*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1563*0b57cec5SDimitry Andric                                                SourceLocation Loc) {
1564480093f4SDimitry Andric   return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
1565*0b57cec5SDimitry Andric                           lvalue.getType(), Loc, lvalue.getBaseInfo(),
1566*0b57cec5SDimitry Andric                           lvalue.getTBAAInfo(), lvalue.isNontemporal());
1567*0b57cec5SDimitry Andric }
1568*0b57cec5SDimitry Andric 
1569*0b57cec5SDimitry Andric static bool hasBooleanRepresentation(QualType Ty) {
1570*0b57cec5SDimitry Andric   if (Ty->isBooleanType())
1571*0b57cec5SDimitry Andric     return true;
1572*0b57cec5SDimitry Andric 
1573*0b57cec5SDimitry Andric   if (const EnumType *ET = Ty->getAs<EnumType>())
1574*0b57cec5SDimitry Andric     return ET->getDecl()->getIntegerType()->isBooleanType();
1575*0b57cec5SDimitry Andric 
1576*0b57cec5SDimitry Andric   if (const AtomicType *AT = Ty->getAs<AtomicType>())
1577*0b57cec5SDimitry Andric     return hasBooleanRepresentation(AT->getValueType());
1578*0b57cec5SDimitry Andric 
1579*0b57cec5SDimitry Andric   return false;
1580*0b57cec5SDimitry Andric }
1581*0b57cec5SDimitry Andric 
1582*0b57cec5SDimitry Andric static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1583*0b57cec5SDimitry Andric                             llvm::APInt &Min, llvm::APInt &End,
1584*0b57cec5SDimitry Andric                             bool StrictEnums, bool IsBool) {
1585*0b57cec5SDimitry Andric   const EnumType *ET = Ty->getAs<EnumType>();
1586*0b57cec5SDimitry Andric   bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1587*0b57cec5SDimitry Andric                                 ET && !ET->getDecl()->isFixed();
1588*0b57cec5SDimitry Andric   if (!IsBool && !IsRegularCPlusPlusEnum)
1589*0b57cec5SDimitry Andric     return false;
1590*0b57cec5SDimitry Andric 
1591*0b57cec5SDimitry Andric   if (IsBool) {
1592*0b57cec5SDimitry Andric     Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1593*0b57cec5SDimitry Andric     End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1594*0b57cec5SDimitry Andric   } else {
1595*0b57cec5SDimitry Andric     const EnumDecl *ED = ET->getDecl();
1596*0b57cec5SDimitry Andric     llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1597*0b57cec5SDimitry Andric     unsigned Bitwidth = LTy->getScalarSizeInBits();
1598*0b57cec5SDimitry Andric     unsigned NumNegativeBits = ED->getNumNegativeBits();
1599*0b57cec5SDimitry Andric     unsigned NumPositiveBits = ED->getNumPositiveBits();
1600*0b57cec5SDimitry Andric 
1601*0b57cec5SDimitry Andric     if (NumNegativeBits) {
1602*0b57cec5SDimitry Andric       unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1603*0b57cec5SDimitry Andric       assert(NumBits <= Bitwidth);
1604*0b57cec5SDimitry Andric       End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1605*0b57cec5SDimitry Andric       Min = -End;
1606*0b57cec5SDimitry Andric     } else {
1607*0b57cec5SDimitry Andric       assert(NumPositiveBits <= Bitwidth);
1608*0b57cec5SDimitry Andric       End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1609*0b57cec5SDimitry Andric       Min = llvm::APInt(Bitwidth, 0);
1610*0b57cec5SDimitry Andric     }
1611*0b57cec5SDimitry Andric   }
1612*0b57cec5SDimitry Andric   return true;
1613*0b57cec5SDimitry Andric }
1614*0b57cec5SDimitry Andric 
1615*0b57cec5SDimitry Andric llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1616*0b57cec5SDimitry Andric   llvm::APInt Min, End;
1617*0b57cec5SDimitry Andric   if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1618*0b57cec5SDimitry Andric                        hasBooleanRepresentation(Ty)))
1619*0b57cec5SDimitry Andric     return nullptr;
1620*0b57cec5SDimitry Andric 
1621*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
1622*0b57cec5SDimitry Andric   return MDHelper.createRange(Min, End);
1623*0b57cec5SDimitry Andric }
1624*0b57cec5SDimitry Andric 
1625*0b57cec5SDimitry Andric bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1626*0b57cec5SDimitry Andric                                            SourceLocation Loc) {
1627*0b57cec5SDimitry Andric   bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1628*0b57cec5SDimitry Andric   bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1629*0b57cec5SDimitry Andric   if (!HasBoolCheck && !HasEnumCheck)
1630*0b57cec5SDimitry Andric     return false;
1631*0b57cec5SDimitry Andric 
1632*0b57cec5SDimitry Andric   bool IsBool = hasBooleanRepresentation(Ty) ||
1633*0b57cec5SDimitry Andric                 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1634*0b57cec5SDimitry Andric   bool NeedsBoolCheck = HasBoolCheck && IsBool;
1635*0b57cec5SDimitry Andric   bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1636*0b57cec5SDimitry Andric   if (!NeedsBoolCheck && !NeedsEnumCheck)
1637*0b57cec5SDimitry Andric     return false;
1638*0b57cec5SDimitry Andric 
1639*0b57cec5SDimitry Andric   // Single-bit booleans don't need to be checked. Special-case this to avoid
1640*0b57cec5SDimitry Andric   // a bit width mismatch when handling bitfield values. This is handled by
1641*0b57cec5SDimitry Andric   // EmitFromMemory for the non-bitfield case.
1642*0b57cec5SDimitry Andric   if (IsBool &&
1643*0b57cec5SDimitry Andric       cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1644*0b57cec5SDimitry Andric     return false;
1645*0b57cec5SDimitry Andric 
1646*0b57cec5SDimitry Andric   llvm::APInt Min, End;
1647*0b57cec5SDimitry Andric   if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1648*0b57cec5SDimitry Andric     return true;
1649*0b57cec5SDimitry Andric 
1650*0b57cec5SDimitry Andric   auto &Ctx = getLLVMContext();
1651*0b57cec5SDimitry Andric   SanitizerScope SanScope(this);
1652*0b57cec5SDimitry Andric   llvm::Value *Check;
1653*0b57cec5SDimitry Andric   --End;
1654*0b57cec5SDimitry Andric   if (!Min) {
1655*0b57cec5SDimitry Andric     Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
1656*0b57cec5SDimitry Andric   } else {
1657*0b57cec5SDimitry Andric     llvm::Value *Upper =
1658*0b57cec5SDimitry Andric         Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1659*0b57cec5SDimitry Andric     llvm::Value *Lower =
1660*0b57cec5SDimitry Andric         Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
1661*0b57cec5SDimitry Andric     Check = Builder.CreateAnd(Upper, Lower);
1662*0b57cec5SDimitry Andric   }
1663*0b57cec5SDimitry Andric   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1664*0b57cec5SDimitry Andric                                   EmitCheckTypeDescriptor(Ty)};
1665*0b57cec5SDimitry Andric   SanitizerMask Kind =
1666*0b57cec5SDimitry Andric       NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1667*0b57cec5SDimitry Andric   EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1668*0b57cec5SDimitry Andric             StaticArgs, EmitCheckValue(Value));
1669*0b57cec5SDimitry Andric   return true;
1670*0b57cec5SDimitry Andric }
1671*0b57cec5SDimitry Andric 
1672*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1673*0b57cec5SDimitry Andric                                                QualType Ty,
1674*0b57cec5SDimitry Andric                                                SourceLocation Loc,
1675*0b57cec5SDimitry Andric                                                LValueBaseInfo BaseInfo,
1676*0b57cec5SDimitry Andric                                                TBAAAccessInfo TBAAInfo,
1677*0b57cec5SDimitry Andric                                                bool isNontemporal) {
1678*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1679*0b57cec5SDimitry Andric     // For better performance, handle vector loads differently.
1680*0b57cec5SDimitry Andric     if (Ty->isVectorType()) {
1681*0b57cec5SDimitry Andric       const llvm::Type *EltTy = Addr.getElementType();
1682*0b57cec5SDimitry Andric 
1683*0b57cec5SDimitry Andric       const auto *VTy = cast<llvm::VectorType>(EltTy);
1684*0b57cec5SDimitry Andric 
1685*0b57cec5SDimitry Andric       // Handle vectors of size 3 like size 4 for better performance.
1686*0b57cec5SDimitry Andric       if (VTy->getNumElements() == 3) {
1687*0b57cec5SDimitry Andric 
1688*0b57cec5SDimitry Andric         // Bitcast to vec4 type.
16895ffd83dbSDimitry Andric         auto *vec4Ty = llvm::FixedVectorType::get(VTy->getElementType(), 4);
1690*0b57cec5SDimitry Andric         Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1691*0b57cec5SDimitry Andric         // Now load value.
1692*0b57cec5SDimitry Andric         llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1693*0b57cec5SDimitry Andric 
1694*0b57cec5SDimitry Andric         // Shuffle vector to get vec3.
1695*0b57cec5SDimitry Andric         V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
16965ffd83dbSDimitry Andric                                         ArrayRef<int>{0, 1, 2}, "extractVec");
1697*0b57cec5SDimitry Andric         return EmitFromMemory(V, Ty);
1698*0b57cec5SDimitry Andric       }
1699*0b57cec5SDimitry Andric     }
1700*0b57cec5SDimitry Andric   }
1701*0b57cec5SDimitry Andric 
1702*0b57cec5SDimitry Andric   // Atomic operations have to be done on integral types.
1703*0b57cec5SDimitry Andric   LValue AtomicLValue =
1704*0b57cec5SDimitry Andric       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1705*0b57cec5SDimitry Andric   if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1706*0b57cec5SDimitry Andric     return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1707*0b57cec5SDimitry Andric   }
1708*0b57cec5SDimitry Andric 
1709*0b57cec5SDimitry Andric   llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1710*0b57cec5SDimitry Andric   if (isNontemporal) {
1711*0b57cec5SDimitry Andric     llvm::MDNode *Node = llvm::MDNode::get(
1712*0b57cec5SDimitry Andric         Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1713*0b57cec5SDimitry Andric     Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1714*0b57cec5SDimitry Andric   }
1715*0b57cec5SDimitry Andric 
1716*0b57cec5SDimitry Andric   CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
1717*0b57cec5SDimitry Andric 
1718*0b57cec5SDimitry Andric   if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1719*0b57cec5SDimitry Andric     // In order to prevent the optimizer from throwing away the check, don't
1720*0b57cec5SDimitry Andric     // attach range metadata to the load.
1721*0b57cec5SDimitry Andric   } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1722*0b57cec5SDimitry Andric     if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1723*0b57cec5SDimitry Andric       Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1724*0b57cec5SDimitry Andric 
1725*0b57cec5SDimitry Andric   return EmitFromMemory(Load, Ty);
1726*0b57cec5SDimitry Andric }
1727*0b57cec5SDimitry Andric 
1728*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1729*0b57cec5SDimitry Andric   // Bool has a different representation in memory than in registers.
1730*0b57cec5SDimitry Andric   if (hasBooleanRepresentation(Ty)) {
1731*0b57cec5SDimitry Andric     // This should really always be an i1, but sometimes it's already
1732*0b57cec5SDimitry Andric     // an i8, and it's awkward to track those cases down.
1733*0b57cec5SDimitry Andric     if (Value->getType()->isIntegerTy(1))
1734*0b57cec5SDimitry Andric       return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1735*0b57cec5SDimitry Andric     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1736*0b57cec5SDimitry Andric            "wrong value rep of bool");
1737*0b57cec5SDimitry Andric   }
1738*0b57cec5SDimitry Andric 
1739*0b57cec5SDimitry Andric   return Value;
1740*0b57cec5SDimitry Andric }
1741*0b57cec5SDimitry Andric 
1742*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1743*0b57cec5SDimitry Andric   // Bool has a different representation in memory than in registers.
1744*0b57cec5SDimitry Andric   if (hasBooleanRepresentation(Ty)) {
1745*0b57cec5SDimitry Andric     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1746*0b57cec5SDimitry Andric            "wrong value rep of bool");
1747*0b57cec5SDimitry Andric     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1748*0b57cec5SDimitry Andric   }
1749*0b57cec5SDimitry Andric 
1750*0b57cec5SDimitry Andric   return Value;
1751*0b57cec5SDimitry Andric }
1752*0b57cec5SDimitry Andric 
17535ffd83dbSDimitry Andric // Convert the pointer of \p Addr to a pointer to a vector (the value type of
17545ffd83dbSDimitry Andric // MatrixType), if it points to a array (the memory type of MatrixType).
17555ffd83dbSDimitry Andric static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF,
17565ffd83dbSDimitry Andric                                          bool IsVector = true) {
17575ffd83dbSDimitry Andric   auto *ArrayTy = dyn_cast<llvm::ArrayType>(
17585ffd83dbSDimitry Andric       cast<llvm::PointerType>(Addr.getPointer()->getType())->getElementType());
17595ffd83dbSDimitry Andric   if (ArrayTy && IsVector) {
17605ffd83dbSDimitry Andric     auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
17615ffd83dbSDimitry Andric                                                 ArrayTy->getNumElements());
17625ffd83dbSDimitry Andric 
17635ffd83dbSDimitry Andric     return Address(CGF.Builder.CreateElementBitCast(Addr, VectorTy));
17645ffd83dbSDimitry Andric   }
17655ffd83dbSDimitry Andric   auto *VectorTy = dyn_cast<llvm::VectorType>(
17665ffd83dbSDimitry Andric       cast<llvm::PointerType>(Addr.getPointer()->getType())->getElementType());
17675ffd83dbSDimitry Andric   if (VectorTy && !IsVector) {
17685ffd83dbSDimitry Andric     auto *ArrayTy = llvm::ArrayType::get(VectorTy->getElementType(),
17695ffd83dbSDimitry Andric                                          VectorTy->getNumElements());
17705ffd83dbSDimitry Andric 
17715ffd83dbSDimitry Andric     return Address(CGF.Builder.CreateElementBitCast(Addr, ArrayTy));
17725ffd83dbSDimitry Andric   }
17735ffd83dbSDimitry Andric 
17745ffd83dbSDimitry Andric   return Addr;
17755ffd83dbSDimitry Andric }
17765ffd83dbSDimitry Andric 
17775ffd83dbSDimitry Andric // Emit a store of a matrix LValue. This may require casting the original
17785ffd83dbSDimitry Andric // pointer to memory address (ArrayType) to a pointer to the value type
17795ffd83dbSDimitry Andric // (VectorType).
17805ffd83dbSDimitry Andric static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
17815ffd83dbSDimitry Andric                                     bool isInit, CodeGenFunction &CGF) {
17825ffd83dbSDimitry Andric   Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF,
17835ffd83dbSDimitry Andric                                            value->getType()->isVectorTy());
17845ffd83dbSDimitry Andric   CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
17855ffd83dbSDimitry Andric                         lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
17865ffd83dbSDimitry Andric                         lvalue.isNontemporal());
17875ffd83dbSDimitry Andric }
17885ffd83dbSDimitry Andric 
1789*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1790*0b57cec5SDimitry Andric                                         bool Volatile, QualType Ty,
1791*0b57cec5SDimitry Andric                                         LValueBaseInfo BaseInfo,
1792*0b57cec5SDimitry Andric                                         TBAAAccessInfo TBAAInfo,
1793*0b57cec5SDimitry Andric                                         bool isInit, bool isNontemporal) {
1794*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1795*0b57cec5SDimitry Andric     // Handle vectors differently to get better performance.
1796*0b57cec5SDimitry Andric     if (Ty->isVectorType()) {
1797*0b57cec5SDimitry Andric       llvm::Type *SrcTy = Value->getType();
1798*0b57cec5SDimitry Andric       auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
1799*0b57cec5SDimitry Andric       // Handle vec3 special.
1800*0b57cec5SDimitry Andric       if (VecTy && VecTy->getNumElements() == 3) {
1801*0b57cec5SDimitry Andric         // Our source is a vec3, do a shuffle vector to make it a vec4.
1802*0b57cec5SDimitry Andric         Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
18035ffd83dbSDimitry Andric                                             ArrayRef<int>{0, 1, 2, -1},
18045ffd83dbSDimitry Andric                                             "extractVec");
18055ffd83dbSDimitry Andric         SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
1806*0b57cec5SDimitry Andric       }
1807*0b57cec5SDimitry Andric       if (Addr.getElementType() != SrcTy) {
1808*0b57cec5SDimitry Andric         Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1809*0b57cec5SDimitry Andric       }
1810*0b57cec5SDimitry Andric     }
1811*0b57cec5SDimitry Andric   }
1812*0b57cec5SDimitry Andric 
1813*0b57cec5SDimitry Andric   Value = EmitToMemory(Value, Ty);
1814*0b57cec5SDimitry Andric 
1815*0b57cec5SDimitry Andric   LValue AtomicLValue =
1816*0b57cec5SDimitry Andric       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1817*0b57cec5SDimitry Andric   if (Ty->isAtomicType() ||
1818*0b57cec5SDimitry Andric       (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1819*0b57cec5SDimitry Andric     EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1820*0b57cec5SDimitry Andric     return;
1821*0b57cec5SDimitry Andric   }
1822*0b57cec5SDimitry Andric 
1823*0b57cec5SDimitry Andric   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1824*0b57cec5SDimitry Andric   if (isNontemporal) {
1825*0b57cec5SDimitry Andric     llvm::MDNode *Node =
1826*0b57cec5SDimitry Andric         llvm::MDNode::get(Store->getContext(),
1827*0b57cec5SDimitry Andric                           llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1828*0b57cec5SDimitry Andric     Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1829*0b57cec5SDimitry Andric   }
1830*0b57cec5SDimitry Andric 
1831*0b57cec5SDimitry Andric   CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
1832*0b57cec5SDimitry Andric }
1833*0b57cec5SDimitry Andric 
1834*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1835*0b57cec5SDimitry Andric                                         bool isInit) {
18365ffd83dbSDimitry Andric   if (lvalue.getType()->isConstantMatrixType()) {
18375ffd83dbSDimitry Andric     EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
18385ffd83dbSDimitry Andric     return;
18395ffd83dbSDimitry Andric   }
18405ffd83dbSDimitry Andric 
1841480093f4SDimitry Andric   EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
1842*0b57cec5SDimitry Andric                     lvalue.getType(), lvalue.getBaseInfo(),
1843*0b57cec5SDimitry Andric                     lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
1844*0b57cec5SDimitry Andric }
1845*0b57cec5SDimitry Andric 
18465ffd83dbSDimitry Andric // Emit a load of a LValue of matrix type. This may require casting the pointer
18475ffd83dbSDimitry Andric // to memory address (ArrayType) to a pointer to the value type (VectorType).
18485ffd83dbSDimitry Andric static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
18495ffd83dbSDimitry Andric                                      CodeGenFunction &CGF) {
18505ffd83dbSDimitry Andric   assert(LV.getType()->isConstantMatrixType());
18515ffd83dbSDimitry Andric   Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
18525ffd83dbSDimitry Andric   LV.setAddress(Addr);
18535ffd83dbSDimitry Andric   return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
18545ffd83dbSDimitry Andric }
18555ffd83dbSDimitry Andric 
1856*0b57cec5SDimitry Andric /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1857*0b57cec5SDimitry Andric /// method emits the address of the lvalue, then loads the result as an rvalue,
1858*0b57cec5SDimitry Andric /// returning the rvalue.
1859*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1860*0b57cec5SDimitry Andric   if (LV.isObjCWeak()) {
1861*0b57cec5SDimitry Andric     // load of a __weak object.
1862480093f4SDimitry Andric     Address AddrWeakObj = LV.getAddress(*this);
1863*0b57cec5SDimitry Andric     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1864*0b57cec5SDimitry Andric                                                              AddrWeakObj));
1865*0b57cec5SDimitry Andric   }
1866*0b57cec5SDimitry Andric   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1867*0b57cec5SDimitry Andric     // In MRC mode, we do a load+autorelease.
1868*0b57cec5SDimitry Andric     if (!getLangOpts().ObjCAutoRefCount) {
1869480093f4SDimitry Andric       return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
1870*0b57cec5SDimitry Andric     }
1871*0b57cec5SDimitry Andric 
1872*0b57cec5SDimitry Andric     // In ARC mode, we load retained and then consume the value.
1873480093f4SDimitry Andric     llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
1874*0b57cec5SDimitry Andric     Object = EmitObjCConsumeObject(LV.getType(), Object);
1875*0b57cec5SDimitry Andric     return RValue::get(Object);
1876*0b57cec5SDimitry Andric   }
1877*0b57cec5SDimitry Andric 
1878*0b57cec5SDimitry Andric   if (LV.isSimple()) {
1879*0b57cec5SDimitry Andric     assert(!LV.getType()->isFunctionType());
1880*0b57cec5SDimitry Andric 
18815ffd83dbSDimitry Andric     if (LV.getType()->isConstantMatrixType())
18825ffd83dbSDimitry Andric       return EmitLoadOfMatrixLValue(LV, Loc, *this);
18835ffd83dbSDimitry Andric 
1884*0b57cec5SDimitry Andric     // Everything needs a load.
1885*0b57cec5SDimitry Andric     return RValue::get(EmitLoadOfScalar(LV, Loc));
1886*0b57cec5SDimitry Andric   }
1887*0b57cec5SDimitry Andric 
1888*0b57cec5SDimitry Andric   if (LV.isVectorElt()) {
1889*0b57cec5SDimitry Andric     llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1890*0b57cec5SDimitry Andric                                               LV.isVolatileQualified());
1891*0b57cec5SDimitry Andric     return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1892*0b57cec5SDimitry Andric                                                     "vecext"));
1893*0b57cec5SDimitry Andric   }
1894*0b57cec5SDimitry Andric 
1895*0b57cec5SDimitry Andric   // If this is a reference to a subset of the elements of a vector, either
1896*0b57cec5SDimitry Andric   // shuffle the input or extract/insert them as appropriate.
18975ffd83dbSDimitry Andric   if (LV.isExtVectorElt()) {
1898*0b57cec5SDimitry Andric     return EmitLoadOfExtVectorElementLValue(LV);
18995ffd83dbSDimitry Andric   }
1900*0b57cec5SDimitry Andric 
1901*0b57cec5SDimitry Andric   // Global Register variables always invoke intrinsics
1902*0b57cec5SDimitry Andric   if (LV.isGlobalReg())
1903*0b57cec5SDimitry Andric     return EmitLoadOfGlobalRegLValue(LV);
1904*0b57cec5SDimitry Andric 
19055ffd83dbSDimitry Andric   if (LV.isMatrixElt()) {
19065ffd83dbSDimitry Andric     llvm::LoadInst *Load =
19075ffd83dbSDimitry Andric         Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
19085ffd83dbSDimitry Andric     return RValue::get(
19095ffd83dbSDimitry Andric         Builder.CreateExtractElement(Load, LV.getMatrixIdx(), "matrixext"));
19105ffd83dbSDimitry Andric   }
19115ffd83dbSDimitry Andric 
1912*0b57cec5SDimitry Andric   assert(LV.isBitField() && "Unknown LValue type!");
1913*0b57cec5SDimitry Andric   return EmitLoadOfBitfieldLValue(LV, Loc);
1914*0b57cec5SDimitry Andric }
1915*0b57cec5SDimitry Andric 
1916*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1917*0b57cec5SDimitry Andric                                                  SourceLocation Loc) {
1918*0b57cec5SDimitry Andric   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1919*0b57cec5SDimitry Andric 
1920*0b57cec5SDimitry Andric   // Get the output type.
1921*0b57cec5SDimitry Andric   llvm::Type *ResLTy = ConvertType(LV.getType());
1922*0b57cec5SDimitry Andric 
1923*0b57cec5SDimitry Andric   Address Ptr = LV.getBitFieldAddress();
1924*0b57cec5SDimitry Andric   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1925*0b57cec5SDimitry Andric 
1926*0b57cec5SDimitry Andric   if (Info.IsSigned) {
1927*0b57cec5SDimitry Andric     assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1928*0b57cec5SDimitry Andric     unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1929*0b57cec5SDimitry Andric     if (HighBits)
1930*0b57cec5SDimitry Andric       Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1931*0b57cec5SDimitry Andric     if (Info.Offset + HighBits)
1932*0b57cec5SDimitry Andric       Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1933*0b57cec5SDimitry Andric   } else {
1934*0b57cec5SDimitry Andric     if (Info.Offset)
1935*0b57cec5SDimitry Andric       Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1936*0b57cec5SDimitry Andric     if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1937*0b57cec5SDimitry Andric       Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1938*0b57cec5SDimitry Andric                                                               Info.Size),
1939*0b57cec5SDimitry Andric                               "bf.clear");
1940*0b57cec5SDimitry Andric   }
1941*0b57cec5SDimitry Andric   Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1942*0b57cec5SDimitry Andric   EmitScalarRangeCheck(Val, LV.getType(), Loc);
1943*0b57cec5SDimitry Andric   return RValue::get(Val);
1944*0b57cec5SDimitry Andric }
1945*0b57cec5SDimitry Andric 
1946*0b57cec5SDimitry Andric // If this is a reference to a subset of the elements of a vector, create an
1947*0b57cec5SDimitry Andric // appropriate shufflevector.
1948*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1949*0b57cec5SDimitry Andric   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1950*0b57cec5SDimitry Andric                                         LV.isVolatileQualified());
1951*0b57cec5SDimitry Andric 
1952*0b57cec5SDimitry Andric   const llvm::Constant *Elts = LV.getExtVectorElts();
1953*0b57cec5SDimitry Andric 
1954*0b57cec5SDimitry Andric   // If the result of the expression is a non-vector type, we must be extracting
1955*0b57cec5SDimitry Andric   // a single element.  Just codegen as an extractelement.
1956*0b57cec5SDimitry Andric   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1957*0b57cec5SDimitry Andric   if (!ExprVT) {
1958*0b57cec5SDimitry Andric     unsigned InIdx = getAccessedFieldNo(0, Elts);
1959*0b57cec5SDimitry Andric     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1960*0b57cec5SDimitry Andric     return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1961*0b57cec5SDimitry Andric   }
1962*0b57cec5SDimitry Andric 
1963*0b57cec5SDimitry Andric   // Always use shuffle vector to try to retain the original program structure
1964*0b57cec5SDimitry Andric   unsigned NumResultElts = ExprVT->getNumElements();
1965*0b57cec5SDimitry Andric 
19665ffd83dbSDimitry Andric   SmallVector<int, 4> Mask;
1967*0b57cec5SDimitry Andric   for (unsigned i = 0; i != NumResultElts; ++i)
19685ffd83dbSDimitry Andric     Mask.push_back(getAccessedFieldNo(i, Elts));
1969*0b57cec5SDimitry Andric 
1970*0b57cec5SDimitry Andric   Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
19715ffd83dbSDimitry Andric                                     Mask);
1972*0b57cec5SDimitry Andric   return RValue::get(Vec);
1973*0b57cec5SDimitry Andric }
1974*0b57cec5SDimitry Andric 
1975*0b57cec5SDimitry Andric /// Generates lvalue for partial ext_vector access.
1976*0b57cec5SDimitry Andric Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1977*0b57cec5SDimitry Andric   Address VectorAddress = LV.getExtVectorAddress();
1978480093f4SDimitry Andric   QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
1979*0b57cec5SDimitry Andric   llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1980*0b57cec5SDimitry Andric 
1981*0b57cec5SDimitry Andric   Address CastToPointerElement =
1982*0b57cec5SDimitry Andric     Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1983*0b57cec5SDimitry Andric                                  "conv.ptr.element");
1984*0b57cec5SDimitry Andric 
1985*0b57cec5SDimitry Andric   const llvm::Constant *Elts = LV.getExtVectorElts();
1986*0b57cec5SDimitry Andric   unsigned ix = getAccessedFieldNo(0, Elts);
1987*0b57cec5SDimitry Andric 
1988*0b57cec5SDimitry Andric   Address VectorBasePtrPlusIx =
1989*0b57cec5SDimitry Andric     Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1990*0b57cec5SDimitry Andric                                    "vector.elt");
1991*0b57cec5SDimitry Andric 
1992*0b57cec5SDimitry Andric   return VectorBasePtrPlusIx;
1993*0b57cec5SDimitry Andric }
1994*0b57cec5SDimitry Andric 
1995*0b57cec5SDimitry Andric /// Load of global gamed gegisters are always calls to intrinsics.
1996*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1997*0b57cec5SDimitry Andric   assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1998*0b57cec5SDimitry Andric          "Bad type for register variable");
1999*0b57cec5SDimitry Andric   llvm::MDNode *RegName = cast<llvm::MDNode>(
2000*0b57cec5SDimitry Andric       cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2001*0b57cec5SDimitry Andric 
2002*0b57cec5SDimitry Andric   // We accept integer and pointer types only
2003*0b57cec5SDimitry Andric   llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2004*0b57cec5SDimitry Andric   llvm::Type *Ty = OrigTy;
2005*0b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
2006*0b57cec5SDimitry Andric     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2007*0b57cec5SDimitry Andric   llvm::Type *Types[] = { Ty };
2008*0b57cec5SDimitry Andric 
2009*0b57cec5SDimitry Andric   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2010*0b57cec5SDimitry Andric   llvm::Value *Call = Builder.CreateCall(
2011*0b57cec5SDimitry Andric       F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2012*0b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
2013*0b57cec5SDimitry Andric     Call = Builder.CreateIntToPtr(Call, OrigTy);
2014*0b57cec5SDimitry Andric   return RValue::get(Call);
2015*0b57cec5SDimitry Andric }
2016*0b57cec5SDimitry Andric 
2017*0b57cec5SDimitry Andric /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2018*0b57cec5SDimitry Andric /// lvalue, where both are guaranteed to the have the same type, and that type
2019*0b57cec5SDimitry Andric /// is 'Ty'.
2020*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
2021*0b57cec5SDimitry Andric                                              bool isInit) {
2022*0b57cec5SDimitry Andric   if (!Dst.isSimple()) {
2023*0b57cec5SDimitry Andric     if (Dst.isVectorElt()) {
2024*0b57cec5SDimitry Andric       // Read/modify/write the vector, inserting the new element.
2025*0b57cec5SDimitry Andric       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2026*0b57cec5SDimitry Andric                                             Dst.isVolatileQualified());
2027*0b57cec5SDimitry Andric       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
2028*0b57cec5SDimitry Andric                                         Dst.getVectorIdx(), "vecins");
2029*0b57cec5SDimitry Andric       Builder.CreateStore(Vec, Dst.getVectorAddress(),
2030*0b57cec5SDimitry Andric                           Dst.isVolatileQualified());
2031*0b57cec5SDimitry Andric       return;
2032*0b57cec5SDimitry Andric     }
2033*0b57cec5SDimitry Andric 
2034*0b57cec5SDimitry Andric     // If this is an update of extended vector elements, insert them as
2035*0b57cec5SDimitry Andric     // appropriate.
2036*0b57cec5SDimitry Andric     if (Dst.isExtVectorElt())
2037*0b57cec5SDimitry Andric       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
2038*0b57cec5SDimitry Andric 
2039*0b57cec5SDimitry Andric     if (Dst.isGlobalReg())
2040*0b57cec5SDimitry Andric       return EmitStoreThroughGlobalRegLValue(Src, Dst);
2041*0b57cec5SDimitry Andric 
20425ffd83dbSDimitry Andric     if (Dst.isMatrixElt()) {
20435ffd83dbSDimitry Andric       llvm::Value *Vec = Builder.CreateLoad(Dst.getMatrixAddress());
20445ffd83dbSDimitry Andric       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
20455ffd83dbSDimitry Andric                                         Dst.getMatrixIdx(), "matins");
20465ffd83dbSDimitry Andric       Builder.CreateStore(Vec, Dst.getMatrixAddress(),
20475ffd83dbSDimitry Andric                           Dst.isVolatileQualified());
20485ffd83dbSDimitry Andric       return;
20495ffd83dbSDimitry Andric     }
20505ffd83dbSDimitry Andric 
2051*0b57cec5SDimitry Andric     assert(Dst.isBitField() && "Unknown LValue type");
2052*0b57cec5SDimitry Andric     return EmitStoreThroughBitfieldLValue(Src, Dst);
2053*0b57cec5SDimitry Andric   }
2054*0b57cec5SDimitry Andric 
2055*0b57cec5SDimitry Andric   // There's special magic for assigning into an ARC-qualified l-value.
2056*0b57cec5SDimitry Andric   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2057*0b57cec5SDimitry Andric     switch (Lifetime) {
2058*0b57cec5SDimitry Andric     case Qualifiers::OCL_None:
2059*0b57cec5SDimitry Andric       llvm_unreachable("present but none");
2060*0b57cec5SDimitry Andric 
2061*0b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
2062*0b57cec5SDimitry Andric       // nothing special
2063*0b57cec5SDimitry Andric       break;
2064*0b57cec5SDimitry Andric 
2065*0b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
2066*0b57cec5SDimitry Andric       if (isInit) {
2067*0b57cec5SDimitry Andric         Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
2068*0b57cec5SDimitry Andric         break;
2069*0b57cec5SDimitry Andric       }
2070*0b57cec5SDimitry Andric       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
2071*0b57cec5SDimitry Andric       return;
2072*0b57cec5SDimitry Andric 
2073*0b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
2074*0b57cec5SDimitry Andric       if (isInit)
2075*0b57cec5SDimitry Andric         // Initialize and then skip the primitive store.
2076480093f4SDimitry Andric         EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
2077*0b57cec5SDimitry Andric       else
2078480093f4SDimitry Andric         EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
2079480093f4SDimitry Andric                          /*ignore*/ true);
2080*0b57cec5SDimitry Andric       return;
2081*0b57cec5SDimitry Andric 
2082*0b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
2083*0b57cec5SDimitry Andric       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
2084*0b57cec5SDimitry Andric                                                      Src.getScalarVal()));
2085*0b57cec5SDimitry Andric       // fall into the normal path
2086*0b57cec5SDimitry Andric       break;
2087*0b57cec5SDimitry Andric     }
2088*0b57cec5SDimitry Andric   }
2089*0b57cec5SDimitry Andric 
2090*0b57cec5SDimitry Andric   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
2091*0b57cec5SDimitry Andric     // load of a __weak object.
2092480093f4SDimitry Andric     Address LvalueDst = Dst.getAddress(*this);
2093*0b57cec5SDimitry Andric     llvm::Value *src = Src.getScalarVal();
2094*0b57cec5SDimitry Andric      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
2095*0b57cec5SDimitry Andric     return;
2096*0b57cec5SDimitry Andric   }
2097*0b57cec5SDimitry Andric 
2098*0b57cec5SDimitry Andric   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
2099*0b57cec5SDimitry Andric     // load of a __strong object.
2100480093f4SDimitry Andric     Address LvalueDst = Dst.getAddress(*this);
2101*0b57cec5SDimitry Andric     llvm::Value *src = Src.getScalarVal();
2102*0b57cec5SDimitry Andric     if (Dst.isObjCIvar()) {
2103*0b57cec5SDimitry Andric       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
2104*0b57cec5SDimitry Andric       llvm::Type *ResultType = IntPtrTy;
2105*0b57cec5SDimitry Andric       Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
2106*0b57cec5SDimitry Andric       llvm::Value *RHS = dst.getPointer();
2107*0b57cec5SDimitry Andric       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
2108*0b57cec5SDimitry Andric       llvm::Value *LHS =
2109*0b57cec5SDimitry Andric         Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
2110*0b57cec5SDimitry Andric                                "sub.ptr.lhs.cast");
2111*0b57cec5SDimitry Andric       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
2112*0b57cec5SDimitry Andric       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
2113*0b57cec5SDimitry Andric                                               BytesBetween);
2114*0b57cec5SDimitry Andric     } else if (Dst.isGlobalObjCRef()) {
2115*0b57cec5SDimitry Andric       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
2116*0b57cec5SDimitry Andric                                                 Dst.isThreadLocalRef());
2117*0b57cec5SDimitry Andric     }
2118*0b57cec5SDimitry Andric     else
2119*0b57cec5SDimitry Andric       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
2120*0b57cec5SDimitry Andric     return;
2121*0b57cec5SDimitry Andric   }
2122*0b57cec5SDimitry Andric 
2123*0b57cec5SDimitry Andric   assert(Src.isScalar() && "Can't emit an agg store with this method");
2124*0b57cec5SDimitry Andric   EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
2125*0b57cec5SDimitry Andric }
2126*0b57cec5SDimitry Andric 
2127*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2128*0b57cec5SDimitry Andric                                                      llvm::Value **Result) {
2129*0b57cec5SDimitry Andric   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
2130*0b57cec5SDimitry Andric   llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
2131*0b57cec5SDimitry Andric   Address Ptr = Dst.getBitFieldAddress();
2132*0b57cec5SDimitry Andric 
2133*0b57cec5SDimitry Andric   // Get the source value, truncated to the width of the bit-field.
2134*0b57cec5SDimitry Andric   llvm::Value *SrcVal = Src.getScalarVal();
2135*0b57cec5SDimitry Andric 
2136*0b57cec5SDimitry Andric   // Cast the source to the storage type and shift it into place.
2137*0b57cec5SDimitry Andric   SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
2138*0b57cec5SDimitry Andric                                  /*isSigned=*/false);
2139*0b57cec5SDimitry Andric   llvm::Value *MaskedVal = SrcVal;
2140*0b57cec5SDimitry Andric 
2141*0b57cec5SDimitry Andric   // See if there are other bits in the bitfield's storage we'll need to load
2142*0b57cec5SDimitry Andric   // and mask together with source before storing.
2143*0b57cec5SDimitry Andric   if (Info.StorageSize != Info.Size) {
2144*0b57cec5SDimitry Andric     assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
2145*0b57cec5SDimitry Andric     llvm::Value *Val =
2146*0b57cec5SDimitry Andric       Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
2147*0b57cec5SDimitry Andric 
2148*0b57cec5SDimitry Andric     // Mask the source value as needed.
2149*0b57cec5SDimitry Andric     if (!hasBooleanRepresentation(Dst.getType()))
2150*0b57cec5SDimitry Andric       SrcVal = Builder.CreateAnd(SrcVal,
2151*0b57cec5SDimitry Andric                                  llvm::APInt::getLowBitsSet(Info.StorageSize,
2152*0b57cec5SDimitry Andric                                                             Info.Size),
2153*0b57cec5SDimitry Andric                                  "bf.value");
2154*0b57cec5SDimitry Andric     MaskedVal = SrcVal;
2155*0b57cec5SDimitry Andric     if (Info.Offset)
2156*0b57cec5SDimitry Andric       SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
2157*0b57cec5SDimitry Andric 
2158*0b57cec5SDimitry Andric     // Mask out the original value.
2159*0b57cec5SDimitry Andric     Val = Builder.CreateAnd(Val,
2160*0b57cec5SDimitry Andric                             ~llvm::APInt::getBitsSet(Info.StorageSize,
2161*0b57cec5SDimitry Andric                                                      Info.Offset,
2162*0b57cec5SDimitry Andric                                                      Info.Offset + Info.Size),
2163*0b57cec5SDimitry Andric                             "bf.clear");
2164*0b57cec5SDimitry Andric 
2165*0b57cec5SDimitry Andric     // Or together the unchanged values and the source value.
2166*0b57cec5SDimitry Andric     SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
2167*0b57cec5SDimitry Andric   } else {
2168*0b57cec5SDimitry Andric     assert(Info.Offset == 0);
21695ffd83dbSDimitry Andric     // According to the AACPS:
21705ffd83dbSDimitry Andric     // When a volatile bit-field is written, and its container does not overlap
21715ffd83dbSDimitry Andric     // with any non-bit-field member, its container must be read exactly once and
21725ffd83dbSDimitry Andric     // written exactly once using the access width appropriate to the type of the
21735ffd83dbSDimitry Andric     // container. The two accesses are not atomic.
21745ffd83dbSDimitry Andric     if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
21755ffd83dbSDimitry Andric         CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
21765ffd83dbSDimitry Andric       Builder.CreateLoad(Ptr, true, "bf.load");
2177*0b57cec5SDimitry Andric   }
2178*0b57cec5SDimitry Andric 
2179*0b57cec5SDimitry Andric   // Write the new value back out.
2180*0b57cec5SDimitry Andric   Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
2181*0b57cec5SDimitry Andric 
2182*0b57cec5SDimitry Andric   // Return the new value of the bit-field, if requested.
2183*0b57cec5SDimitry Andric   if (Result) {
2184*0b57cec5SDimitry Andric     llvm::Value *ResultVal = MaskedVal;
2185*0b57cec5SDimitry Andric 
2186*0b57cec5SDimitry Andric     // Sign extend the value if needed.
2187*0b57cec5SDimitry Andric     if (Info.IsSigned) {
2188*0b57cec5SDimitry Andric       assert(Info.Size <= Info.StorageSize);
2189*0b57cec5SDimitry Andric       unsigned HighBits = Info.StorageSize - Info.Size;
2190*0b57cec5SDimitry Andric       if (HighBits) {
2191*0b57cec5SDimitry Andric         ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
2192*0b57cec5SDimitry Andric         ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
2193*0b57cec5SDimitry Andric       }
2194*0b57cec5SDimitry Andric     }
2195*0b57cec5SDimitry Andric 
2196*0b57cec5SDimitry Andric     ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
2197*0b57cec5SDimitry Andric                                       "bf.result.cast");
2198*0b57cec5SDimitry Andric     *Result = EmitFromMemory(ResultVal, Dst.getType());
2199*0b57cec5SDimitry Andric   }
2200*0b57cec5SDimitry Andric }
2201*0b57cec5SDimitry Andric 
2202*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
2203*0b57cec5SDimitry Andric                                                                LValue Dst) {
2204*0b57cec5SDimitry Andric   // This access turns into a read/modify/write of the vector.  Load the input
2205*0b57cec5SDimitry Andric   // value now.
2206*0b57cec5SDimitry Andric   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
2207*0b57cec5SDimitry Andric                                         Dst.isVolatileQualified());
2208*0b57cec5SDimitry Andric   const llvm::Constant *Elts = Dst.getExtVectorElts();
2209*0b57cec5SDimitry Andric 
2210*0b57cec5SDimitry Andric   llvm::Value *SrcVal = Src.getScalarVal();
2211*0b57cec5SDimitry Andric 
2212*0b57cec5SDimitry Andric   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2213*0b57cec5SDimitry Andric     unsigned NumSrcElts = VTy->getNumElements();
22145ffd83dbSDimitry Andric     unsigned NumDstElts =
22155ffd83dbSDimitry Andric         cast<llvm::VectorType>(Vec->getType())->getNumElements();
2216*0b57cec5SDimitry Andric     if (NumDstElts == NumSrcElts) {
2217*0b57cec5SDimitry Andric       // Use shuffle vector is the src and destination are the same number of
2218*0b57cec5SDimitry Andric       // elements and restore the vector mask since it is on the side it will be
2219*0b57cec5SDimitry Andric       // stored.
22205ffd83dbSDimitry Andric       SmallVector<int, 4> Mask(NumDstElts);
2221*0b57cec5SDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
22225ffd83dbSDimitry Andric         Mask[getAccessedFieldNo(i, Elts)] = i;
2223*0b57cec5SDimitry Andric 
22245ffd83dbSDimitry Andric       Vec = Builder.CreateShuffleVector(
22255ffd83dbSDimitry Andric           SrcVal, llvm::UndefValue::get(Vec->getType()), Mask);
2226*0b57cec5SDimitry Andric     } else if (NumDstElts > NumSrcElts) {
2227*0b57cec5SDimitry Andric       // Extended the source vector to the same length and then shuffle it
2228*0b57cec5SDimitry Andric       // into the destination.
2229*0b57cec5SDimitry Andric       // FIXME: since we're shuffling with undef, can we just use the indices
2230*0b57cec5SDimitry Andric       //        into that?  This could be simpler.
22315ffd83dbSDimitry Andric       SmallVector<int, 4> ExtMask;
2232*0b57cec5SDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
22335ffd83dbSDimitry Andric         ExtMask.push_back(i);
22345ffd83dbSDimitry Andric       ExtMask.resize(NumDstElts, -1);
22355ffd83dbSDimitry Andric       llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(
22365ffd83dbSDimitry Andric           SrcVal, llvm::UndefValue::get(SrcVal->getType()), ExtMask);
2237*0b57cec5SDimitry Andric       // build identity
22385ffd83dbSDimitry Andric       SmallVector<int, 4> Mask;
2239*0b57cec5SDimitry Andric       for (unsigned i = 0; i != NumDstElts; ++i)
22405ffd83dbSDimitry Andric         Mask.push_back(i);
2241*0b57cec5SDimitry Andric 
2242*0b57cec5SDimitry Andric       // When the vector size is odd and .odd or .hi is used, the last element
2243*0b57cec5SDimitry Andric       // of the Elts constant array will be one past the size of the vector.
2244*0b57cec5SDimitry Andric       // Ignore the last element here, if it is greater than the mask size.
2245*0b57cec5SDimitry Andric       if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2246*0b57cec5SDimitry Andric         NumSrcElts--;
2247*0b57cec5SDimitry Andric 
2248*0b57cec5SDimitry Andric       // modify when what gets shuffled in
2249*0b57cec5SDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
22505ffd83dbSDimitry Andric         Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
22515ffd83dbSDimitry Andric       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
2252*0b57cec5SDimitry Andric     } else {
2253*0b57cec5SDimitry Andric       // We should never shorten the vector
2254*0b57cec5SDimitry Andric       llvm_unreachable("unexpected shorten vector length");
2255*0b57cec5SDimitry Andric     }
2256*0b57cec5SDimitry Andric   } else {
2257*0b57cec5SDimitry Andric     // If the Src is a scalar (not a vector) it must be updating one element.
2258*0b57cec5SDimitry Andric     unsigned InIdx = getAccessedFieldNo(0, Elts);
2259*0b57cec5SDimitry Andric     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2260*0b57cec5SDimitry Andric     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2261*0b57cec5SDimitry Andric   }
2262*0b57cec5SDimitry Andric 
2263*0b57cec5SDimitry Andric   Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2264*0b57cec5SDimitry Andric                       Dst.isVolatileQualified());
2265*0b57cec5SDimitry Andric }
2266*0b57cec5SDimitry Andric 
2267*0b57cec5SDimitry Andric /// Store of global named registers are always calls to intrinsics.
2268*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
2269*0b57cec5SDimitry Andric   assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2270*0b57cec5SDimitry Andric          "Bad type for register variable");
2271*0b57cec5SDimitry Andric   llvm::MDNode *RegName = cast<llvm::MDNode>(
2272*0b57cec5SDimitry Andric       cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2273*0b57cec5SDimitry Andric   assert(RegName && "Register LValue is not metadata");
2274*0b57cec5SDimitry Andric 
2275*0b57cec5SDimitry Andric   // We accept integer and pointer types only
2276*0b57cec5SDimitry Andric   llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2277*0b57cec5SDimitry Andric   llvm::Type *Ty = OrigTy;
2278*0b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
2279*0b57cec5SDimitry Andric     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2280*0b57cec5SDimitry Andric   llvm::Type *Types[] = { Ty };
2281*0b57cec5SDimitry Andric 
2282*0b57cec5SDimitry Andric   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2283*0b57cec5SDimitry Andric   llvm::Value *Value = Src.getScalarVal();
2284*0b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
2285*0b57cec5SDimitry Andric     Value = Builder.CreatePtrToInt(Value, Ty);
2286*0b57cec5SDimitry Andric   Builder.CreateCall(
2287*0b57cec5SDimitry Andric       F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2288*0b57cec5SDimitry Andric }
2289*0b57cec5SDimitry Andric 
2290*0b57cec5SDimitry Andric // setObjCGCLValueClass - sets class of the lvalue for the purpose of
2291*0b57cec5SDimitry Andric // generating write-barries API. It is currently a global, ivar,
2292*0b57cec5SDimitry Andric // or neither.
2293*0b57cec5SDimitry Andric static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2294*0b57cec5SDimitry Andric                                  LValue &LV,
2295*0b57cec5SDimitry Andric                                  bool IsMemberAccess=false) {
2296*0b57cec5SDimitry Andric   if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2297*0b57cec5SDimitry Andric     return;
2298*0b57cec5SDimitry Andric 
2299*0b57cec5SDimitry Andric   if (isa<ObjCIvarRefExpr>(E)) {
2300*0b57cec5SDimitry Andric     QualType ExpTy = E->getType();
2301*0b57cec5SDimitry Andric     if (IsMemberAccess && ExpTy->isPointerType()) {
2302*0b57cec5SDimitry Andric       // If ivar is a structure pointer, assigning to field of
2303*0b57cec5SDimitry Andric       // this struct follows gcc's behavior and makes it a non-ivar
2304*0b57cec5SDimitry Andric       // writer-barrier conservatively.
2305a7dea167SDimitry Andric       ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2306*0b57cec5SDimitry Andric       if (ExpTy->isRecordType()) {
2307*0b57cec5SDimitry Andric         LV.setObjCIvar(false);
2308*0b57cec5SDimitry Andric         return;
2309*0b57cec5SDimitry Andric       }
2310*0b57cec5SDimitry Andric     }
2311*0b57cec5SDimitry Andric     LV.setObjCIvar(true);
2312*0b57cec5SDimitry Andric     auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2313*0b57cec5SDimitry Andric     LV.setBaseIvarExp(Exp->getBase());
2314*0b57cec5SDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
2315*0b57cec5SDimitry Andric     return;
2316*0b57cec5SDimitry Andric   }
2317*0b57cec5SDimitry Andric 
2318*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2319*0b57cec5SDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2320*0b57cec5SDimitry Andric       if (VD->hasGlobalStorage()) {
2321*0b57cec5SDimitry Andric         LV.setGlobalObjCRef(true);
2322*0b57cec5SDimitry Andric         LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2323*0b57cec5SDimitry Andric       }
2324*0b57cec5SDimitry Andric     }
2325*0b57cec5SDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
2326*0b57cec5SDimitry Andric     return;
2327*0b57cec5SDimitry Andric   }
2328*0b57cec5SDimitry Andric 
2329*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2330*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2331*0b57cec5SDimitry Andric     return;
2332*0b57cec5SDimitry Andric   }
2333*0b57cec5SDimitry Andric 
2334*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2335*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2336*0b57cec5SDimitry Andric     if (LV.isObjCIvar()) {
2337*0b57cec5SDimitry Andric       // If cast is to a structure pointer, follow gcc's behavior and make it
2338*0b57cec5SDimitry Andric       // a non-ivar write-barrier.
2339*0b57cec5SDimitry Andric       QualType ExpTy = E->getType();
2340*0b57cec5SDimitry Andric       if (ExpTy->isPointerType())
2341a7dea167SDimitry Andric         ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2342*0b57cec5SDimitry Andric       if (ExpTy->isRecordType())
2343*0b57cec5SDimitry Andric         LV.setObjCIvar(false);
2344*0b57cec5SDimitry Andric     }
2345*0b57cec5SDimitry Andric     return;
2346*0b57cec5SDimitry Andric   }
2347*0b57cec5SDimitry Andric 
2348*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2349*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2350*0b57cec5SDimitry Andric     return;
2351*0b57cec5SDimitry Andric   }
2352*0b57cec5SDimitry Andric 
2353*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2354*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2355*0b57cec5SDimitry Andric     return;
2356*0b57cec5SDimitry Andric   }
2357*0b57cec5SDimitry Andric 
2358*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2359*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2360*0b57cec5SDimitry Andric     return;
2361*0b57cec5SDimitry Andric   }
2362*0b57cec5SDimitry Andric 
2363*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2364*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2365*0b57cec5SDimitry Andric     return;
2366*0b57cec5SDimitry Andric   }
2367*0b57cec5SDimitry Andric 
2368*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2369*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2370*0b57cec5SDimitry Andric     if (LV.isObjCIvar() && !LV.isObjCArray())
2371*0b57cec5SDimitry Andric       // Using array syntax to assigning to what an ivar points to is not
2372*0b57cec5SDimitry Andric       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2373*0b57cec5SDimitry Andric       LV.setObjCIvar(false);
2374*0b57cec5SDimitry Andric     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2375*0b57cec5SDimitry Andric       // Using array syntax to assigning to what global points to is not
2376*0b57cec5SDimitry Andric       // same as assigning to the global itself. {id *G;} G[i] = 0;
2377*0b57cec5SDimitry Andric       LV.setGlobalObjCRef(false);
2378*0b57cec5SDimitry Andric     return;
2379*0b57cec5SDimitry Andric   }
2380*0b57cec5SDimitry Andric 
2381*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2382*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2383*0b57cec5SDimitry Andric     // We don't know if member is an 'ivar', but this flag is looked at
2384*0b57cec5SDimitry Andric     // only in the context of LV.isObjCIvar().
2385*0b57cec5SDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
2386*0b57cec5SDimitry Andric     return;
2387*0b57cec5SDimitry Andric   }
2388*0b57cec5SDimitry Andric }
2389*0b57cec5SDimitry Andric 
2390*0b57cec5SDimitry Andric static llvm::Value *
2391*0b57cec5SDimitry Andric EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2392*0b57cec5SDimitry Andric                                 llvm::Value *V, llvm::Type *IRType,
2393*0b57cec5SDimitry Andric                                 StringRef Name = StringRef()) {
2394*0b57cec5SDimitry Andric   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2395*0b57cec5SDimitry Andric   return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2396*0b57cec5SDimitry Andric }
2397*0b57cec5SDimitry Andric 
2398*0b57cec5SDimitry Andric static LValue EmitThreadPrivateVarDeclLValue(
2399*0b57cec5SDimitry Andric     CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2400*0b57cec5SDimitry Andric     llvm::Type *RealVarTy, SourceLocation Loc) {
24015ffd83dbSDimitry Andric   if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
24025ffd83dbSDimitry Andric     Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
24035ffd83dbSDimitry Andric         CGF, VD, Addr, Loc);
24045ffd83dbSDimitry Andric   else
24055ffd83dbSDimitry Andric     Addr =
24065ffd83dbSDimitry Andric         CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
24075ffd83dbSDimitry Andric 
2408*0b57cec5SDimitry Andric   Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2409*0b57cec5SDimitry Andric   return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2410*0b57cec5SDimitry Andric }
2411*0b57cec5SDimitry Andric 
2412*0b57cec5SDimitry Andric static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
2413*0b57cec5SDimitry Andric                                            const VarDecl *VD, QualType T) {
2414*0b57cec5SDimitry Andric   llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2415*0b57cec5SDimitry Andric       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2416*0b57cec5SDimitry Andric   // Return an invalid address if variable is MT_To and unified
2417*0b57cec5SDimitry Andric   // memory is not enabled. For all other cases: MT_Link and
2418*0b57cec5SDimitry Andric   // MT_To with unified memory, return a valid address.
2419*0b57cec5SDimitry Andric   if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2420*0b57cec5SDimitry Andric                !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
2421*0b57cec5SDimitry Andric     return Address::invalid();
2422*0b57cec5SDimitry Andric   assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2423*0b57cec5SDimitry Andric           (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2424*0b57cec5SDimitry Andric            CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
2425*0b57cec5SDimitry Andric          "Expected link clause OR to clause with unified memory enabled.");
2426*0b57cec5SDimitry Andric   QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
2427*0b57cec5SDimitry Andric   Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2428*0b57cec5SDimitry Andric   return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
2429*0b57cec5SDimitry Andric }
2430*0b57cec5SDimitry Andric 
2431*0b57cec5SDimitry Andric Address
2432*0b57cec5SDimitry Andric CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2433*0b57cec5SDimitry Andric                                      LValueBaseInfo *PointeeBaseInfo,
2434*0b57cec5SDimitry Andric                                      TBAAAccessInfo *PointeeTBAAInfo) {
2435480093f4SDimitry Andric   llvm::LoadInst *Load =
2436480093f4SDimitry Andric       Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
2437*0b57cec5SDimitry Andric   CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
2438*0b57cec5SDimitry Andric 
24395ffd83dbSDimitry Andric   CharUnits Align = CGM.getNaturalTypeAlignment(
24405ffd83dbSDimitry Andric       RefLVal.getType()->getPointeeType(), PointeeBaseInfo, PointeeTBAAInfo,
2441*0b57cec5SDimitry Andric       /* forPointeeType= */ true);
2442*0b57cec5SDimitry Andric   return Address(Load, Align);
2443*0b57cec5SDimitry Andric }
2444*0b57cec5SDimitry Andric 
2445*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2446*0b57cec5SDimitry Andric   LValueBaseInfo PointeeBaseInfo;
2447*0b57cec5SDimitry Andric   TBAAAccessInfo PointeeTBAAInfo;
2448*0b57cec5SDimitry Andric   Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2449*0b57cec5SDimitry Andric                                             &PointeeTBAAInfo);
2450*0b57cec5SDimitry Andric   return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2451*0b57cec5SDimitry Andric                         PointeeBaseInfo, PointeeTBAAInfo);
2452*0b57cec5SDimitry Andric }
2453*0b57cec5SDimitry Andric 
2454*0b57cec5SDimitry Andric Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2455*0b57cec5SDimitry Andric                                            const PointerType *PtrTy,
2456*0b57cec5SDimitry Andric                                            LValueBaseInfo *BaseInfo,
2457*0b57cec5SDimitry Andric                                            TBAAAccessInfo *TBAAInfo) {
2458*0b57cec5SDimitry Andric   llvm::Value *Addr = Builder.CreateLoad(Ptr);
24595ffd83dbSDimitry Andric   return Address(Addr, CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(),
2460*0b57cec5SDimitry Andric                                                    BaseInfo, TBAAInfo,
2461*0b57cec5SDimitry Andric                                                    /*forPointeeType=*/true));
2462*0b57cec5SDimitry Andric }
2463*0b57cec5SDimitry Andric 
2464*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2465*0b57cec5SDimitry Andric                                                 const PointerType *PtrTy) {
2466*0b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
2467*0b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
2468*0b57cec5SDimitry Andric   Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2469*0b57cec5SDimitry Andric   return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
2470*0b57cec5SDimitry Andric }
2471*0b57cec5SDimitry Andric 
2472*0b57cec5SDimitry Andric static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2473*0b57cec5SDimitry Andric                                       const Expr *E, const VarDecl *VD) {
2474*0b57cec5SDimitry Andric   QualType T = E->getType();
2475*0b57cec5SDimitry Andric 
2476*0b57cec5SDimitry Andric   // If it's thread_local, emit a call to its wrapper function instead.
2477*0b57cec5SDimitry Andric   if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2478a7dea167SDimitry Andric       CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
2479*0b57cec5SDimitry Andric     return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2480*0b57cec5SDimitry Andric   // Check if the variable is marked as declare target with link clause in
2481*0b57cec5SDimitry Andric   // device codegen.
2482*0b57cec5SDimitry Andric   if (CGF.getLangOpts().OpenMPIsDevice) {
2483*0b57cec5SDimitry Andric     Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
2484*0b57cec5SDimitry Andric     if (Addr.isValid())
2485*0b57cec5SDimitry Andric       return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2486*0b57cec5SDimitry Andric   }
2487*0b57cec5SDimitry Andric 
2488*0b57cec5SDimitry Andric   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2489*0b57cec5SDimitry Andric   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2490*0b57cec5SDimitry Andric   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2491*0b57cec5SDimitry Andric   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2492*0b57cec5SDimitry Andric   Address Addr(V, Alignment);
2493*0b57cec5SDimitry Andric   // Emit reference to the private copy of the variable if it is an OpenMP
2494*0b57cec5SDimitry Andric   // threadprivate variable.
2495*0b57cec5SDimitry Andric   if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
2496*0b57cec5SDimitry Andric       VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2497*0b57cec5SDimitry Andric     return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2498*0b57cec5SDimitry Andric                                           E->getExprLoc());
2499*0b57cec5SDimitry Andric   }
2500*0b57cec5SDimitry Andric   LValue LV = VD->getType()->isReferenceType() ?
2501*0b57cec5SDimitry Andric       CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2502*0b57cec5SDimitry Andric                                     AlignmentSource::Decl) :
2503*0b57cec5SDimitry Andric       CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2504*0b57cec5SDimitry Andric   setObjCGCLValueClass(CGF.getContext(), E, LV);
2505*0b57cec5SDimitry Andric   return LV;
2506*0b57cec5SDimitry Andric }
2507*0b57cec5SDimitry Andric 
2508*0b57cec5SDimitry Andric static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
25095ffd83dbSDimitry Andric                                                GlobalDecl GD) {
25105ffd83dbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2511*0b57cec5SDimitry Andric   if (FD->hasAttr<WeakRefAttr>()) {
2512*0b57cec5SDimitry Andric     ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2513*0b57cec5SDimitry Andric     return aliasee.getPointer();
2514*0b57cec5SDimitry Andric   }
2515*0b57cec5SDimitry Andric 
25165ffd83dbSDimitry Andric   llvm::Constant *V = CGM.GetAddrOfFunction(GD);
2517*0b57cec5SDimitry Andric   if (!FD->hasPrototype()) {
2518*0b57cec5SDimitry Andric     if (const FunctionProtoType *Proto =
2519*0b57cec5SDimitry Andric             FD->getType()->getAs<FunctionProtoType>()) {
2520*0b57cec5SDimitry Andric       // Ugly case: for a K&R-style definition, the type of the definition
2521*0b57cec5SDimitry Andric       // isn't the same as the type of a use.  Correct for this with a
2522*0b57cec5SDimitry Andric       // bitcast.
2523*0b57cec5SDimitry Andric       QualType NoProtoType =
2524*0b57cec5SDimitry Andric           CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2525*0b57cec5SDimitry Andric       NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2526*0b57cec5SDimitry Andric       V = llvm::ConstantExpr::getBitCast(V,
2527*0b57cec5SDimitry Andric                                       CGM.getTypes().ConvertType(NoProtoType));
2528*0b57cec5SDimitry Andric     }
2529*0b57cec5SDimitry Andric   }
2530*0b57cec5SDimitry Andric   return V;
2531*0b57cec5SDimitry Andric }
2532*0b57cec5SDimitry Andric 
25335ffd83dbSDimitry Andric static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
25345ffd83dbSDimitry Andric                                      GlobalDecl GD) {
25355ffd83dbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
25365ffd83dbSDimitry Andric   llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
2537*0b57cec5SDimitry Andric   CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2538*0b57cec5SDimitry Andric   return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2539*0b57cec5SDimitry Andric                             AlignmentSource::Decl);
2540*0b57cec5SDimitry Andric }
2541*0b57cec5SDimitry Andric 
2542*0b57cec5SDimitry Andric static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2543*0b57cec5SDimitry Andric                                       llvm::Value *ThisValue) {
2544*0b57cec5SDimitry Andric   QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2545*0b57cec5SDimitry Andric   LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2546*0b57cec5SDimitry Andric   return CGF.EmitLValueForField(LV, FD);
2547*0b57cec5SDimitry Andric }
2548*0b57cec5SDimitry Andric 
2549*0b57cec5SDimitry Andric /// Named Registers are named metadata pointing to the register name
2550*0b57cec5SDimitry Andric /// which will be read from/written to as an argument to the intrinsic
2551*0b57cec5SDimitry Andric /// @llvm.read/write_register.
2552*0b57cec5SDimitry Andric /// So far, only the name is being passed down, but other options such as
2553*0b57cec5SDimitry Andric /// register type, allocation type or even optimization options could be
2554*0b57cec5SDimitry Andric /// passed down via the metadata node.
2555*0b57cec5SDimitry Andric static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2556*0b57cec5SDimitry Andric   SmallString<64> Name("llvm.named.register.");
2557*0b57cec5SDimitry Andric   AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2558*0b57cec5SDimitry Andric   assert(Asm->getLabel().size() < 64-Name.size() &&
2559*0b57cec5SDimitry Andric       "Register name too big");
2560*0b57cec5SDimitry Andric   Name.append(Asm->getLabel());
2561*0b57cec5SDimitry Andric   llvm::NamedMDNode *M =
2562*0b57cec5SDimitry Andric     CGM.getModule().getOrInsertNamedMetadata(Name);
2563*0b57cec5SDimitry Andric   if (M->getNumOperands() == 0) {
2564*0b57cec5SDimitry Andric     llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2565*0b57cec5SDimitry Andric                                               Asm->getLabel());
2566*0b57cec5SDimitry Andric     llvm::Metadata *Ops[] = {Str};
2567*0b57cec5SDimitry Andric     M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2568*0b57cec5SDimitry Andric   }
2569*0b57cec5SDimitry Andric 
2570*0b57cec5SDimitry Andric   CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2571*0b57cec5SDimitry Andric 
2572*0b57cec5SDimitry Andric   llvm::Value *Ptr =
2573*0b57cec5SDimitry Andric     llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2574*0b57cec5SDimitry Andric   return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2575*0b57cec5SDimitry Andric }
2576*0b57cec5SDimitry Andric 
2577*0b57cec5SDimitry Andric /// Determine whether we can emit a reference to \p VD from the current
2578*0b57cec5SDimitry Andric /// context, despite not necessarily having seen an odr-use of the variable in
2579*0b57cec5SDimitry Andric /// this context.
2580*0b57cec5SDimitry Andric static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
2581*0b57cec5SDimitry Andric                                                const DeclRefExpr *E,
2582*0b57cec5SDimitry Andric                                                const VarDecl *VD,
2583*0b57cec5SDimitry Andric                                                bool IsConstant) {
2584*0b57cec5SDimitry Andric   // For a variable declared in an enclosing scope, do not emit a spurious
2585*0b57cec5SDimitry Andric   // reference even if we have a capture, as that will emit an unwarranted
2586*0b57cec5SDimitry Andric   // reference to our capture state, and will likely generate worse code than
2587*0b57cec5SDimitry Andric   // emitting a local copy.
2588*0b57cec5SDimitry Andric   if (E->refersToEnclosingVariableOrCapture())
2589*0b57cec5SDimitry Andric     return false;
2590*0b57cec5SDimitry Andric 
2591*0b57cec5SDimitry Andric   // For a local declaration declared in this function, we can always reference
2592*0b57cec5SDimitry Andric   // it even if we don't have an odr-use.
2593*0b57cec5SDimitry Andric   if (VD->hasLocalStorage()) {
2594*0b57cec5SDimitry Andric     return VD->getDeclContext() ==
2595*0b57cec5SDimitry Andric            dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
2596*0b57cec5SDimitry Andric   }
2597*0b57cec5SDimitry Andric 
2598*0b57cec5SDimitry Andric   // For a global declaration, we can emit a reference to it if we know
2599*0b57cec5SDimitry Andric   // for sure that we are able to emit a definition of it.
2600*0b57cec5SDimitry Andric   VD = VD->getDefinition(CGF.getContext());
2601*0b57cec5SDimitry Andric   if (!VD)
2602*0b57cec5SDimitry Andric     return false;
2603*0b57cec5SDimitry Andric 
2604*0b57cec5SDimitry Andric   // Don't emit a spurious reference if it might be to a variable that only
2605*0b57cec5SDimitry Andric   // exists on a different device / target.
2606*0b57cec5SDimitry Andric   // FIXME: This is unnecessarily broad. Check whether this would actually be a
2607*0b57cec5SDimitry Andric   // cross-target reference.
2608*0b57cec5SDimitry Andric   if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
2609*0b57cec5SDimitry Andric       CGF.getLangOpts().OpenCL) {
2610*0b57cec5SDimitry Andric     return false;
2611*0b57cec5SDimitry Andric   }
2612*0b57cec5SDimitry Andric 
2613*0b57cec5SDimitry Andric   // We can emit a spurious reference only if the linkage implies that we'll
2614*0b57cec5SDimitry Andric   // be emitting a non-interposable symbol that will be retained until link
2615*0b57cec5SDimitry Andric   // time.
2616*0b57cec5SDimitry Andric   switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
2617*0b57cec5SDimitry Andric   case llvm::GlobalValue::ExternalLinkage:
2618*0b57cec5SDimitry Andric   case llvm::GlobalValue::LinkOnceODRLinkage:
2619*0b57cec5SDimitry Andric   case llvm::GlobalValue::WeakODRLinkage:
2620*0b57cec5SDimitry Andric   case llvm::GlobalValue::InternalLinkage:
2621*0b57cec5SDimitry Andric   case llvm::GlobalValue::PrivateLinkage:
2622*0b57cec5SDimitry Andric     return true;
2623*0b57cec5SDimitry Andric   default:
2624*0b57cec5SDimitry Andric     return false;
2625*0b57cec5SDimitry Andric   }
2626*0b57cec5SDimitry Andric }
2627*0b57cec5SDimitry Andric 
2628*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2629*0b57cec5SDimitry Andric   const NamedDecl *ND = E->getDecl();
2630*0b57cec5SDimitry Andric   QualType T = E->getType();
2631*0b57cec5SDimitry Andric 
2632*0b57cec5SDimitry Andric   assert(E->isNonOdrUse() != NOUR_Unevaluated &&
2633*0b57cec5SDimitry Andric          "should not emit an unevaluated operand");
2634*0b57cec5SDimitry Andric 
2635*0b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2636*0b57cec5SDimitry Andric     // Global Named registers access via intrinsics only
2637*0b57cec5SDimitry Andric     if (VD->getStorageClass() == SC_Register &&
2638*0b57cec5SDimitry Andric         VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2639*0b57cec5SDimitry Andric       return EmitGlobalNamedRegister(VD, CGM);
2640*0b57cec5SDimitry Andric 
2641*0b57cec5SDimitry Andric     // If this DeclRefExpr does not constitute an odr-use of the variable,
2642*0b57cec5SDimitry Andric     // we're not permitted to emit a reference to it in general, and it might
2643*0b57cec5SDimitry Andric     // not be captured if capture would be necessary for a use. Emit the
2644*0b57cec5SDimitry Andric     // constant value directly instead.
2645*0b57cec5SDimitry Andric     if (E->isNonOdrUse() == NOUR_Constant &&
2646*0b57cec5SDimitry Andric         (VD->getType()->isReferenceType() ||
2647*0b57cec5SDimitry Andric          !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
2648*0b57cec5SDimitry Andric       VD->getAnyInitializer(VD);
2649*0b57cec5SDimitry Andric       llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
2650*0b57cec5SDimitry Andric           E->getLocation(), *VD->evaluateValue(), VD->getType());
2651*0b57cec5SDimitry Andric       assert(Val && "failed to emit constant expression");
2652*0b57cec5SDimitry Andric 
2653*0b57cec5SDimitry Andric       Address Addr = Address::invalid();
2654*0b57cec5SDimitry Andric       if (!VD->getType()->isReferenceType()) {
2655*0b57cec5SDimitry Andric         // Spill the constant value to a global.
2656*0b57cec5SDimitry Andric         Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
2657*0b57cec5SDimitry Andric                                            getContext().getDeclAlign(VD));
2658c14a5a88SDimitry Andric         llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
2659c14a5a88SDimitry Andric         auto *PTy = llvm::PointerType::get(
2660c14a5a88SDimitry Andric             VarTy, getContext().getTargetAddressSpace(VD->getType()));
2661c14a5a88SDimitry Andric         if (PTy != Addr.getType())
2662c14a5a88SDimitry Andric           Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy);
2663*0b57cec5SDimitry Andric       } else {
2664*0b57cec5SDimitry Andric         // Should we be using the alignment of the constant pointer we emitted?
2665*0b57cec5SDimitry Andric         CharUnits Alignment =
26665ffd83dbSDimitry Andric             CGM.getNaturalTypeAlignment(E->getType(),
2667*0b57cec5SDimitry Andric                                         /* BaseInfo= */ nullptr,
2668*0b57cec5SDimitry Andric                                         /* TBAAInfo= */ nullptr,
2669*0b57cec5SDimitry Andric                                         /* forPointeeType= */ true);
2670*0b57cec5SDimitry Andric         Addr = Address(Val, Alignment);
2671*0b57cec5SDimitry Andric       }
2672*0b57cec5SDimitry Andric       return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2673*0b57cec5SDimitry Andric     }
2674*0b57cec5SDimitry Andric 
2675*0b57cec5SDimitry Andric     // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
2676*0b57cec5SDimitry Andric 
2677*0b57cec5SDimitry Andric     // Check for captured variables.
2678*0b57cec5SDimitry Andric     if (E->refersToEnclosingVariableOrCapture()) {
2679*0b57cec5SDimitry Andric       VD = VD->getCanonicalDecl();
2680*0b57cec5SDimitry Andric       if (auto *FD = LambdaCaptureFields.lookup(VD))
2681*0b57cec5SDimitry Andric         return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2682480093f4SDimitry Andric       if (CapturedStmtInfo) {
2683*0b57cec5SDimitry Andric         auto I = LocalDeclMap.find(VD);
2684*0b57cec5SDimitry Andric         if (I != LocalDeclMap.end()) {
2685480093f4SDimitry Andric           LValue CapLVal;
2686*0b57cec5SDimitry Andric           if (VD->getType()->isReferenceType())
2687480093f4SDimitry Andric             CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
2688*0b57cec5SDimitry Andric                                                 AlignmentSource::Decl);
2689480093f4SDimitry Andric           else
2690480093f4SDimitry Andric             CapLVal = MakeAddrLValue(I->second, T);
2691480093f4SDimitry Andric           // Mark lvalue as nontemporal if the variable is marked as nontemporal
2692480093f4SDimitry Andric           // in simd context.
2693480093f4SDimitry Andric           if (getLangOpts().OpenMP &&
2694480093f4SDimitry Andric               CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2695480093f4SDimitry Andric             CapLVal.setNontemporal(/*Value=*/true);
2696480093f4SDimitry Andric           return CapLVal;
2697*0b57cec5SDimitry Andric         }
2698*0b57cec5SDimitry Andric         LValue CapLVal =
2699*0b57cec5SDimitry Andric             EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2700*0b57cec5SDimitry Andric                                     CapturedStmtInfo->getContextValue());
2701480093f4SDimitry Andric         CapLVal = MakeAddrLValue(
2702480093f4SDimitry Andric             Address(CapLVal.getPointer(*this), getContext().getDeclAlign(VD)),
2703*0b57cec5SDimitry Andric             CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2704*0b57cec5SDimitry Andric             CapLVal.getTBAAInfo());
2705480093f4SDimitry Andric         // Mark lvalue as nontemporal if the variable is marked as nontemporal
2706480093f4SDimitry Andric         // in simd context.
2707480093f4SDimitry Andric         if (getLangOpts().OpenMP &&
2708480093f4SDimitry Andric             CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2709480093f4SDimitry Andric           CapLVal.setNontemporal(/*Value=*/true);
2710480093f4SDimitry Andric         return CapLVal;
2711*0b57cec5SDimitry Andric       }
2712*0b57cec5SDimitry Andric 
2713*0b57cec5SDimitry Andric       assert(isa<BlockDecl>(CurCodeDecl));
2714*0b57cec5SDimitry Andric       Address addr = GetAddrOfBlockDecl(VD);
2715*0b57cec5SDimitry Andric       return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2716*0b57cec5SDimitry Andric     }
2717*0b57cec5SDimitry Andric   }
2718*0b57cec5SDimitry Andric 
2719*0b57cec5SDimitry Andric   // FIXME: We should be able to assert this for FunctionDecls as well!
2720*0b57cec5SDimitry Andric   // FIXME: We should be able to assert this for all DeclRefExprs, not just
2721*0b57cec5SDimitry Andric   // those with a valid source location.
2722*0b57cec5SDimitry Andric   assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
2723*0b57cec5SDimitry Andric           !E->getLocation().isValid()) &&
2724*0b57cec5SDimitry Andric          "Should not use decl without marking it used!");
2725*0b57cec5SDimitry Andric 
2726*0b57cec5SDimitry Andric   if (ND->hasAttr<WeakRefAttr>()) {
2727*0b57cec5SDimitry Andric     const auto *VD = cast<ValueDecl>(ND);
2728*0b57cec5SDimitry Andric     ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2729*0b57cec5SDimitry Andric     return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2730*0b57cec5SDimitry Andric   }
2731*0b57cec5SDimitry Andric 
2732*0b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2733*0b57cec5SDimitry Andric     // Check if this is a global variable.
2734*0b57cec5SDimitry Andric     if (VD->hasLinkage() || VD->isStaticDataMember())
2735*0b57cec5SDimitry Andric       return EmitGlobalVarDeclLValue(*this, E, VD);
2736*0b57cec5SDimitry Andric 
2737*0b57cec5SDimitry Andric     Address addr = Address::invalid();
2738*0b57cec5SDimitry Andric 
2739*0b57cec5SDimitry Andric     // The variable should generally be present in the local decl map.
2740*0b57cec5SDimitry Andric     auto iter = LocalDeclMap.find(VD);
2741*0b57cec5SDimitry Andric     if (iter != LocalDeclMap.end()) {
2742*0b57cec5SDimitry Andric       addr = iter->second;
2743*0b57cec5SDimitry Andric 
2744*0b57cec5SDimitry Andric     // Otherwise, it might be static local we haven't emitted yet for
2745*0b57cec5SDimitry Andric     // some reason; most likely, because it's in an outer function.
2746*0b57cec5SDimitry Andric     } else if (VD->isStaticLocal()) {
2747*0b57cec5SDimitry Andric       addr = Address(CGM.getOrCreateStaticVarDecl(
2748*0b57cec5SDimitry Andric           *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false)),
2749*0b57cec5SDimitry Andric                      getContext().getDeclAlign(VD));
2750*0b57cec5SDimitry Andric 
2751*0b57cec5SDimitry Andric     // No other cases for now.
2752*0b57cec5SDimitry Andric     } else {
2753*0b57cec5SDimitry Andric       llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2754*0b57cec5SDimitry Andric     }
2755*0b57cec5SDimitry Andric 
2756*0b57cec5SDimitry Andric 
2757*0b57cec5SDimitry Andric     // Check for OpenMP threadprivate variables.
2758*0b57cec5SDimitry Andric     if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
2759*0b57cec5SDimitry Andric         VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2760*0b57cec5SDimitry Andric       return EmitThreadPrivateVarDeclLValue(
2761*0b57cec5SDimitry Andric           *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2762*0b57cec5SDimitry Andric           E->getExprLoc());
2763*0b57cec5SDimitry Andric     }
2764*0b57cec5SDimitry Andric 
2765*0b57cec5SDimitry Andric     // Drill into block byref variables.
2766*0b57cec5SDimitry Andric     bool isBlockByref = VD->isEscapingByref();
2767*0b57cec5SDimitry Andric     if (isBlockByref) {
2768*0b57cec5SDimitry Andric       addr = emitBlockByrefAddress(addr, VD);
2769*0b57cec5SDimitry Andric     }
2770*0b57cec5SDimitry Andric 
2771*0b57cec5SDimitry Andric     // Drill into reference types.
2772*0b57cec5SDimitry Andric     LValue LV = VD->getType()->isReferenceType() ?
2773*0b57cec5SDimitry Andric         EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2774*0b57cec5SDimitry Andric         MakeAddrLValue(addr, T, AlignmentSource::Decl);
2775*0b57cec5SDimitry Andric 
2776*0b57cec5SDimitry Andric     bool isLocalStorage = VD->hasLocalStorage();
2777*0b57cec5SDimitry Andric 
2778*0b57cec5SDimitry Andric     bool NonGCable = isLocalStorage &&
2779*0b57cec5SDimitry Andric                      !VD->getType()->isReferenceType() &&
2780*0b57cec5SDimitry Andric                      !isBlockByref;
2781*0b57cec5SDimitry Andric     if (NonGCable) {
2782*0b57cec5SDimitry Andric       LV.getQuals().removeObjCGCAttr();
2783*0b57cec5SDimitry Andric       LV.setNonGC(true);
2784*0b57cec5SDimitry Andric     }
2785*0b57cec5SDimitry Andric 
2786*0b57cec5SDimitry Andric     bool isImpreciseLifetime =
2787*0b57cec5SDimitry Andric       (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2788*0b57cec5SDimitry Andric     if (isImpreciseLifetime)
2789*0b57cec5SDimitry Andric       LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2790*0b57cec5SDimitry Andric     setObjCGCLValueClass(getContext(), E, LV);
2791*0b57cec5SDimitry Andric     return LV;
2792*0b57cec5SDimitry Andric   }
2793*0b57cec5SDimitry Andric 
2794*0b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2795*0b57cec5SDimitry Andric     return EmitFunctionDeclLValue(*this, E, FD);
2796*0b57cec5SDimitry Andric 
2797*0b57cec5SDimitry Andric   // FIXME: While we're emitting a binding from an enclosing scope, all other
2798*0b57cec5SDimitry Andric   // DeclRefExprs we see should be implicitly treated as if they also refer to
2799*0b57cec5SDimitry Andric   // an enclosing scope.
2800*0b57cec5SDimitry Andric   if (const auto *BD = dyn_cast<BindingDecl>(ND))
2801*0b57cec5SDimitry Andric     return EmitLValue(BD->getBinding());
2802*0b57cec5SDimitry Andric 
28035ffd83dbSDimitry Andric   // We can form DeclRefExprs naming GUID declarations when reconstituting
28045ffd83dbSDimitry Andric   // non-type template parameters into expressions.
28055ffd83dbSDimitry Andric   if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
28065ffd83dbSDimitry Andric     return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
28075ffd83dbSDimitry Andric                           AlignmentSource::Decl);
28085ffd83dbSDimitry Andric 
2809*0b57cec5SDimitry Andric   llvm_unreachable("Unhandled DeclRefExpr");
2810*0b57cec5SDimitry Andric }
2811*0b57cec5SDimitry Andric 
2812*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2813*0b57cec5SDimitry Andric   // __extension__ doesn't affect lvalue-ness.
2814*0b57cec5SDimitry Andric   if (E->getOpcode() == UO_Extension)
2815*0b57cec5SDimitry Andric     return EmitLValue(E->getSubExpr());
2816*0b57cec5SDimitry Andric 
2817*0b57cec5SDimitry Andric   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2818*0b57cec5SDimitry Andric   switch (E->getOpcode()) {
2819*0b57cec5SDimitry Andric   default: llvm_unreachable("Unknown unary operator lvalue!");
2820*0b57cec5SDimitry Andric   case UO_Deref: {
2821*0b57cec5SDimitry Andric     QualType T = E->getSubExpr()->getType()->getPointeeType();
2822*0b57cec5SDimitry Andric     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2823*0b57cec5SDimitry Andric 
2824*0b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
2825*0b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
2826*0b57cec5SDimitry Andric     Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2827*0b57cec5SDimitry Andric                                             &TBAAInfo);
2828*0b57cec5SDimitry Andric     LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
2829*0b57cec5SDimitry Andric     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2830*0b57cec5SDimitry Andric 
2831*0b57cec5SDimitry Andric     // We should not generate __weak write barrier on indirect reference
2832*0b57cec5SDimitry Andric     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2833*0b57cec5SDimitry Andric     // But, we continue to generate __strong write barrier on indirect write
2834*0b57cec5SDimitry Andric     // into a pointer to object.
2835*0b57cec5SDimitry Andric     if (getLangOpts().ObjC &&
2836*0b57cec5SDimitry Andric         getLangOpts().getGC() != LangOptions::NonGC &&
2837*0b57cec5SDimitry Andric         LV.isObjCWeak())
2838*0b57cec5SDimitry Andric       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2839*0b57cec5SDimitry Andric     return LV;
2840*0b57cec5SDimitry Andric   }
2841*0b57cec5SDimitry Andric   case UO_Real:
2842*0b57cec5SDimitry Andric   case UO_Imag: {
2843*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
2844*0b57cec5SDimitry Andric     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2845*0b57cec5SDimitry Andric 
2846*0b57cec5SDimitry Andric     // __real is valid on scalars.  This is a faster way of testing that.
2847*0b57cec5SDimitry Andric     // __imag can only produce an rvalue on scalars.
2848*0b57cec5SDimitry Andric     if (E->getOpcode() == UO_Real &&
2849480093f4SDimitry Andric         !LV.getAddress(*this).getElementType()->isStructTy()) {
2850*0b57cec5SDimitry Andric       assert(E->getSubExpr()->getType()->isArithmeticType());
2851*0b57cec5SDimitry Andric       return LV;
2852*0b57cec5SDimitry Andric     }
2853*0b57cec5SDimitry Andric 
2854*0b57cec5SDimitry Andric     QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2855*0b57cec5SDimitry Andric 
2856*0b57cec5SDimitry Andric     Address Component =
2857*0b57cec5SDimitry Andric         (E->getOpcode() == UO_Real
2858480093f4SDimitry Andric              ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
2859480093f4SDimitry Andric              : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType()));
2860*0b57cec5SDimitry Andric     LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
2861*0b57cec5SDimitry Andric                                    CGM.getTBAAInfoForSubobject(LV, T));
2862*0b57cec5SDimitry Andric     ElemLV.getQuals().addQualifiers(LV.getQuals());
2863*0b57cec5SDimitry Andric     return ElemLV;
2864*0b57cec5SDimitry Andric   }
2865*0b57cec5SDimitry Andric   case UO_PreInc:
2866*0b57cec5SDimitry Andric   case UO_PreDec: {
2867*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
2868*0b57cec5SDimitry Andric     bool isInc = E->getOpcode() == UO_PreInc;
2869*0b57cec5SDimitry Andric 
2870*0b57cec5SDimitry Andric     if (E->getType()->isAnyComplexType())
2871*0b57cec5SDimitry Andric       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2872*0b57cec5SDimitry Andric     else
2873*0b57cec5SDimitry Andric       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2874*0b57cec5SDimitry Andric     return LV;
2875*0b57cec5SDimitry Andric   }
2876*0b57cec5SDimitry Andric   }
2877*0b57cec5SDimitry Andric }
2878*0b57cec5SDimitry Andric 
2879*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2880*0b57cec5SDimitry Andric   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2881*0b57cec5SDimitry Andric                         E->getType(), AlignmentSource::Decl);
2882*0b57cec5SDimitry Andric }
2883*0b57cec5SDimitry Andric 
2884*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2885*0b57cec5SDimitry Andric   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2886*0b57cec5SDimitry Andric                         E->getType(), AlignmentSource::Decl);
2887*0b57cec5SDimitry Andric }
2888*0b57cec5SDimitry Andric 
2889*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2890*0b57cec5SDimitry Andric   auto SL = E->getFunctionName();
2891*0b57cec5SDimitry Andric   assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2892*0b57cec5SDimitry Andric   StringRef FnName = CurFn->getName();
2893*0b57cec5SDimitry Andric   if (FnName.startswith("\01"))
2894*0b57cec5SDimitry Andric     FnName = FnName.substr(1);
2895*0b57cec5SDimitry Andric   StringRef NameItems[] = {
2896*0b57cec5SDimitry Andric       PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
2897*0b57cec5SDimitry Andric   std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2898*0b57cec5SDimitry Andric   if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
28995ffd83dbSDimitry Andric     std::string Name = std::string(SL->getString());
2900*0b57cec5SDimitry Andric     if (!Name.empty()) {
2901*0b57cec5SDimitry Andric       unsigned Discriminator =
2902*0b57cec5SDimitry Andric           CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2903*0b57cec5SDimitry Andric       if (Discriminator)
2904*0b57cec5SDimitry Andric         Name += "_" + Twine(Discriminator + 1).str();
2905*0b57cec5SDimitry Andric       auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2906*0b57cec5SDimitry Andric       return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2907*0b57cec5SDimitry Andric     } else {
29085ffd83dbSDimitry Andric       auto C =
29095ffd83dbSDimitry Andric           CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
2910*0b57cec5SDimitry Andric       return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2911*0b57cec5SDimitry Andric     }
2912*0b57cec5SDimitry Andric   }
2913*0b57cec5SDimitry Andric   auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2914*0b57cec5SDimitry Andric   return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2915*0b57cec5SDimitry Andric }
2916*0b57cec5SDimitry Andric 
2917*0b57cec5SDimitry Andric /// Emit a type description suitable for use by a runtime sanitizer library. The
2918*0b57cec5SDimitry Andric /// format of a type descriptor is
2919*0b57cec5SDimitry Andric ///
2920*0b57cec5SDimitry Andric /// \code
2921*0b57cec5SDimitry Andric ///   { i16 TypeKind, i16 TypeInfo }
2922*0b57cec5SDimitry Andric /// \endcode
2923*0b57cec5SDimitry Andric ///
2924*0b57cec5SDimitry Andric /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2925*0b57cec5SDimitry Andric /// integer, 1 for a floating point value, and -1 for anything else.
2926*0b57cec5SDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2927*0b57cec5SDimitry Andric   // Only emit each type's descriptor once.
2928*0b57cec5SDimitry Andric   if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2929*0b57cec5SDimitry Andric     return C;
2930*0b57cec5SDimitry Andric 
2931*0b57cec5SDimitry Andric   uint16_t TypeKind = -1;
2932*0b57cec5SDimitry Andric   uint16_t TypeInfo = 0;
2933*0b57cec5SDimitry Andric 
2934*0b57cec5SDimitry Andric   if (T->isIntegerType()) {
2935*0b57cec5SDimitry Andric     TypeKind = 0;
2936*0b57cec5SDimitry Andric     TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2937*0b57cec5SDimitry Andric                (T->isSignedIntegerType() ? 1 : 0);
2938*0b57cec5SDimitry Andric   } else if (T->isFloatingType()) {
2939*0b57cec5SDimitry Andric     TypeKind = 1;
2940*0b57cec5SDimitry Andric     TypeInfo = getContext().getTypeSize(T);
2941*0b57cec5SDimitry Andric   }
2942*0b57cec5SDimitry Andric 
2943*0b57cec5SDimitry Andric   // Format the type name as if for a diagnostic, including quotes and
2944*0b57cec5SDimitry Andric   // optionally an 'aka'.
2945*0b57cec5SDimitry Andric   SmallString<32> Buffer;
2946*0b57cec5SDimitry Andric   CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2947*0b57cec5SDimitry Andric                                     (intptr_t)T.getAsOpaquePtr(),
2948*0b57cec5SDimitry Andric                                     StringRef(), StringRef(), None, Buffer,
2949*0b57cec5SDimitry Andric                                     None);
2950*0b57cec5SDimitry Andric 
2951*0b57cec5SDimitry Andric   llvm::Constant *Components[] = {
2952*0b57cec5SDimitry Andric     Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2953*0b57cec5SDimitry Andric     llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2954*0b57cec5SDimitry Andric   };
2955*0b57cec5SDimitry Andric   llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2956*0b57cec5SDimitry Andric 
2957*0b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
2958*0b57cec5SDimitry Andric       CGM.getModule(), Descriptor->getType(),
2959*0b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2960*0b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2961*0b57cec5SDimitry Andric   CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2962*0b57cec5SDimitry Andric 
2963*0b57cec5SDimitry Andric   // Remember the descriptor for this type.
2964*0b57cec5SDimitry Andric   CGM.setTypeDescriptorInMap(T, GV);
2965*0b57cec5SDimitry Andric 
2966*0b57cec5SDimitry Andric   return GV;
2967*0b57cec5SDimitry Andric }
2968*0b57cec5SDimitry Andric 
2969*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2970*0b57cec5SDimitry Andric   llvm::Type *TargetTy = IntPtrTy;
2971*0b57cec5SDimitry Andric 
2972*0b57cec5SDimitry Andric   if (V->getType() == TargetTy)
2973*0b57cec5SDimitry Andric     return V;
2974*0b57cec5SDimitry Andric 
2975*0b57cec5SDimitry Andric   // Floating-point types which fit into intptr_t are bitcast to integers
2976*0b57cec5SDimitry Andric   // and then passed directly (after zero-extension, if necessary).
2977*0b57cec5SDimitry Andric   if (V->getType()->isFloatingPointTy()) {
2978*0b57cec5SDimitry Andric     unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2979*0b57cec5SDimitry Andric     if (Bits <= TargetTy->getIntegerBitWidth())
2980*0b57cec5SDimitry Andric       V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2981*0b57cec5SDimitry Andric                                                          Bits));
2982*0b57cec5SDimitry Andric   }
2983*0b57cec5SDimitry Andric 
2984*0b57cec5SDimitry Andric   // Integers which fit in intptr_t are zero-extended and passed directly.
2985*0b57cec5SDimitry Andric   if (V->getType()->isIntegerTy() &&
2986*0b57cec5SDimitry Andric       V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2987*0b57cec5SDimitry Andric     return Builder.CreateZExt(V, TargetTy);
2988*0b57cec5SDimitry Andric 
2989*0b57cec5SDimitry Andric   // Pointers are passed directly, everything else is passed by address.
2990*0b57cec5SDimitry Andric   if (!V->getType()->isPointerTy()) {
2991*0b57cec5SDimitry Andric     Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2992*0b57cec5SDimitry Andric     Builder.CreateStore(V, Ptr);
2993*0b57cec5SDimitry Andric     V = Ptr.getPointer();
2994*0b57cec5SDimitry Andric   }
2995*0b57cec5SDimitry Andric   return Builder.CreatePtrToInt(V, TargetTy);
2996*0b57cec5SDimitry Andric }
2997*0b57cec5SDimitry Andric 
2998*0b57cec5SDimitry Andric /// Emit a representation of a SourceLocation for passing to a handler
2999*0b57cec5SDimitry Andric /// in a sanitizer runtime library. The format for this data is:
3000*0b57cec5SDimitry Andric /// \code
3001*0b57cec5SDimitry Andric ///   struct SourceLocation {
3002*0b57cec5SDimitry Andric ///     const char *Filename;
3003*0b57cec5SDimitry Andric ///     int32_t Line, Column;
3004*0b57cec5SDimitry Andric ///   };
3005*0b57cec5SDimitry Andric /// \endcode
3006*0b57cec5SDimitry Andric /// For an invalid SourceLocation, the Filename pointer is null.
3007*0b57cec5SDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
3008*0b57cec5SDimitry Andric   llvm::Constant *Filename;
3009*0b57cec5SDimitry Andric   int Line, Column;
3010*0b57cec5SDimitry Andric 
3011*0b57cec5SDimitry Andric   PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
3012*0b57cec5SDimitry Andric   if (PLoc.isValid()) {
3013*0b57cec5SDimitry Andric     StringRef FilenameString = PLoc.getFilename();
3014*0b57cec5SDimitry Andric 
3015*0b57cec5SDimitry Andric     int PathComponentsToStrip =
3016*0b57cec5SDimitry Andric         CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
3017*0b57cec5SDimitry Andric     if (PathComponentsToStrip < 0) {
3018*0b57cec5SDimitry Andric       assert(PathComponentsToStrip != INT_MIN);
3019*0b57cec5SDimitry Andric       int PathComponentsToKeep = -PathComponentsToStrip;
3020*0b57cec5SDimitry Andric       auto I = llvm::sys::path::rbegin(FilenameString);
3021*0b57cec5SDimitry Andric       auto E = llvm::sys::path::rend(FilenameString);
3022*0b57cec5SDimitry Andric       while (I != E && --PathComponentsToKeep)
3023*0b57cec5SDimitry Andric         ++I;
3024*0b57cec5SDimitry Andric 
3025*0b57cec5SDimitry Andric       FilenameString = FilenameString.substr(I - E);
3026*0b57cec5SDimitry Andric     } else if (PathComponentsToStrip > 0) {
3027*0b57cec5SDimitry Andric       auto I = llvm::sys::path::begin(FilenameString);
3028*0b57cec5SDimitry Andric       auto E = llvm::sys::path::end(FilenameString);
3029*0b57cec5SDimitry Andric       while (I != E && PathComponentsToStrip--)
3030*0b57cec5SDimitry Andric         ++I;
3031*0b57cec5SDimitry Andric 
3032*0b57cec5SDimitry Andric       if (I != E)
3033*0b57cec5SDimitry Andric         FilenameString =
3034*0b57cec5SDimitry Andric             FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
3035*0b57cec5SDimitry Andric       else
3036*0b57cec5SDimitry Andric         FilenameString = llvm::sys::path::filename(FilenameString);
3037*0b57cec5SDimitry Andric     }
3038*0b57cec5SDimitry Andric 
30395ffd83dbSDimitry Andric     auto FilenameGV =
30405ffd83dbSDimitry Andric         CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
3041*0b57cec5SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
3042*0b57cec5SDimitry Andric                           cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
3043*0b57cec5SDimitry Andric     Filename = FilenameGV.getPointer();
3044*0b57cec5SDimitry Andric     Line = PLoc.getLine();
3045*0b57cec5SDimitry Andric     Column = PLoc.getColumn();
3046*0b57cec5SDimitry Andric   } else {
3047*0b57cec5SDimitry Andric     Filename = llvm::Constant::getNullValue(Int8PtrTy);
3048*0b57cec5SDimitry Andric     Line = Column = 0;
3049*0b57cec5SDimitry Andric   }
3050*0b57cec5SDimitry Andric 
3051*0b57cec5SDimitry Andric   llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
3052*0b57cec5SDimitry Andric                             Builder.getInt32(Column)};
3053*0b57cec5SDimitry Andric 
3054*0b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Data);
3055*0b57cec5SDimitry Andric }
3056*0b57cec5SDimitry Andric 
3057*0b57cec5SDimitry Andric namespace {
3058*0b57cec5SDimitry Andric /// Specify under what conditions this check can be recovered
3059*0b57cec5SDimitry Andric enum class CheckRecoverableKind {
3060*0b57cec5SDimitry Andric   /// Always terminate program execution if this check fails.
3061*0b57cec5SDimitry Andric   Unrecoverable,
3062*0b57cec5SDimitry Andric   /// Check supports recovering, runtime has both fatal (noreturn) and
3063*0b57cec5SDimitry Andric   /// non-fatal handlers for this check.
3064*0b57cec5SDimitry Andric   Recoverable,
3065*0b57cec5SDimitry Andric   /// Runtime conditionally aborts, always need to support recovery.
3066*0b57cec5SDimitry Andric   AlwaysRecoverable
3067*0b57cec5SDimitry Andric };
3068*0b57cec5SDimitry Andric }
3069*0b57cec5SDimitry Andric 
3070*0b57cec5SDimitry Andric static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
3071*0b57cec5SDimitry Andric   assert(Kind.countPopulation() == 1);
3072*0b57cec5SDimitry Andric   if (Kind == SanitizerKind::Function || Kind == SanitizerKind::Vptr)
3073*0b57cec5SDimitry Andric     return CheckRecoverableKind::AlwaysRecoverable;
3074*0b57cec5SDimitry Andric   else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
3075*0b57cec5SDimitry Andric     return CheckRecoverableKind::Unrecoverable;
3076*0b57cec5SDimitry Andric   else
3077*0b57cec5SDimitry Andric     return CheckRecoverableKind::Recoverable;
3078*0b57cec5SDimitry Andric }
3079*0b57cec5SDimitry Andric 
3080*0b57cec5SDimitry Andric namespace {
3081*0b57cec5SDimitry Andric struct SanitizerHandlerInfo {
3082*0b57cec5SDimitry Andric   char const *const Name;
3083*0b57cec5SDimitry Andric   unsigned Version;
3084*0b57cec5SDimitry Andric };
3085*0b57cec5SDimitry Andric }
3086*0b57cec5SDimitry Andric 
3087*0b57cec5SDimitry Andric const SanitizerHandlerInfo SanitizerHandlers[] = {
3088*0b57cec5SDimitry Andric #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
3089*0b57cec5SDimitry Andric     LIST_SANITIZER_CHECKS
3090*0b57cec5SDimitry Andric #undef SANITIZER_CHECK
3091*0b57cec5SDimitry Andric };
3092*0b57cec5SDimitry Andric 
3093*0b57cec5SDimitry Andric static void emitCheckHandlerCall(CodeGenFunction &CGF,
3094*0b57cec5SDimitry Andric                                  llvm::FunctionType *FnType,
3095*0b57cec5SDimitry Andric                                  ArrayRef<llvm::Value *> FnArgs,
3096*0b57cec5SDimitry Andric                                  SanitizerHandler CheckHandler,
3097*0b57cec5SDimitry Andric                                  CheckRecoverableKind RecoverKind, bool IsFatal,
3098*0b57cec5SDimitry Andric                                  llvm::BasicBlock *ContBB) {
3099*0b57cec5SDimitry Andric   assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
3100*0b57cec5SDimitry Andric   Optional<ApplyDebugLocation> DL;
3101*0b57cec5SDimitry Andric   if (!CGF.Builder.getCurrentDebugLocation()) {
3102*0b57cec5SDimitry Andric     // Ensure that the call has at least an artificial debug location.
3103*0b57cec5SDimitry Andric     DL.emplace(CGF, SourceLocation());
3104*0b57cec5SDimitry Andric   }
3105*0b57cec5SDimitry Andric   bool NeedsAbortSuffix =
3106*0b57cec5SDimitry Andric       IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
3107*0b57cec5SDimitry Andric   bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
3108*0b57cec5SDimitry Andric   const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
3109*0b57cec5SDimitry Andric   const StringRef CheckName = CheckInfo.Name;
3110*0b57cec5SDimitry Andric   std::string FnName = "__ubsan_handle_" + CheckName.str();
3111*0b57cec5SDimitry Andric   if (CheckInfo.Version && !MinimalRuntime)
3112*0b57cec5SDimitry Andric     FnName += "_v" + llvm::utostr(CheckInfo.Version);
3113*0b57cec5SDimitry Andric   if (MinimalRuntime)
3114*0b57cec5SDimitry Andric     FnName += "_minimal";
3115*0b57cec5SDimitry Andric   if (NeedsAbortSuffix)
3116*0b57cec5SDimitry Andric     FnName += "_abort";
3117*0b57cec5SDimitry Andric   bool MayReturn =
3118*0b57cec5SDimitry Andric       !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
3119*0b57cec5SDimitry Andric 
3120*0b57cec5SDimitry Andric   llvm::AttrBuilder B;
3121*0b57cec5SDimitry Andric   if (!MayReturn) {
3122*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoReturn)
3123*0b57cec5SDimitry Andric         .addAttribute(llvm::Attribute::NoUnwind);
3124*0b57cec5SDimitry Andric   }
3125*0b57cec5SDimitry Andric   B.addAttribute(llvm::Attribute::UWTable);
3126*0b57cec5SDimitry Andric 
3127*0b57cec5SDimitry Andric   llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
3128*0b57cec5SDimitry Andric       FnType, FnName,
3129*0b57cec5SDimitry Andric       llvm::AttributeList::get(CGF.getLLVMContext(),
3130*0b57cec5SDimitry Andric                                llvm::AttributeList::FunctionIndex, B),
3131*0b57cec5SDimitry Andric       /*Local=*/true);
3132*0b57cec5SDimitry Andric   llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
3133*0b57cec5SDimitry Andric   if (!MayReturn) {
3134*0b57cec5SDimitry Andric     HandlerCall->setDoesNotReturn();
3135*0b57cec5SDimitry Andric     CGF.Builder.CreateUnreachable();
3136*0b57cec5SDimitry Andric   } else {
3137*0b57cec5SDimitry Andric     CGF.Builder.CreateBr(ContBB);
3138*0b57cec5SDimitry Andric   }
3139*0b57cec5SDimitry Andric }
3140*0b57cec5SDimitry Andric 
3141*0b57cec5SDimitry Andric void CodeGenFunction::EmitCheck(
3142*0b57cec5SDimitry Andric     ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3143*0b57cec5SDimitry Andric     SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
3144*0b57cec5SDimitry Andric     ArrayRef<llvm::Value *> DynamicArgs) {
3145*0b57cec5SDimitry Andric   assert(IsSanitizerScope);
3146*0b57cec5SDimitry Andric   assert(Checked.size() > 0);
3147*0b57cec5SDimitry Andric   assert(CheckHandler >= 0 &&
3148*0b57cec5SDimitry Andric          size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
3149*0b57cec5SDimitry Andric   const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
3150*0b57cec5SDimitry Andric 
3151*0b57cec5SDimitry Andric   llvm::Value *FatalCond = nullptr;
3152*0b57cec5SDimitry Andric   llvm::Value *RecoverableCond = nullptr;
3153*0b57cec5SDimitry Andric   llvm::Value *TrapCond = nullptr;
3154*0b57cec5SDimitry Andric   for (int i = 0, n = Checked.size(); i < n; ++i) {
3155*0b57cec5SDimitry Andric     llvm::Value *Check = Checked[i].first;
3156*0b57cec5SDimitry Andric     // -fsanitize-trap= overrides -fsanitize-recover=.
3157*0b57cec5SDimitry Andric     llvm::Value *&Cond =
3158*0b57cec5SDimitry Andric         CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
3159*0b57cec5SDimitry Andric             ? TrapCond
3160*0b57cec5SDimitry Andric             : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
3161*0b57cec5SDimitry Andric                   ? RecoverableCond
3162*0b57cec5SDimitry Andric                   : FatalCond;
3163*0b57cec5SDimitry Andric     Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
3164*0b57cec5SDimitry Andric   }
3165*0b57cec5SDimitry Andric 
3166*0b57cec5SDimitry Andric   if (TrapCond)
3167*0b57cec5SDimitry Andric     EmitTrapCheck(TrapCond);
3168*0b57cec5SDimitry Andric   if (!FatalCond && !RecoverableCond)
3169*0b57cec5SDimitry Andric     return;
3170*0b57cec5SDimitry Andric 
3171*0b57cec5SDimitry Andric   llvm::Value *JointCond;
3172*0b57cec5SDimitry Andric   if (FatalCond && RecoverableCond)
3173*0b57cec5SDimitry Andric     JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
3174*0b57cec5SDimitry Andric   else
3175*0b57cec5SDimitry Andric     JointCond = FatalCond ? FatalCond : RecoverableCond;
3176*0b57cec5SDimitry Andric   assert(JointCond);
3177*0b57cec5SDimitry Andric 
3178*0b57cec5SDimitry Andric   CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
3179*0b57cec5SDimitry Andric   assert(SanOpts.has(Checked[0].second));
3180*0b57cec5SDimitry Andric #ifndef NDEBUG
3181*0b57cec5SDimitry Andric   for (int i = 1, n = Checked.size(); i < n; ++i) {
3182*0b57cec5SDimitry Andric     assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
3183*0b57cec5SDimitry Andric            "All recoverable kinds in a single check must be same!");
3184*0b57cec5SDimitry Andric     assert(SanOpts.has(Checked[i].second));
3185*0b57cec5SDimitry Andric   }
3186*0b57cec5SDimitry Andric #endif
3187*0b57cec5SDimitry Andric 
3188*0b57cec5SDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cont");
3189*0b57cec5SDimitry Andric   llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
3190*0b57cec5SDimitry Andric   llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
3191*0b57cec5SDimitry Andric   // Give hint that we very much don't expect to execute the handler
3192*0b57cec5SDimitry Andric   // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
3193*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
3194*0b57cec5SDimitry Andric   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3195*0b57cec5SDimitry Andric   Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
3196*0b57cec5SDimitry Andric   EmitBlock(Handlers);
3197*0b57cec5SDimitry Andric 
3198*0b57cec5SDimitry Andric   // Handler functions take an i8* pointing to the (handler-specific) static
3199*0b57cec5SDimitry Andric   // information block, followed by a sequence of intptr_t arguments
3200*0b57cec5SDimitry Andric   // representing operand values.
3201*0b57cec5SDimitry Andric   SmallVector<llvm::Value *, 4> Args;
3202*0b57cec5SDimitry Andric   SmallVector<llvm::Type *, 4> ArgTypes;
3203*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
3204*0b57cec5SDimitry Andric     Args.reserve(DynamicArgs.size() + 1);
3205*0b57cec5SDimitry Andric     ArgTypes.reserve(DynamicArgs.size() + 1);
3206*0b57cec5SDimitry Andric 
3207*0b57cec5SDimitry Andric     // Emit handler arguments and create handler function type.
3208*0b57cec5SDimitry Andric     if (!StaticArgs.empty()) {
3209*0b57cec5SDimitry Andric       llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3210*0b57cec5SDimitry Andric       auto *InfoPtr =
3211*0b57cec5SDimitry Andric           new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3212*0b57cec5SDimitry Andric                                    llvm::GlobalVariable::PrivateLinkage, Info);
3213*0b57cec5SDimitry Andric       InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3214*0b57cec5SDimitry Andric       CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3215*0b57cec5SDimitry Andric       Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
3216*0b57cec5SDimitry Andric       ArgTypes.push_back(Int8PtrTy);
3217*0b57cec5SDimitry Andric     }
3218*0b57cec5SDimitry Andric 
3219*0b57cec5SDimitry Andric     for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
3220*0b57cec5SDimitry Andric       Args.push_back(EmitCheckValue(DynamicArgs[i]));
3221*0b57cec5SDimitry Andric       ArgTypes.push_back(IntPtrTy);
3222*0b57cec5SDimitry Andric     }
3223*0b57cec5SDimitry Andric   }
3224*0b57cec5SDimitry Andric 
3225*0b57cec5SDimitry Andric   llvm::FunctionType *FnType =
3226*0b57cec5SDimitry Andric     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
3227*0b57cec5SDimitry Andric 
3228*0b57cec5SDimitry Andric   if (!FatalCond || !RecoverableCond) {
3229*0b57cec5SDimitry Andric     // Simple case: we need to generate a single handler call, either
3230*0b57cec5SDimitry Andric     // fatal, or non-fatal.
3231*0b57cec5SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
3232*0b57cec5SDimitry Andric                          (FatalCond != nullptr), Cont);
3233*0b57cec5SDimitry Andric   } else {
3234*0b57cec5SDimitry Andric     // Emit two handler calls: first one for set of unrecoverable checks,
3235*0b57cec5SDimitry Andric     // another one for recoverable.
3236*0b57cec5SDimitry Andric     llvm::BasicBlock *NonFatalHandlerBB =
3237*0b57cec5SDimitry Andric         createBasicBlock("non_fatal." + CheckName);
3238*0b57cec5SDimitry Andric     llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
3239*0b57cec5SDimitry Andric     Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
3240*0b57cec5SDimitry Andric     EmitBlock(FatalHandlerBB);
3241*0b57cec5SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
3242*0b57cec5SDimitry Andric                          NonFatalHandlerBB);
3243*0b57cec5SDimitry Andric     EmitBlock(NonFatalHandlerBB);
3244*0b57cec5SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
3245*0b57cec5SDimitry Andric                          Cont);
3246*0b57cec5SDimitry Andric   }
3247*0b57cec5SDimitry Andric 
3248*0b57cec5SDimitry Andric   EmitBlock(Cont);
3249*0b57cec5SDimitry Andric }
3250*0b57cec5SDimitry Andric 
3251*0b57cec5SDimitry Andric void CodeGenFunction::EmitCfiSlowPathCheck(
3252*0b57cec5SDimitry Andric     SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
3253*0b57cec5SDimitry Andric     llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
3254*0b57cec5SDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
3255*0b57cec5SDimitry Andric 
3256*0b57cec5SDimitry Andric   llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
3257*0b57cec5SDimitry Andric   llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
3258*0b57cec5SDimitry Andric 
3259*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
3260*0b57cec5SDimitry Andric   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3261*0b57cec5SDimitry Andric   BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
3262*0b57cec5SDimitry Andric 
3263*0b57cec5SDimitry Andric   EmitBlock(CheckBB);
3264*0b57cec5SDimitry Andric 
3265*0b57cec5SDimitry Andric   bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
3266*0b57cec5SDimitry Andric 
3267*0b57cec5SDimitry Andric   llvm::CallInst *CheckCall;
3268*0b57cec5SDimitry Andric   llvm::FunctionCallee SlowPathFn;
3269*0b57cec5SDimitry Andric   if (WithDiag) {
3270*0b57cec5SDimitry Andric     llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3271*0b57cec5SDimitry Andric     auto *InfoPtr =
3272*0b57cec5SDimitry Andric         new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3273*0b57cec5SDimitry Andric                                  llvm::GlobalVariable::PrivateLinkage, Info);
3274*0b57cec5SDimitry Andric     InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3275*0b57cec5SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3276*0b57cec5SDimitry Andric 
3277*0b57cec5SDimitry Andric     SlowPathFn = CGM.getModule().getOrInsertFunction(
3278*0b57cec5SDimitry Andric         "__cfi_slowpath_diag",
3279*0b57cec5SDimitry Andric         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
3280*0b57cec5SDimitry Andric                                 false));
3281*0b57cec5SDimitry Andric     CheckCall = Builder.CreateCall(
3282*0b57cec5SDimitry Andric         SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
3283*0b57cec5SDimitry Andric   } else {
3284*0b57cec5SDimitry Andric     SlowPathFn = CGM.getModule().getOrInsertFunction(
3285*0b57cec5SDimitry Andric         "__cfi_slowpath",
3286*0b57cec5SDimitry Andric         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
3287*0b57cec5SDimitry Andric     CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
3288*0b57cec5SDimitry Andric   }
3289*0b57cec5SDimitry Andric 
3290*0b57cec5SDimitry Andric   CGM.setDSOLocal(
3291*0b57cec5SDimitry Andric       cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
3292*0b57cec5SDimitry Andric   CheckCall->setDoesNotThrow();
3293*0b57cec5SDimitry Andric 
3294*0b57cec5SDimitry Andric   EmitBlock(Cont);
3295*0b57cec5SDimitry Andric }
3296*0b57cec5SDimitry Andric 
3297*0b57cec5SDimitry Andric // Emit a stub for __cfi_check function so that the linker knows about this
3298*0b57cec5SDimitry Andric // symbol in LTO mode.
3299*0b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckStub() {
3300*0b57cec5SDimitry Andric   llvm::Module *M = &CGM.getModule();
3301*0b57cec5SDimitry Andric   auto &Ctx = M->getContext();
3302*0b57cec5SDimitry Andric   llvm::Function *F = llvm::Function::Create(
3303*0b57cec5SDimitry Andric       llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
3304*0b57cec5SDimitry Andric       llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
3305*0b57cec5SDimitry Andric   CGM.setDSOLocal(F);
3306*0b57cec5SDimitry Andric   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
3307*0b57cec5SDimitry Andric   // FIXME: consider emitting an intrinsic call like
3308*0b57cec5SDimitry Andric   // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
3309*0b57cec5SDimitry Andric   // which can be lowered in CrossDSOCFI pass to the actual contents of
3310*0b57cec5SDimitry Andric   // __cfi_check. This would allow inlining of __cfi_check calls.
3311*0b57cec5SDimitry Andric   llvm::CallInst::Create(
3312*0b57cec5SDimitry Andric       llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
3313*0b57cec5SDimitry Andric   llvm::ReturnInst::Create(Ctx, nullptr, BB);
3314*0b57cec5SDimitry Andric }
3315*0b57cec5SDimitry Andric 
3316*0b57cec5SDimitry Andric // This function is basically a switch over the CFI failure kind, which is
3317*0b57cec5SDimitry Andric // extracted from CFICheckFailData (1st function argument). Each case is either
3318*0b57cec5SDimitry Andric // llvm.trap or a call to one of the two runtime handlers, based on
3319*0b57cec5SDimitry Andric // -fsanitize-trap and -fsanitize-recover settings.  Default case (invalid
3320*0b57cec5SDimitry Andric // failure kind) traps, but this should really never happen.  CFICheckFailData
3321*0b57cec5SDimitry Andric // can be nullptr if the calling module has -fsanitize-trap behavior for this
3322*0b57cec5SDimitry Andric // check kind; in this case __cfi_check_fail traps as well.
3323*0b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckFail() {
3324*0b57cec5SDimitry Andric   SanitizerScope SanScope(this);
3325*0b57cec5SDimitry Andric   FunctionArgList Args;
3326*0b57cec5SDimitry Andric   ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3327*0b57cec5SDimitry Andric                             ImplicitParamDecl::Other);
3328*0b57cec5SDimitry Andric   ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3329*0b57cec5SDimitry Andric                             ImplicitParamDecl::Other);
3330*0b57cec5SDimitry Andric   Args.push_back(&ArgData);
3331*0b57cec5SDimitry Andric   Args.push_back(&ArgAddr);
3332*0b57cec5SDimitry Andric 
3333*0b57cec5SDimitry Andric   const CGFunctionInfo &FI =
3334*0b57cec5SDimitry Andric     CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
3335*0b57cec5SDimitry Andric 
3336*0b57cec5SDimitry Andric   llvm::Function *F = llvm::Function::Create(
3337*0b57cec5SDimitry Andric       llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3338*0b57cec5SDimitry Andric       llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3339480093f4SDimitry Andric 
3340480093f4SDimitry Andric   CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F);
3341480093f4SDimitry Andric   CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
3342*0b57cec5SDimitry Andric   F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3343*0b57cec5SDimitry Andric 
3344*0b57cec5SDimitry Andric   StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3345*0b57cec5SDimitry Andric                 SourceLocation());
3346*0b57cec5SDimitry Andric 
3347*0b57cec5SDimitry Andric   // This function should not be affected by blacklist. This function does
3348*0b57cec5SDimitry Andric   // not have a source location, but "src:*" would still apply. Revert any
3349*0b57cec5SDimitry Andric   // changes to SanOpts made in StartFunction.
3350*0b57cec5SDimitry Andric   SanOpts = CGM.getLangOpts().Sanitize;
3351*0b57cec5SDimitry Andric 
3352*0b57cec5SDimitry Andric   llvm::Value *Data =
3353*0b57cec5SDimitry Andric       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3354*0b57cec5SDimitry Andric                        CGM.getContext().VoidPtrTy, ArgData.getLocation());
3355*0b57cec5SDimitry Andric   llvm::Value *Addr =
3356*0b57cec5SDimitry Andric       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3357*0b57cec5SDimitry Andric                        CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3358*0b57cec5SDimitry Andric 
3359*0b57cec5SDimitry Andric   // Data == nullptr means the calling module has trap behaviour for this check.
3360*0b57cec5SDimitry Andric   llvm::Value *DataIsNotNullPtr =
3361*0b57cec5SDimitry Andric       Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3362*0b57cec5SDimitry Andric   EmitTrapCheck(DataIsNotNullPtr);
3363*0b57cec5SDimitry Andric 
3364*0b57cec5SDimitry Andric   llvm::StructType *SourceLocationTy =
3365*0b57cec5SDimitry Andric       llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
3366*0b57cec5SDimitry Andric   llvm::StructType *CfiCheckFailDataTy =
3367*0b57cec5SDimitry Andric       llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
3368*0b57cec5SDimitry Andric 
3369*0b57cec5SDimitry Andric   llvm::Value *V = Builder.CreateConstGEP2_32(
3370*0b57cec5SDimitry Andric       CfiCheckFailDataTy,
3371*0b57cec5SDimitry Andric       Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3372*0b57cec5SDimitry Andric       0);
3373*0b57cec5SDimitry Andric   Address CheckKindAddr(V, getIntAlign());
3374*0b57cec5SDimitry Andric   llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3375*0b57cec5SDimitry Andric 
3376*0b57cec5SDimitry Andric   llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3377*0b57cec5SDimitry Andric       CGM.getLLVMContext(),
3378*0b57cec5SDimitry Andric       llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3379*0b57cec5SDimitry Andric   llvm::Value *ValidVtable = Builder.CreateZExt(
3380*0b57cec5SDimitry Andric       Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
3381*0b57cec5SDimitry Andric                          {Addr, AllVtables}),
3382*0b57cec5SDimitry Andric       IntPtrTy);
3383*0b57cec5SDimitry Andric 
3384*0b57cec5SDimitry Andric   const std::pair<int, SanitizerMask> CheckKinds[] = {
3385*0b57cec5SDimitry Andric       {CFITCK_VCall, SanitizerKind::CFIVCall},
3386*0b57cec5SDimitry Andric       {CFITCK_NVCall, SanitizerKind::CFINVCall},
3387*0b57cec5SDimitry Andric       {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3388*0b57cec5SDimitry Andric       {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3389*0b57cec5SDimitry Andric       {CFITCK_ICall, SanitizerKind::CFIICall}};
3390*0b57cec5SDimitry Andric 
3391*0b57cec5SDimitry Andric   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3392*0b57cec5SDimitry Andric   for (auto CheckKindMaskPair : CheckKinds) {
3393*0b57cec5SDimitry Andric     int Kind = CheckKindMaskPair.first;
3394*0b57cec5SDimitry Andric     SanitizerMask Mask = CheckKindMaskPair.second;
3395*0b57cec5SDimitry Andric     llvm::Value *Cond =
3396*0b57cec5SDimitry Andric         Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3397*0b57cec5SDimitry Andric     if (CGM.getLangOpts().Sanitize.has(Mask))
3398*0b57cec5SDimitry Andric       EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3399*0b57cec5SDimitry Andric                 {Data, Addr, ValidVtable});
3400*0b57cec5SDimitry Andric     else
3401*0b57cec5SDimitry Andric       EmitTrapCheck(Cond);
3402*0b57cec5SDimitry Andric   }
3403*0b57cec5SDimitry Andric 
3404*0b57cec5SDimitry Andric   FinishFunction();
3405*0b57cec5SDimitry Andric   // The only reference to this function will be created during LTO link.
3406*0b57cec5SDimitry Andric   // Make sure it survives until then.
3407*0b57cec5SDimitry Andric   CGM.addUsedGlobal(F);
3408*0b57cec5SDimitry Andric }
3409*0b57cec5SDimitry Andric 
3410*0b57cec5SDimitry Andric void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
3411*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Unreachable)) {
3412*0b57cec5SDimitry Andric     SanitizerScope SanScope(this);
3413*0b57cec5SDimitry Andric     EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3414*0b57cec5SDimitry Andric                              SanitizerKind::Unreachable),
3415*0b57cec5SDimitry Andric               SanitizerHandler::BuiltinUnreachable,
3416*0b57cec5SDimitry Andric               EmitCheckSourceLocation(Loc), None);
3417*0b57cec5SDimitry Andric   }
3418*0b57cec5SDimitry Andric   Builder.CreateUnreachable();
3419*0b57cec5SDimitry Andric }
3420*0b57cec5SDimitry Andric 
3421*0b57cec5SDimitry Andric void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
3422*0b57cec5SDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cont");
3423*0b57cec5SDimitry Andric 
3424*0b57cec5SDimitry Andric   // If we're optimizing, collapse all calls to trap down to just one per
3425*0b57cec5SDimitry Andric   // function to save on code size.
3426*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3427*0b57cec5SDimitry Andric     TrapBB = createBasicBlock("trap");
3428*0b57cec5SDimitry Andric     Builder.CreateCondBr(Checked, Cont, TrapBB);
3429*0b57cec5SDimitry Andric     EmitBlock(TrapBB);
3430*0b57cec5SDimitry Andric     llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3431*0b57cec5SDimitry Andric     TrapCall->setDoesNotReturn();
3432*0b57cec5SDimitry Andric     TrapCall->setDoesNotThrow();
3433*0b57cec5SDimitry Andric     Builder.CreateUnreachable();
3434*0b57cec5SDimitry Andric   } else {
3435*0b57cec5SDimitry Andric     Builder.CreateCondBr(Checked, Cont, TrapBB);
3436*0b57cec5SDimitry Andric   }
3437*0b57cec5SDimitry Andric 
3438*0b57cec5SDimitry Andric   EmitBlock(Cont);
3439*0b57cec5SDimitry Andric }
3440*0b57cec5SDimitry Andric 
3441*0b57cec5SDimitry Andric llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3442*0b57cec5SDimitry Andric   llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
3443*0b57cec5SDimitry Andric 
3444*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3445*0b57cec5SDimitry Andric     auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3446*0b57cec5SDimitry Andric                                   CGM.getCodeGenOpts().TrapFuncName);
3447*0b57cec5SDimitry Andric     TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
3448*0b57cec5SDimitry Andric   }
3449*0b57cec5SDimitry Andric 
3450*0b57cec5SDimitry Andric   return TrapCall;
3451*0b57cec5SDimitry Andric }
3452*0b57cec5SDimitry Andric 
3453*0b57cec5SDimitry Andric Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
3454*0b57cec5SDimitry Andric                                                  LValueBaseInfo *BaseInfo,
3455*0b57cec5SDimitry Andric                                                  TBAAAccessInfo *TBAAInfo) {
3456*0b57cec5SDimitry Andric   assert(E->getType()->isArrayType() &&
3457*0b57cec5SDimitry Andric          "Array to pointer decay must have array source type!");
3458*0b57cec5SDimitry Andric 
3459*0b57cec5SDimitry Andric   // Expressions of array type can't be bitfields or vector elements.
3460*0b57cec5SDimitry Andric   LValue LV = EmitLValue(E);
3461480093f4SDimitry Andric   Address Addr = LV.getAddress(*this);
3462*0b57cec5SDimitry Andric 
3463*0b57cec5SDimitry Andric   // If the array type was an incomplete type, we need to make sure
3464*0b57cec5SDimitry Andric   // the decay ends up being the right type.
3465*0b57cec5SDimitry Andric   llvm::Type *NewTy = ConvertType(E->getType());
3466*0b57cec5SDimitry Andric   Addr = Builder.CreateElementBitCast(Addr, NewTy);
3467*0b57cec5SDimitry Andric 
3468*0b57cec5SDimitry Andric   // Note that VLA pointers are always decayed, so we don't need to do
3469*0b57cec5SDimitry Andric   // anything here.
3470*0b57cec5SDimitry Andric   if (!E->getType()->isVariableArrayType()) {
3471*0b57cec5SDimitry Andric     assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3472*0b57cec5SDimitry Andric            "Expected pointer to array");
3473*0b57cec5SDimitry Andric     Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3474*0b57cec5SDimitry Andric   }
3475*0b57cec5SDimitry Andric 
3476*0b57cec5SDimitry Andric   // The result of this decay conversion points to an array element within the
3477*0b57cec5SDimitry Andric   // base lvalue. However, since TBAA currently does not support representing
3478*0b57cec5SDimitry Andric   // accesses to elements of member arrays, we conservatively represent accesses
3479*0b57cec5SDimitry Andric   // to the pointee object as if it had no any base lvalue specified.
3480*0b57cec5SDimitry Andric   // TODO: Support TBAA for member arrays.
3481*0b57cec5SDimitry Andric   QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3482*0b57cec5SDimitry Andric   if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3483*0b57cec5SDimitry Andric   if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3484*0b57cec5SDimitry Andric 
3485*0b57cec5SDimitry Andric   return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3486*0b57cec5SDimitry Andric }
3487*0b57cec5SDimitry Andric 
3488*0b57cec5SDimitry Andric /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3489*0b57cec5SDimitry Andric /// array to pointer, return the array subexpression.
3490*0b57cec5SDimitry Andric static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3491*0b57cec5SDimitry Andric   // If this isn't just an array->pointer decay, bail out.
3492*0b57cec5SDimitry Andric   const auto *CE = dyn_cast<CastExpr>(E);
3493*0b57cec5SDimitry Andric   if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3494*0b57cec5SDimitry Andric     return nullptr;
3495*0b57cec5SDimitry Andric 
3496*0b57cec5SDimitry Andric   // If this is a decay from variable width array, bail out.
3497*0b57cec5SDimitry Andric   const Expr *SubExpr = CE->getSubExpr();
3498*0b57cec5SDimitry Andric   if (SubExpr->getType()->isVariableArrayType())
3499*0b57cec5SDimitry Andric     return nullptr;
3500*0b57cec5SDimitry Andric 
3501*0b57cec5SDimitry Andric   return SubExpr;
3502*0b57cec5SDimitry Andric }
3503*0b57cec5SDimitry Andric 
3504*0b57cec5SDimitry Andric static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3505*0b57cec5SDimitry Andric                                           llvm::Value *ptr,
3506*0b57cec5SDimitry Andric                                           ArrayRef<llvm::Value*> indices,
3507*0b57cec5SDimitry Andric                                           bool inbounds,
3508*0b57cec5SDimitry Andric                                           bool signedIndices,
3509*0b57cec5SDimitry Andric                                           SourceLocation loc,
3510*0b57cec5SDimitry Andric                                     const llvm::Twine &name = "arrayidx") {
3511*0b57cec5SDimitry Andric   if (inbounds) {
3512*0b57cec5SDimitry Andric     return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3513*0b57cec5SDimitry Andric                                       CodeGenFunction::NotSubtraction, loc,
3514*0b57cec5SDimitry Andric                                       name);
3515*0b57cec5SDimitry Andric   } else {
3516*0b57cec5SDimitry Andric     return CGF.Builder.CreateGEP(ptr, indices, name);
3517*0b57cec5SDimitry Andric   }
3518*0b57cec5SDimitry Andric }
3519*0b57cec5SDimitry Andric 
3520*0b57cec5SDimitry Andric static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3521*0b57cec5SDimitry Andric                                       llvm::Value *idx,
3522*0b57cec5SDimitry Andric                                       CharUnits eltSize) {
3523*0b57cec5SDimitry Andric   // If we have a constant index, we can use the exact offset of the
3524*0b57cec5SDimitry Andric   // element we're accessing.
3525*0b57cec5SDimitry Andric   if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3526*0b57cec5SDimitry Andric     CharUnits offset = constantIdx->getZExtValue() * eltSize;
3527*0b57cec5SDimitry Andric     return arrayAlign.alignmentAtOffset(offset);
3528*0b57cec5SDimitry Andric 
3529*0b57cec5SDimitry Andric   // Otherwise, use the worst-case alignment for any element.
3530*0b57cec5SDimitry Andric   } else {
3531*0b57cec5SDimitry Andric     return arrayAlign.alignmentOfArrayElement(eltSize);
3532*0b57cec5SDimitry Andric   }
3533*0b57cec5SDimitry Andric }
3534*0b57cec5SDimitry Andric 
3535*0b57cec5SDimitry Andric static QualType getFixedSizeElementType(const ASTContext &ctx,
3536*0b57cec5SDimitry Andric                                         const VariableArrayType *vla) {
3537*0b57cec5SDimitry Andric   QualType eltType;
3538*0b57cec5SDimitry Andric   do {
3539*0b57cec5SDimitry Andric     eltType = vla->getElementType();
3540*0b57cec5SDimitry Andric   } while ((vla = ctx.getAsVariableArrayType(eltType)));
3541*0b57cec5SDimitry Andric   return eltType;
3542*0b57cec5SDimitry Andric }
3543*0b57cec5SDimitry Andric 
3544480093f4SDimitry Andric /// Given an array base, check whether its member access belongs to a record
3545480093f4SDimitry Andric /// with preserve_access_index attribute or not.
3546480093f4SDimitry Andric static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3547480093f4SDimitry Andric   if (!ArrayBase || !CGF.getDebugInfo())
3548480093f4SDimitry Andric     return false;
3549480093f4SDimitry Andric 
3550480093f4SDimitry Andric   // Only support base as either a MemberExpr or DeclRefExpr.
3551480093f4SDimitry Andric   // DeclRefExpr to cover cases like:
3552480093f4SDimitry Andric   //    struct s { int a; int b[10]; };
3553480093f4SDimitry Andric   //    struct s *p;
3554480093f4SDimitry Andric   //    p[1].a
3555480093f4SDimitry Andric   // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3556480093f4SDimitry Andric   // p->b[5] is a MemberExpr example.
3557480093f4SDimitry Andric   const Expr *E = ArrayBase->IgnoreImpCasts();
3558480093f4SDimitry Andric   if (const auto *ME = dyn_cast<MemberExpr>(E))
3559480093f4SDimitry Andric     return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3560480093f4SDimitry Andric 
3561480093f4SDimitry Andric   if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3562480093f4SDimitry Andric     const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
3563480093f4SDimitry Andric     if (!VarDef)
3564480093f4SDimitry Andric       return false;
3565480093f4SDimitry Andric 
3566480093f4SDimitry Andric     const auto *PtrT = VarDef->getType()->getAs<PointerType>();
3567480093f4SDimitry Andric     if (!PtrT)
3568480093f4SDimitry Andric       return false;
3569480093f4SDimitry Andric 
3570480093f4SDimitry Andric     const auto *PointeeT = PtrT->getPointeeType()
3571480093f4SDimitry Andric                              ->getUnqualifiedDesugaredType();
3572480093f4SDimitry Andric     if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
3573480093f4SDimitry Andric       return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3574480093f4SDimitry Andric     return false;
3575480093f4SDimitry Andric   }
3576480093f4SDimitry Andric 
3577480093f4SDimitry Andric   return false;
3578480093f4SDimitry Andric }
3579480093f4SDimitry Andric 
3580*0b57cec5SDimitry Andric static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3581*0b57cec5SDimitry Andric                                      ArrayRef<llvm::Value *> indices,
3582*0b57cec5SDimitry Andric                                      QualType eltType, bool inbounds,
3583*0b57cec5SDimitry Andric                                      bool signedIndices, SourceLocation loc,
3584a7dea167SDimitry Andric                                      QualType *arrayType = nullptr,
3585480093f4SDimitry Andric                                      const Expr *Base = nullptr,
3586*0b57cec5SDimitry Andric                                      const llvm::Twine &name = "arrayidx") {
3587*0b57cec5SDimitry Andric   // All the indices except that last must be zero.
3588*0b57cec5SDimitry Andric #ifndef NDEBUG
3589*0b57cec5SDimitry Andric   for (auto idx : indices.drop_back())
3590*0b57cec5SDimitry Andric     assert(isa<llvm::ConstantInt>(idx) &&
3591*0b57cec5SDimitry Andric            cast<llvm::ConstantInt>(idx)->isZero());
3592*0b57cec5SDimitry Andric #endif
3593*0b57cec5SDimitry Andric 
3594*0b57cec5SDimitry Andric   // Determine the element size of the statically-sized base.  This is
3595*0b57cec5SDimitry Andric   // the thing that the indices are expressed in terms of.
3596*0b57cec5SDimitry Andric   if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3597*0b57cec5SDimitry Andric     eltType = getFixedSizeElementType(CGF.getContext(), vla);
3598*0b57cec5SDimitry Andric   }
3599*0b57cec5SDimitry Andric 
3600*0b57cec5SDimitry Andric   // We can use that to compute the best alignment of the element.
3601*0b57cec5SDimitry Andric   CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3602*0b57cec5SDimitry Andric   CharUnits eltAlign =
3603*0b57cec5SDimitry Andric     getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3604*0b57cec5SDimitry Andric 
3605*0b57cec5SDimitry Andric   llvm::Value *eltPtr;
3606*0b57cec5SDimitry Andric   auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
3607480093f4SDimitry Andric   if (!LastIndex ||
3608480093f4SDimitry Andric       (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
3609*0b57cec5SDimitry Andric     eltPtr = emitArraySubscriptGEP(
3610*0b57cec5SDimitry Andric         CGF, addr.getPointer(), indices, inbounds, signedIndices,
3611*0b57cec5SDimitry Andric         loc, name);
3612*0b57cec5SDimitry Andric   } else {
3613*0b57cec5SDimitry Andric     // Remember the original array subscript for bpf target
3614*0b57cec5SDimitry Andric     unsigned idx = LastIndex->getZExtValue();
3615a7dea167SDimitry Andric     llvm::DIType *DbgInfo = nullptr;
3616a7dea167SDimitry Andric     if (arrayType)
3617a7dea167SDimitry Andric       DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
3618480093f4SDimitry Andric     eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
3619480093f4SDimitry Andric                                                         addr.getPointer(),
3620*0b57cec5SDimitry Andric                                                         indices.size() - 1,
3621a7dea167SDimitry Andric                                                         idx, DbgInfo);
3622*0b57cec5SDimitry Andric   }
3623*0b57cec5SDimitry Andric 
3624*0b57cec5SDimitry Andric   return Address(eltPtr, eltAlign);
3625*0b57cec5SDimitry Andric }
3626*0b57cec5SDimitry Andric 
3627*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3628*0b57cec5SDimitry Andric                                                bool Accessed) {
3629*0b57cec5SDimitry Andric   // The index must always be an integer, which is not an aggregate.  Emit it
3630*0b57cec5SDimitry Andric   // in lexical order (this complexity is, sadly, required by C++17).
3631*0b57cec5SDimitry Andric   llvm::Value *IdxPre =
3632*0b57cec5SDimitry Andric       (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3633*0b57cec5SDimitry Andric   bool SignedIndices = false;
3634*0b57cec5SDimitry Andric   auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3635*0b57cec5SDimitry Andric     auto *Idx = IdxPre;
3636*0b57cec5SDimitry Andric     if (E->getLHS() != E->getIdx()) {
3637*0b57cec5SDimitry Andric       assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3638*0b57cec5SDimitry Andric       Idx = EmitScalarExpr(E->getIdx());
3639*0b57cec5SDimitry Andric     }
3640*0b57cec5SDimitry Andric 
3641*0b57cec5SDimitry Andric     QualType IdxTy = E->getIdx()->getType();
3642*0b57cec5SDimitry Andric     bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3643*0b57cec5SDimitry Andric     SignedIndices |= IdxSigned;
3644*0b57cec5SDimitry Andric 
3645*0b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::ArrayBounds))
3646*0b57cec5SDimitry Andric       EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3647*0b57cec5SDimitry Andric 
3648*0b57cec5SDimitry Andric     // Extend or truncate the index type to 32 or 64-bits.
3649*0b57cec5SDimitry Andric     if (Promote && Idx->getType() != IntPtrTy)
3650*0b57cec5SDimitry Andric       Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3651*0b57cec5SDimitry Andric 
3652*0b57cec5SDimitry Andric     return Idx;
3653*0b57cec5SDimitry Andric   };
3654*0b57cec5SDimitry Andric   IdxPre = nullptr;
3655*0b57cec5SDimitry Andric 
3656*0b57cec5SDimitry Andric   // If the base is a vector type, then we are forming a vector element lvalue
3657*0b57cec5SDimitry Andric   // with this subscript.
3658*0b57cec5SDimitry Andric   if (E->getBase()->getType()->isVectorType() &&
3659*0b57cec5SDimitry Andric       !isa<ExtVectorElementExpr>(E->getBase())) {
3660*0b57cec5SDimitry Andric     // Emit the vector as an lvalue to get its address.
3661*0b57cec5SDimitry Andric     LValue LHS = EmitLValue(E->getBase());
3662*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3663*0b57cec5SDimitry Andric     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3664480093f4SDimitry Andric     return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
3665480093f4SDimitry Andric                                  E->getBase()->getType(), LHS.getBaseInfo(),
3666480093f4SDimitry Andric                                  TBAAAccessInfo());
3667*0b57cec5SDimitry Andric   }
3668*0b57cec5SDimitry Andric 
3669*0b57cec5SDimitry Andric   // All the other cases basically behave like simple offsetting.
3670*0b57cec5SDimitry Andric 
3671*0b57cec5SDimitry Andric   // Handle the extvector case we ignored above.
3672*0b57cec5SDimitry Andric   if (isa<ExtVectorElementExpr>(E->getBase())) {
3673*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getBase());
3674*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3675*0b57cec5SDimitry Andric     Address Addr = EmitExtVectorElementLValue(LV);
3676*0b57cec5SDimitry Andric 
3677*0b57cec5SDimitry Andric     QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3678*0b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3679*0b57cec5SDimitry Andric                                  SignedIndices, E->getExprLoc());
3680*0b57cec5SDimitry Andric     return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3681*0b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, EltType));
3682*0b57cec5SDimitry Andric   }
3683*0b57cec5SDimitry Andric 
3684*0b57cec5SDimitry Andric   LValueBaseInfo EltBaseInfo;
3685*0b57cec5SDimitry Andric   TBAAAccessInfo EltTBAAInfo;
3686*0b57cec5SDimitry Andric   Address Addr = Address::invalid();
3687*0b57cec5SDimitry Andric   if (const VariableArrayType *vla =
3688*0b57cec5SDimitry Andric            getContext().getAsVariableArrayType(E->getType())) {
3689*0b57cec5SDimitry Andric     // The base must be a pointer, which is not an aggregate.  Emit
3690*0b57cec5SDimitry Andric     // it.  It needs to be emitted first in case it's what captures
3691*0b57cec5SDimitry Andric     // the VLA bounds.
3692*0b57cec5SDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3693*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3694*0b57cec5SDimitry Andric 
3695*0b57cec5SDimitry Andric     // The element count here is the total number of non-VLA elements.
3696*0b57cec5SDimitry Andric     llvm::Value *numElements = getVLASize(vla).NumElts;
3697*0b57cec5SDimitry Andric 
3698*0b57cec5SDimitry Andric     // Effectively, the multiply by the VLA size is part of the GEP.
3699*0b57cec5SDimitry Andric     // GEP indexes are signed, and scaling an index isn't permitted to
3700*0b57cec5SDimitry Andric     // signed-overflow, so we use the same semantics for our explicit
3701*0b57cec5SDimitry Andric     // multiply.  We suppress this if overflow is not undefined behavior.
3702*0b57cec5SDimitry Andric     if (getLangOpts().isSignedOverflowDefined()) {
3703*0b57cec5SDimitry Andric       Idx = Builder.CreateMul(Idx, numElements);
3704*0b57cec5SDimitry Andric     } else {
3705*0b57cec5SDimitry Andric       Idx = Builder.CreateNSWMul(Idx, numElements);
3706*0b57cec5SDimitry Andric     }
3707*0b57cec5SDimitry Andric 
3708*0b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3709*0b57cec5SDimitry Andric                                  !getLangOpts().isSignedOverflowDefined(),
3710*0b57cec5SDimitry Andric                                  SignedIndices, E->getExprLoc());
3711*0b57cec5SDimitry Andric 
3712*0b57cec5SDimitry Andric   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3713*0b57cec5SDimitry Andric     // Indexing over an interface, as in "NSString *P; P[4];"
3714*0b57cec5SDimitry Andric 
3715*0b57cec5SDimitry Andric     // Emit the base pointer.
3716*0b57cec5SDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3717*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3718*0b57cec5SDimitry Andric 
3719*0b57cec5SDimitry Andric     CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3720*0b57cec5SDimitry Andric     llvm::Value *InterfaceSizeVal =
3721*0b57cec5SDimitry Andric         llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3722*0b57cec5SDimitry Andric 
3723*0b57cec5SDimitry Andric     llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3724*0b57cec5SDimitry Andric 
3725*0b57cec5SDimitry Andric     // We don't necessarily build correct LLVM struct types for ObjC
3726*0b57cec5SDimitry Andric     // interfaces, so we can't rely on GEP to do this scaling
3727*0b57cec5SDimitry Andric     // correctly, so we need to cast to i8*.  FIXME: is this actually
3728*0b57cec5SDimitry Andric     // true?  A lot of other things in the fragile ABI would break...
3729*0b57cec5SDimitry Andric     llvm::Type *OrigBaseTy = Addr.getType();
3730*0b57cec5SDimitry Andric     Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3731*0b57cec5SDimitry Andric 
3732*0b57cec5SDimitry Andric     // Do the GEP.
3733*0b57cec5SDimitry Andric     CharUnits EltAlign =
3734*0b57cec5SDimitry Andric       getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3735*0b57cec5SDimitry Andric     llvm::Value *EltPtr =
3736*0b57cec5SDimitry Andric         emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3737*0b57cec5SDimitry Andric                               SignedIndices, E->getExprLoc());
3738*0b57cec5SDimitry Andric     Addr = Address(EltPtr, EltAlign);
3739*0b57cec5SDimitry Andric 
3740*0b57cec5SDimitry Andric     // Cast back.
3741*0b57cec5SDimitry Andric     Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3742*0b57cec5SDimitry Andric   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3743*0b57cec5SDimitry Andric     // If this is A[i] where A is an array, the frontend will have decayed the
3744*0b57cec5SDimitry Andric     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
3745*0b57cec5SDimitry Andric     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3746*0b57cec5SDimitry Andric     // "gep x, i" here.  Emit one "gep A, 0, i".
3747*0b57cec5SDimitry Andric     assert(Array->getType()->isArrayType() &&
3748*0b57cec5SDimitry Andric            "Array to pointer decay must have array source type!");
3749*0b57cec5SDimitry Andric     LValue ArrayLV;
3750*0b57cec5SDimitry Andric     // For simple multidimensional array indexing, set the 'accessed' flag for
3751*0b57cec5SDimitry Andric     // better bounds-checking of the base expression.
3752*0b57cec5SDimitry Andric     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3753*0b57cec5SDimitry Andric       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3754*0b57cec5SDimitry Andric     else
3755*0b57cec5SDimitry Andric       ArrayLV = EmitLValue(Array);
3756*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3757*0b57cec5SDimitry Andric 
3758*0b57cec5SDimitry Andric     // Propagate the alignment from the array itself to the result.
3759a7dea167SDimitry Andric     QualType arrayType = Array->getType();
3760*0b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(
3761480093f4SDimitry Andric         *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
3762*0b57cec5SDimitry Andric         E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3763480093f4SDimitry Andric         E->getExprLoc(), &arrayType, E->getBase());
3764*0b57cec5SDimitry Andric     EltBaseInfo = ArrayLV.getBaseInfo();
3765*0b57cec5SDimitry Andric     EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
3766*0b57cec5SDimitry Andric   } else {
3767*0b57cec5SDimitry Andric     // The base must be a pointer; emit it with an estimate of its alignment.
3768*0b57cec5SDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3769*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3770a7dea167SDimitry Andric     QualType ptrType = E->getBase()->getType();
3771*0b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3772*0b57cec5SDimitry Andric                                  !getLangOpts().isSignedOverflowDefined(),
3773480093f4SDimitry Andric                                  SignedIndices, E->getExprLoc(), &ptrType,
3774480093f4SDimitry Andric                                  E->getBase());
3775*0b57cec5SDimitry Andric   }
3776*0b57cec5SDimitry Andric 
3777*0b57cec5SDimitry Andric   LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
3778*0b57cec5SDimitry Andric 
3779*0b57cec5SDimitry Andric   if (getLangOpts().ObjC &&
3780*0b57cec5SDimitry Andric       getLangOpts().getGC() != LangOptions::NonGC) {
3781*0b57cec5SDimitry Andric     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3782*0b57cec5SDimitry Andric     setObjCGCLValueClass(getContext(), E, LV);
3783*0b57cec5SDimitry Andric   }
3784*0b57cec5SDimitry Andric   return LV;
3785*0b57cec5SDimitry Andric }
3786*0b57cec5SDimitry Andric 
37875ffd83dbSDimitry Andric LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
37885ffd83dbSDimitry Andric   assert(
37895ffd83dbSDimitry Andric       !E->isIncomplete() &&
37905ffd83dbSDimitry Andric       "incomplete matrix subscript expressions should be rejected during Sema");
37915ffd83dbSDimitry Andric   LValue Base = EmitLValue(E->getBase());
37925ffd83dbSDimitry Andric   llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
37935ffd83dbSDimitry Andric   llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
37945ffd83dbSDimitry Andric   llvm::Value *NumRows = Builder.getIntN(
37955ffd83dbSDimitry Andric       RowIdx->getType()->getScalarSizeInBits(),
37965ffd83dbSDimitry Andric       E->getBase()->getType()->getAs<ConstantMatrixType>()->getNumRows());
37975ffd83dbSDimitry Andric   llvm::Value *FinalIdx =
37985ffd83dbSDimitry Andric       Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
37995ffd83dbSDimitry Andric   return LValue::MakeMatrixElt(
38005ffd83dbSDimitry Andric       MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
38015ffd83dbSDimitry Andric       E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
38025ffd83dbSDimitry Andric }
38035ffd83dbSDimitry Andric 
3804*0b57cec5SDimitry Andric static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3805*0b57cec5SDimitry Andric                                        LValueBaseInfo &BaseInfo,
3806*0b57cec5SDimitry Andric                                        TBAAAccessInfo &TBAAInfo,
3807*0b57cec5SDimitry Andric                                        QualType BaseTy, QualType ElTy,
3808*0b57cec5SDimitry Andric                                        bool IsLowerBound) {
3809*0b57cec5SDimitry Andric   LValue BaseLVal;
3810*0b57cec5SDimitry Andric   if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3811*0b57cec5SDimitry Andric     BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3812*0b57cec5SDimitry Andric     if (BaseTy->isArrayType()) {
3813480093f4SDimitry Andric       Address Addr = BaseLVal.getAddress(CGF);
3814*0b57cec5SDimitry Andric       BaseInfo = BaseLVal.getBaseInfo();
3815*0b57cec5SDimitry Andric 
3816*0b57cec5SDimitry Andric       // If the array type was an incomplete type, we need to make sure
3817*0b57cec5SDimitry Andric       // the decay ends up being the right type.
3818*0b57cec5SDimitry Andric       llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3819*0b57cec5SDimitry Andric       Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3820*0b57cec5SDimitry Andric 
3821*0b57cec5SDimitry Andric       // Note that VLA pointers are always decayed, so we don't need to do
3822*0b57cec5SDimitry Andric       // anything here.
3823*0b57cec5SDimitry Andric       if (!BaseTy->isVariableArrayType()) {
3824*0b57cec5SDimitry Andric         assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3825*0b57cec5SDimitry Andric                "Expected pointer to array");
3826*0b57cec5SDimitry Andric         Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3827*0b57cec5SDimitry Andric       }
3828*0b57cec5SDimitry Andric 
3829*0b57cec5SDimitry Andric       return CGF.Builder.CreateElementBitCast(Addr,
3830*0b57cec5SDimitry Andric                                               CGF.ConvertTypeForMem(ElTy));
3831*0b57cec5SDimitry Andric     }
3832*0b57cec5SDimitry Andric     LValueBaseInfo TypeBaseInfo;
3833*0b57cec5SDimitry Andric     TBAAAccessInfo TypeTBAAInfo;
38345ffd83dbSDimitry Andric     CharUnits Align =
38355ffd83dbSDimitry Andric         CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
3836*0b57cec5SDimitry Andric     BaseInfo.mergeForCast(TypeBaseInfo);
3837*0b57cec5SDimitry Andric     TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
3838480093f4SDimitry Andric     return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)), Align);
3839*0b57cec5SDimitry Andric   }
3840*0b57cec5SDimitry Andric   return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
3841*0b57cec5SDimitry Andric }
3842*0b57cec5SDimitry Andric 
3843*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3844*0b57cec5SDimitry Andric                                                 bool IsLowerBound) {
3845*0b57cec5SDimitry Andric   QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
3846*0b57cec5SDimitry Andric   QualType ResultExprTy;
3847*0b57cec5SDimitry Andric   if (auto *AT = getContext().getAsArrayType(BaseTy))
3848*0b57cec5SDimitry Andric     ResultExprTy = AT->getElementType();
3849*0b57cec5SDimitry Andric   else
3850*0b57cec5SDimitry Andric     ResultExprTy = BaseTy->getPointeeType();
3851*0b57cec5SDimitry Andric   llvm::Value *Idx = nullptr;
38525ffd83dbSDimitry Andric   if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
3853*0b57cec5SDimitry Andric     // Requesting lower bound or upper bound, but without provided length and
3854*0b57cec5SDimitry Andric     // without ':' symbol for the default length -> length = 1.
3855*0b57cec5SDimitry Andric     // Idx = LowerBound ?: 0;
3856*0b57cec5SDimitry Andric     if (auto *LowerBound = E->getLowerBound()) {
3857*0b57cec5SDimitry Andric       Idx = Builder.CreateIntCast(
3858*0b57cec5SDimitry Andric           EmitScalarExpr(LowerBound), IntPtrTy,
3859*0b57cec5SDimitry Andric           LowerBound->getType()->hasSignedIntegerRepresentation());
3860*0b57cec5SDimitry Andric     } else
3861*0b57cec5SDimitry Andric       Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3862*0b57cec5SDimitry Andric   } else {
3863*0b57cec5SDimitry Andric     // Try to emit length or lower bound as constant. If this is possible, 1
3864*0b57cec5SDimitry Andric     // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3865*0b57cec5SDimitry Andric     // IR (LB + Len) - 1.
3866*0b57cec5SDimitry Andric     auto &C = CGM.getContext();
3867*0b57cec5SDimitry Andric     auto *Length = E->getLength();
3868*0b57cec5SDimitry Andric     llvm::APSInt ConstLength;
3869*0b57cec5SDimitry Andric     if (Length) {
3870*0b57cec5SDimitry Andric       // Idx = LowerBound + Length - 1;
3871*0b57cec5SDimitry Andric       if (Length->isIntegerConstantExpr(ConstLength, C)) {
3872*0b57cec5SDimitry Andric         ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3873*0b57cec5SDimitry Andric         Length = nullptr;
3874*0b57cec5SDimitry Andric       }
3875*0b57cec5SDimitry Andric       auto *LowerBound = E->getLowerBound();
3876*0b57cec5SDimitry Andric       llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3877*0b57cec5SDimitry Andric       if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3878*0b57cec5SDimitry Andric         ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3879*0b57cec5SDimitry Andric         LowerBound = nullptr;
3880*0b57cec5SDimitry Andric       }
3881*0b57cec5SDimitry Andric       if (!Length)
3882*0b57cec5SDimitry Andric         --ConstLength;
3883*0b57cec5SDimitry Andric       else if (!LowerBound)
3884*0b57cec5SDimitry Andric         --ConstLowerBound;
3885*0b57cec5SDimitry Andric 
3886*0b57cec5SDimitry Andric       if (Length || LowerBound) {
3887*0b57cec5SDimitry Andric         auto *LowerBoundVal =
3888*0b57cec5SDimitry Andric             LowerBound
3889*0b57cec5SDimitry Andric                 ? Builder.CreateIntCast(
3890*0b57cec5SDimitry Andric                       EmitScalarExpr(LowerBound), IntPtrTy,
3891*0b57cec5SDimitry Andric                       LowerBound->getType()->hasSignedIntegerRepresentation())
3892*0b57cec5SDimitry Andric                 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3893*0b57cec5SDimitry Andric         auto *LengthVal =
3894*0b57cec5SDimitry Andric             Length
3895*0b57cec5SDimitry Andric                 ? Builder.CreateIntCast(
3896*0b57cec5SDimitry Andric                       EmitScalarExpr(Length), IntPtrTy,
3897*0b57cec5SDimitry Andric                       Length->getType()->hasSignedIntegerRepresentation())
3898*0b57cec5SDimitry Andric                 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3899*0b57cec5SDimitry Andric         Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3900*0b57cec5SDimitry Andric                                 /*HasNUW=*/false,
3901*0b57cec5SDimitry Andric                                 !getLangOpts().isSignedOverflowDefined());
3902*0b57cec5SDimitry Andric         if (Length && LowerBound) {
3903*0b57cec5SDimitry Andric           Idx = Builder.CreateSub(
3904*0b57cec5SDimitry Andric               Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3905*0b57cec5SDimitry Andric               /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3906*0b57cec5SDimitry Andric         }
3907*0b57cec5SDimitry Andric       } else
3908*0b57cec5SDimitry Andric         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3909*0b57cec5SDimitry Andric     } else {
3910*0b57cec5SDimitry Andric       // Idx = ArraySize - 1;
3911*0b57cec5SDimitry Andric       QualType ArrayTy = BaseTy->isPointerType()
3912*0b57cec5SDimitry Andric                              ? E->getBase()->IgnoreParenImpCasts()->getType()
3913*0b57cec5SDimitry Andric                              : BaseTy;
3914*0b57cec5SDimitry Andric       if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3915*0b57cec5SDimitry Andric         Length = VAT->getSizeExpr();
3916*0b57cec5SDimitry Andric         if (Length->isIntegerConstantExpr(ConstLength, C))
3917*0b57cec5SDimitry Andric           Length = nullptr;
3918*0b57cec5SDimitry Andric       } else {
3919*0b57cec5SDimitry Andric         auto *CAT = C.getAsConstantArrayType(ArrayTy);
3920*0b57cec5SDimitry Andric         ConstLength = CAT->getSize();
3921*0b57cec5SDimitry Andric       }
3922*0b57cec5SDimitry Andric       if (Length) {
3923*0b57cec5SDimitry Andric         auto *LengthVal = Builder.CreateIntCast(
3924*0b57cec5SDimitry Andric             EmitScalarExpr(Length), IntPtrTy,
3925*0b57cec5SDimitry Andric             Length->getType()->hasSignedIntegerRepresentation());
3926*0b57cec5SDimitry Andric         Idx = Builder.CreateSub(
3927*0b57cec5SDimitry Andric             LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3928*0b57cec5SDimitry Andric             /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3929*0b57cec5SDimitry Andric       } else {
3930*0b57cec5SDimitry Andric         ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3931*0b57cec5SDimitry Andric         --ConstLength;
3932*0b57cec5SDimitry Andric         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3933*0b57cec5SDimitry Andric       }
3934*0b57cec5SDimitry Andric     }
3935*0b57cec5SDimitry Andric   }
3936*0b57cec5SDimitry Andric   assert(Idx);
3937*0b57cec5SDimitry Andric 
3938*0b57cec5SDimitry Andric   Address EltPtr = Address::invalid();
3939*0b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
3940*0b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
3941*0b57cec5SDimitry Andric   if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3942*0b57cec5SDimitry Andric     // The base must be a pointer, which is not an aggregate.  Emit
3943*0b57cec5SDimitry Andric     // it.  It needs to be emitted first in case it's what captures
3944*0b57cec5SDimitry Andric     // the VLA bounds.
3945*0b57cec5SDimitry Andric     Address Base =
3946*0b57cec5SDimitry Andric         emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
3947*0b57cec5SDimitry Andric                                 BaseTy, VLA->getElementType(), IsLowerBound);
3948*0b57cec5SDimitry Andric     // The element count here is the total number of non-VLA elements.
3949*0b57cec5SDimitry Andric     llvm::Value *NumElements = getVLASize(VLA).NumElts;
3950*0b57cec5SDimitry Andric 
3951*0b57cec5SDimitry Andric     // Effectively, the multiply by the VLA size is part of the GEP.
3952*0b57cec5SDimitry Andric     // GEP indexes are signed, and scaling an index isn't permitted to
3953*0b57cec5SDimitry Andric     // signed-overflow, so we use the same semantics for our explicit
3954*0b57cec5SDimitry Andric     // multiply.  We suppress this if overflow is not undefined behavior.
3955*0b57cec5SDimitry Andric     if (getLangOpts().isSignedOverflowDefined())
3956*0b57cec5SDimitry Andric       Idx = Builder.CreateMul(Idx, NumElements);
3957*0b57cec5SDimitry Andric     else
3958*0b57cec5SDimitry Andric       Idx = Builder.CreateNSWMul(Idx, NumElements);
3959*0b57cec5SDimitry Andric     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3960*0b57cec5SDimitry Andric                                    !getLangOpts().isSignedOverflowDefined(),
3961*0b57cec5SDimitry Andric                                    /*signedIndices=*/false, E->getExprLoc());
3962*0b57cec5SDimitry Andric   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3963*0b57cec5SDimitry Andric     // If this is A[i] where A is an array, the frontend will have decayed the
3964*0b57cec5SDimitry Andric     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
3965*0b57cec5SDimitry Andric     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3966*0b57cec5SDimitry Andric     // "gep x, i" here.  Emit one "gep A, 0, i".
3967*0b57cec5SDimitry Andric     assert(Array->getType()->isArrayType() &&
3968*0b57cec5SDimitry Andric            "Array to pointer decay must have array source type!");
3969*0b57cec5SDimitry Andric     LValue ArrayLV;
3970*0b57cec5SDimitry Andric     // For simple multidimensional array indexing, set the 'accessed' flag for
3971*0b57cec5SDimitry Andric     // better bounds-checking of the base expression.
3972*0b57cec5SDimitry Andric     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3973*0b57cec5SDimitry Andric       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3974*0b57cec5SDimitry Andric     else
3975*0b57cec5SDimitry Andric       ArrayLV = EmitLValue(Array);
3976*0b57cec5SDimitry Andric 
3977*0b57cec5SDimitry Andric     // Propagate the alignment from the array itself to the result.
3978*0b57cec5SDimitry Andric     EltPtr = emitArraySubscriptGEP(
3979480093f4SDimitry Andric         *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
3980*0b57cec5SDimitry Andric         ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
3981*0b57cec5SDimitry Andric         /*signedIndices=*/false, E->getExprLoc());
3982*0b57cec5SDimitry Andric     BaseInfo = ArrayLV.getBaseInfo();
3983*0b57cec5SDimitry Andric     TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
3984*0b57cec5SDimitry Andric   } else {
3985*0b57cec5SDimitry Andric     Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
3986*0b57cec5SDimitry Andric                                            TBAAInfo, BaseTy, ResultExprTy,
3987*0b57cec5SDimitry Andric                                            IsLowerBound);
3988*0b57cec5SDimitry Andric     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3989*0b57cec5SDimitry Andric                                    !getLangOpts().isSignedOverflowDefined(),
3990*0b57cec5SDimitry Andric                                    /*signedIndices=*/false, E->getExprLoc());
3991*0b57cec5SDimitry Andric   }
3992*0b57cec5SDimitry Andric 
3993*0b57cec5SDimitry Andric   return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
3994*0b57cec5SDimitry Andric }
3995*0b57cec5SDimitry Andric 
3996*0b57cec5SDimitry Andric LValue CodeGenFunction::
3997*0b57cec5SDimitry Andric EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3998*0b57cec5SDimitry Andric   // Emit the base vector as an l-value.
3999*0b57cec5SDimitry Andric   LValue Base;
4000*0b57cec5SDimitry Andric 
4001*0b57cec5SDimitry Andric   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
4002*0b57cec5SDimitry Andric   if (E->isArrow()) {
4003*0b57cec5SDimitry Andric     // If it is a pointer to a vector, emit the address and form an lvalue with
4004*0b57cec5SDimitry Andric     // it.
4005*0b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
4006*0b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
4007*0b57cec5SDimitry Andric     Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4008480093f4SDimitry Andric     const auto *PT = E->getBase()->getType()->castAs<PointerType>();
4009*0b57cec5SDimitry Andric     Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
4010*0b57cec5SDimitry Andric     Base.getQuals().removeObjCGCAttr();
4011*0b57cec5SDimitry Andric   } else if (E->getBase()->isGLValue()) {
4012*0b57cec5SDimitry Andric     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
4013*0b57cec5SDimitry Andric     // emit the base as an lvalue.
4014*0b57cec5SDimitry Andric     assert(E->getBase()->getType()->isVectorType());
4015*0b57cec5SDimitry Andric     Base = EmitLValue(E->getBase());
4016*0b57cec5SDimitry Andric   } else {
4017*0b57cec5SDimitry Andric     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
4018*0b57cec5SDimitry Andric     assert(E->getBase()->getType()->isVectorType() &&
4019*0b57cec5SDimitry Andric            "Result must be a vector");
4020*0b57cec5SDimitry Andric     llvm::Value *Vec = EmitScalarExpr(E->getBase());
4021*0b57cec5SDimitry Andric 
4022*0b57cec5SDimitry Andric     // Store the vector to memory (because LValue wants an address).
4023*0b57cec5SDimitry Andric     Address VecMem = CreateMemTemp(E->getBase()->getType());
4024*0b57cec5SDimitry Andric     Builder.CreateStore(Vec, VecMem);
4025*0b57cec5SDimitry Andric     Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
4026*0b57cec5SDimitry Andric                           AlignmentSource::Decl);
4027*0b57cec5SDimitry Andric   }
4028*0b57cec5SDimitry Andric 
4029*0b57cec5SDimitry Andric   QualType type =
4030*0b57cec5SDimitry Andric     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
4031*0b57cec5SDimitry Andric 
4032*0b57cec5SDimitry Andric   // Encode the element access list into a vector of unsigned indices.
4033*0b57cec5SDimitry Andric   SmallVector<uint32_t, 4> Indices;
4034*0b57cec5SDimitry Andric   E->getEncodedElementAccess(Indices);
4035*0b57cec5SDimitry Andric 
4036*0b57cec5SDimitry Andric   if (Base.isSimple()) {
4037*0b57cec5SDimitry Andric     llvm::Constant *CV =
4038*0b57cec5SDimitry Andric         llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4039480093f4SDimitry Andric     return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
4040*0b57cec5SDimitry Andric                                     Base.getBaseInfo(), TBAAAccessInfo());
4041*0b57cec5SDimitry Andric   }
4042*0b57cec5SDimitry Andric   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
4043*0b57cec5SDimitry Andric 
4044*0b57cec5SDimitry Andric   llvm::Constant *BaseElts = Base.getExtVectorElts();
4045*0b57cec5SDimitry Andric   SmallVector<llvm::Constant *, 4> CElts;
4046*0b57cec5SDimitry Andric 
4047*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
4048*0b57cec5SDimitry Andric     CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
4049*0b57cec5SDimitry Andric   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
4050*0b57cec5SDimitry Andric   return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
4051*0b57cec5SDimitry Andric                                   Base.getBaseInfo(), TBAAAccessInfo());
4052*0b57cec5SDimitry Andric }
4053*0b57cec5SDimitry Andric 
4054*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
4055*0b57cec5SDimitry Andric   if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
4056*0b57cec5SDimitry Andric     EmitIgnoredExpr(E->getBase());
4057*0b57cec5SDimitry Andric     return EmitDeclRefLValue(DRE);
4058*0b57cec5SDimitry Andric   }
4059*0b57cec5SDimitry Andric 
4060*0b57cec5SDimitry Andric   Expr *BaseExpr = E->getBase();
4061*0b57cec5SDimitry Andric   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
4062*0b57cec5SDimitry Andric   LValue BaseLV;
4063*0b57cec5SDimitry Andric   if (E->isArrow()) {
4064*0b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
4065*0b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
4066*0b57cec5SDimitry Andric     Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
4067*0b57cec5SDimitry Andric     QualType PtrTy = BaseExpr->getType()->getPointeeType();
4068*0b57cec5SDimitry Andric     SanitizerSet SkippedChecks;
4069*0b57cec5SDimitry Andric     bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
4070*0b57cec5SDimitry Andric     if (IsBaseCXXThis)
4071*0b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::Alignment, true);
4072*0b57cec5SDimitry Andric     if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
4073*0b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::Null, true);
4074*0b57cec5SDimitry Andric     EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
4075*0b57cec5SDimitry Andric                   /*Alignment=*/CharUnits::Zero(), SkippedChecks);
4076*0b57cec5SDimitry Andric     BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
4077*0b57cec5SDimitry Andric   } else
4078*0b57cec5SDimitry Andric     BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
4079*0b57cec5SDimitry Andric 
4080*0b57cec5SDimitry Andric   NamedDecl *ND = E->getMemberDecl();
4081*0b57cec5SDimitry Andric   if (auto *Field = dyn_cast<FieldDecl>(ND)) {
4082*0b57cec5SDimitry Andric     LValue LV = EmitLValueForField(BaseLV, Field);
4083*0b57cec5SDimitry Andric     setObjCGCLValueClass(getContext(), E, LV);
4084480093f4SDimitry Andric     if (getLangOpts().OpenMP) {
4085480093f4SDimitry Andric       // If the member was explicitly marked as nontemporal, mark it as
4086480093f4SDimitry Andric       // nontemporal. If the base lvalue is marked as nontemporal, mark access
4087480093f4SDimitry Andric       // to children as nontemporal too.
4088480093f4SDimitry Andric       if ((IsWrappedCXXThis(BaseExpr) &&
4089480093f4SDimitry Andric            CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
4090480093f4SDimitry Andric           BaseLV.isNontemporal())
4091480093f4SDimitry Andric         LV.setNontemporal(/*Value=*/true);
4092480093f4SDimitry Andric     }
4093*0b57cec5SDimitry Andric     return LV;
4094*0b57cec5SDimitry Andric   }
4095*0b57cec5SDimitry Andric 
4096*0b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
4097*0b57cec5SDimitry Andric     return EmitFunctionDeclLValue(*this, E, FD);
4098*0b57cec5SDimitry Andric 
4099*0b57cec5SDimitry Andric   llvm_unreachable("Unhandled member declaration!");
4100*0b57cec5SDimitry Andric }
4101*0b57cec5SDimitry Andric 
4102*0b57cec5SDimitry Andric /// Given that we are currently emitting a lambda, emit an l-value for
4103*0b57cec5SDimitry Andric /// one of its members.
4104*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
4105*0b57cec5SDimitry Andric   assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
4106*0b57cec5SDimitry Andric   assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
4107*0b57cec5SDimitry Andric   QualType LambdaTagType =
4108*0b57cec5SDimitry Andric     getContext().getTagDeclType(Field->getParent());
4109*0b57cec5SDimitry Andric   LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
4110*0b57cec5SDimitry Andric   return EmitLValueForField(LambdaLV, Field);
4111*0b57cec5SDimitry Andric }
4112*0b57cec5SDimitry Andric 
4113*0b57cec5SDimitry Andric /// Get the field index in the debug info. The debug info structure/union
4114*0b57cec5SDimitry Andric /// will ignore the unnamed bitfields.
4115*0b57cec5SDimitry Andric unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
4116*0b57cec5SDimitry Andric                                              unsigned FieldIndex) {
4117*0b57cec5SDimitry Andric   unsigned I = 0, Skipped = 0;
4118*0b57cec5SDimitry Andric 
4119*0b57cec5SDimitry Andric   for (auto F : Rec->getDefinition()->fields()) {
4120*0b57cec5SDimitry Andric     if (I == FieldIndex)
4121*0b57cec5SDimitry Andric       break;
4122*0b57cec5SDimitry Andric     if (F->isUnnamedBitfield())
4123*0b57cec5SDimitry Andric       Skipped++;
4124*0b57cec5SDimitry Andric     I++;
4125*0b57cec5SDimitry Andric   }
4126*0b57cec5SDimitry Andric 
4127*0b57cec5SDimitry Andric   return FieldIndex - Skipped;
4128*0b57cec5SDimitry Andric }
4129*0b57cec5SDimitry Andric 
4130*0b57cec5SDimitry Andric /// Get the address of a zero-sized field within a record. The resulting
4131*0b57cec5SDimitry Andric /// address doesn't necessarily have the right type.
4132*0b57cec5SDimitry Andric static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
4133*0b57cec5SDimitry Andric                                        const FieldDecl *Field) {
4134*0b57cec5SDimitry Andric   CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
4135*0b57cec5SDimitry Andric       CGF.getContext().getFieldOffset(Field));
4136*0b57cec5SDimitry Andric   if (Offset.isZero())
4137*0b57cec5SDimitry Andric     return Base;
4138*0b57cec5SDimitry Andric   Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
4139*0b57cec5SDimitry Andric   return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
4140*0b57cec5SDimitry Andric }
4141*0b57cec5SDimitry Andric 
4142*0b57cec5SDimitry Andric /// Drill down to the storage of a field without walking into
4143*0b57cec5SDimitry Andric /// reference types.
4144*0b57cec5SDimitry Andric ///
4145*0b57cec5SDimitry Andric /// The resulting address doesn't necessarily have the right type.
4146*0b57cec5SDimitry Andric static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
4147*0b57cec5SDimitry Andric                                       const FieldDecl *field) {
4148*0b57cec5SDimitry Andric   if (field->isZeroSize(CGF.getContext()))
4149*0b57cec5SDimitry Andric     return emitAddrOfZeroSizeField(CGF, base, field);
4150*0b57cec5SDimitry Andric 
4151*0b57cec5SDimitry Andric   const RecordDecl *rec = field->getParent();
4152*0b57cec5SDimitry Andric 
4153*0b57cec5SDimitry Andric   unsigned idx =
4154*0b57cec5SDimitry Andric     CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4155*0b57cec5SDimitry Andric 
4156*0b57cec5SDimitry Andric   return CGF.Builder.CreateStructGEP(base, idx, field->getName());
4157*0b57cec5SDimitry Andric }
4158*0b57cec5SDimitry Andric 
41595ffd83dbSDimitry Andric static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
41605ffd83dbSDimitry Andric                                         Address addr, const FieldDecl *field) {
4161*0b57cec5SDimitry Andric   const RecordDecl *rec = field->getParent();
41625ffd83dbSDimitry Andric   llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
41635ffd83dbSDimitry Andric       base.getType(), rec->getLocation());
4164*0b57cec5SDimitry Andric 
4165*0b57cec5SDimitry Andric   unsigned idx =
4166*0b57cec5SDimitry Andric       CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4167*0b57cec5SDimitry Andric 
4168*0b57cec5SDimitry Andric   return CGF.Builder.CreatePreserveStructAccessIndex(
41695ffd83dbSDimitry Andric       addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
4170*0b57cec5SDimitry Andric }
4171*0b57cec5SDimitry Andric 
4172*0b57cec5SDimitry Andric static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
4173*0b57cec5SDimitry Andric   const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
4174*0b57cec5SDimitry Andric   if (!RD)
4175*0b57cec5SDimitry Andric     return false;
4176*0b57cec5SDimitry Andric 
4177*0b57cec5SDimitry Andric   if (RD->isDynamicClass())
4178*0b57cec5SDimitry Andric     return true;
4179*0b57cec5SDimitry Andric 
4180*0b57cec5SDimitry Andric   for (const auto &Base : RD->bases())
4181*0b57cec5SDimitry Andric     if (hasAnyVptr(Base.getType(), Context))
4182*0b57cec5SDimitry Andric       return true;
4183*0b57cec5SDimitry Andric 
4184*0b57cec5SDimitry Andric   for (const FieldDecl *Field : RD->fields())
4185*0b57cec5SDimitry Andric     if (hasAnyVptr(Field->getType(), Context))
4186*0b57cec5SDimitry Andric       return true;
4187*0b57cec5SDimitry Andric 
4188*0b57cec5SDimitry Andric   return false;
4189*0b57cec5SDimitry Andric }
4190*0b57cec5SDimitry Andric 
4191*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForField(LValue base,
4192*0b57cec5SDimitry Andric                                            const FieldDecl *field) {
4193*0b57cec5SDimitry Andric   LValueBaseInfo BaseInfo = base.getBaseInfo();
4194*0b57cec5SDimitry Andric 
4195*0b57cec5SDimitry Andric   if (field->isBitField()) {
4196*0b57cec5SDimitry Andric     const CGRecordLayout &RL =
4197*0b57cec5SDimitry Andric       CGM.getTypes().getCGRecordLayout(field->getParent());
4198*0b57cec5SDimitry Andric     const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4199480093f4SDimitry Andric     Address Addr = base.getAddress(*this);
4200*0b57cec5SDimitry Andric     unsigned Idx = RL.getLLVMFieldNo(field);
4201480093f4SDimitry Andric     const RecordDecl *rec = field->getParent();
4202480093f4SDimitry Andric     if (!IsInPreservedAIRegion &&
4203480093f4SDimitry Andric         (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4204*0b57cec5SDimitry Andric       if (Idx != 0)
4205*0b57cec5SDimitry Andric         // For structs, we GEP to the field that the record layout suggests.
4206*0b57cec5SDimitry Andric         Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4207a7dea167SDimitry Andric     } else {
4208a7dea167SDimitry Andric       llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4209a7dea167SDimitry Andric           getContext().getRecordType(rec), rec->getLocation());
4210a7dea167SDimitry Andric       Addr = Builder.CreatePreserveStructAccessIndex(Addr, Idx,
4211a7dea167SDimitry Andric           getDebugInfoFIndex(rec, field->getFieldIndex()),
4212a7dea167SDimitry Andric           DbgInfo);
4213a7dea167SDimitry Andric     }
4214a7dea167SDimitry Andric 
4215*0b57cec5SDimitry Andric     // Get the access type.
4216*0b57cec5SDimitry Andric     llvm::Type *FieldIntTy =
4217*0b57cec5SDimitry Andric       llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
4218*0b57cec5SDimitry Andric     if (Addr.getElementType() != FieldIntTy)
4219*0b57cec5SDimitry Andric       Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
4220*0b57cec5SDimitry Andric 
4221*0b57cec5SDimitry Andric     QualType fieldType =
4222*0b57cec5SDimitry Andric       field->getType().withCVRQualifiers(base.getVRQualifiers());
4223*0b57cec5SDimitry Andric     // TODO: Support TBAA for bit fields.
4224*0b57cec5SDimitry Andric     LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
4225*0b57cec5SDimitry Andric     return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
4226*0b57cec5SDimitry Andric                                 TBAAAccessInfo());
4227*0b57cec5SDimitry Andric   }
4228*0b57cec5SDimitry Andric 
4229*0b57cec5SDimitry Andric   // Fields of may-alias structures are may-alias themselves.
4230*0b57cec5SDimitry Andric   // FIXME: this should get propagated down through anonymous structs
4231*0b57cec5SDimitry Andric   // and unions.
4232*0b57cec5SDimitry Andric   QualType FieldType = field->getType();
4233*0b57cec5SDimitry Andric   const RecordDecl *rec = field->getParent();
4234*0b57cec5SDimitry Andric   AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
4235*0b57cec5SDimitry Andric   LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
4236*0b57cec5SDimitry Andric   TBAAAccessInfo FieldTBAAInfo;
4237*0b57cec5SDimitry Andric   if (base.getTBAAInfo().isMayAlias() ||
4238*0b57cec5SDimitry Andric           rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
4239*0b57cec5SDimitry Andric     FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4240*0b57cec5SDimitry Andric   } else if (rec->isUnion()) {
4241*0b57cec5SDimitry Andric     // TODO: Support TBAA for unions.
4242*0b57cec5SDimitry Andric     FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4243*0b57cec5SDimitry Andric   } else {
4244*0b57cec5SDimitry Andric     // If no base type been assigned for the base access, then try to generate
4245*0b57cec5SDimitry Andric     // one for this base lvalue.
4246*0b57cec5SDimitry Andric     FieldTBAAInfo = base.getTBAAInfo();
4247*0b57cec5SDimitry Andric     if (!FieldTBAAInfo.BaseType) {
4248*0b57cec5SDimitry Andric         FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
4249*0b57cec5SDimitry Andric         assert(!FieldTBAAInfo.Offset &&
4250*0b57cec5SDimitry Andric                "Nonzero offset for an access with no base type!");
4251*0b57cec5SDimitry Andric     }
4252*0b57cec5SDimitry Andric 
4253*0b57cec5SDimitry Andric     // Adjust offset to be relative to the base type.
4254*0b57cec5SDimitry Andric     const ASTRecordLayout &Layout =
4255*0b57cec5SDimitry Andric         getContext().getASTRecordLayout(field->getParent());
4256*0b57cec5SDimitry Andric     unsigned CharWidth = getContext().getCharWidth();
4257*0b57cec5SDimitry Andric     if (FieldTBAAInfo.BaseType)
4258*0b57cec5SDimitry Andric       FieldTBAAInfo.Offset +=
4259*0b57cec5SDimitry Andric           Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
4260*0b57cec5SDimitry Andric 
4261*0b57cec5SDimitry Andric     // Update the final access type and size.
4262*0b57cec5SDimitry Andric     FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
4263*0b57cec5SDimitry Andric     FieldTBAAInfo.Size =
4264*0b57cec5SDimitry Andric         getContext().getTypeSizeInChars(FieldType).getQuantity();
4265*0b57cec5SDimitry Andric   }
4266*0b57cec5SDimitry Andric 
4267480093f4SDimitry Andric   Address addr = base.getAddress(*this);
4268*0b57cec5SDimitry Andric   if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
4269*0b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().StrictVTablePointers &&
4270*0b57cec5SDimitry Andric         ClassDef->isDynamicClass()) {
4271*0b57cec5SDimitry Andric       // Getting to any field of dynamic object requires stripping dynamic
4272*0b57cec5SDimitry Andric       // information provided by invariant.group.  This is because accessing
4273*0b57cec5SDimitry Andric       // fields may leak the real address of dynamic object, which could result
4274*0b57cec5SDimitry Andric       // in miscompilation when leaked pointer would be compared.
4275*0b57cec5SDimitry Andric       auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
4276*0b57cec5SDimitry Andric       addr = Address(stripped, addr.getAlignment());
4277*0b57cec5SDimitry Andric     }
4278*0b57cec5SDimitry Andric   }
4279*0b57cec5SDimitry Andric 
4280*0b57cec5SDimitry Andric   unsigned RecordCVR = base.getVRQualifiers();
4281*0b57cec5SDimitry Andric   if (rec->isUnion()) {
4282*0b57cec5SDimitry Andric     // For unions, there is no pointer adjustment.
4283*0b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().StrictVTablePointers &&
4284*0b57cec5SDimitry Andric         hasAnyVptr(FieldType, getContext()))
4285*0b57cec5SDimitry Andric       // Because unions can easily skip invariant.barriers, we need to add
4286*0b57cec5SDimitry Andric       // a barrier every time CXXRecord field with vptr is referenced.
4287*0b57cec5SDimitry Andric       addr = Address(Builder.CreateLaunderInvariantGroup(addr.getPointer()),
4288*0b57cec5SDimitry Andric                      addr.getAlignment());
4289*0b57cec5SDimitry Andric 
4290480093f4SDimitry Andric     if (IsInPreservedAIRegion ||
4291480093f4SDimitry Andric         (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4292*0b57cec5SDimitry Andric       // Remember the original union field index
42935ffd83dbSDimitry Andric       llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
42945ffd83dbSDimitry Andric           rec->getLocation());
4295*0b57cec5SDimitry Andric       addr = Address(
4296*0b57cec5SDimitry Andric           Builder.CreatePreserveUnionAccessIndex(
4297*0b57cec5SDimitry Andric               addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
4298*0b57cec5SDimitry Andric           addr.getAlignment());
4299*0b57cec5SDimitry Andric     }
4300*0b57cec5SDimitry Andric 
4301a7dea167SDimitry Andric     if (FieldType->isReferenceType())
4302a7dea167SDimitry Andric       addr = Builder.CreateElementBitCast(
4303a7dea167SDimitry Andric           addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4304a7dea167SDimitry Andric   } else {
4305480093f4SDimitry Andric     if (!IsInPreservedAIRegion &&
4306480093f4SDimitry Andric         (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
4307*0b57cec5SDimitry Andric       // For structs, we GEP to the field that the record layout suggests.
4308*0b57cec5SDimitry Andric       addr = emitAddrOfFieldStorage(*this, addr, field);
4309*0b57cec5SDimitry Andric     else
4310*0b57cec5SDimitry Andric       // Remember the original struct field index
43115ffd83dbSDimitry Andric       addr = emitPreserveStructAccess(*this, base, addr, field);
4312a7dea167SDimitry Andric   }
4313*0b57cec5SDimitry Andric 
4314*0b57cec5SDimitry Andric   // If this is a reference field, load the reference right now.
4315*0b57cec5SDimitry Andric   if (FieldType->isReferenceType()) {
4316a7dea167SDimitry Andric     LValue RefLVal =
4317a7dea167SDimitry Andric         MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4318*0b57cec5SDimitry Andric     if (RecordCVR & Qualifiers::Volatile)
4319*0b57cec5SDimitry Andric       RefLVal.getQuals().addVolatile();
4320*0b57cec5SDimitry Andric     addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
4321*0b57cec5SDimitry Andric 
4322*0b57cec5SDimitry Andric     // Qualifiers on the struct don't apply to the referencee.
4323*0b57cec5SDimitry Andric     RecordCVR = 0;
4324*0b57cec5SDimitry Andric     FieldType = FieldType->getPointeeType();
4325*0b57cec5SDimitry Andric   }
4326*0b57cec5SDimitry Andric 
4327*0b57cec5SDimitry Andric   // Make sure that the address is pointing to the right type.  This is critical
4328*0b57cec5SDimitry Andric   // for both unions and structs.  A union needs a bitcast, a struct element
4329*0b57cec5SDimitry Andric   // will need a bitcast if the LLVM type laid out doesn't match the desired
4330*0b57cec5SDimitry Andric   // type.
4331*0b57cec5SDimitry Andric   addr = Builder.CreateElementBitCast(
4332*0b57cec5SDimitry Andric       addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4333*0b57cec5SDimitry Andric 
4334*0b57cec5SDimitry Andric   if (field->hasAttr<AnnotateAttr>())
4335*0b57cec5SDimitry Andric     addr = EmitFieldAnnotations(field, addr);
4336*0b57cec5SDimitry Andric 
4337*0b57cec5SDimitry Andric   LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4338*0b57cec5SDimitry Andric   LV.getQuals().addCVRQualifiers(RecordCVR);
4339*0b57cec5SDimitry Andric 
4340*0b57cec5SDimitry Andric   // __weak attribute on a field is ignored.
4341*0b57cec5SDimitry Andric   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
4342*0b57cec5SDimitry Andric     LV.getQuals().removeObjCGCAttr();
4343*0b57cec5SDimitry Andric 
4344*0b57cec5SDimitry Andric   return LV;
4345*0b57cec5SDimitry Andric }
4346*0b57cec5SDimitry Andric 
4347*0b57cec5SDimitry Andric LValue
4348*0b57cec5SDimitry Andric CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
4349*0b57cec5SDimitry Andric                                                   const FieldDecl *Field) {
4350*0b57cec5SDimitry Andric   QualType FieldType = Field->getType();
4351*0b57cec5SDimitry Andric 
4352*0b57cec5SDimitry Andric   if (!FieldType->isReferenceType())
4353*0b57cec5SDimitry Andric     return EmitLValueForField(Base, Field);
4354*0b57cec5SDimitry Andric 
4355480093f4SDimitry Andric   Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
4356*0b57cec5SDimitry Andric 
4357*0b57cec5SDimitry Andric   // Make sure that the address is pointing to the right type.
4358*0b57cec5SDimitry Andric   llvm::Type *llvmType = ConvertTypeForMem(FieldType);
4359*0b57cec5SDimitry Andric   V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
4360*0b57cec5SDimitry Andric 
4361*0b57cec5SDimitry Andric   // TODO: Generate TBAA information that describes this access as a structure
4362*0b57cec5SDimitry Andric   // member access and not just an access to an object of the field's type. This
4363*0b57cec5SDimitry Andric   // should be similar to what we do in EmitLValueForField().
4364*0b57cec5SDimitry Andric   LValueBaseInfo BaseInfo = Base.getBaseInfo();
4365*0b57cec5SDimitry Andric   AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
4366*0b57cec5SDimitry Andric   LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
4367*0b57cec5SDimitry Andric   return MakeAddrLValue(V, FieldType, FieldBaseInfo,
4368*0b57cec5SDimitry Andric                         CGM.getTBAAInfoForSubobject(Base, FieldType));
4369*0b57cec5SDimitry Andric }
4370*0b57cec5SDimitry Andric 
4371*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
4372*0b57cec5SDimitry Andric   if (E->isFileScope()) {
4373*0b57cec5SDimitry Andric     ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
4374*0b57cec5SDimitry Andric     return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
4375*0b57cec5SDimitry Andric   }
4376*0b57cec5SDimitry Andric   if (E->getType()->isVariablyModifiedType())
4377*0b57cec5SDimitry Andric     // make sure to emit the VLA size.
4378*0b57cec5SDimitry Andric     EmitVariablyModifiedType(E->getType());
4379*0b57cec5SDimitry Andric 
4380*0b57cec5SDimitry Andric   Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
4381*0b57cec5SDimitry Andric   const Expr *InitExpr = E->getInitializer();
4382*0b57cec5SDimitry Andric   LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
4383*0b57cec5SDimitry Andric 
4384*0b57cec5SDimitry Andric   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
4385*0b57cec5SDimitry Andric                    /*Init*/ true);
4386*0b57cec5SDimitry Andric 
43875ffd83dbSDimitry Andric   // Block-scope compound literals are destroyed at the end of the enclosing
43885ffd83dbSDimitry Andric   // scope in C.
43895ffd83dbSDimitry Andric   if (!getLangOpts().CPlusPlus)
43905ffd83dbSDimitry Andric     if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
43915ffd83dbSDimitry Andric       pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
43925ffd83dbSDimitry Andric                                   E->getType(), getDestroyer(DtorKind),
43935ffd83dbSDimitry Andric                                   DtorKind & EHCleanup);
43945ffd83dbSDimitry Andric 
4395*0b57cec5SDimitry Andric   return Result;
4396*0b57cec5SDimitry Andric }
4397*0b57cec5SDimitry Andric 
4398*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
4399*0b57cec5SDimitry Andric   if (!E->isGLValue())
4400*0b57cec5SDimitry Andric     // Initializing an aggregate temporary in C++11: T{...}.
4401*0b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
4402*0b57cec5SDimitry Andric 
4403*0b57cec5SDimitry Andric   // An lvalue initializer list must be initializing a reference.
4404*0b57cec5SDimitry Andric   assert(E->isTransparent() && "non-transparent glvalue init list");
4405*0b57cec5SDimitry Andric   return EmitLValue(E->getInit(0));
4406*0b57cec5SDimitry Andric }
4407*0b57cec5SDimitry Andric 
4408*0b57cec5SDimitry Andric /// Emit the operand of a glvalue conditional operator. This is either a glvalue
4409*0b57cec5SDimitry Andric /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
4410*0b57cec5SDimitry Andric /// LValue is returned and the current block has been terminated.
4411*0b57cec5SDimitry Andric static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
4412*0b57cec5SDimitry Andric                                                     const Expr *Operand) {
4413*0b57cec5SDimitry Andric   if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
4414*0b57cec5SDimitry Andric     CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
4415*0b57cec5SDimitry Andric     return None;
4416*0b57cec5SDimitry Andric   }
4417*0b57cec5SDimitry Andric 
4418*0b57cec5SDimitry Andric   return CGF.EmitLValue(Operand);
4419*0b57cec5SDimitry Andric }
4420*0b57cec5SDimitry Andric 
4421*0b57cec5SDimitry Andric LValue CodeGenFunction::
4422*0b57cec5SDimitry Andric EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
4423*0b57cec5SDimitry Andric   if (!expr->isGLValue()) {
4424*0b57cec5SDimitry Andric     // ?: here should be an aggregate.
4425*0b57cec5SDimitry Andric     assert(hasAggregateEvaluationKind(expr->getType()) &&
4426*0b57cec5SDimitry Andric            "Unexpected conditional operator!");
4427*0b57cec5SDimitry Andric     return EmitAggExprToLValue(expr);
4428*0b57cec5SDimitry Andric   }
4429*0b57cec5SDimitry Andric 
4430*0b57cec5SDimitry Andric   OpaqueValueMapping binding(*this, expr);
4431*0b57cec5SDimitry Andric 
4432*0b57cec5SDimitry Andric   const Expr *condExpr = expr->getCond();
4433*0b57cec5SDimitry Andric   bool CondExprBool;
4434*0b57cec5SDimitry Andric   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4435*0b57cec5SDimitry Andric     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
4436*0b57cec5SDimitry Andric     if (!CondExprBool) std::swap(live, dead);
4437*0b57cec5SDimitry Andric 
4438*0b57cec5SDimitry Andric     if (!ContainsLabel(dead)) {
4439*0b57cec5SDimitry Andric       // If the true case is live, we need to track its region.
4440*0b57cec5SDimitry Andric       if (CondExprBool)
4441*0b57cec5SDimitry Andric         incrementProfileCounter(expr);
44425ffd83dbSDimitry Andric       // If a throw expression we emit it and return an undefined lvalue
44435ffd83dbSDimitry Andric       // because it can't be used.
44445ffd83dbSDimitry Andric       if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(live->IgnoreParens())) {
44455ffd83dbSDimitry Andric         EmitCXXThrowExpr(ThrowExpr);
44465ffd83dbSDimitry Andric         llvm::Type *Ty =
44475ffd83dbSDimitry Andric             llvm::PointerType::getUnqual(ConvertType(dead->getType()));
44485ffd83dbSDimitry Andric         return MakeAddrLValue(
44495ffd83dbSDimitry Andric             Address(llvm::UndefValue::get(Ty), CharUnits::One()),
44505ffd83dbSDimitry Andric             dead->getType());
44515ffd83dbSDimitry Andric       }
4452*0b57cec5SDimitry Andric       return EmitLValue(live);
4453*0b57cec5SDimitry Andric     }
4454*0b57cec5SDimitry Andric   }
4455*0b57cec5SDimitry Andric 
4456*0b57cec5SDimitry Andric   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
4457*0b57cec5SDimitry Andric   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
4458*0b57cec5SDimitry Andric   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
4459*0b57cec5SDimitry Andric 
4460*0b57cec5SDimitry Andric   ConditionalEvaluation eval(*this);
4461*0b57cec5SDimitry Andric   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
4462*0b57cec5SDimitry Andric 
4463*0b57cec5SDimitry Andric   // Any temporaries created here are conditional.
4464*0b57cec5SDimitry Andric   EmitBlock(lhsBlock);
4465*0b57cec5SDimitry Andric   incrementProfileCounter(expr);
4466*0b57cec5SDimitry Andric   eval.begin(*this);
4467*0b57cec5SDimitry Andric   Optional<LValue> lhs =
4468*0b57cec5SDimitry Andric       EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
4469*0b57cec5SDimitry Andric   eval.end(*this);
4470*0b57cec5SDimitry Andric 
4471*0b57cec5SDimitry Andric   if (lhs && !lhs->isSimple())
4472*0b57cec5SDimitry Andric     return EmitUnsupportedLValue(expr, "conditional operator");
4473*0b57cec5SDimitry Andric 
4474*0b57cec5SDimitry Andric   lhsBlock = Builder.GetInsertBlock();
4475*0b57cec5SDimitry Andric   if (lhs)
4476*0b57cec5SDimitry Andric     Builder.CreateBr(contBlock);
4477*0b57cec5SDimitry Andric 
4478*0b57cec5SDimitry Andric   // Any temporaries created here are conditional.
4479*0b57cec5SDimitry Andric   EmitBlock(rhsBlock);
4480*0b57cec5SDimitry Andric   eval.begin(*this);
4481*0b57cec5SDimitry Andric   Optional<LValue> rhs =
4482*0b57cec5SDimitry Andric       EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
4483*0b57cec5SDimitry Andric   eval.end(*this);
4484*0b57cec5SDimitry Andric   if (rhs && !rhs->isSimple())
4485*0b57cec5SDimitry Andric     return EmitUnsupportedLValue(expr, "conditional operator");
4486*0b57cec5SDimitry Andric   rhsBlock = Builder.GetInsertBlock();
4487*0b57cec5SDimitry Andric 
4488*0b57cec5SDimitry Andric   EmitBlock(contBlock);
4489*0b57cec5SDimitry Andric 
4490*0b57cec5SDimitry Andric   if (lhs && rhs) {
4491480093f4SDimitry Andric     llvm::PHINode *phi =
4492480093f4SDimitry Andric         Builder.CreatePHI(lhs->getPointer(*this)->getType(), 2, "cond-lvalue");
4493480093f4SDimitry Andric     phi->addIncoming(lhs->getPointer(*this), lhsBlock);
4494480093f4SDimitry Andric     phi->addIncoming(rhs->getPointer(*this), rhsBlock);
4495*0b57cec5SDimitry Andric     Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
4496*0b57cec5SDimitry Andric     AlignmentSource alignSource =
4497*0b57cec5SDimitry Andric       std::max(lhs->getBaseInfo().getAlignmentSource(),
4498*0b57cec5SDimitry Andric                rhs->getBaseInfo().getAlignmentSource());
4499*0b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
4500*0b57cec5SDimitry Andric         lhs->getTBAAInfo(), rhs->getTBAAInfo());
4501*0b57cec5SDimitry Andric     return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
4502*0b57cec5SDimitry Andric                           TBAAInfo);
4503*0b57cec5SDimitry Andric   } else {
4504*0b57cec5SDimitry Andric     assert((lhs || rhs) &&
4505*0b57cec5SDimitry Andric            "both operands of glvalue conditional are throw-expressions?");
4506*0b57cec5SDimitry Andric     return lhs ? *lhs : *rhs;
4507*0b57cec5SDimitry Andric   }
4508*0b57cec5SDimitry Andric }
4509*0b57cec5SDimitry Andric 
4510*0b57cec5SDimitry Andric /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
4511*0b57cec5SDimitry Andric /// type. If the cast is to a reference, we can have the usual lvalue result,
4512*0b57cec5SDimitry Andric /// otherwise if a cast is needed by the code generator in an lvalue context,
4513*0b57cec5SDimitry Andric /// then it must mean that we need the address of an aggregate in order to
4514*0b57cec5SDimitry Andric /// access one of its members.  This can happen for all the reasons that casts
4515*0b57cec5SDimitry Andric /// are permitted with aggregate result, including noop aggregate casts, and
4516*0b57cec5SDimitry Andric /// cast from scalar to union.
4517*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
4518*0b57cec5SDimitry Andric   switch (E->getCastKind()) {
4519*0b57cec5SDimitry Andric   case CK_ToVoid:
4520*0b57cec5SDimitry Andric   case CK_BitCast:
4521*0b57cec5SDimitry Andric   case CK_LValueToRValueBitCast:
4522*0b57cec5SDimitry Andric   case CK_ArrayToPointerDecay:
4523*0b57cec5SDimitry Andric   case CK_FunctionToPointerDecay:
4524*0b57cec5SDimitry Andric   case CK_NullToMemberPointer:
4525*0b57cec5SDimitry Andric   case CK_NullToPointer:
4526*0b57cec5SDimitry Andric   case CK_IntegralToPointer:
4527*0b57cec5SDimitry Andric   case CK_PointerToIntegral:
4528*0b57cec5SDimitry Andric   case CK_PointerToBoolean:
4529*0b57cec5SDimitry Andric   case CK_VectorSplat:
4530*0b57cec5SDimitry Andric   case CK_IntegralCast:
4531*0b57cec5SDimitry Andric   case CK_BooleanToSignedIntegral:
4532*0b57cec5SDimitry Andric   case CK_IntegralToBoolean:
4533*0b57cec5SDimitry Andric   case CK_IntegralToFloating:
4534*0b57cec5SDimitry Andric   case CK_FloatingToIntegral:
4535*0b57cec5SDimitry Andric   case CK_FloatingToBoolean:
4536*0b57cec5SDimitry Andric   case CK_FloatingCast:
4537*0b57cec5SDimitry Andric   case CK_FloatingRealToComplex:
4538*0b57cec5SDimitry Andric   case CK_FloatingComplexToReal:
4539*0b57cec5SDimitry Andric   case CK_FloatingComplexToBoolean:
4540*0b57cec5SDimitry Andric   case CK_FloatingComplexCast:
4541*0b57cec5SDimitry Andric   case CK_FloatingComplexToIntegralComplex:
4542*0b57cec5SDimitry Andric   case CK_IntegralRealToComplex:
4543*0b57cec5SDimitry Andric   case CK_IntegralComplexToReal:
4544*0b57cec5SDimitry Andric   case CK_IntegralComplexToBoolean:
4545*0b57cec5SDimitry Andric   case CK_IntegralComplexCast:
4546*0b57cec5SDimitry Andric   case CK_IntegralComplexToFloatingComplex:
4547*0b57cec5SDimitry Andric   case CK_DerivedToBaseMemberPointer:
4548*0b57cec5SDimitry Andric   case CK_BaseToDerivedMemberPointer:
4549*0b57cec5SDimitry Andric   case CK_MemberPointerToBoolean:
4550*0b57cec5SDimitry Andric   case CK_ReinterpretMemberPointer:
4551*0b57cec5SDimitry Andric   case CK_AnyPointerToBlockPointerCast:
4552*0b57cec5SDimitry Andric   case CK_ARCProduceObject:
4553*0b57cec5SDimitry Andric   case CK_ARCConsumeObject:
4554*0b57cec5SDimitry Andric   case CK_ARCReclaimReturnedObject:
4555*0b57cec5SDimitry Andric   case CK_ARCExtendBlockObject:
4556*0b57cec5SDimitry Andric   case CK_CopyAndAutoreleaseBlockObject:
4557*0b57cec5SDimitry Andric   case CK_IntToOCLSampler:
4558*0b57cec5SDimitry Andric   case CK_FixedPointCast:
4559*0b57cec5SDimitry Andric   case CK_FixedPointToBoolean:
4560*0b57cec5SDimitry Andric   case CK_FixedPointToIntegral:
4561*0b57cec5SDimitry Andric   case CK_IntegralToFixedPoint:
4562*0b57cec5SDimitry Andric     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4563*0b57cec5SDimitry Andric 
4564*0b57cec5SDimitry Andric   case CK_Dependent:
4565*0b57cec5SDimitry Andric     llvm_unreachable("dependent cast kind in IR gen!");
4566*0b57cec5SDimitry Andric 
4567*0b57cec5SDimitry Andric   case CK_BuiltinFnToFnPtr:
4568*0b57cec5SDimitry Andric     llvm_unreachable("builtin functions are handled elsewhere");
4569*0b57cec5SDimitry Andric 
4570*0b57cec5SDimitry Andric   // These are never l-values; just use the aggregate emission code.
4571*0b57cec5SDimitry Andric   case CK_NonAtomicToAtomic:
4572*0b57cec5SDimitry Andric   case CK_AtomicToNonAtomic:
4573*0b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
4574*0b57cec5SDimitry Andric 
4575*0b57cec5SDimitry Andric   case CK_Dynamic: {
4576*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4577480093f4SDimitry Andric     Address V = LV.getAddress(*this);
4578*0b57cec5SDimitry Andric     const auto *DCE = cast<CXXDynamicCastExpr>(E);
4579*0b57cec5SDimitry Andric     return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
4580*0b57cec5SDimitry Andric   }
4581*0b57cec5SDimitry Andric 
4582*0b57cec5SDimitry Andric   case CK_ConstructorConversion:
4583*0b57cec5SDimitry Andric   case CK_UserDefinedConversion:
4584*0b57cec5SDimitry Andric   case CK_CPointerToObjCPointerCast:
4585*0b57cec5SDimitry Andric   case CK_BlockPointerToObjCPointerCast:
4586*0b57cec5SDimitry Andric   case CK_NoOp:
4587*0b57cec5SDimitry Andric   case CK_LValueToRValue:
4588*0b57cec5SDimitry Andric     return EmitLValue(E->getSubExpr());
4589*0b57cec5SDimitry Andric 
4590*0b57cec5SDimitry Andric   case CK_UncheckedDerivedToBase:
4591*0b57cec5SDimitry Andric   case CK_DerivedToBase: {
4592480093f4SDimitry Andric     const auto *DerivedClassTy =
4593480093f4SDimitry Andric         E->getSubExpr()->getType()->castAs<RecordType>();
4594*0b57cec5SDimitry Andric     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4595*0b57cec5SDimitry Andric 
4596*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4597480093f4SDimitry Andric     Address This = LV.getAddress(*this);
4598*0b57cec5SDimitry Andric 
4599*0b57cec5SDimitry Andric     // Perform the derived-to-base conversion
4600*0b57cec5SDimitry Andric     Address Base = GetAddressOfBaseClass(
4601*0b57cec5SDimitry Andric         This, DerivedClassDecl, E->path_begin(), E->path_end(),
4602*0b57cec5SDimitry Andric         /*NullCheckValue=*/false, E->getExprLoc());
4603*0b57cec5SDimitry Andric 
4604*0b57cec5SDimitry Andric     // TODO: Support accesses to members of base classes in TBAA. For now, we
4605*0b57cec5SDimitry Andric     // conservatively pretend that the complete object is of the base class
4606*0b57cec5SDimitry Andric     // type.
4607*0b57cec5SDimitry Andric     return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4608*0b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4609*0b57cec5SDimitry Andric   }
4610*0b57cec5SDimitry Andric   case CK_ToUnion:
4611*0b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
4612*0b57cec5SDimitry Andric   case CK_BaseToDerived: {
4613480093f4SDimitry Andric     const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
4614*0b57cec5SDimitry Andric     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4615*0b57cec5SDimitry Andric 
4616*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4617*0b57cec5SDimitry Andric 
4618*0b57cec5SDimitry Andric     // Perform the base-to-derived conversion
4619480093f4SDimitry Andric     Address Derived = GetAddressOfDerivedClass(
4620480093f4SDimitry Andric         LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
4621*0b57cec5SDimitry Andric         /*NullCheckValue=*/false);
4622*0b57cec5SDimitry Andric 
4623*0b57cec5SDimitry Andric     // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4624*0b57cec5SDimitry Andric     // performed and the object is not of the derived type.
4625*0b57cec5SDimitry Andric     if (sanitizePerformTypeCheck())
4626*0b57cec5SDimitry Andric       EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
4627*0b57cec5SDimitry Andric                     Derived.getPointer(), E->getType());
4628*0b57cec5SDimitry Andric 
4629*0b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::CFIDerivedCast))
4630*0b57cec5SDimitry Andric       EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4631*0b57cec5SDimitry Andric                                 /*MayBeNull=*/false, CFITCK_DerivedCast,
4632*0b57cec5SDimitry Andric                                 E->getBeginLoc());
4633*0b57cec5SDimitry Andric 
4634*0b57cec5SDimitry Andric     return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4635*0b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4636*0b57cec5SDimitry Andric   }
4637*0b57cec5SDimitry Andric   case CK_LValueBitCast: {
4638*0b57cec5SDimitry Andric     // This must be a reinterpret_cast (or c-style equivalent).
4639*0b57cec5SDimitry Andric     const auto *CE = cast<ExplicitCastExpr>(E);
4640*0b57cec5SDimitry Andric 
4641*0b57cec5SDimitry Andric     CGM.EmitExplicitCastExprType(CE, this);
4642*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4643480093f4SDimitry Andric     Address V = Builder.CreateBitCast(LV.getAddress(*this),
4644*0b57cec5SDimitry Andric                                       ConvertType(CE->getTypeAsWritten()));
4645*0b57cec5SDimitry Andric 
4646*0b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4647*0b57cec5SDimitry Andric       EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4648*0b57cec5SDimitry Andric                                 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
4649*0b57cec5SDimitry Andric                                 E->getBeginLoc());
4650*0b57cec5SDimitry Andric 
4651*0b57cec5SDimitry Andric     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4652*0b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4653*0b57cec5SDimitry Andric   }
4654*0b57cec5SDimitry Andric   case CK_AddressSpaceConversion: {
4655*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4656*0b57cec5SDimitry Andric     QualType DestTy = getContext().getPointerType(E->getType());
4657*0b57cec5SDimitry Andric     llvm::Value *V = getTargetHooks().performAddrSpaceCast(
4658480093f4SDimitry Andric         *this, LV.getPointer(*this),
4659480093f4SDimitry Andric         E->getSubExpr()->getType().getAddressSpace(),
4660*0b57cec5SDimitry Andric         E->getType().getAddressSpace(), ConvertType(DestTy));
4661480093f4SDimitry Andric     return MakeAddrLValue(Address(V, LV.getAddress(*this).getAlignment()),
4662*0b57cec5SDimitry Andric                           E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
4663*0b57cec5SDimitry Andric   }
4664*0b57cec5SDimitry Andric   case CK_ObjCObjectLValueCast: {
4665*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4666480093f4SDimitry Andric     Address V = Builder.CreateElementBitCast(LV.getAddress(*this),
4667*0b57cec5SDimitry Andric                                              ConvertType(E->getType()));
4668*0b57cec5SDimitry Andric     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4669*0b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4670*0b57cec5SDimitry Andric   }
4671*0b57cec5SDimitry Andric   case CK_ZeroToOCLOpaqueType:
4672*0b57cec5SDimitry Andric     llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
4673*0b57cec5SDimitry Andric   }
4674*0b57cec5SDimitry Andric 
4675*0b57cec5SDimitry Andric   llvm_unreachable("Unhandled lvalue cast kind?");
4676*0b57cec5SDimitry Andric }
4677*0b57cec5SDimitry Andric 
4678*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4679*0b57cec5SDimitry Andric   assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4680*0b57cec5SDimitry Andric   return getOrCreateOpaqueLValueMapping(e);
4681*0b57cec5SDimitry Andric }
4682*0b57cec5SDimitry Andric 
4683*0b57cec5SDimitry Andric LValue
4684*0b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
4685*0b57cec5SDimitry Andric   assert(OpaqueValueMapping::shouldBindAsLValue(e));
4686*0b57cec5SDimitry Andric 
4687*0b57cec5SDimitry Andric   llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
4688*0b57cec5SDimitry Andric       it = OpaqueLValues.find(e);
4689*0b57cec5SDimitry Andric 
4690*0b57cec5SDimitry Andric   if (it != OpaqueLValues.end())
4691*0b57cec5SDimitry Andric     return it->second;
4692*0b57cec5SDimitry Andric 
4693*0b57cec5SDimitry Andric   assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
4694*0b57cec5SDimitry Andric   return EmitLValue(e->getSourceExpr());
4695*0b57cec5SDimitry Andric }
4696*0b57cec5SDimitry Andric 
4697*0b57cec5SDimitry Andric RValue
4698*0b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
4699*0b57cec5SDimitry Andric   assert(!OpaqueValueMapping::shouldBindAsLValue(e));
4700*0b57cec5SDimitry Andric 
4701*0b57cec5SDimitry Andric   llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
4702*0b57cec5SDimitry Andric       it = OpaqueRValues.find(e);
4703*0b57cec5SDimitry Andric 
4704*0b57cec5SDimitry Andric   if (it != OpaqueRValues.end())
4705*0b57cec5SDimitry Andric     return it->second;
4706*0b57cec5SDimitry Andric 
4707*0b57cec5SDimitry Andric   assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
4708*0b57cec5SDimitry Andric   return EmitAnyExpr(e->getSourceExpr());
4709*0b57cec5SDimitry Andric }
4710*0b57cec5SDimitry Andric 
4711*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitRValueForField(LValue LV,
4712*0b57cec5SDimitry Andric                                            const FieldDecl *FD,
4713*0b57cec5SDimitry Andric                                            SourceLocation Loc) {
4714*0b57cec5SDimitry Andric   QualType FT = FD->getType();
4715*0b57cec5SDimitry Andric   LValue FieldLV = EmitLValueForField(LV, FD);
4716*0b57cec5SDimitry Andric   switch (getEvaluationKind(FT)) {
4717*0b57cec5SDimitry Andric   case TEK_Complex:
4718*0b57cec5SDimitry Andric     return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4719*0b57cec5SDimitry Andric   case TEK_Aggregate:
4720480093f4SDimitry Andric     return FieldLV.asAggregateRValue(*this);
4721*0b57cec5SDimitry Andric   case TEK_Scalar:
4722*0b57cec5SDimitry Andric     // This routine is used to load fields one-by-one to perform a copy, so
4723*0b57cec5SDimitry Andric     // don't load reference fields.
4724*0b57cec5SDimitry Andric     if (FD->getType()->isReferenceType())
4725480093f4SDimitry Andric       return RValue::get(FieldLV.getPointer(*this));
4726480093f4SDimitry Andric     // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
4727480093f4SDimitry Andric     // primitive load.
4728480093f4SDimitry Andric     if (FieldLV.isBitField())
4729*0b57cec5SDimitry Andric       return EmitLoadOfLValue(FieldLV, Loc);
4730480093f4SDimitry Andric     return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
4731*0b57cec5SDimitry Andric   }
4732*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
4733*0b57cec5SDimitry Andric }
4734*0b57cec5SDimitry Andric 
4735*0b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
4736*0b57cec5SDimitry Andric //                             Expression Emission
4737*0b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
4738*0b57cec5SDimitry Andric 
4739*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
4740*0b57cec5SDimitry Andric                                      ReturnValueSlot ReturnValue) {
4741*0b57cec5SDimitry Andric   // Builtins never have block type.
4742*0b57cec5SDimitry Andric   if (E->getCallee()->getType()->isBlockPointerType())
4743*0b57cec5SDimitry Andric     return EmitBlockCallExpr(E, ReturnValue);
4744*0b57cec5SDimitry Andric 
4745*0b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4746*0b57cec5SDimitry Andric     return EmitCXXMemberCallExpr(CE, ReturnValue);
4747*0b57cec5SDimitry Andric 
4748*0b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
4749*0b57cec5SDimitry Andric     return EmitCUDAKernelCallExpr(CE, ReturnValue);
4750*0b57cec5SDimitry Andric 
4751*0b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
4752*0b57cec5SDimitry Andric     if (const CXXMethodDecl *MD =
4753*0b57cec5SDimitry Andric           dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4754*0b57cec5SDimitry Andric       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4755*0b57cec5SDimitry Andric 
4756*0b57cec5SDimitry Andric   CGCallee callee = EmitCallee(E->getCallee());
4757*0b57cec5SDimitry Andric 
4758*0b57cec5SDimitry Andric   if (callee.isBuiltin()) {
4759*0b57cec5SDimitry Andric     return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4760*0b57cec5SDimitry Andric                            E, ReturnValue);
4761*0b57cec5SDimitry Andric   }
4762*0b57cec5SDimitry Andric 
4763*0b57cec5SDimitry Andric   if (callee.isPseudoDestructor()) {
4764*0b57cec5SDimitry Andric     return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4765*0b57cec5SDimitry Andric   }
4766*0b57cec5SDimitry Andric 
4767*0b57cec5SDimitry Andric   return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4768*0b57cec5SDimitry Andric }
4769*0b57cec5SDimitry Andric 
4770*0b57cec5SDimitry Andric /// Emit a CallExpr without considering whether it might be a subclass.
4771*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4772*0b57cec5SDimitry Andric                                            ReturnValueSlot ReturnValue) {
4773*0b57cec5SDimitry Andric   CGCallee Callee = EmitCallee(E->getCallee());
4774*0b57cec5SDimitry Andric   return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4775*0b57cec5SDimitry Andric }
4776*0b57cec5SDimitry Andric 
47775ffd83dbSDimitry Andric static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
47785ffd83dbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4779480093f4SDimitry Andric 
4780*0b57cec5SDimitry Andric   if (auto builtinID = FD->getBuiltinID()) {
4781480093f4SDimitry Andric     // Replaceable builtin provide their own implementation of a builtin. Unless
4782480093f4SDimitry Andric     // we are in the builtin implementation itself, don't call the actual
4783480093f4SDimitry Andric     // builtin. If we are in the builtin implementation, avoid trivial infinite
4784480093f4SDimitry Andric     // recursion.
4785480093f4SDimitry Andric     if (!FD->isInlineBuiltinDeclaration() ||
4786480093f4SDimitry Andric         CGF.CurFn->getName() == FD->getName())
4787*0b57cec5SDimitry Andric       return CGCallee::forBuiltin(builtinID, FD);
4788*0b57cec5SDimitry Andric   }
4789*0b57cec5SDimitry Andric 
47905ffd83dbSDimitry Andric   llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
47915ffd83dbSDimitry Andric   return CGCallee::forDirect(calleePtr, GD);
4792*0b57cec5SDimitry Andric }
4793*0b57cec5SDimitry Andric 
4794*0b57cec5SDimitry Andric CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4795*0b57cec5SDimitry Andric   E = E->IgnoreParens();
4796*0b57cec5SDimitry Andric 
4797*0b57cec5SDimitry Andric   // Look through function-to-pointer decay.
4798*0b57cec5SDimitry Andric   if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4799*0b57cec5SDimitry Andric     if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4800*0b57cec5SDimitry Andric         ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4801*0b57cec5SDimitry Andric       return EmitCallee(ICE->getSubExpr());
4802*0b57cec5SDimitry Andric     }
4803*0b57cec5SDimitry Andric 
4804*0b57cec5SDimitry Andric   // Resolve direct calls.
4805*0b57cec5SDimitry Andric   } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4806*0b57cec5SDimitry Andric     if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4807*0b57cec5SDimitry Andric       return EmitDirectCallee(*this, FD);
4808*0b57cec5SDimitry Andric     }
4809*0b57cec5SDimitry Andric   } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4810*0b57cec5SDimitry Andric     if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4811*0b57cec5SDimitry Andric       EmitIgnoredExpr(ME->getBase());
4812*0b57cec5SDimitry Andric       return EmitDirectCallee(*this, FD);
4813*0b57cec5SDimitry Andric     }
4814*0b57cec5SDimitry Andric 
4815*0b57cec5SDimitry Andric   // Look through template substitutions.
4816*0b57cec5SDimitry Andric   } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4817*0b57cec5SDimitry Andric     return EmitCallee(NTTP->getReplacement());
4818*0b57cec5SDimitry Andric 
4819*0b57cec5SDimitry Andric   // Treat pseudo-destructor calls differently.
4820*0b57cec5SDimitry Andric   } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4821*0b57cec5SDimitry Andric     return CGCallee::forPseudoDestructor(PDE);
4822*0b57cec5SDimitry Andric   }
4823*0b57cec5SDimitry Andric 
4824*0b57cec5SDimitry Andric   // Otherwise, we have an indirect reference.
4825*0b57cec5SDimitry Andric   llvm::Value *calleePtr;
4826*0b57cec5SDimitry Andric   QualType functionType;
4827*0b57cec5SDimitry Andric   if (auto ptrType = E->getType()->getAs<PointerType>()) {
4828*0b57cec5SDimitry Andric     calleePtr = EmitScalarExpr(E);
4829*0b57cec5SDimitry Andric     functionType = ptrType->getPointeeType();
4830*0b57cec5SDimitry Andric   } else {
4831*0b57cec5SDimitry Andric     functionType = E->getType();
4832480093f4SDimitry Andric     calleePtr = EmitLValue(E).getPointer(*this);
4833*0b57cec5SDimitry Andric   }
4834*0b57cec5SDimitry Andric   assert(functionType->isFunctionType());
4835*0b57cec5SDimitry Andric 
4836*0b57cec5SDimitry Andric   GlobalDecl GD;
4837*0b57cec5SDimitry Andric   if (const auto *VD =
4838*0b57cec5SDimitry Andric           dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
4839*0b57cec5SDimitry Andric     GD = GlobalDecl(VD);
4840*0b57cec5SDimitry Andric 
4841*0b57cec5SDimitry Andric   CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
4842*0b57cec5SDimitry Andric   CGCallee callee(calleeInfo, calleePtr);
4843*0b57cec5SDimitry Andric   return callee;
4844*0b57cec5SDimitry Andric }
4845*0b57cec5SDimitry Andric 
4846*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
4847*0b57cec5SDimitry Andric   // Comma expressions just emit their LHS then their RHS as an l-value.
4848*0b57cec5SDimitry Andric   if (E->getOpcode() == BO_Comma) {
4849*0b57cec5SDimitry Andric     EmitIgnoredExpr(E->getLHS());
4850*0b57cec5SDimitry Andric     EnsureInsertPoint();
4851*0b57cec5SDimitry Andric     return EmitLValue(E->getRHS());
4852*0b57cec5SDimitry Andric   }
4853*0b57cec5SDimitry Andric 
4854*0b57cec5SDimitry Andric   if (E->getOpcode() == BO_PtrMemD ||
4855*0b57cec5SDimitry Andric       E->getOpcode() == BO_PtrMemI)
4856*0b57cec5SDimitry Andric     return EmitPointerToDataMemberBinaryExpr(E);
4857*0b57cec5SDimitry Andric 
4858*0b57cec5SDimitry Andric   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4859*0b57cec5SDimitry Andric 
4860*0b57cec5SDimitry Andric   // Note that in all of these cases, __block variables need the RHS
4861*0b57cec5SDimitry Andric   // evaluated first just in case the variable gets moved by the RHS.
4862*0b57cec5SDimitry Andric 
4863*0b57cec5SDimitry Andric   switch (getEvaluationKind(E->getType())) {
4864*0b57cec5SDimitry Andric   case TEK_Scalar: {
4865*0b57cec5SDimitry Andric     switch (E->getLHS()->getType().getObjCLifetime()) {
4866*0b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
4867*0b57cec5SDimitry Andric       return EmitARCStoreStrong(E, /*ignored*/ false).first;
4868*0b57cec5SDimitry Andric 
4869*0b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
4870*0b57cec5SDimitry Andric       return EmitARCStoreAutoreleasing(E).first;
4871*0b57cec5SDimitry Andric 
4872*0b57cec5SDimitry Andric     // No reason to do any of these differently.
4873*0b57cec5SDimitry Andric     case Qualifiers::OCL_None:
4874*0b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
4875*0b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
4876*0b57cec5SDimitry Andric       break;
4877*0b57cec5SDimitry Andric     }
4878*0b57cec5SDimitry Andric 
4879*0b57cec5SDimitry Andric     RValue RV = EmitAnyExpr(E->getRHS());
4880*0b57cec5SDimitry Andric     LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
4881*0b57cec5SDimitry Andric     if (RV.isScalar())
4882*0b57cec5SDimitry Andric       EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
4883*0b57cec5SDimitry Andric     EmitStoreThroughLValue(RV, LV);
4884480093f4SDimitry Andric     if (getLangOpts().OpenMP)
4885480093f4SDimitry Andric       CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
4886480093f4SDimitry Andric                                                                 E->getLHS());
4887*0b57cec5SDimitry Andric     return LV;
4888*0b57cec5SDimitry Andric   }
4889*0b57cec5SDimitry Andric 
4890*0b57cec5SDimitry Andric   case TEK_Complex:
4891*0b57cec5SDimitry Andric     return EmitComplexAssignmentLValue(E);
4892*0b57cec5SDimitry Andric 
4893*0b57cec5SDimitry Andric   case TEK_Aggregate:
4894*0b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
4895*0b57cec5SDimitry Andric   }
4896*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
4897*0b57cec5SDimitry Andric }
4898*0b57cec5SDimitry Andric 
4899*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
4900*0b57cec5SDimitry Andric   RValue RV = EmitCallExpr(E);
4901*0b57cec5SDimitry Andric 
4902*0b57cec5SDimitry Andric   if (!RV.isScalar())
4903*0b57cec5SDimitry Andric     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4904*0b57cec5SDimitry Andric                           AlignmentSource::Decl);
4905*0b57cec5SDimitry Andric 
4906*0b57cec5SDimitry Andric   assert(E->getCallReturnType(getContext())->isReferenceType() &&
4907*0b57cec5SDimitry Andric          "Can't have a scalar return unless the return type is a "
4908*0b57cec5SDimitry Andric          "reference type!");
4909*0b57cec5SDimitry Andric 
4910*0b57cec5SDimitry Andric   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4911*0b57cec5SDimitry Andric }
4912*0b57cec5SDimitry Andric 
4913*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4914*0b57cec5SDimitry Andric   // FIXME: This shouldn't require another copy.
4915*0b57cec5SDimitry Andric   return EmitAggExprToLValue(E);
4916*0b57cec5SDimitry Andric }
4917*0b57cec5SDimitry Andric 
4918*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
4919*0b57cec5SDimitry Andric   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4920*0b57cec5SDimitry Andric          && "binding l-value to type which needs a temporary");
4921*0b57cec5SDimitry Andric   AggValueSlot Slot = CreateAggTemp(E->getType());
4922*0b57cec5SDimitry Andric   EmitCXXConstructExpr(E, Slot);
4923*0b57cec5SDimitry Andric   return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
4924*0b57cec5SDimitry Andric }
4925*0b57cec5SDimitry Andric 
4926*0b57cec5SDimitry Andric LValue
4927*0b57cec5SDimitry Andric CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
4928*0b57cec5SDimitry Andric   return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4929*0b57cec5SDimitry Andric }
4930*0b57cec5SDimitry Andric 
4931*0b57cec5SDimitry Andric Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
49325ffd83dbSDimitry Andric   return Builder.CreateElementBitCast(CGM.GetAddrOfMSGuidDecl(E->getGuidDecl()),
4933*0b57cec5SDimitry Andric                                       ConvertType(E->getType()));
4934*0b57cec5SDimitry Andric }
4935*0b57cec5SDimitry Andric 
4936*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4937*0b57cec5SDimitry Andric   return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4938*0b57cec5SDimitry Andric                         AlignmentSource::Decl);
4939*0b57cec5SDimitry Andric }
4940*0b57cec5SDimitry Andric 
4941*0b57cec5SDimitry Andric LValue
4942*0b57cec5SDimitry Andric CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4943*0b57cec5SDimitry Andric   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4944*0b57cec5SDimitry Andric   Slot.setExternallyDestructed();
4945*0b57cec5SDimitry Andric   EmitAggExpr(E->getSubExpr(), Slot);
4946*0b57cec5SDimitry Andric   EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4947*0b57cec5SDimitry Andric   return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
4948*0b57cec5SDimitry Andric }
4949*0b57cec5SDimitry Andric 
4950*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4951*0b57cec5SDimitry Andric   RValue RV = EmitObjCMessageExpr(E);
4952*0b57cec5SDimitry Andric 
4953*0b57cec5SDimitry Andric   if (!RV.isScalar())
4954*0b57cec5SDimitry Andric     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4955*0b57cec5SDimitry Andric                           AlignmentSource::Decl);
4956*0b57cec5SDimitry Andric 
4957*0b57cec5SDimitry Andric   assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4958*0b57cec5SDimitry Andric          "Can't have a scalar return unless the return type is a "
4959*0b57cec5SDimitry Andric          "reference type!");
4960*0b57cec5SDimitry Andric 
4961*0b57cec5SDimitry Andric   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4962*0b57cec5SDimitry Andric }
4963*0b57cec5SDimitry Andric 
4964*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4965*0b57cec5SDimitry Andric   Address V =
4966*0b57cec5SDimitry Andric     CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4967*0b57cec5SDimitry Andric   return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
4968*0b57cec5SDimitry Andric }
4969*0b57cec5SDimitry Andric 
4970*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4971*0b57cec5SDimitry Andric                                              const ObjCIvarDecl *Ivar) {
4972*0b57cec5SDimitry Andric   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4973*0b57cec5SDimitry Andric }
4974*0b57cec5SDimitry Andric 
4975*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4976*0b57cec5SDimitry Andric                                           llvm::Value *BaseValue,
4977*0b57cec5SDimitry Andric                                           const ObjCIvarDecl *Ivar,
4978*0b57cec5SDimitry Andric                                           unsigned CVRQualifiers) {
4979*0b57cec5SDimitry Andric   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4980*0b57cec5SDimitry Andric                                                    Ivar, CVRQualifiers);
4981*0b57cec5SDimitry Andric }
4982*0b57cec5SDimitry Andric 
4983*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4984*0b57cec5SDimitry Andric   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4985*0b57cec5SDimitry Andric   llvm::Value *BaseValue = nullptr;
4986*0b57cec5SDimitry Andric   const Expr *BaseExpr = E->getBase();
4987*0b57cec5SDimitry Andric   Qualifiers BaseQuals;
4988*0b57cec5SDimitry Andric   QualType ObjectTy;
4989*0b57cec5SDimitry Andric   if (E->isArrow()) {
4990*0b57cec5SDimitry Andric     BaseValue = EmitScalarExpr(BaseExpr);
4991*0b57cec5SDimitry Andric     ObjectTy = BaseExpr->getType()->getPointeeType();
4992*0b57cec5SDimitry Andric     BaseQuals = ObjectTy.getQualifiers();
4993*0b57cec5SDimitry Andric   } else {
4994*0b57cec5SDimitry Andric     LValue BaseLV = EmitLValue(BaseExpr);
4995480093f4SDimitry Andric     BaseValue = BaseLV.getPointer(*this);
4996*0b57cec5SDimitry Andric     ObjectTy = BaseExpr->getType();
4997*0b57cec5SDimitry Andric     BaseQuals = ObjectTy.getQualifiers();
4998*0b57cec5SDimitry Andric   }
4999*0b57cec5SDimitry Andric 
5000*0b57cec5SDimitry Andric   LValue LV =
5001*0b57cec5SDimitry Andric     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
5002*0b57cec5SDimitry Andric                       BaseQuals.getCVRQualifiers());
5003*0b57cec5SDimitry Andric   setObjCGCLValueClass(getContext(), E, LV);
5004*0b57cec5SDimitry Andric   return LV;
5005*0b57cec5SDimitry Andric }
5006*0b57cec5SDimitry Andric 
5007*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
5008*0b57cec5SDimitry Andric   // Can only get l-value for message expression returning aggregate type
5009*0b57cec5SDimitry Andric   RValue RV = EmitAnyExprToTemp(E);
5010*0b57cec5SDimitry Andric   return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5011*0b57cec5SDimitry Andric                         AlignmentSource::Decl);
5012*0b57cec5SDimitry Andric }
5013*0b57cec5SDimitry Andric 
5014*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
5015*0b57cec5SDimitry Andric                                  const CallExpr *E, ReturnValueSlot ReturnValue,
5016*0b57cec5SDimitry Andric                                  llvm::Value *Chain) {
5017*0b57cec5SDimitry Andric   // Get the actual function type. The callee type will always be a pointer to
5018*0b57cec5SDimitry Andric   // function type or a block pointer type.
5019*0b57cec5SDimitry Andric   assert(CalleeType->isFunctionPointerType() &&
5020*0b57cec5SDimitry Andric          "Call must have function pointer type!");
5021*0b57cec5SDimitry Andric 
5022*0b57cec5SDimitry Andric   const Decl *TargetDecl =
5023*0b57cec5SDimitry Andric       OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
5024*0b57cec5SDimitry Andric 
5025*0b57cec5SDimitry Andric   CalleeType = getContext().getCanonicalType(CalleeType);
5026*0b57cec5SDimitry Andric 
5027*0b57cec5SDimitry Andric   auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
5028*0b57cec5SDimitry Andric 
5029*0b57cec5SDimitry Andric   CGCallee Callee = OrigCallee;
5030*0b57cec5SDimitry Andric 
5031*0b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
5032*0b57cec5SDimitry Andric       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5033*0b57cec5SDimitry Andric     if (llvm::Constant *PrefixSig =
5034*0b57cec5SDimitry Andric             CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
5035*0b57cec5SDimitry Andric       SanitizerScope SanScope(this);
5036*0b57cec5SDimitry Andric       // Remove any (C++17) exception specifications, to allow calling e.g. a
5037*0b57cec5SDimitry Andric       // noexcept function through a non-noexcept pointer.
5038*0b57cec5SDimitry Andric       auto ProtoTy =
5039*0b57cec5SDimitry Andric         getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
5040*0b57cec5SDimitry Andric       llvm::Constant *FTRTTIConst =
5041*0b57cec5SDimitry Andric           CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
5042*0b57cec5SDimitry Andric       llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
5043*0b57cec5SDimitry Andric       llvm::StructType *PrefixStructTy = llvm::StructType::get(
5044*0b57cec5SDimitry Andric           CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
5045*0b57cec5SDimitry Andric 
5046*0b57cec5SDimitry Andric       llvm::Value *CalleePtr = Callee.getFunctionPointer();
5047*0b57cec5SDimitry Andric 
5048*0b57cec5SDimitry Andric       llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
5049*0b57cec5SDimitry Andric           CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
5050*0b57cec5SDimitry Andric       llvm::Value *CalleeSigPtr =
5051*0b57cec5SDimitry Andric           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
5052*0b57cec5SDimitry Andric       llvm::Value *CalleeSig =
5053*0b57cec5SDimitry Andric           Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
5054*0b57cec5SDimitry Andric       llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
5055*0b57cec5SDimitry Andric 
5056*0b57cec5SDimitry Andric       llvm::BasicBlock *Cont = createBasicBlock("cont");
5057*0b57cec5SDimitry Andric       llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
5058*0b57cec5SDimitry Andric       Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
5059*0b57cec5SDimitry Andric 
5060*0b57cec5SDimitry Andric       EmitBlock(TypeCheck);
5061*0b57cec5SDimitry Andric       llvm::Value *CalleeRTTIPtr =
5062*0b57cec5SDimitry Andric           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
5063*0b57cec5SDimitry Andric       llvm::Value *CalleeRTTIEncoded =
5064*0b57cec5SDimitry Andric           Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
5065*0b57cec5SDimitry Andric       llvm::Value *CalleeRTTI =
5066*0b57cec5SDimitry Andric           DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
5067*0b57cec5SDimitry Andric       llvm::Value *CalleeRTTIMatch =
5068*0b57cec5SDimitry Andric           Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
5069*0b57cec5SDimitry Andric       llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
5070*0b57cec5SDimitry Andric                                       EmitCheckTypeDescriptor(CalleeType)};
5071*0b57cec5SDimitry Andric       EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
5072*0b57cec5SDimitry Andric                 SanitizerHandler::FunctionTypeMismatch, StaticData,
5073*0b57cec5SDimitry Andric                 {CalleePtr, CalleeRTTI, FTRTTIConst});
5074*0b57cec5SDimitry Andric 
5075*0b57cec5SDimitry Andric       Builder.CreateBr(Cont);
5076*0b57cec5SDimitry Andric       EmitBlock(Cont);
5077*0b57cec5SDimitry Andric     }
5078*0b57cec5SDimitry Andric   }
5079*0b57cec5SDimitry Andric 
5080*0b57cec5SDimitry Andric   const auto *FnType = cast<FunctionType>(PointeeType);
5081*0b57cec5SDimitry Andric 
5082*0b57cec5SDimitry Andric   // If we are checking indirect calls and this call is indirect, check that the
5083*0b57cec5SDimitry Andric   // function pointer is a member of the bit set for the function type.
5084*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::CFIICall) &&
5085*0b57cec5SDimitry Andric       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5086*0b57cec5SDimitry Andric     SanitizerScope SanScope(this);
5087*0b57cec5SDimitry Andric     EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
5088*0b57cec5SDimitry Andric 
5089*0b57cec5SDimitry Andric     llvm::Metadata *MD;
5090*0b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
5091*0b57cec5SDimitry Andric       MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
5092*0b57cec5SDimitry Andric     else
5093*0b57cec5SDimitry Andric       MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
5094*0b57cec5SDimitry Andric 
5095*0b57cec5SDimitry Andric     llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
5096*0b57cec5SDimitry Andric 
5097*0b57cec5SDimitry Andric     llvm::Value *CalleePtr = Callee.getFunctionPointer();
5098*0b57cec5SDimitry Andric     llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
5099*0b57cec5SDimitry Andric     llvm::Value *TypeTest = Builder.CreateCall(
5100*0b57cec5SDimitry Andric         CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
5101*0b57cec5SDimitry Andric 
5102*0b57cec5SDimitry Andric     auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
5103*0b57cec5SDimitry Andric     llvm::Constant *StaticData[] = {
5104*0b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
5105*0b57cec5SDimitry Andric         EmitCheckSourceLocation(E->getBeginLoc()),
5106*0b57cec5SDimitry Andric         EmitCheckTypeDescriptor(QualType(FnType, 0)),
5107*0b57cec5SDimitry Andric     };
5108*0b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
5109*0b57cec5SDimitry Andric       EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
5110*0b57cec5SDimitry Andric                            CastedCallee, StaticData);
5111*0b57cec5SDimitry Andric     } else {
5112*0b57cec5SDimitry Andric       EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
5113*0b57cec5SDimitry Andric                 SanitizerHandler::CFICheckFail, StaticData,
5114*0b57cec5SDimitry Andric                 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
5115*0b57cec5SDimitry Andric     }
5116*0b57cec5SDimitry Andric   }
5117*0b57cec5SDimitry Andric 
5118*0b57cec5SDimitry Andric   CallArgList Args;
5119*0b57cec5SDimitry Andric   if (Chain)
5120*0b57cec5SDimitry Andric     Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
5121*0b57cec5SDimitry Andric              CGM.getContext().VoidPtrTy);
5122*0b57cec5SDimitry Andric 
5123*0b57cec5SDimitry Andric   // C++17 requires that we evaluate arguments to a call using assignment syntax
5124*0b57cec5SDimitry Andric   // right-to-left, and that we evaluate arguments to certain other operators
5125*0b57cec5SDimitry Andric   // left-to-right. Note that we allow this to override the order dictated by
5126*0b57cec5SDimitry Andric   // the calling convention on the MS ABI, which means that parameter
5127*0b57cec5SDimitry Andric   // destruction order is not necessarily reverse construction order.
5128*0b57cec5SDimitry Andric   // FIXME: Revisit this based on C++ committee response to unimplementability.
5129*0b57cec5SDimitry Andric   EvaluationOrder Order = EvaluationOrder::Default;
5130*0b57cec5SDimitry Andric   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
5131*0b57cec5SDimitry Andric     if (OCE->isAssignmentOp())
5132*0b57cec5SDimitry Andric       Order = EvaluationOrder::ForceRightToLeft;
5133*0b57cec5SDimitry Andric     else {
5134*0b57cec5SDimitry Andric       switch (OCE->getOperator()) {
5135*0b57cec5SDimitry Andric       case OO_LessLess:
5136*0b57cec5SDimitry Andric       case OO_GreaterGreater:
5137*0b57cec5SDimitry Andric       case OO_AmpAmp:
5138*0b57cec5SDimitry Andric       case OO_PipePipe:
5139*0b57cec5SDimitry Andric       case OO_Comma:
5140*0b57cec5SDimitry Andric       case OO_ArrowStar:
5141*0b57cec5SDimitry Andric         Order = EvaluationOrder::ForceLeftToRight;
5142*0b57cec5SDimitry Andric         break;
5143*0b57cec5SDimitry Andric       default:
5144*0b57cec5SDimitry Andric         break;
5145*0b57cec5SDimitry Andric       }
5146*0b57cec5SDimitry Andric     }
5147*0b57cec5SDimitry Andric   }
5148*0b57cec5SDimitry Andric 
5149*0b57cec5SDimitry Andric   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
5150*0b57cec5SDimitry Andric                E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
5151*0b57cec5SDimitry Andric 
5152*0b57cec5SDimitry Andric   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
5153*0b57cec5SDimitry Andric       Args, FnType, /*ChainCall=*/Chain);
5154*0b57cec5SDimitry Andric 
5155*0b57cec5SDimitry Andric   // C99 6.5.2.2p6:
5156*0b57cec5SDimitry Andric   //   If the expression that denotes the called function has a type
5157*0b57cec5SDimitry Andric   //   that does not include a prototype, [the default argument
5158*0b57cec5SDimitry Andric   //   promotions are performed]. If the number of arguments does not
5159*0b57cec5SDimitry Andric   //   equal the number of parameters, the behavior is undefined. If
5160*0b57cec5SDimitry Andric   //   the function is defined with a type that includes a prototype,
5161*0b57cec5SDimitry Andric   //   and either the prototype ends with an ellipsis (, ...) or the
5162*0b57cec5SDimitry Andric   //   types of the arguments after promotion are not compatible with
5163*0b57cec5SDimitry Andric   //   the types of the parameters, the behavior is undefined. If the
5164*0b57cec5SDimitry Andric   //   function is defined with a type that does not include a
5165*0b57cec5SDimitry Andric   //   prototype, and the types of the arguments after promotion are
5166*0b57cec5SDimitry Andric   //   not compatible with those of the parameters after promotion,
5167*0b57cec5SDimitry Andric   //   the behavior is undefined [except in some trivial cases].
5168*0b57cec5SDimitry Andric   // That is, in the general case, we should assume that a call
5169*0b57cec5SDimitry Andric   // through an unprototyped function type works like a *non-variadic*
5170*0b57cec5SDimitry Andric   // call.  The way we make this work is to cast to the exact type
5171*0b57cec5SDimitry Andric   // of the promoted arguments.
5172*0b57cec5SDimitry Andric   //
5173*0b57cec5SDimitry Andric   // Chain calls use this same code path to add the invisible chain parameter
5174*0b57cec5SDimitry Andric   // to the function type.
5175*0b57cec5SDimitry Andric   if (isa<FunctionNoProtoType>(FnType) || Chain) {
5176*0b57cec5SDimitry Andric     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
51775ffd83dbSDimitry Andric     int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
51785ffd83dbSDimitry Andric     CalleeTy = CalleeTy->getPointerTo(AS);
5179*0b57cec5SDimitry Andric 
5180*0b57cec5SDimitry Andric     llvm::Value *CalleePtr = Callee.getFunctionPointer();
5181*0b57cec5SDimitry Andric     CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
5182*0b57cec5SDimitry Andric     Callee.setFunctionPointer(CalleePtr);
5183*0b57cec5SDimitry Andric   }
5184*0b57cec5SDimitry Andric 
5185*0b57cec5SDimitry Andric   llvm::CallBase *CallOrInvoke = nullptr;
5186*0b57cec5SDimitry Andric   RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
5187*0b57cec5SDimitry Andric                          E->getExprLoc());
5188*0b57cec5SDimitry Andric 
5189*0b57cec5SDimitry Andric   // Generate function declaration DISuprogram in order to be used
5190*0b57cec5SDimitry Andric   // in debug info about call sites.
5191*0b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
5192*0b57cec5SDimitry Andric     if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl))
5193*0b57cec5SDimitry Andric       DI->EmitFuncDeclForCallSite(CallOrInvoke, QualType(FnType, 0),
5194*0b57cec5SDimitry Andric                                   CalleeDecl);
5195*0b57cec5SDimitry Andric   }
5196*0b57cec5SDimitry Andric 
5197*0b57cec5SDimitry Andric   return Call;
5198*0b57cec5SDimitry Andric }
5199*0b57cec5SDimitry Andric 
5200*0b57cec5SDimitry Andric LValue CodeGenFunction::
5201*0b57cec5SDimitry Andric EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
5202*0b57cec5SDimitry Andric   Address BaseAddr = Address::invalid();
5203*0b57cec5SDimitry Andric   if (E->getOpcode() == BO_PtrMemI) {
5204*0b57cec5SDimitry Andric     BaseAddr = EmitPointerWithAlignment(E->getLHS());
5205*0b57cec5SDimitry Andric   } else {
5206480093f4SDimitry Andric     BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
5207*0b57cec5SDimitry Andric   }
5208*0b57cec5SDimitry Andric 
5209*0b57cec5SDimitry Andric   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
5210480093f4SDimitry Andric   const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
5211*0b57cec5SDimitry Andric 
5212*0b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
5213*0b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
5214*0b57cec5SDimitry Andric   Address MemberAddr =
5215*0b57cec5SDimitry Andric     EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
5216*0b57cec5SDimitry Andric                                     &TBAAInfo);
5217*0b57cec5SDimitry Andric 
5218*0b57cec5SDimitry Andric   return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
5219*0b57cec5SDimitry Andric }
5220*0b57cec5SDimitry Andric 
5221*0b57cec5SDimitry Andric /// Given the address of a temporary variable, produce an r-value of
5222*0b57cec5SDimitry Andric /// its type.
5223*0b57cec5SDimitry Andric RValue CodeGenFunction::convertTempToRValue(Address addr,
5224*0b57cec5SDimitry Andric                                             QualType type,
5225*0b57cec5SDimitry Andric                                             SourceLocation loc) {
5226*0b57cec5SDimitry Andric   LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
5227*0b57cec5SDimitry Andric   switch (getEvaluationKind(type)) {
5228*0b57cec5SDimitry Andric   case TEK_Complex:
5229*0b57cec5SDimitry Andric     return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
5230*0b57cec5SDimitry Andric   case TEK_Aggregate:
5231480093f4SDimitry Andric     return lvalue.asAggregateRValue(*this);
5232*0b57cec5SDimitry Andric   case TEK_Scalar:
5233*0b57cec5SDimitry Andric     return RValue::get(EmitLoadOfScalar(lvalue, loc));
5234*0b57cec5SDimitry Andric   }
5235*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
5236*0b57cec5SDimitry Andric }
5237*0b57cec5SDimitry Andric 
5238*0b57cec5SDimitry Andric void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
5239*0b57cec5SDimitry Andric   assert(Val->getType()->isFPOrFPVectorTy());
5240*0b57cec5SDimitry Andric   if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
5241*0b57cec5SDimitry Andric     return;
5242*0b57cec5SDimitry Andric 
5243*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
5244*0b57cec5SDimitry Andric   llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
5245*0b57cec5SDimitry Andric 
5246*0b57cec5SDimitry Andric   cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
5247*0b57cec5SDimitry Andric }
5248*0b57cec5SDimitry Andric 
5249*0b57cec5SDimitry Andric namespace {
5250*0b57cec5SDimitry Andric   struct LValueOrRValue {
5251*0b57cec5SDimitry Andric     LValue LV;
5252*0b57cec5SDimitry Andric     RValue RV;
5253*0b57cec5SDimitry Andric   };
5254*0b57cec5SDimitry Andric }
5255*0b57cec5SDimitry Andric 
5256*0b57cec5SDimitry Andric static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
5257*0b57cec5SDimitry Andric                                            const PseudoObjectExpr *E,
5258*0b57cec5SDimitry Andric                                            bool forLValue,
5259*0b57cec5SDimitry Andric                                            AggValueSlot slot) {
5260*0b57cec5SDimitry Andric   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
5261*0b57cec5SDimitry Andric 
5262*0b57cec5SDimitry Andric   // Find the result expression, if any.
5263*0b57cec5SDimitry Andric   const Expr *resultExpr = E->getResultExpr();
5264*0b57cec5SDimitry Andric   LValueOrRValue result;
5265*0b57cec5SDimitry Andric 
5266*0b57cec5SDimitry Andric   for (PseudoObjectExpr::const_semantics_iterator
5267*0b57cec5SDimitry Andric          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
5268*0b57cec5SDimitry Andric     const Expr *semantic = *i;
5269*0b57cec5SDimitry Andric 
5270*0b57cec5SDimitry Andric     // If this semantic expression is an opaque value, bind it
5271*0b57cec5SDimitry Andric     // to the result of its source expression.
5272*0b57cec5SDimitry Andric     if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
5273*0b57cec5SDimitry Andric       // Skip unique OVEs.
5274*0b57cec5SDimitry Andric       if (ov->isUnique()) {
5275*0b57cec5SDimitry Andric         assert(ov != resultExpr &&
5276*0b57cec5SDimitry Andric                "A unique OVE cannot be used as the result expression");
5277*0b57cec5SDimitry Andric         continue;
5278*0b57cec5SDimitry Andric       }
5279*0b57cec5SDimitry Andric 
5280*0b57cec5SDimitry Andric       // If this is the result expression, we may need to evaluate
5281*0b57cec5SDimitry Andric       // directly into the slot.
5282*0b57cec5SDimitry Andric       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
5283*0b57cec5SDimitry Andric       OVMA opaqueData;
5284*0b57cec5SDimitry Andric       if (ov == resultExpr && ov->isRValue() && !forLValue &&
5285*0b57cec5SDimitry Andric           CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
5286*0b57cec5SDimitry Andric         CGF.EmitAggExpr(ov->getSourceExpr(), slot);
5287*0b57cec5SDimitry Andric         LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
5288*0b57cec5SDimitry Andric                                        AlignmentSource::Decl);
5289*0b57cec5SDimitry Andric         opaqueData = OVMA::bind(CGF, ov, LV);
5290*0b57cec5SDimitry Andric         result.RV = slot.asRValue();
5291*0b57cec5SDimitry Andric 
5292*0b57cec5SDimitry Andric       // Otherwise, emit as normal.
5293*0b57cec5SDimitry Andric       } else {
5294*0b57cec5SDimitry Andric         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
5295*0b57cec5SDimitry Andric 
5296*0b57cec5SDimitry Andric         // If this is the result, also evaluate the result now.
5297*0b57cec5SDimitry Andric         if (ov == resultExpr) {
5298*0b57cec5SDimitry Andric           if (forLValue)
5299*0b57cec5SDimitry Andric             result.LV = CGF.EmitLValue(ov);
5300*0b57cec5SDimitry Andric           else
5301*0b57cec5SDimitry Andric             result.RV = CGF.EmitAnyExpr(ov, slot);
5302*0b57cec5SDimitry Andric         }
5303*0b57cec5SDimitry Andric       }
5304*0b57cec5SDimitry Andric 
5305*0b57cec5SDimitry Andric       opaques.push_back(opaqueData);
5306*0b57cec5SDimitry Andric 
5307*0b57cec5SDimitry Andric     // Otherwise, if the expression is the result, evaluate it
5308*0b57cec5SDimitry Andric     // and remember the result.
5309*0b57cec5SDimitry Andric     } else if (semantic == resultExpr) {
5310*0b57cec5SDimitry Andric       if (forLValue)
5311*0b57cec5SDimitry Andric         result.LV = CGF.EmitLValue(semantic);
5312*0b57cec5SDimitry Andric       else
5313*0b57cec5SDimitry Andric         result.RV = CGF.EmitAnyExpr(semantic, slot);
5314*0b57cec5SDimitry Andric 
5315*0b57cec5SDimitry Andric     // Otherwise, evaluate the expression in an ignored context.
5316*0b57cec5SDimitry Andric     } else {
5317*0b57cec5SDimitry Andric       CGF.EmitIgnoredExpr(semantic);
5318*0b57cec5SDimitry Andric     }
5319*0b57cec5SDimitry Andric   }
5320*0b57cec5SDimitry Andric 
5321*0b57cec5SDimitry Andric   // Unbind all the opaques now.
5322*0b57cec5SDimitry Andric   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
5323*0b57cec5SDimitry Andric     opaques[i].unbind(CGF);
5324*0b57cec5SDimitry Andric 
5325*0b57cec5SDimitry Andric   return result;
5326*0b57cec5SDimitry Andric }
5327*0b57cec5SDimitry Andric 
5328*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
5329*0b57cec5SDimitry Andric                                                AggValueSlot slot) {
5330*0b57cec5SDimitry Andric   return emitPseudoObjectExpr(*this, E, false, slot).RV;
5331*0b57cec5SDimitry Andric }
5332*0b57cec5SDimitry Andric 
5333*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
5334*0b57cec5SDimitry Andric   return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
5335*0b57cec5SDimitry Andric }
5336