blob: 50d116ec7d8cfd32171a46356aaf0009e06b32d2 [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere47e4402007-06-01 18:02:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGCall.h"
Tim Shen421119f2016-07-01 21:08:47 +000016#include "CGCleanup.h"
Devang Pateld3a6b0f2011-03-04 18:54:42 +000017#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Alexey Bataev97720002014-11-11 04:05:39 +000019#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CGRecordLayout.h"
Tim Shen421119f2016-07-01 21:08:47 +000021#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000023#include "ConstantEmitter.h"
John McCallcbc038a2011-09-21 08:08:30 +000024#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000025#include "clang/AST/ASTContext.h"
Renato Golin230c5eb2014-05-19 18:15:42 +000026#include "clang/AST/Attr.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000027#include "clang/AST/DeclObjC.h"
Vedant Kumar4593a462016-12-09 23:48:18 +000028#include "clang/AST/NSAPI.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000029#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000031#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000036#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000037#include "llvm/Support/MathExtras.h"
Filipe Cabecinhasab731f72016-05-12 16:51:36 +000038#include "llvm/Support/Path.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000039#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000040
Filipe Cabecinhas84171bd2016-12-12 16:43:40 +000041#include <string>
42
Chris Lattnere47e4402007-06-01 18:02:12 +000043using namespace clang;
44using namespace CodeGen;
45
Chris Lattnerd7f58862007-06-02 05:24:33 +000046//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000047// Miscellaneous Helper Methods
48//===--------------------------------------------------------------------===//
49
John McCallad7c5c12011-02-08 08:22:06 +000050llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
51 unsigned addressSpace =
Yaxun Liu39195062017-08-04 18:16:31 +000052 cast<llvm::PointerType>(value->getType())->getAddressSpace();
John McCallad7c5c12011-02-08 08:22:06 +000053
Chris Lattner2192fe52011-07-18 04:24:23 +000054 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000055 if (addressSpace)
56 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
57
58 if (value->getType() == destType) return value;
59 return Builder.CreateBitCast(value, destType);
60}
61
Chris Lattnere9a64532007-06-22 21:44:33 +000062/// CreateTempAlloca - This creates a alloca and inserts it into the entry
63/// block.
John McCall7f416cc2015-09-08 08:05:57 +000064Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +000065 const Twine &Name,
66 llvm::Value *ArraySize,
67 bool CastToDefaultAddrSpace) {
68 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
John McCall7f416cc2015-09-08 08:05:57 +000069 Alloca->setAlignment(Align.getQuantity());
Yaxun Liu84744c12017-06-19 17:03:41 +000070 llvm::Value *V = Alloca;
71 // Alloca always returns a pointer in alloca address space, which may
72 // be different from the type defined by the language. For example,
73 // in C++ the auto variables are in the default address space. Therefore
74 // cast alloca to the default address space when necessary.
75 if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
76 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
Yaxun Liue45b3d52017-10-24 19:14:43 +000077 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
Yaxun Liu561ac062017-10-30 14:38:30 +000078 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
79 // otherwise alloca is inserted at the current insertion point of the
80 // builder.
81 if (!ArraySize)
82 Builder.SetInsertPoint(AllocaInsertPt);
Yaxun Liu84744c12017-06-19 17:03:41 +000083 V = getTargetHooks().performAddrSpaceCast(
84 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
85 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
86 }
87
88 return Address(V, Align);
John McCall7f416cc2015-09-08 08:05:57 +000089}
90
Yaxun Liu84744c12017-06-19 17:03:41 +000091/// CreateTempAlloca - This creates an alloca and inserts it into the entry
92/// block if \p ArraySize is nullptr, otherwise inserts it at the current
93/// insertion point of the builder.
Chris Lattner2192fe52011-07-18 04:24:23 +000094llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Yaxun Liu84744c12017-06-19 17:03:41 +000095 const Twine &Name,
96 llvm::Value *ArraySize) {
97 if (ArraySize)
98 return Builder.CreateAlloca(Ty, ArraySize, Name);
Matt Arsenault502ad602017-04-10 22:28:02 +000099 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
Yaxun Liu84744c12017-06-19 17:03:41 +0000100 ArraySize, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +0000101}
Chris Lattner8394d792007-06-05 20:53:16 +0000102
John McCall7f416cc2015-09-08 08:05:57 +0000103/// CreateDefaultAlignTempAlloca - This creates an alloca with the
104/// default alignment of the corresponding LLVM type, which is *not*
105/// guaranteed to be related in any way to the expected alignment of
106/// an AST type that might have been lowered to Ty.
107Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
108 const Twine &Name) {
109 CharUnits Align =
110 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
111 return CreateTempAlloca(Ty, Align, Name);
112}
113
114void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
115 assert(isa<llvm::AllocaInst>(Var.getPointer()));
116 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
117 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +0000118 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000119 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +0000120}
121
John McCall7f416cc2015-09-08 08:05:57 +0000122Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +0000123 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +0000124 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +0000125}
126
Yaxun Liu84744c12017-06-19 17:03:41 +0000127Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
128 bool CastToDefaultAddrSpace) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000129 // FIXME: Should we prefer the preferred type alignment here?
Yaxun Liu84744c12017-06-19 17:03:41 +0000130 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
131 CastToDefaultAddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +0000132}
133
134Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +0000135 const Twine &Name,
136 bool CastToDefaultAddrSpace) {
137 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
138 CastToDefaultAddrSpace);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000139}
140
Chris Lattner8394d792007-06-05 20:53:16 +0000141/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
142/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000143llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000144 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000145 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000146 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000147 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000148 }
John McCall7a9aac22010-08-23 01:21:21 +0000149
150 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000151 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000152 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000153 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000154
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000155 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
156 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000157}
158
John McCalla2342eb2010-12-05 02:00:02 +0000159/// EmitIgnoredExpr - Emit code to compute the specified expression,
160/// ignoring the result.
161void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
162 if (E->isRValue())
163 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
164
165 // Just emit it as an l-value and drop the result.
166 EmitLValue(E);
167}
168
John McCall7a626f62010-09-15 10:14:12 +0000169/// EmitAnyExpr - Emit code to compute the specified expression which
170/// can have any type. The result is returned as an RValue struct.
171/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000172/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000173RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
174 AggValueSlot aggSlot,
175 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000176 switch (getEvaluationKind(E->getType())) {
177 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000178 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000179 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000180 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000181 case TEK_Aggregate:
182 if (!ignoreResult && aggSlot.isIgnored())
183 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
184 EmitAggExpr(E, aggSlot);
185 return aggSlot.asRValue();
186 }
187 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000188}
189
Mike Stump4a3999f2009-09-09 13:00:44 +0000190/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
191/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000192RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
193 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000194
John McCall47fb9502013-03-07 21:37:08 +0000195 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000196 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
197 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000198}
199
John McCall21886962010-04-21 10:05:39 +0000200/// EmitAnyExprToMem - Evaluate an expression into a given memory
201/// location.
202void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000203 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000204 Qualifiers Quals,
205 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000206 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000207 switch (getEvaluationKind(E->getType())) {
208 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000209 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000210 /*isInit*/ false);
211 return;
212
213 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000214 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000215 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000216 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000217 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000218 return;
219 }
220
221 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000222 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000223 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000224 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000225 return;
John McCall21886962010-04-21 10:05:39 +0000226 }
John McCall47fb9502013-03-07 21:37:08 +0000227 }
228 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000229}
230
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000231static void
232pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000233 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000234 // Objective-C++ ARC:
235 // If we are binding a reference to a temporary that has ownership, we
236 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000237 //
238 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000239 if (auto Lifetime = M->getType().getObjCLifetime()) {
240 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000241 case Qualifiers::OCL_None:
242 case Qualifiers::OCL_ExplicitNone:
243 // Carry on to normal cleanup handling.
244 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000245
Richard Smith736a9472013-06-12 20:42:33 +0000246 case Qualifiers::OCL_Autoreleasing:
247 // Nothing to do; cleaned up by an autorelease pool.
248 return;
249
250 case Qualifiers::OCL_Strong:
251 case Qualifiers::OCL_Weak:
252 switch (StorageDuration Duration = M->getStorageDuration()) {
253 case SD_Static:
254 // Note: we intentionally do not register a cleanup to release
255 // the object on program termination.
256 return;
257
258 case SD_Thread:
259 // FIXME: We should probably register a cleanup in this case.
260 return;
261
262 case SD_Automatic:
263 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000264 CodeGenFunction::Destroyer *Destroy;
265 CleanupKind CleanupKind;
266 if (Lifetime == Qualifiers::OCL_Strong) {
267 const ValueDecl *VD = M->getExtendingDecl();
268 bool Precise =
269 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
270 CleanupKind = CGF.getARCCleanupKind();
271 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
272 : &CodeGenFunction::destroyARCStrongImprecise;
273 } else {
274 // __weak objects always get EH cleanups; otherwise, exceptions
275 // could cause really nasty crashes instead of mere leaks.
276 CleanupKind = NormalAndEHCleanup;
277 Destroy = &CodeGenFunction::destroyARCWeak;
278 }
279 if (Duration == SD_FullExpression)
280 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000281 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000282 CleanupKind & EHCleanup);
283 else
284 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000285 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000286 *Destroy, CleanupKind & EHCleanup);
287 return;
288
289 case SD_Dynamic:
290 llvm_unreachable("temporary cannot have dynamic storage duration");
291 }
292 llvm_unreachable("unknown storage duration");
293 }
294 }
295
Craig Topper8a13c412014-05-21 05:09:00 +0000296 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000297 if (const RecordType *RT =
298 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
299 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000300 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000301 if (!ClassDecl->hasTrivialDestructor())
302 ReferenceTemporaryDtor = ClassDecl->getDestructor();
303 }
304
305 if (!ReferenceTemporaryDtor)
306 return;
307
308 // Call the destructor for the temporary.
309 switch (M->getStorageDuration()) {
310 case SD_Static:
311 case SD_Thread: {
312 llvm::Constant *CleanupFn;
313 llvm::Constant *CleanupArg;
314 if (E->getType()->isArrayType()) {
315 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000316 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000317 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
318 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000319 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
320 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000321 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
322 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000323 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000324 }
325 CGF.CGM.getCXXABI().registerGlobalDtor(
326 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
327 break;
328 }
329
330 case SD_FullExpression:
331 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
332 CodeGenFunction::destroyCXXObject,
333 CGF.getLangOpts().Exceptions);
334 break;
335
336 case SD_Automatic:
337 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
338 ReferenceTemporary, E->getType(),
339 CodeGenFunction::destroyCXXObject,
340 CGF.getLangOpts().Exceptions);
341 break;
342
343 case SD_Dynamic:
344 llvm_unreachable("temporary cannot have dynamic storage duration");
345 }
346}
347
Yaxun Liucbf647c2017-07-08 13:24:52 +0000348static Address createReferenceTemporary(CodeGenFunction &CGF,
349 const MaterializeTemporaryExpr *M,
350 const Expr *Inner) {
351 auto &TCG = CGF.getTargetHooks();
Richard Smith736a9472013-06-12 20:42:33 +0000352 switch (M->getStorageDuration()) {
353 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000354 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000355 // If we have a constant temporary array or record try to promote it into a
356 // constant global under the same rules a normal constant would've been
357 // promoted. This is easier on the optimizer and generally emits fewer
358 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000359 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000360 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000361 (Ty->isArrayType() || Ty->isRecordType()) &&
362 CGF.CGM.isTypeConstant(Ty, true))
John McCallde0fe072017-08-15 21:42:52 +0000363 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000364 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
365 auto AS = AddrSpace.getValue();
366 auto *GV = new llvm::GlobalVariable(
367 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
368 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
369 llvm::GlobalValue::NotThreadLocal,
370 CGF.getContext().getTargetAddressSpace(AS));
371 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
372 GV->setAlignment(alignment.getQuantity());
373 llvm::Constant *C = GV;
374 if (AS != LangAS::Default)
375 C = TCG.performAddrSpaceCast(
376 CGF.CGM, GV, AS, LangAS::Default,
377 GV->getValueType()->getPointerTo(
378 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
379 // FIXME: Should we put the new global into a COMDAT?
380 return Address(C, alignment);
381 }
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000382 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000383 return CGF.CreateMemTemp(Ty, "ref.tmp");
384 }
Richard Smith736a9472013-06-12 20:42:33 +0000385 case SD_Thread:
386 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000387 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000388
389 case SD_Dynamic:
390 llvm_unreachable("temporary can't have dynamic storage duration");
391 }
392 llvm_unreachable("unknown storage duration");
393}
394
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000395LValue CodeGenFunction::
396EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000397 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000398
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000399 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
400 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000401 auto ownership = M->getType().getObjCLifetime();
402 if (ownership != Qualifiers::OCL_None &&
403 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000404 Address Object = createReferenceTemporary(*this, M, E);
405 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
406 Object = Address(llvm::ConstantExpr::getBitCast(Var,
407 ConvertTypeForMem(E->getType())
408 ->getPointerTo(Object.getAddressSpace())),
409 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000410
411 // createReferenceTemporary will promote the temporary to a global with a
412 // constant initializer if it can. It can only do this to a value of
413 // ARC-manageable type if the value is global and therefore "immune" to
414 // ref-counting operations. Therefore we have no need to emit either a
415 // dynamic initialization or a cleanup and we can just return the address
416 // of the temporary.
417 if (Var->hasInitializer())
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000418 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000419
Richard Smitha509f2f2013-06-14 03:07:01 +0000420 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
421 }
John McCall7f416cc2015-09-08 08:05:57 +0000422 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000423 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000424
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000425 switch (getEvaluationKind(E->getType())) {
426 default: llvm_unreachable("expected scalar or aggregate expression");
427 case TEK_Scalar:
428 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
429 break;
430 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000431 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000432 E->getType().getQualifiers(),
433 AggValueSlot::IsDestructed,
434 AggValueSlot::DoesNotNeedGCBarriers,
435 AggValueSlot::IsNotAliased));
436 break;
437 }
438 }
Richard Smith736a9472013-06-12 20:42:33 +0000439
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000440 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000441 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000442 }
443
Richard Smithf3fabd22013-06-03 00:17:11 +0000444 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000445 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000446 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
447
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000448 for (const auto &Ignored : CommaLHSs)
449 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000450
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000451 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000452 if (opaque->getType()->isRecordType()) {
453 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000454 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000455 }
456 }
457
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000458 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000459 Address Object = createReferenceTemporary(*this, M, E);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000460 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
461 Object.getPointer()->stripPointerCasts())) {
John McCall7f416cc2015-09-08 08:05:57 +0000462 Object = Address(llvm::ConstantExpr::getBitCast(
Yaxun Liucbf647c2017-07-08 13:24:52 +0000463 cast<llvm::Constant>(Object.getPointer()),
464 ConvertTypeForMem(E->getType())->getPointerTo()),
John McCall7f416cc2015-09-08 08:05:57 +0000465 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000466 // If the temporary is a global and has a constant initializer or is a
467 // constant temporary that we promoted to a global, we may have already
468 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000469 if (!Var->hasInitializer()) {
470 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
471 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
472 }
473 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000474 switch (M->getStorageDuration()) {
475 case SD_Automatic:
476 case SD_FullExpression:
477 if (auto *Size = EmitLifetimeStart(
478 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
479 Object.getPointer())) {
480 if (M->getStorageDuration() == SD_Automatic)
481 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
482 Object, Size);
483 else
484 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
485 Size);
486 }
487 break;
488 default:
489 break;
490 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000491 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
492 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000493 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000494
Richard Smith736a9472013-06-12 20:42:33 +0000495 // Perform derived-to-base casts and/or field accesses, to get from the
496 // temporary object we created (and, potentially, for which we extended
497 // the lifetime) to the subobject we're binding the reference to.
498 for (unsigned I = Adjustments.size(); I != 0; --I) {
499 SubobjectAdjustment &Adjustment = Adjustments[I-1];
500 switch (Adjustment.Kind) {
501 case SubobjectAdjustment::DerivedToBaseAdjustment:
502 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000503 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
504 Adjustment.DerivedToBase.BasePath->path_begin(),
505 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000506 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000507 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000508
Richard Smith736a9472013-06-12 20:42:33 +0000509 case SubobjectAdjustment::FieldAdjustment: {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000510 LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000511 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000512 assert(LV.isSimple() &&
513 "materialized temporary field is not a simple lvalue");
514 Object = LV.getAddress();
515 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000516 }
517
Richard Smith736a9472013-06-12 20:42:33 +0000518 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000519 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000520 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
521 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000522 break;
523 }
524 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000525 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000526
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000527 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000528}
529
530RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000531CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
532 // Emit the expression as an lvalue.
533 LValue LV = EmitLValue(E);
534 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000535 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000536
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000537 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000538 // C++11 [dcl.ref]p5 (as amended by core issue 453):
539 // If a glvalue to which a reference is directly bound designates neither
540 // an existing object or function of an appropriate type nor a region of
541 // storage of suitable size and alignment to contain an object of the
542 // reference's type, the behavior is undefined.
543 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000544 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000545 }
John McCall8680f872010-07-21 06:29:51 +0000546
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000547 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000548}
549
550
Mike Stump4a3999f2009-09-09 13:00:44 +0000551/// getAccessedFieldNo - Given an encoded value and a result number, return the
552/// input field number being accessed.
553unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000554 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000555 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
556 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000557}
558
Richard Smith4d3110a2012-10-25 02:14:12 +0000559/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
560static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
561 llvm::Value *High) {
562 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
563 llvm::Value *K47 = Builder.getInt64(47);
564 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
565 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
566 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
567 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
568 return Builder.CreateMul(B1, KMul);
569}
570
Vedant Kumar24792e32017-10-03 01:27:25 +0000571bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
572 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
573 TCK == TCK_UpcastToVirtualBase;
574}
575
576bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
577 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
578 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
579 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
580 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
581 TCK == TCK_UpcastToVirtualBase);
582}
583
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000584bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000585 return SanOpts.has(SanitizerKind::Null) |
586 SanOpts.has(SanitizerKind::Alignment) |
587 SanOpts.has(SanitizerKind::ObjectSize) |
588 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000589}
590
Richard Smithe30752c2012-10-09 19:52:38 +0000591void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000592 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000593 CharUnits Alignment,
594 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000595 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000596 return;
597
Richard Smith2d8b2942012-11-01 07:22:08 +0000598 // Don't check pointers outside the default address space. The null check
599 // isn't correct, the object-size check isn't supported by LLVM, and we can't
600 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000601 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000602 return;
603
Vedant Kumarc420d142017-06-16 03:27:36 +0000604 // Don't check pointers to volatile data. The behavior here is implementation-
605 // defined.
606 if (Ty.isVolatileQualified())
607 return;
608
Alexey Samsonov24cad992014-07-17 18:46:27 +0000609 SanitizerScope SanScope(this);
610
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000611 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000612 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000613
Vedant Kumare859ebb2017-04-26 02:17:21 +0000614 // Quickly determine whether we have a pointer to an alloca. It's possible
615 // to skip null checks, and some alignment checks, for these pointers. This
616 // can reduce compile-time significantly.
617 auto PtrToAlloca =
618 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
619
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000620 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000621 llvm::Value *IsNonNull = nullptr;
622 bool IsGuaranteedNonNull =
623 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
Vedant Kumar24792e32017-10-03 01:27:25 +0000624 bool AllowNullPointers = isNullPointerAllowed(TCK);
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000625 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000626 !IsGuaranteedNonNull) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000627 // The glvalue must not be an empty glvalue.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000628 IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000629
Vedant Kumardbbdda42017-04-17 22:26:10 +0000630 // The IR builder can constant-fold the null check if the pointer points to
631 // a constant.
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000632 IsGuaranteedNonNull = IsNonNull == True;
Vedant Kumardbbdda42017-04-17 22:26:10 +0000633
634 // Skip the null check if the pointer is known to be non-null.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000635 if (!IsGuaranteedNonNull) {
Vedant Kumardbbdda42017-04-17 22:26:10 +0000636 if (AllowNullPointers) {
637 // When performing pointer casts, it's OK if the value is null.
638 // Skip the remaining checks in that case.
639 Done = createBasicBlock("null");
640 llvm::BasicBlock *Rest = createBasicBlock("not.null");
641 Builder.CreateCondBr(IsNonNull, Rest, Done);
642 EmitBlock(Rest);
643 } else {
644 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
645 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000646 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000647 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000648
Vedant Kumar18348ea2017-02-17 23:22:55 +0000649 if (SanOpts.has(SanitizerKind::ObjectSize) &&
650 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
651 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000652 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000653
Richard Smith69d0d262012-08-24 00:54:33 +0000654 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000655 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000656 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000657 // FIXME: Get object address space
658 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
659 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000660 llvm::Value *Min = Builder.getFalse();
George Burgess IVa63f9152017-03-21 20:09:35 +0000661 llvm::Value *NullIsUnknown = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000662 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
George Burgess IVa63f9152017-03-21 20:09:35 +0000663 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
664 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
665 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000666 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000667 }
Richard Smith69d0d262012-08-24 00:54:33 +0000668
Richard Smithb1b0ab42012-11-05 22:21:05 +0000669 uint64_t AlignVal = 0;
Vedant Kumar8a715332017-10-03 01:27:24 +0000670 llvm::Value *PtrAsInt = nullptr;
Richard Smithb1b0ab42012-11-05 22:21:05 +0000671
Vedant Kumar18348ea2017-02-17 23:22:55 +0000672 if (SanOpts.has(SanitizerKind::Alignment) &&
673 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000674 AlignVal = Alignment.getQuantity();
675 if (!Ty->isIncompleteType() && !AlignVal)
676 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
677
Richard Smith69d0d262012-08-24 00:54:33 +0000678 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000679 if (AlignVal > 1 &&
680 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Vedant Kumar8a715332017-10-03 01:27:24 +0000681 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
682 llvm::Value *Align = Builder.CreateAnd(
683 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000684 llvm::Value *Aligned =
Vedant Kumar8a715332017-10-03 01:27:24 +0000685 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000686 if (Aligned != True)
687 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000688 }
Richard Smith69d0d262012-08-24 00:54:33 +0000689 }
690
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000691 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000692 // Make sure we're not losing information. Alignment needs to be a power of
693 // 2
694 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000695 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000696 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
697 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
698 llvm::ConstantInt::get(Int8Ty, TCK)};
Vedant Kumar8a715332017-10-03 01:27:24 +0000699 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
700 PtrAsInt ? PtrAsInt : Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000701 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000702
Richard Smithb1b0ab42012-11-05 22:21:05 +0000703 // If possible, check that the vptr indicates that there is a subobject of
704 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000705 //
706 // C++11 [basic.life]p5,6:
707 // [For storage which does not refer to an object within its lifetime]
708 // The program has undefined behavior if:
709 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000710 // or call a non-static member function
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000711 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumar24792e32017-10-03 01:27:25 +0000712 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000713 // Ensure that the pointer is non-null before loading it. If there is no
Vedant Kumara0c36712017-08-02 18:10:31 +0000714 // compile-time guarantee, reuse the run-time null check or emit a new one.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000715 if (!IsGuaranteedNonNull) {
Vedant Kumara0c36712017-08-02 18:10:31 +0000716 if (!IsNonNull)
717 IsNonNull = Builder.CreateIsNotNull(Ptr);
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000718 if (!Done)
719 Done = createBasicBlock("vptr.null");
720 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
721 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
722 EmitBlock(VptrNotNull);
723 }
724
Richard Smith4d3110a2012-10-25 02:14:12 +0000725 // Compute a hash of the mangled name of the type.
726 //
727 // FIXME: This is not guaranteed to be deterministic! Move to a
728 // fingerprinting mechanism once LLVM provides one. For the time
729 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000730 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000731 llvm::raw_svector_ostream Out(MangledName);
732 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
733 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000734
Alexey Samsonov84856012014-07-10 22:34:19 +0000735 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000736 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +0000737 SanitizerKind::Vptr, Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000738 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000739
Alexey Samsonov84856012014-07-10 22:34:19 +0000740 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
741 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
742 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000743 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000744 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
745 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000746
Alexey Samsonov84856012014-07-10 22:34:19 +0000747 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
748 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000749
Alexey Samsonov84856012014-07-10 22:34:19 +0000750 // Look the hash up in our cache.
751 const int CacheSize = 128;
752 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
753 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
754 "__ubsan_vptr_type_cache");
755 llvm::Value *Slot = Builder.CreateAnd(Hash,
756 llvm::ConstantInt::get(IntPtrTy,
757 CacheSize-1));
758 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
759 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000760 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
761 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000762
763 // If the hash isn't in the cache, call a runtime handler to perform the
764 // hard work of checking whether the vptr is for an object of the right
765 // type. This will either fill in the cache and return, or produce a
766 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000767 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000768 llvm::Constant *StaticData[] = {
769 EmitCheckSourceLocation(Loc),
770 EmitCheckTypeDescriptor(Ty),
771 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
772 llvm::ConstantInt::get(Int8Ty, TCK)
773 };
John McCall7f416cc2015-09-08 08:05:57 +0000774 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000775 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000776 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
777 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000778 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000779 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000780
781 if (Done) {
782 Builder.CreateBr(Done);
783 EmitBlock(Done);
784 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000785}
Chris Lattner4647a212007-08-31 22:49:20 +0000786
Richard Smith539e4a72013-02-23 02:53:19 +0000787/// Determine whether this expression refers to a flexible array member in a
788/// struct. We disable array bounds checks for such members.
789static bool isFlexibleArrayMemberExpr(const Expr *E) {
790 // For compatibility with existing code, we treat arrays of length 0 or
791 // 1 as flexible array members.
792 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000793 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000794 if (CAT->getSize().ugt(1))
795 return false;
796 } else if (!isa<IncompleteArrayType>(AT))
797 return false;
798
799 E = E->IgnoreParens();
800
801 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000802 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000803 // FIXME: If the base type of the member expr is not FD->getParent(),
804 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000805 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000806 RecordDecl::field_iterator FI(
807 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
808 return ++FI == FD->getParent()->field_end();
809 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000810 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
811 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000812 }
813
814 return false;
815}
816
817/// If Base is known to point to the start of an array, return the length of
818/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000819static llvm::Value *getArrayIndexingBound(
820 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000821 // For the vector indexing extension, the bound is the number of elements.
822 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
823 IndexedType = Base->getType();
824 return CGF.Builder.getInt32(VT->getNumElements());
825 }
826
827 Base = Base->IgnoreParens();
828
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000829 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000830 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
831 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
832 IndexedType = CE->getSubExpr()->getType();
833 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000834 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000835 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000836 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000837 return CGF.getVLASize(VAT).first;
838 }
839 }
840
Craig Topper8a13c412014-05-21 05:09:00 +0000841 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000842}
843
844void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
845 llvm::Value *Index, QualType IndexType,
846 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000847 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000848 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000849 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000850
Richard Smith539e4a72013-02-23 02:53:19 +0000851 QualType IndexedType;
852 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
853 if (!Bound)
854 return;
855
856 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
857 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
858 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
859
860 llvm::Constant *StaticData[] = {
861 EmitCheckSourceLocation(E->getExprLoc()),
862 EmitCheckTypeDescriptor(IndexedType),
863 EmitCheckTypeDescriptor(IndexType)
864 };
865 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
866 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000867 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
868 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000869}
870
Chris Lattner116ce8f2010-01-09 21:40:03 +0000871
Chris Lattner116ce8f2010-01-09 21:40:03 +0000872CodeGenFunction::ComplexPairTy CodeGenFunction::
873EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
874 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000875 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000876
Chris Lattner116ce8f2010-01-09 21:40:03 +0000877 llvm::Value *NextVal;
878 if (isa<llvm::IntegerType>(InVal.first->getType())) {
879 uint64_t AmountVal = isInc ? 1 : -1;
880 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000881
Chris Lattner116ce8f2010-01-09 21:40:03 +0000882 // Add the inc/dec to the real part.
883 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
884 } else {
885 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
886 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
887 if (!isInc)
888 FVal.changeSign();
889 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000890
Chris Lattner116ce8f2010-01-09 21:40:03 +0000891 // Add the inc/dec to the real part.
892 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
893 }
Craig Topper99e79272013-07-26 05:59:26 +0000894
Chris Lattner116ce8f2010-01-09 21:40:03 +0000895 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000896
Chris Lattner116ce8f2010-01-09 21:40:03 +0000897 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000898 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000899
Chris Lattner116ce8f2010-01-09 21:40:03 +0000900 // If this is a postinc, return the value read from memory, otherwise use the
901 // updated value.
902 return isPre ? IncVal : InVal;
903}
904
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000905void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
906 CodeGenFunction *CGF) {
907 // Bind VLAs in the cast type.
908 if (CGF && E->getType()->isVariablyModifiedType())
909 CGF->EmitVariablyModifiedType(E->getType());
910
911 if (CGDebugInfo *DI = getModuleDebugInfo())
912 DI->EmitExplicitCastType(E->getType());
913}
914
Chris Lattnera45c5af2007-06-02 19:47:04 +0000915//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000916// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000917//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000918
John McCall7f416cc2015-09-08 08:05:57 +0000919/// EmitPointerWithAlignment - Given an expression of pointer type, try to
920/// derive a more accurate bound on the alignment of the pointer.
921Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000922 LValueBaseInfo *BaseInfo,
923 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000924 // We allow this with ObjC object pointers because of fragile ABIs.
925 assert(E->getType()->isPointerType() ||
926 E->getType()->isObjCObjectPointerType());
927 E = E->IgnoreParens();
928
929 // Casts:
930 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000931 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
932 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000933
934 switch (CE->getCastKind()) {
935 // Non-converting casts (but not C's implicit conversion from void*).
936 case CK_BitCast:
937 case CK_NoOp:
Anastasia Stulova0a72ed42017-09-27 14:37:00 +0000938 case CK_AddressSpaceConversion:
John McCall7f416cc2015-09-08 08:05:57 +0000939 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
940 if (PtrTy->getPointeeType()->isVoidType())
941 break;
942
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000943 LValueBaseInfo InnerBaseInfo;
944 TBAAAccessInfo InnerTBAAInfo;
945 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
946 &InnerBaseInfo,
947 &InnerTBAAInfo);
948 if (BaseInfo) *BaseInfo = InnerBaseInfo;
949 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +0000950
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000951 if (isa<ExplicitCastExpr>(CE)) {
952 LValueBaseInfo TargetTypeBaseInfo;
953 TBAAAccessInfo TargetTypeTBAAInfo;
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000954 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000955 &TargetTypeBaseInfo,
956 &TargetTypeTBAAInfo);
957 if (TBAAInfo)
958 *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
959 TargetTypeTBAAInfo);
960 // If the source l-value is opaque, honor the alignment of the
961 // casted-to type.
962 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
963 if (BaseInfo)
964 BaseInfo->mergeForCast(TargetTypeBaseInfo);
965 Addr = Address(Addr.getPointer(), Align);
966 }
John McCall7f416cc2015-09-08 08:05:57 +0000967 }
968
Peter Collingbourne574975e2016-01-14 02:49:48 +0000969 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
970 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000971 if (auto PT = E->getType()->getAs<PointerType>())
972 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
973 /*MayBeNull=*/true,
974 CodeGenFunction::CFITCK_UnrelatedCast,
975 CE->getLocStart());
976 }
Anastasia Stulova0a72ed42017-09-27 14:37:00 +0000977 return CE->getCastKind() != CK_AddressSpaceConversion
978 ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
979 : Builder.CreateAddrSpaceCast(Addr,
980 ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000981 }
982 break;
983
984 // Array-to-pointer decay.
985 case CK_ArrayToPointerDecay:
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000986 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000987
988 // Derived-to-base conversions.
989 case CK_UncheckedDerivedToBase:
990 case CK_DerivedToBase: {
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000991 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo,
992 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000993 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
994 return GetAddressOfBaseClass(Addr, Derived,
995 CE->path_begin(), CE->path_end(),
996 ShouldNullCheckClassCastValue(CE),
997 CE->getExprLoc());
998 }
999
1000 // TODO: Is there any reason to treat base-to-derived conversions
1001 // specially?
1002 default:
1003 break;
1004 }
1005 }
1006
1007 // Unary &.
1008 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1009 if (UO->getOpcode() == UO_AddrOf) {
1010 LValue LV = EmitLValue(UO->getSubExpr());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001011 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001012 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
John McCall7f416cc2015-09-08 08:05:57 +00001013 return LV.getAddress();
1014 }
1015 }
1016
1017 // TODO: conditional operators, comma.
1018
1019 // Otherwise, use the alignment of the type.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001020 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo,
1021 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001022 return Address(EmitScalarExpr(E), Align);
1023}
1024
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001025RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001026 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001027 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +00001028
1029 switch (getEvaluationKind(Ty)) {
1030 case TEK_Complex: {
1031 llvm::Type *EltTy =
1032 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +00001033 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001034 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001035 }
Craig Topper99e79272013-07-26 05:59:26 +00001036
Chris Lattner65526f02010-08-23 05:26:13 +00001037 // If this is a use of an undefined aggregate type, the aggregate must have an
1038 // identifiable address. Just because the contents of the value are undefined
1039 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +00001040 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00001041 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +00001042 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001043 }
John McCall47fb9502013-03-07 21:37:08 +00001044
1045 case TEK_Scalar:
1046 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1047 }
1048 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +00001049}
1050
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001051RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1052 const char *Name) {
1053 ErrorUnsupported(E, Name);
1054 return GetUndefRValue(E->getType());
1055}
1056
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001057LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1058 const char *Name) {
1059 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001060 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001061 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1062 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001063}
1064
Vedant Kumarffd7c882017-04-14 22:03:34 +00001065bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001066 const Expr *Base = Obj;
1067 while (!isa<CXXThisExpr>(Base)) {
1068 // The result of a dynamic_cast can be null.
1069 if (isa<CXXDynamicCastExpr>(Base))
1070 return false;
1071
1072 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1073 Base = CE->getSubExpr();
1074 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1075 Base = PE->getSubExpr();
1076 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1077 if (UO->getOpcode() == UO_Extension)
1078 Base = UO->getSubExpr();
1079 else
1080 return false;
1081 } else {
1082 return false;
1083 }
1084 }
1085 return true;
1086}
1087
Richard Smith4d1458e2012-09-08 02:08:36 +00001088LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +00001089 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001090 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +00001091 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1092 else
1093 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001094 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1095 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001096 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1097 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1098 if (IsBaseCXXThis)
1099 SkippedChecks.set(SanitizerKind::Alignment, true);
1100 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001101 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001102 }
John McCall7f416cc2015-09-08 08:05:57 +00001103 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001104 E->getType(), LV.getAlignment(), SkippedChecks);
1105 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001106 return LV;
1107}
1108
Chris Lattner8394d792007-06-05 20:53:16 +00001109/// EmitLValue - Emit code to compute a designator that specifies the location
1110/// of the expression.
1111///
Mike Stump4a3999f2009-09-09 13:00:44 +00001112/// This can return one of two things: a simple address or a bitfield reference.
1113/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1114/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001115///
Mike Stump4a3999f2009-09-09 13:00:44 +00001116/// If this returns a bitfield reference, nothing about the pointee type of the
1117/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001118///
Mike Stump4a3999f2009-09-09 13:00:44 +00001119/// If this returns a normal address, and if the lvalue's C type is fixed size,
1120/// this method guarantees that the returned pointer type will point to an LLVM
1121/// type of the same size of the lvalue's type. If the lvalue has a variable
1122/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001123///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001124LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001125 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001126 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001127 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001128
John McCallc109a252011-11-07 03:59:57 +00001129 case Expr::ObjCPropertyRefExprClass:
1130 llvm_unreachable("cannot emit a property reference directly");
1131
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001132 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001133 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001134 case Expr::ObjCIsaExprClass:
1135 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001136 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001137 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001138 case Expr::CompoundAssignOperatorClass: {
1139 QualType Ty = E->getType();
1140 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1141 Ty = AT->getValueType();
1142 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001143 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1144 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001145 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001146 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001147 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001148 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001149 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001150 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001151 case Expr::VAArgExprClass:
1152 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001153 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001154 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001155 case Expr::ParenExprClass:
1156 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001157 case Expr::GenericSelectionExprClass:
1158 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001159 case Expr::PredefinedExprClass:
1160 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001161 case Expr::StringLiteralClass:
1162 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001163 case Expr::ObjCEncodeExprClass:
1164 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001165 case Expr::PseudoObjectExprClass:
1166 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001167 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001168 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001169 case Expr::CXXTemporaryObjectExprClass:
1170 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001171 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1172 case Expr::CXXBindTemporaryExprClass:
1173 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001174 case Expr::CXXUuidofExprClass:
1175 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001176 case Expr::LambdaExprClass:
1177 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001178
1179 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001180 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001181 enterFullExpression(cleanups);
1182 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001183 LValue LV = EmitLValue(cleanups->getSubExpr());
1184 if (LV.isSimple()) {
1185 // Defend against branches out of gnu statement expressions surrounded by
1186 // cleanups.
1187 llvm::Value *V = LV.getPointer();
1188 Scope.ForceCleanup({&V});
1189 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001190 getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
Reid Kleckner092d0652017-03-06 22:18:34 +00001191 }
1192 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1193 // bitfield lvalue or some other non-simple lvalue?
1194 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001195 }
1196
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001197 case Expr::CXXDefaultArgExprClass:
1198 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001199 case Expr::CXXDefaultInitExprClass: {
1200 CXXDefaultInitExprScope Scope(*this);
1201 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1202 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001203 case Expr::CXXTypeidExprClass:
1204 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001205
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001206 case Expr::ObjCMessageExprClass:
1207 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001208 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001209 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001210 case Expr::StmtExprClass:
1211 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001212 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001213 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001214 case Expr::ArraySubscriptExprClass:
1215 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001216 case Expr::OMPArraySectionExprClass:
1217 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001218 case Expr::ExtVectorElementExprClass:
1219 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001220 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001221 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001222 case Expr::CompoundLiteralExprClass:
1223 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001224 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001225 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001226 case Expr::BinaryConditionalOperatorClass:
1227 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001228 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001229 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001230 case Expr::OpaqueValueExprClass:
1231 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001232 case Expr::SubstNonTypeTemplateParmExprClass:
1233 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001234 case Expr::ImplicitCastExprClass:
1235 case Expr::CStyleCastExprClass:
1236 case Expr::CXXFunctionalCastExprClass:
1237 case Expr::CXXStaticCastExprClass:
1238 case Expr::CXXDynamicCastExprClass:
1239 case Expr::CXXReinterpretCastExprClass:
1240 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001241 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001242 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001243
Douglas Gregorfe314812011-06-21 17:03:29 +00001244 case Expr::MaterializeTemporaryExprClass:
1245 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Eric Fiseliercddaf872017-06-15 19:43:36 +00001246
1247 case Expr::CoawaitExprClass:
1248 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1249 case Expr::CoyieldExprClass:
1250 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001251 }
1252}
1253
John McCall71335052012-03-10 03:05:10 +00001254/// Given an object of the given canonical type, can we safely copy a
1255/// value out of it based on its initializer?
1256static bool isConstantEmittableObjectType(QualType type) {
1257 assert(type.isCanonical());
1258 assert(!type->isReferenceType());
1259
1260 // Must be const-qualified but non-volatile.
1261 Qualifiers qs = type.getLocalQualifiers();
1262 if (!qs.hasConst() || qs.hasVolatile()) return false;
1263
1264 // Otherwise, all object types satisfy this except C++ classes with
1265 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001266 if (const auto *RT = dyn_cast<RecordType>(type))
1267 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001268 if (RD->hasMutableFields() || !RD->isTrivial())
1269 return false;
1270
1271 return true;
1272}
1273
1274/// Can we constant-emit a load of a reference to a variable of the
1275/// given type? This is different from predicates like
1276/// Decl::isUsableInConstantExpressions because we do want it to apply
1277/// in situations that don't necessarily satisfy the language's rules
1278/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1279/// to do this with const float variables even if those variables
1280/// aren't marked 'constexpr'.
1281enum ConstantEmissionKind {
1282 CEK_None,
1283 CEK_AsReferenceOnly,
1284 CEK_AsValueOrReference,
1285 CEK_AsValueOnly
1286};
1287static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1288 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001289 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001290 if (isConstantEmittableObjectType(ref->getPointeeType()))
1291 return CEK_AsValueOrReference;
1292 return CEK_AsReferenceOnly;
1293 }
1294 if (isConstantEmittableObjectType(type))
1295 return CEK_AsValueOnly;
1296 return CEK_None;
1297}
1298
1299/// Try to emit a reference to the given value without producing it as
1300/// an l-value. This is actually more than an optimization: we can't
1301/// produce an l-value for variables that we never actually captured
1302/// in a block or lambda, which means const int variables or constexpr
1303/// literals or similar.
1304CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001305CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1306 ValueDecl *value = refExpr->getDecl();
1307
John McCall71335052012-03-10 03:05:10 +00001308 // The value needs to be an enum constant or a constant variable.
1309 ConstantEmissionKind CEK;
1310 if (isa<ParmVarDecl>(value)) {
1311 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001312 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001313 CEK = checkVarTypeForConstantEmission(var->getType());
1314 } else if (isa<EnumConstantDecl>(value)) {
1315 CEK = CEK_AsValueOnly;
1316 } else {
1317 CEK = CEK_None;
1318 }
1319 if (CEK == CEK_None) return ConstantEmission();
1320
John McCall71335052012-03-10 03:05:10 +00001321 Expr::EvalResult result;
1322 bool resultIsReference;
1323 QualType resultType;
1324
1325 // It's best to evaluate all the way as an r-value if that's permitted.
1326 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001327 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001328 resultIsReference = false;
1329 resultType = refExpr->getType();
1330
1331 // Otherwise, try to evaluate as an l-value.
1332 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001333 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001334 resultIsReference = true;
1335 resultType = value->getType();
1336
1337 // Failure.
1338 } else {
1339 return ConstantEmission();
1340 }
1341
1342 // In any case, if the initializer has side-effects, abandon ship.
1343 if (result.HasSideEffects)
1344 return ConstantEmission();
1345
1346 // Emit as a constant.
John McCallde0fe072017-08-15 21:42:52 +00001347 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1348 result.Val, resultType);
John McCall71335052012-03-10 03:05:10 +00001349
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001350 // Make sure we emit a debug reference to the global variable.
1351 // This should probably fire even for
1352 if (isa<VarDecl>(value)) {
1353 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001354 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001355 } else {
1356 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001357 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001358 }
John McCall71335052012-03-10 03:05:10 +00001359
1360 // If we emitted a reference constant, we need to dereference that.
1361 if (resultIsReference)
1362 return ConstantEmission::forReference(C);
1363
1364 return ConstantEmission::forValue(C);
1365}
1366
Alex Lorenz6cc83172017-08-25 10:07:00 +00001367static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1368 const MemberExpr *ME) {
1369 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1370 // Try to emit static variable member expressions as DREs.
1371 return DeclRefExpr::Create(
1372 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1373 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1374 ME->getType(), ME->getValueKind());
1375 }
1376 return nullptr;
1377}
1378
1379CodeGenFunction::ConstantEmission
1380CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1381 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1382 return tryEmitAsConstant(DRE);
1383 return ConstantEmission();
1384}
1385
Nick Lewycky2d84e842013-10-02 02:29:49 +00001386llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1387 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001388 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001389 lvalue.getType(), Loc, lvalue.getBaseInfo(),
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001390 lvalue.getTBAAInfo(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001391}
1392
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001393static bool hasBooleanRepresentation(QualType Ty) {
1394 if (Ty->isBooleanType())
1395 return true;
1396
1397 if (const EnumType *ET = Ty->getAs<EnumType>())
1398 return ET->getDecl()->getIntegerType()->isBooleanType();
1399
Douglas Gregor298f43d2012-04-12 20:42:30 +00001400 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1401 return hasBooleanRepresentation(AT->getValueType());
1402
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001403 return false;
1404}
1405
Richard Smith1629da92012-12-13 07:11:50 +00001406static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1407 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001408 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001409 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001410 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1411 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001412 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001413 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001414
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001415 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001416 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1417 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001418 } else {
1419 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001420 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001421 unsigned Bitwidth = LTy->getScalarSizeInBits();
1422 unsigned NumNegativeBits = ED->getNumNegativeBits();
1423 unsigned NumPositiveBits = ED->getNumPositiveBits();
1424
1425 if (NumNegativeBits) {
1426 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1427 assert(NumBits <= Bitwidth);
1428 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1429 Min = -End;
1430 } else {
1431 assert(NumPositiveBits <= Bitwidth);
1432 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1433 Min = llvm::APInt(Bitwidth, 0);
1434 }
1435 }
Richard Smith1629da92012-12-13 07:11:50 +00001436 return true;
1437}
1438
1439llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1440 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001441 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1442 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001443 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001444
Duncan Sandsc720e782012-04-15 18:04:54 +00001445 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001446 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001447}
1448
Vedant Kumar5a972652017-02-27 19:46:19 +00001449bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1450 SourceLocation Loc) {
1451 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1452 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1453 if (!HasBoolCheck && !HasEnumCheck)
1454 return false;
1455
1456 bool IsBool = hasBooleanRepresentation(Ty) ||
1457 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1458 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1459 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1460 if (!NeedsBoolCheck && !NeedsEnumCheck)
1461 return false;
1462
Vedant Kumar129edab2017-03-09 16:06:27 +00001463 // Single-bit booleans don't need to be checked. Special-case this to avoid
1464 // a bit width mismatch when handling bitfield values. This is handled by
1465 // EmitFromMemory for the non-bitfield case.
1466 if (IsBool &&
1467 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1468 return false;
1469
Vedant Kumar5a972652017-02-27 19:46:19 +00001470 llvm::APInt Min, End;
1471 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1472 return true;
1473
Vedant Kumar791f7012017-10-03 01:27:26 +00001474 auto &Ctx = getLLVMContext();
Vedant Kumar5a972652017-02-27 19:46:19 +00001475 SanitizerScope SanScope(this);
1476 llvm::Value *Check;
1477 --End;
1478 if (!Min) {
Vedant Kumar791f7012017-10-03 01:27:26 +00001479 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
Vedant Kumar5a972652017-02-27 19:46:19 +00001480 } else {
Vedant Kumar791f7012017-10-03 01:27:26 +00001481 llvm::Value *Upper =
1482 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1483 llvm::Value *Lower =
1484 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
Vedant Kumar5a972652017-02-27 19:46:19 +00001485 Check = Builder.CreateAnd(Upper, Lower);
1486 }
1487 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1488 EmitCheckTypeDescriptor(Ty)};
1489 SanitizerMask Kind =
1490 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1491 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1492 StaticArgs, EmitCheckValue(Value));
1493 return true;
1494}
1495
John McCall7f416cc2015-09-08 08:05:57 +00001496llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1497 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001498 SourceLocation Loc,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001499 LValueBaseInfo BaseInfo,
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001500 TBAAAccessInfo TBAAInfo,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001501 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001502 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1503 // For better performance, handle vector loads differently.
1504 if (Ty->isVectorType()) {
1505 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001506
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001507 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001508
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001509 // Handle vectors of size 3 like size 4 for better performance.
1510 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001511
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001512 // Bitcast to vec4 type.
1513 llvm::VectorType *vec4Ty =
1514 llvm::VectorType::get(VTy->getElementType(), 4);
1515 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1516 // Now load value.
1517 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001518
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001519 // Shuffle vector to get vec3.
1520 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1521 {0, 1, 2}, "extractVec");
1522 return EmitFromMemory(V, Ty);
1523 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001524 }
1525 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001526
1527 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001528 LValue AtomicLValue =
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001529 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001530 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1531 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001532 }
Craig Topper99e79272013-07-26 05:59:26 +00001533
John McCall7f416cc2015-09-08 08:05:57 +00001534 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001535 if (isNontemporal) {
1536 llvm::MDNode *Node = llvm::MDNode::get(
1537 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1538 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1539 }
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001540
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001541 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001542
Vedant Kumar5a972652017-02-27 19:46:19 +00001543 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1544 // In order to prevent the optimizer from throwing away the check, don't
1545 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001546 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001547 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1548 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001549
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001550 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001551}
1552
John McCall3a7f6922010-10-27 20:58:56 +00001553llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1554 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001555 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001556 // This should really always be an i1, but sometimes it's already
1557 // an i8, and it's awkward to track those cases down.
1558 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001559 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1560 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1561 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001562 }
1563
1564 return Value;
1565}
1566
1567llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1568 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001569 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001570 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1571 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001572 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1573 }
1574
1575 return Value;
1576}
1577
John McCall7f416cc2015-09-08 08:05:57 +00001578void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1579 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001580 LValueBaseInfo BaseInfo,
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001581 TBAAAccessInfo TBAAInfo,
1582 bool isInit, bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001583 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1584 // Handle vectors differently to get better performance.
1585 if (Ty->isVectorType()) {
1586 llvm::Type *SrcTy = Value->getType();
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001587 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001588 // Handle vec3 special.
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001589 if (VecTy && VecTy->getNumElements() == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001590 // Our source is a vec3, do a shuffle vector to make it a vec4.
1591 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1592 Builder.getInt32(2),
1593 llvm::UndefValue::get(Builder.getInt32Ty())};
1594 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1595 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1596 MaskV, "extractVec");
1597 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1598 }
1599 if (Addr.getElementType() != SrcTy) {
1600 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1601 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001602 }
1603 }
Craig Topper99e79272013-07-26 05:59:26 +00001604
John McCall3a7f6922010-10-27 20:58:56 +00001605 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001606
David Majnemera38c9f12016-05-24 16:09:25 +00001607 LValue AtomicLValue =
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001608 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001609 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001610 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1611 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001612 return;
1613 }
1614
Daniel Dunbar03816342010-08-21 02:24:36 +00001615 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001616 if (isNontemporal) {
1617 llvm::MDNode *Node =
1618 llvm::MDNode::get(Store->getContext(),
1619 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1620 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1621 }
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001622
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001623 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001624}
1625
David Chisnallfa35df62012-01-16 17:27:18 +00001626void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001627 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001628 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001629 lvalue.getType(), lvalue.getBaseInfo(),
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001630 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001631}
1632
Mike Stump4a3999f2009-09-09 13:00:44 +00001633/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1634/// method emits the address of the lvalue, then loads the result as an rvalue,
1635/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001636RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001637 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001638 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001639 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001640 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1641 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001642 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001643 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001644 // In MRC mode, we do a load+autorelease.
1645 if (!getLangOpts().ObjCAutoRefCount) {
1646 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1647 }
1648
1649 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001650 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1651 Object = EmitObjCConsumeObject(LV.getType(), Object);
1652 return RValue::get(Object);
1653 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001654
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001655 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001656 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001657
John McCalla1dee5302010-08-22 10:59:02 +00001658 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001659 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001660 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001661
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001662 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001663 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001664 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001665 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001666 "vecext"));
1667 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001668
1669 // If this is a reference to a subset of the elements of a vector, either
1670 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001671 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001672 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001673
Renato Golin230c5eb2014-05-19 18:15:42 +00001674 // Global Register variables always invoke intrinsics
1675 if (LV.isGlobalReg())
1676 return EmitLoadOfGlobalRegLValue(LV);
1677
John McCallc109a252011-11-07 03:59:57 +00001678 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001679 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001680}
1681
Vedant Kumar129edab2017-03-09 16:06:27 +00001682RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1683 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001684 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001685
Daniel Dunbar3447a022010-04-13 23:34:15 +00001686 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001687 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001688
John McCall7f416cc2015-09-08 08:05:57 +00001689 Address Ptr = LV.getBitFieldAddress();
1690 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001691
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001692 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001693 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001694 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1695 if (HighBits)
1696 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1697 if (Info.Offset + HighBits)
1698 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1699 } else {
1700 if (Info.Offset)
1701 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001702 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001703 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1704 Info.Size),
1705 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001706 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001707 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001708 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001709 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001710}
1711
Nate Begemanb699c9b2009-01-18 06:42:49 +00001712// If this is a reference to a subset of the elements of a vector, create an
1713// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001714RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001715 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1716 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001717
Nate Begemanf322eab2008-05-09 06:41:27 +00001718 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001719
1720 // If the result of the expression is a non-vector type, we must be extracting
1721 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001722 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001723 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001724 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001725 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001726 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001727 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001728
1729 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001730 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001731
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001732 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001733 for (unsigned i = 0; i != NumResultElts; ++i)
1734 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001735
Chris Lattner91c08ad2011-02-15 00:14:06 +00001736 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1737 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001738 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001739 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001740}
1741
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001742/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001743Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1744 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001745 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1746 QualType EQT = ExprVT->getElementType();
1747 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001748
John McCall7f416cc2015-09-08 08:05:57 +00001749 Address CastToPointerElement =
1750 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1751 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001752
1753 const llvm::Constant *Elts = LV.getExtVectorElts();
1754 unsigned ix = getAccessedFieldNo(0, Elts);
1755
John McCall7f416cc2015-09-08 08:05:57 +00001756 Address VectorBasePtrPlusIx =
1757 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1758 getContext().getTypeSizeInChars(EQT),
1759 "vector.elt");
1760
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001761 return VectorBasePtrPlusIx;
1762}
1763
Renato Golin230c5eb2014-05-19 18:15:42 +00001764/// @brief Load of global gamed gegisters are always calls to intrinsics.
1765RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001766 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1767 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001768 llvm::MDNode *RegName = cast<llvm::MDNode>(
1769 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001770
1771 // We accept integer and pointer types only
1772 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1773 llvm::Type *Ty = OrigTy;
1774 if (OrigTy->isPointerTy())
1775 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1776 llvm::Type *Types[] = { Ty };
1777
Renato Golin230c5eb2014-05-19 18:15:42 +00001778 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001779 llvm::Value *Call = Builder.CreateCall(
1780 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001781 if (OrigTy->isPointerTy())
1782 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001783 return RValue::get(Call);
1784}
Chris Lattner40ff7012007-08-03 16:18:34 +00001785
Chris Lattner9369a562007-06-29 16:31:29 +00001786
Chris Lattner8394d792007-06-05 20:53:16 +00001787/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1788/// lvalue, where both are guaranteed to the have the same type, and that type
1789/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001790void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001791 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001792 if (!Dst.isSimple()) {
1793 if (Dst.isVectorElt()) {
1794 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001795 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1796 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001797 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001798 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001799 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1800 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001801 return;
1802 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001803
Nate Begemance4d7fc2008-04-18 23:10:10 +00001804 // If this is an update of extended vector elements, insert them as
1805 // appropriate.
1806 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001807 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001808
Renato Golin230c5eb2014-05-19 18:15:42 +00001809 if (Dst.isGlobalReg())
1810 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1811
John McCallc109a252011-11-07 03:59:57 +00001812 assert(Dst.isBitField() && "Unknown LValue type");
1813 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001814 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001815
John McCall31168b02011-06-15 23:02:42 +00001816 // There's special magic for assigning into an ARC-qualified l-value.
1817 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1818 switch (Lifetime) {
1819 case Qualifiers::OCL_None:
1820 llvm_unreachable("present but none");
1821
1822 case Qualifiers::OCL_ExplicitNone:
1823 // nothing special
1824 break;
1825
1826 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001827 if (isInit) {
1828 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1829 break;
1830 }
John McCall55e1fbc2011-06-25 02:11:03 +00001831 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001832 return;
1833
1834 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001835 if (isInit)
1836 // Initialize and then skip the primitive store.
1837 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1838 else
1839 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001840 return;
1841
1842 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001843 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1844 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001845 // fall into the normal path
1846 break;
1847 }
1848 }
1849
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001850 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001851 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001852 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001853 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001854 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001855 return;
1856 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001857
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001858 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001859 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001860 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001861 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001862 if (Dst.isObjCIvar()) {
1863 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001864 llvm::Type *ResultType = IntPtrTy;
1865 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1866 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001867 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001868 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001869 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1870 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001871 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001872 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001873 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001874 } else if (Dst.isGlobalObjCRef()) {
1875 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1876 Dst.isThreadLocalRef());
1877 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001878 else
1879 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001880 return;
1881 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001882
Chris Lattner6278e6a2007-08-11 00:04:45 +00001883 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001884 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001885}
1886
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001887void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001888 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001889 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001890 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001891 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001892
Daniel Dunbar67aba792010-04-15 03:47:33 +00001893 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001894 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001895
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001896 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001897 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001898 /*IsSigned=*/false);
1899 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001900
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001901 // See if there are other bits in the bitfield's storage we'll need to load
1902 // and mask together with source before storing.
1903 if (Info.StorageSize != Info.Size) {
1904 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001905 llvm::Value *Val =
1906 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001907
1908 // Mask the source value as needed.
1909 if (!hasBooleanRepresentation(Dst.getType()))
1910 SrcVal = Builder.CreateAnd(SrcVal,
1911 llvm::APInt::getLowBitsSet(Info.StorageSize,
1912 Info.Size),
1913 "bf.value");
1914 MaskedVal = SrcVal;
1915 if (Info.Offset)
1916 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1917
1918 // Mask out the original value.
1919 Val = Builder.CreateAnd(Val,
1920 ~llvm::APInt::getBitsSet(Info.StorageSize,
1921 Info.Offset,
1922 Info.Offset + Info.Size),
1923 "bf.clear");
1924
1925 // Or together the unchanged values and the source value.
1926 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1927 } else {
1928 assert(Info.Offset == 0);
1929 }
1930
1931 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001932 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001933
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001934 // Return the new value of the bit-field, if requested.
1935 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001936 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001937
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001938 // Sign extend the value if needed.
1939 if (Info.IsSigned) {
1940 assert(Info.Size <= Info.StorageSize);
1941 unsigned HighBits = Info.StorageSize - Info.Size;
1942 if (HighBits) {
1943 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1944 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1945 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001946 }
1947
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001948 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1949 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001950 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001951 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001952}
1953
Nate Begemance4d7fc2008-04-18 23:10:10 +00001954void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001955 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001956 // This access turns into a read/modify/write of the vector. Load the input
1957 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001958 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1959 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001960 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001961
Chris Lattner4647a212007-08-31 22:49:20 +00001962 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001963
John McCall55e1fbc2011-06-25 02:11:03 +00001964 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001965 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001966 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001967 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001968 // Use shuffle vector is the src and destination are the same number of
1969 // elements and restore the vector mask since it is on the side it will be
1970 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001971 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001972 for (unsigned i = 0; i != NumSrcElts; ++i)
1973 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001974
Chris Lattner91c08ad2011-02-15 00:14:06 +00001975 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001976 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001977 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001978 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001979 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001980 // Extended the source vector to the same length and then shuffle it
1981 // into the destination.
1982 // FIXME: since we're shuffling with undef, can we just use the indices
1983 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001984 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001985 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001986 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001987 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001988 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001989 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001990 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001991 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001992 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001993 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001994 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001995 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001996 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001997
Joey Goulycf4143b2013-11-21 17:09:05 +00001998 // When the vector size is odd and .odd or .hi is used, the last element
1999 // of the Elts constant array will be one past the size of the vector.
2000 // Ignore the last element here, if it is greater than the mask size.
2001 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2002 NumSrcElts--;
2003
Nate Begemanb699c9b2009-01-18 06:42:49 +00002004 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002005 for (unsigned i = 0; i != NumSrcElts; ++i)
2006 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00002007 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002008 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00002009 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00002010 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00002011 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00002012 }
2013 } else {
2014 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00002015 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00002016 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002017 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00002018 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002019
John McCall7f416cc2015-09-08 08:05:57 +00002020 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2021 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00002022}
2023
Renato Golin230c5eb2014-05-19 18:15:42 +00002024/// @brief Store of global named registers are always calls to intrinsics.
2025void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00002026 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2027 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002028 llvm::MDNode *RegName = cast<llvm::MDNode>(
2029 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00002030 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00002031
2032 // We accept integer and pointer types only
2033 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2034 llvm::Type *Ty = OrigTy;
2035 if (OrigTy->isPointerTy())
2036 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2037 llvm::Type *Types[] = { Ty };
2038
Renato Golin230c5eb2014-05-19 18:15:42 +00002039 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2040 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00002041 if (OrigTy->isPointerTy())
2042 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00002043 Builder.CreateCall(
2044 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00002045}
2046
Eric Christopherc9e2a682014-05-20 17:10:39 +00002047// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002048// generating write-barries API. It is currently a global, ivar,
2049// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002050static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002051 LValue &LV,
2052 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002053 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002054 return;
Craig Topper99e79272013-07-26 05:59:26 +00002055
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002056 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002057 QualType ExpTy = E->getType();
2058 if (IsMemberAccess && ExpTy->isPointerType()) {
2059 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00002060 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002061 // writer-barrier conservatively.
2062 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2063 if (ExpTy->isRecordType()) {
2064 LV.setObjCIvar(false);
2065 return;
2066 }
2067 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002068 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002069 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002070 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002071 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002072 return;
2073 }
Craig Topper99e79272013-07-26 05:59:26 +00002074
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002075 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2076 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00002077 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002078 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00002079 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002080 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002081 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002082 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002083 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002084 }
Craig Topper99e79272013-07-26 05:59:26 +00002085
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002086 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002087 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002088 return;
2089 }
Craig Topper99e79272013-07-26 05:59:26 +00002090
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002091 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002092 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002093 if (LV.isObjCIvar()) {
2094 // If cast is to a structure pointer, follow gcc's behavior and make it
2095 // a non-ivar write-barrier.
2096 QualType ExpTy = E->getType();
2097 if (ExpTy->isPointerType())
2098 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2099 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002100 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002101 }
2102 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002103 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002104
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002105 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002106 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2107 return;
2108 }
2109
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002110 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002111 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002112 return;
2113 }
Craig Topper99e79272013-07-26 05:59:26 +00002114
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002115 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002116 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002117 return;
2118 }
John McCall31168b02011-06-15 23:02:42 +00002119
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002120 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002121 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002122 return;
2123 }
2124
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002125 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002126 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002127 if (LV.isObjCIvar() && !LV.isObjCArray())
2128 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002129 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002130 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002131 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002132 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002133 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002134 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002135 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002136 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002137
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002138 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002139 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002140 // We don't know if member is an 'ivar', but this flag is looked at
2141 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002142 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002143 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002144 }
2145}
2146
Chris Lattner3f32d692011-07-12 06:52:18 +00002147static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002148EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002149 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002150 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002151 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002152 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002153}
2154
Alexey Bataev97720002014-11-11 04:05:39 +00002155static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002156 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2157 llvm::Type *RealVarTy, SourceLocation Loc) {
2158 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2159 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002160 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
John McCall7f416cc2015-09-08 08:05:57 +00002161}
2162
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002163Address
2164CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2165 LValueBaseInfo *PointeeBaseInfo,
2166 TBAAAccessInfo *PointeeTBAAInfo) {
2167 llvm::LoadInst *Load = Builder.CreateLoad(RefLVal.getAddress(),
2168 RefLVal.isVolatile());
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00002169 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002170
2171 CharUnits Align = getNaturalTypeAlignment(RefLVal.getType()->getPointeeType(),
2172 PointeeBaseInfo, PointeeTBAAInfo,
2173 /* forPointeeType= */ true);
2174 return Address(Load, Align);
John McCall7f416cc2015-09-08 08:05:57 +00002175}
2176
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002177LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2178 LValueBaseInfo PointeeBaseInfo;
2179 TBAAAccessInfo PointeeTBAAInfo;
2180 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2181 &PointeeTBAAInfo);
2182 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2183 PointeeBaseInfo, PointeeTBAAInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002184}
2185
Alexey Bataev31300ed2016-02-04 11:27:03 +00002186Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2187 const PointerType *PtrTy,
Ivan A. Kosarev90295642017-10-13 16:47:22 +00002188 LValueBaseInfo *BaseInfo,
2189 TBAAAccessInfo *TBAAInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002190 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002191 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +00002192 BaseInfo, TBAAInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002193 /*forPointeeType=*/true));
2194}
2195
2196LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2197 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002198 LValueBaseInfo BaseInfo;
Ivan A. Kosarev90295642017-10-13 16:47:22 +00002199 TBAAAccessInfo TBAAInfo;
2200 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2201 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002202}
2203
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002204static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2205 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002206 QualType T = E->getType();
2207
2208 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002209 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2210 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002211 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2212
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002213 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002214 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2215 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002216 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002217 Address Addr(V, Alignment);
Alexey Bataev97720002014-11-11 04:05:39 +00002218 // Emit reference to the private copy of the variable if it is an OpenMP
2219 // threadprivate variable.
2220 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002221 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002222 E->getExprLoc());
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002223 LValue LV = VD->getType()->isReferenceType() ?
2224 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2225 AlignmentSource::Decl) :
2226 CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002227 setObjCGCLValueClass(CGF.getContext(), E, LV);
2228 return LV;
2229}
2230
John McCallb92ab1a2016-10-26 23:46:34 +00002231static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2232 const FunctionDecl *FD) {
2233 if (FD->hasAttr<WeakRefAttr>()) {
2234 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2235 return aliasee.getPointer();
2236 }
2237
2238 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002239 if (!FD->hasPrototype()) {
2240 if (const FunctionProtoType *Proto =
2241 FD->getType()->getAs<FunctionProtoType>()) {
2242 // Ugly case: for a K&R-style definition, the type of the definition
2243 // isn't the same as the type of a use. Correct for this with a
2244 // bitcast.
2245 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002246 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2247 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2248 V = llvm::ConstantExpr::getBitCast(V,
2249 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002250 }
2251 }
John McCallb92ab1a2016-10-26 23:46:34 +00002252 return V;
2253}
2254
2255static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2256 const Expr *E, const FunctionDecl *FD) {
2257 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002258 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002259 return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2260 AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002261}
2262
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002263static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2264 llvm::Value *ThisValue) {
2265 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2266 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2267 return CGF.EmitLValueForField(LV, FD);
2268}
2269
Renato Golin230c5eb2014-05-19 18:15:42 +00002270/// Named Registers are named metadata pointing to the register name
2271/// which will be read from/written to as an argument to the intrinsic
2272/// @llvm.read/write_register.
2273/// So far, only the name is being passed down, but other options such as
2274/// register type, allocation type or even optimization options could be
2275/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002276static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002277 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002278 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002279 assert(Asm->getLabel().size() < 64-Name.size() &&
2280 "Register name too big");
2281 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002282 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002283 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002284 if (M->getNumOperands() == 0) {
2285 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2286 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002287 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002288 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2289 }
John McCall7f416cc2015-09-08 08:05:57 +00002290
2291 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2292
2293 llvm::Value *Ptr =
2294 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2295 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002296}
2297
Chris Lattnerd7f58862007-06-02 05:24:33 +00002298LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002299 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002300 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002301
Renato Goline7b3d5d2014-05-27 16:46:27 +00002302 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2303 // Global Named registers access via intrinsics only
2304 if (VD->getStorageClass() == SC_Register &&
2305 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002306 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002307
Renato Goline7b3d5d2014-05-27 16:46:27 +00002308 // A DeclRefExpr for a reference initialized by a constant expression can
2309 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002310 const Expr *Init = VD->getAnyInitializer(VD);
2311 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2312 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002313 VD->checkInitIsICE() &&
2314 // Do not emit if it is private OpenMP variable.
Alexey Bataevcab496d2017-10-06 16:17:25 +00002315 !(E->refersToEnclosingVariableOrCapture() &&
2316 ((CapturedStmtInfo &&
2317 (LocalDeclMap.count(VD->getCanonicalDecl()) ||
2318 CapturedStmtInfo->lookup(VD->getCanonicalDecl()))) ||
2319 LambdaCaptureFields.lookup(VD->getCanonicalDecl()) ||
2320 isa<BlockDecl>(CurCodeDecl)))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002321 llvm::Constant *Val =
John McCallde0fe072017-08-15 21:42:52 +00002322 ConstantEmitter(*this).emitAbstract(E->getLocation(),
2323 *VD->evaluateValue(),
2324 VD->getType());
Richard Smith5a1104b2012-10-20 01:38:33 +00002325 assert(Val && "failed to emit reference constant expression");
2326 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002327
2328 // Should we be using the alignment of the constant pointer we emitted?
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +00002329 CharUnits Alignment = getNaturalTypeAlignment(E->getType(),
2330 /* BaseInfo= */ nullptr,
2331 /* TBAAInfo= */ nullptr,
2332 /* forPointeeType= */ true);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002333 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002334 }
David Majnemer602cfe72015-01-01 09:49:44 +00002335
2336 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002337 if (E->refersToEnclosingVariableOrCapture()) {
Alexey Bataev6a71f362017-08-22 17:54:52 +00002338 VD = VD->getCanonicalDecl();
David Majnemer602cfe72015-01-01 09:49:44 +00002339 if (auto *FD = LambdaCaptureFields.lookup(VD))
2340 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2341 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002342 auto I = LocalDeclMap.find(VD);
2343 if (I != LocalDeclMap.end()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002344 if (VD->getType()->isReferenceType())
2345 return EmitLoadOfReferenceLValue(I->second, VD->getType(),
2346 AlignmentSource::Decl);
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002347 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002348 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002349 LValue CapLVal =
2350 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2351 CapturedStmtInfo->getContextValue());
2352 return MakeAddrLValue(
2353 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00002354 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2355 CapLVal.getTBAAInfo());
David Majnemer602cfe72015-01-01 09:49:44 +00002356 }
John McCall7f416cc2015-09-08 08:05:57 +00002357
David Majnemer602cfe72015-01-01 09:49:44 +00002358 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002359 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002360 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002361 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002362 }
2363
Eli Friedman5720e342012-01-21 04:52:58 +00002364 // FIXME: We should be able to assert this for FunctionDecls as well!
2365 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2366 // those with a valid source location.
2367 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2368 !E->getLocation().isValid()) &&
2369 "Should not use decl without marking it used!");
2370
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002371 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002372 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002373 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002374 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002375 }
2376
Renato Goline7b3d5d2014-05-27 16:46:27 +00002377 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002378 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002379 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002380 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002381
John McCall7f416cc2015-09-08 08:05:57 +00002382 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002383
John McCall7f416cc2015-09-08 08:05:57 +00002384 // The variable should generally be present in the local decl map.
2385 auto iter = LocalDeclMap.find(VD);
2386 if (iter != LocalDeclMap.end()) {
2387 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002388
John McCall7f416cc2015-09-08 08:05:57 +00002389 // Otherwise, it might be static local we haven't emitted yet for
2390 // some reason; most likely, because it's in an outer function.
2391 } else if (VD->isStaticLocal()) {
2392 addr = Address(CGM.getOrCreateStaticVarDecl(
2393 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2394 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002395
John McCall7f416cc2015-09-08 08:05:57 +00002396 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002397 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002398 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2399 }
2400
2401
2402 // Check for OpenMP threadprivate variables.
2403 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2404 return EmitThreadPrivateVarDeclLValue(
2405 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2406 E->getExprLoc());
2407 }
2408
2409 // Drill into block byref variables.
2410 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2411 if (isBlockByref) {
2412 addr = emitBlockByrefAddress(addr, VD);
2413 }
2414
2415 // Drill into reference types.
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002416 LValue LV = VD->getType()->isReferenceType() ?
2417 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2418 MakeAddrLValue(addr, T, AlignmentSource::Decl);
Chris Lattner3f32d692011-07-12 06:52:18 +00002419
John McCallcdda29c2013-03-13 03:10:54 +00002420 bool isLocalStorage = VD->hasLocalStorage();
2421
2422 bool NonGCable = isLocalStorage &&
2423 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002424 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002425 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002426 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002427 LV.setNonGC(true);
2428 }
John McCallcdda29c2013-03-13 03:10:54 +00002429
2430 bool isImpreciseLifetime =
2431 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2432 if (isImpreciseLifetime)
2433 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002434 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002435 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002436 }
John McCallf3a88602011-02-03 08:15:49 +00002437
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002438 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002439 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002440
Richard Smithda383632016-08-15 01:33:41 +00002441 // FIXME: While we're emitting a binding from an enclosing scope, all other
2442 // DeclRefExprs we see should be implicitly treated as if they also refer to
2443 // an enclosing scope.
2444 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2445 return EmitLValue(BD->getBinding());
2446
David Blaikie83d382b2011-09-23 05:06:16 +00002447 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002448}
Chris Lattnere47e4402007-06-01 18:02:12 +00002449
Chris Lattner8394d792007-06-05 20:53:16 +00002450LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2451 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002452 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002453 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002454
Chris Lattner0f398c42008-07-26 22:37:01 +00002455 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002456 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002457 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002458 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002459 QualType T = E->getSubExpr()->getType()->getPointeeType();
2460 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002461
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002462 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00002463 TBAAAccessInfo TBAAInfo;
2464 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2465 &TBAAInfo);
2466 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002467 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002468
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002469 // We should not generate __weak write barrier on indirect reference
2470 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2471 // But, we continue to generate __strong write barrier on indirect write
2472 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002473 if (getLangOpts().ObjC1 &&
2474 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002475 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002476 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002477 return LV;
2478 }
John McCalle3027922010-08-25 11:45:40 +00002479 case UO_Real:
2480 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002481 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002482 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002483
Richard Smith0b6b8e42012-02-18 20:53:32 +00002484 // __real is valid on scalars. This is a faster way of testing that.
2485 // __imag can only produce an rvalue on scalars.
2486 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002487 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002488 assert(E->getSubExpr()->getType()->isArithmeticType());
2489 return LV;
2490 }
2491
Alexey Bataev611b0a12016-11-07 18:15:02 +00002492 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002493
John McCall7f416cc2015-09-08 08:05:57 +00002494 Address Component =
2495 (E->getOpcode() == UO_Real
2496 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2497 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00002498 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00002499 CGM.getTBAAInfoForSubobject(LV, T));
Alexey Bataev611b0a12016-11-07 18:15:02 +00002500 ElemLV.getQuals().addQualifiers(LV.getQuals());
2501 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002502 }
John McCalle3027922010-08-25 11:45:40 +00002503 case UO_PreInc:
2504 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002505 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002506 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002507
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002508 if (E->getType()->isAnyComplexType())
2509 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2510 else
2511 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2512 return LV;
2513 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002514 }
Chris Lattner8394d792007-06-05 20:53:16 +00002515}
2516
Chris Lattner4347e3692007-06-06 04:54:52 +00002517LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002518 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002519 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002520}
2521
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002522LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002523 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002524 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002525}
2526
Mike Stump4a3999f2009-09-09 13:00:44 +00002527LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002528 auto SL = E->getFunctionName();
2529 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2530 StringRef FnName = CurFn->getName();
2531 if (FnName.startswith("\01"))
2532 FnName = FnName.substr(1);
2533 StringRef NameItems[] = {
2534 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2535 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002536 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2537 std::string Name = SL->getString();
2538 if (!Name.empty()) {
2539 unsigned Discriminator =
2540 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2541 if (Discriminator)
2542 Name += "_" + Twine(Discriminator + 1).str();
2543 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002544 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002545 } else {
2546 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002547 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002548 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002549 }
Alexey Bataevec474782014-10-09 08:45:04 +00002550 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002551 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002552}
2553
Richard Smithe30752c2012-10-09 19:52:38 +00002554/// Emit a type description suitable for use by a runtime sanitizer library. The
2555/// format of a type descriptor is
2556///
2557/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002558/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002559/// \endcode
2560///
Richard Smith683398a2012-10-09 23:55:19 +00002561/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2562/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002563llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002564 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002565 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002566 return C;
2567
Richard Smithe30752c2012-10-09 19:52:38 +00002568 uint16_t TypeKind = -1;
2569 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002570
Richard Smithe30752c2012-10-09 19:52:38 +00002571 if (T->isIntegerType()) {
2572 TypeKind = 0;
2573 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002574 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002575 } else if (T->isFloatingType()) {
2576 TypeKind = 1;
2577 TypeInfo = getContext().getTypeSize(T);
2578 }
2579
2580 // Format the type name as if for a diagnostic, including quotes and
2581 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002582 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002583 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2584 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002585 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002586 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002587
2588 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002589 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2590 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002591 };
2592 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2593
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002594 auto *GV = new llvm::GlobalVariable(
2595 CGM.getModule(), Descriptor->getType(),
2596 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002597 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002598 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002599
2600 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002601 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002602
Richard Smithe30752c2012-10-09 19:52:38 +00002603 return GV;
2604}
2605
2606llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2607 llvm::Type *TargetTy = IntPtrTy;
2608
Vedant Kumar8a715332017-10-03 01:27:24 +00002609 if (V->getType() == TargetTy)
2610 return V;
2611
Richard Smith48366f72013-03-22 00:47:07 +00002612 // Floating-point types which fit into intptr_t are bitcast to integers
2613 // and then passed directly (after zero-extension, if necessary).
2614 if (V->getType()->isFloatingPointTy()) {
2615 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2616 if (Bits <= TargetTy->getIntegerBitWidth())
2617 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2618 Bits));
2619 }
2620
Richard Smithe30752c2012-10-09 19:52:38 +00002621 // Integers which fit in intptr_t are zero-extended and passed directly.
2622 if (V->getType()->isIntegerTy() &&
2623 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2624 return Builder.CreateZExt(V, TargetTy);
2625
2626 // Pointers are passed directly, everything else is passed by address.
2627 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002628 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002629 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002630 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002631 }
2632 return Builder.CreatePtrToInt(V, TargetTy);
2633}
2634
2635/// \brief Emit a representation of a SourceLocation for passing to a handler
2636/// in a sanitizer runtime library. The format for this data is:
2637/// \code
2638/// struct SourceLocation {
2639/// const char *Filename;
2640/// int32_t Line, Column;
2641/// };
2642/// \endcode
2643/// For an invalid SourceLocation, the Filename pointer is null.
2644llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002645 llvm::Constant *Filename;
2646 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002647
Alexey Samsonov6c124142014-07-18 17:50:06 +00002648 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2649 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002650 StringRef FilenameString = PLoc.getFilename();
2651
2652 int PathComponentsToStrip =
2653 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2654 if (PathComponentsToStrip < 0) {
2655 assert(PathComponentsToStrip != INT_MIN);
2656 int PathComponentsToKeep = -PathComponentsToStrip;
2657 auto I = llvm::sys::path::rbegin(FilenameString);
2658 auto E = llvm::sys::path::rend(FilenameString);
2659 while (I != E && --PathComponentsToKeep)
2660 ++I;
2661
2662 FilenameString = FilenameString.substr(I - E);
2663 } else if (PathComponentsToStrip > 0) {
2664 auto I = llvm::sys::path::begin(FilenameString);
2665 auto E = llvm::sys::path::end(FilenameString);
2666 while (I != E && PathComponentsToStrip--)
2667 ++I;
2668
2669 if (I != E)
2670 FilenameString =
2671 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2672 else
2673 FilenameString = llvm::sys::path::filename(FilenameString);
2674 }
2675
2676 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002677 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2678 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2679 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002680 Line = PLoc.getLine();
2681 Column = PLoc.getColumn();
2682 } else {
2683 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2684 Line = Column = 0;
2685 }
2686
2687 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2688 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002689
2690 return llvm::ConstantStruct::getAnon(Data);
2691}
2692
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002693namespace {
2694/// \brief Specify under what conditions this check can be recovered
2695enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002696 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002697 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002698 /// Check supports recovering, runtime has both fatal (noreturn) and
2699 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002700 Recoverable,
2701 /// Runtime conditionally aborts, always need to support recovery.
2702 AlwaysRecoverable
2703};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002704}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002705
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002706static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2707 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002708 switch (Kind) {
2709 case SanitizerKind::Vptr:
2710 return CheckRecoverableKind::AlwaysRecoverable;
2711 case SanitizerKind::Return:
2712 case SanitizerKind::Unreachable:
2713 return CheckRecoverableKind::Unrecoverable;
2714 default:
2715 return CheckRecoverableKind::Recoverable;
2716 }
2717}
2718
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002719namespace {
2720struct SanitizerHandlerInfo {
2721 char const *const Name;
2722 unsigned Version;
2723};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002724}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002725
2726const SanitizerHandlerInfo SanitizerHandlers[] = {
2727#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2728 LIST_SANITIZER_CHECKS
2729#undef SANITIZER_CHECK
2730};
2731
Alexey Samsonov88459522015-01-12 22:39:12 +00002732static void emitCheckHandlerCall(CodeGenFunction &CGF,
2733 llvm::FunctionType *FnType,
2734 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002735 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002736 CheckRecoverableKind RecoverKind, bool IsFatal,
2737 llvm::BasicBlock *ContBB) {
2738 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2739 bool NeedsAbortSuffix =
2740 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002741 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002742 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2743 const StringRef CheckName = CheckInfo.Name;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002744 std::string FnName = "__ubsan_handle_" + CheckName.str();
2745 if (CheckInfo.Version && !MinimalRuntime)
2746 FnName += "_v" + llvm::utostr(CheckInfo.Version);
2747 if (MinimalRuntime)
2748 FnName += "_minimal";
2749 if (NeedsAbortSuffix)
2750 FnName += "_abort";
Alexey Samsonov88459522015-01-12 22:39:12 +00002751 bool MayReturn =
2752 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2753
2754 llvm::AttrBuilder B;
2755 if (!MayReturn) {
2756 B.addAttribute(llvm::Attribute::NoReturn)
2757 .addAttribute(llvm::Attribute::NoUnwind);
2758 }
2759 B.addAttribute(llvm::Attribute::UWTable);
2760
2761 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2762 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002763 llvm::AttributeList::get(CGF.getLLVMContext(),
2764 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002765 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002766 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2767 if (!MayReturn) {
2768 HandlerCall->setDoesNotReturn();
2769 CGF.Builder.CreateUnreachable();
2770 } else {
2771 CGF.Builder.CreateBr(ContBB);
2772 }
2773}
2774
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002775void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002776 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002777 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002778 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002779 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002780 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002781 assert(CheckHandler >= 0 &&
2782 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2783 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002784
2785 llvm::Value *FatalCond = nullptr;
2786 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002787 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002788 for (int i = 0, n = Checked.size(); i < n; ++i) {
2789 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002790 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002791 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002792 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2793 ? TrapCond
2794 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2795 ? RecoverableCond
2796 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002797 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2798 }
2799
Peter Collingbourne9881b782015-06-18 23:59:22 +00002800 if (TrapCond)
2801 EmitTrapCheck(TrapCond);
2802 if (!FatalCond && !RecoverableCond)
2803 return;
2804
Alexey Samsonov88459522015-01-12 22:39:12 +00002805 llvm::Value *JointCond;
2806 if (FatalCond && RecoverableCond)
2807 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2808 else
2809 JointCond = FatalCond ? FatalCond : RecoverableCond;
2810 assert(JointCond);
2811
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002812 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002813 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002814#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002815 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002816 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002817 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002818 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002819 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002820#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002821
Richard Smith4d1458e2012-09-08 02:08:36 +00002822 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002823 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2824 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002825 // Give hint that we very much don't expect to execute the handler
2826 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2827 llvm::MDBuilder MDHelper(getLLVMContext());
2828 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2829 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002830 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002831
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002832 // Handler functions take an i8* pointing to the (handler-specific) static
2833 // information block, followed by a sequence of intptr_t arguments
2834 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002835 SmallVector<llvm::Value *, 4> Args;
2836 SmallVector<llvm::Type *, 4> ArgTypes;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002837 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
2838 Args.reserve(DynamicArgs.size() + 1);
2839 ArgTypes.reserve(DynamicArgs.size() + 1);
Richard Smithe30752c2012-10-09 19:52:38 +00002840
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002841 // Emit handler arguments and create handler function type.
2842 if (!StaticArgs.empty()) {
2843 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2844 auto *InfoPtr =
2845 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2846 llvm::GlobalVariable::PrivateLinkage, Info);
2847 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2848 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2849 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2850 ArgTypes.push_back(Int8PtrTy);
2851 }
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002852
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002853 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2854 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2855 ArgTypes.push_back(IntPtrTy);
2856 }
Richard Smithe30752c2012-10-09 19:52:38 +00002857 }
2858
2859 llvm::FunctionType *FnType =
2860 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002861
Alexey Samsonov88459522015-01-12 22:39:12 +00002862 if (!FatalCond || !RecoverableCond) {
2863 // Simple case: we need to generate a single handler call, either
2864 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002865 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002866 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002867 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002868 // Emit two handler calls: first one for set of unrecoverable checks,
2869 // another one for recoverable.
2870 llvm::BasicBlock *NonFatalHandlerBB =
2871 createBasicBlock("non_fatal." + CheckName);
2872 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2873 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2874 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002875 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002876 NonFatalHandlerBB);
2877 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002878 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002879 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002880 }
Richard Smithe30752c2012-10-09 19:52:38 +00002881
Richard Smith4d1458e2012-09-08 02:08:36 +00002882 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002883}
2884
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002885void CodeGenFunction::EmitCfiSlowPathCheck(
2886 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2887 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002888 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2889
2890 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2891 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2892
2893 llvm::MDBuilder MDHelper(getLLVMContext());
2894 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2895 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2896
2897 EmitBlock(CheckBB);
2898
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002899 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2900
2901 llvm::CallInst *CheckCall;
2902 if (WithDiag) {
2903 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2904 auto *InfoPtr =
2905 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2906 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002907 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002908 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2909
2910 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2911 "__cfi_slowpath_diag",
2912 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2913 false));
2914 CheckCall = Builder.CreateCall(
2915 SlowPathDiagFn,
2916 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2917 } else {
2918 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2919 "__cfi_slowpath",
2920 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2921 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2922 }
2923
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002924 CheckCall->setDoesNotThrow();
2925
2926 EmitBlock(Cont);
2927}
2928
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00002929// Emit a stub for __cfi_check function so that the linker knows about this
2930// symbol in LTO mode.
2931void CodeGenFunction::EmitCfiCheckStub() {
2932 llvm::Module *M = &CGM.getModule();
2933 auto &Ctx = M->getContext();
2934 llvm::Function *F = llvm::Function::Create(
2935 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2936 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2937 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2938 // FIXME: consider emitting an intrinsic call like
2939 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2940 // which can be lowered in CrossDSOCFI pass to the actual contents of
2941 // __cfi_check. This would allow inlining of __cfi_check calls.
2942 llvm::CallInst::Create(
2943 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2944 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2945}
2946
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002947// This function is basically a switch over the CFI failure kind, which is
2948// extracted from CFICheckFailData (1st function argument). Each case is either
2949// llvm.trap or a call to one of the two runtime handlers, based on
2950// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2951// failure kind) traps, but this should really never happen. CFICheckFailData
2952// can be nullptr if the calling module has -fsanitize-trap behavior for this
2953// check kind; in this case __cfi_check_fail traps as well.
2954void CodeGenFunction::EmitCfiCheckFail() {
2955 SanitizerScope SanScope(this);
2956 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002957 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2958 ImplicitParamDecl::Other);
2959 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2960 ImplicitParamDecl::Other);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002961 Args.push_back(&ArgData);
2962 Args.push_back(&ArgAddr);
2963
John McCallc56a8b32016-03-11 04:30:31 +00002964 const CGFunctionInfo &FI =
2965 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002966
2967 llvm::Function *F = llvm::Function::Create(
2968 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2969 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2970 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2971
2972 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2973 SourceLocation());
2974
2975 llvm::Value *Data =
2976 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2977 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2978 llvm::Value *Addr =
2979 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2980 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2981
2982 // Data == nullptr means the calling module has trap behaviour for this check.
2983 llvm::Value *DataIsNotNullPtr =
2984 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2985 EmitTrapCheck(DataIsNotNullPtr);
2986
2987 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002988 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002989 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002990 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002991
2992 llvm::Value *V = Builder.CreateConstGEP2_32(
2993 CfiCheckFailDataTy,
2994 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2995 0);
2996 Address CheckKindAddr(V, getIntAlign());
2997 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2998
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002999 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3000 CGM.getLLVMContext(),
3001 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3002 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00003003 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003004 {Addr, AllVtables}),
3005 IntPtrTy);
3006
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00003007 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003008 {CFITCK_VCall, SanitizerKind::CFIVCall},
3009 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3010 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3011 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3012 {CFITCK_ICall, SanitizerKind::CFIICall}};
3013
3014 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3015 for (auto CheckKindMaskPair : CheckKinds) {
3016 int Kind = CheckKindMaskPair.first;
3017 SanitizerMask Mask = CheckKindMaskPair.second;
3018 llvm::Value *Cond =
3019 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003020 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003021 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003022 {Data, Addr, ValidVtable});
3023 else
3024 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003025 }
3026
3027 FinishFunction();
3028 // The only reference to this function will be created during LTO link.
3029 // Make sure it survives until then.
3030 CGM.addUsedGlobal(F);
3031}
3032
Chad Rosierae229d52013-01-29 23:31:22 +00003033void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00003034 llvm::BasicBlock *Cont = createBasicBlock("cont");
3035
3036 // If we're optimizing, collapse all calls to trap down to just one per
3037 // function to save on code size.
3038 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3039 TrapBB = createBasicBlock("trap");
3040 Builder.CreateCondBr(Checked, Cont, TrapBB);
3041 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003042 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00003043 TrapCall->setDoesNotReturn();
3044 TrapCall->setDoesNotThrow();
3045 Builder.CreateUnreachable();
3046 } else {
3047 Builder.CreateCondBr(Checked, Cont, TrapBB);
3048 }
3049
3050 EmitBlock(Cont);
3051}
3052
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003053llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00003054 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003055
Amaury Sechet21f51b32016-09-09 04:42:49 +00003056 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3057 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3058 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00003059 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00003060 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003061
3062 return TrapCall;
3063}
3064
John McCall7f416cc2015-09-08 08:05:57 +00003065Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003066 LValueBaseInfo *BaseInfo,
3067 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00003068 assert(E->getType()->isArrayType() &&
3069 "Array to pointer decay must have array source type!");
3070
3071 // Expressions of array type can't be bitfields or vector elements.
3072 LValue LV = EmitLValue(E);
3073 Address Addr = LV.getAddress();
John McCall7f416cc2015-09-08 08:05:57 +00003074
3075 // If the array type was an incomplete type, we need to make sure
3076 // the decay ends up being the right type.
3077 llvm::Type *NewTy = ConvertType(E->getType());
3078 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3079
3080 // Note that VLA pointers are always decayed, so we don't need to do
3081 // anything here.
3082 if (!E->getType()->isVariableArrayType()) {
3083 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3084 "Expected pointer to array");
3085 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3086 }
3087
Ivan A. Kosarevf761d0e2017-10-20 12:35:17 +00003088 // The result of this decay conversion points to an array element within the
3089 // base lvalue. However, since TBAA currently does not support representing
3090 // accesses to elements of member arrays, we conservatively represent accesses
3091 // to the pointee object as if it had no any base lvalue specified.
3092 // TODO: Support TBAA for member arrays.
John McCall7f416cc2015-09-08 08:05:57 +00003093 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
Ivan A. Kosarevf761d0e2017-10-20 12:35:17 +00003094 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3095 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3096
John McCall7f416cc2015-09-08 08:05:57 +00003097 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3098}
3099
Chris Lattner6c5abe82010-06-26 23:03:20 +00003100/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3101/// array to pointer, return the array subexpression.
3102static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3103 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003104 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00003105 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00003106 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003107
Chris Lattner6c5abe82010-06-26 23:03:20 +00003108 // If this is a decay from variable width array, bail out.
3109 const Expr *SubExpr = CE->getSubExpr();
3110 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00003111 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003112
Chris Lattner6c5abe82010-06-26 23:03:20 +00003113 return SubExpr;
3114}
3115
John McCall7f416cc2015-09-08 08:05:57 +00003116static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3117 llvm::Value *ptr,
3118 ArrayRef<llvm::Value*> indices,
3119 bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003120 bool signedIndices,
Vedant Kumara125eb52017-06-01 19:22:18 +00003121 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003122 const llvm::Twine &name = "arrayidx") {
3123 if (inbounds) {
Vedant Kumar175b6d12017-07-13 20:55:26 +00003124 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3125 CodeGenFunction::NotSubtraction, loc,
3126 name);
John McCall7f416cc2015-09-08 08:05:57 +00003127 } else {
3128 return CGF.Builder.CreateGEP(ptr, indices, name);
3129 }
3130}
3131
3132static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3133 llvm::Value *idx,
3134 CharUnits eltSize) {
3135 // If we have a constant index, we can use the exact offset of the
3136 // element we're accessing.
3137 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3138 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3139 return arrayAlign.alignmentAtOffset(offset);
3140
3141 // Otherwise, use the worst-case alignment for any element.
3142 } else {
3143 return arrayAlign.alignmentOfArrayElement(eltSize);
3144 }
3145}
3146
3147static QualType getFixedSizeElementType(const ASTContext &ctx,
3148 const VariableArrayType *vla) {
3149 QualType eltType;
3150 do {
3151 eltType = vla->getElementType();
3152 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3153 return eltType;
3154}
3155
3156static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
Vedant Kumara125eb52017-06-01 19:22:18 +00003157 ArrayRef<llvm::Value *> indices,
John McCall7f416cc2015-09-08 08:05:57 +00003158 QualType eltType, bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003159 bool signedIndices, SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003160 const llvm::Twine &name = "arrayidx") {
3161 // All the indices except that last must be zero.
3162#ifndef NDEBUG
3163 for (auto idx : indices.drop_back())
3164 assert(isa<llvm::ConstantInt>(idx) &&
3165 cast<llvm::ConstantInt>(idx)->isZero());
3166#endif
3167
3168 // Determine the element size of the statically-sized base. This is
3169 // the thing that the indices are expressed in terms of.
3170 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3171 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3172 }
3173
3174 // We can use that to compute the best alignment of the element.
3175 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3176 CharUnits eltAlign =
3177 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3178
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003179 llvm::Value *eltPtr = emitArraySubscriptGEP(
3180 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
John McCall7f416cc2015-09-08 08:05:57 +00003181 return Address(eltPtr, eltAlign);
3182}
3183
Richard Smith539e4a72013-02-23 02:53:19 +00003184LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3185 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003186 // The index must always be an integer, which is not an aggregate. Emit it
3187 // in lexical order (this complexity is, sadly, required by C++17).
3188 llvm::Value *IdxPre =
3189 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003190 bool SignedIndices = false;
Richard Smith40885712016-09-27 00:53:24 +00003191 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003192 auto *Idx = IdxPre;
3193 if (E->getLHS() != E->getIdx()) {
3194 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3195 Idx = EmitScalarExpr(E->getIdx());
3196 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003197
Richard Smith9e67b992016-09-26 23:49:47 +00003198 QualType IdxTy = E->getIdx()->getType();
3199 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003200 SignedIndices |= IdxSigned;
Richard Smith9e67b992016-09-26 23:49:47 +00003201
3202 if (SanOpts.has(SanitizerKind::ArrayBounds))
3203 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3204
3205 // Extend or truncate the index type to 32 or 64-bits.
3206 if (Promote && Idx->getType() != IntPtrTy)
3207 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3208
3209 return Idx;
3210 };
3211 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003212
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003213 // If the base is a vector type, then we are forming a vector element lvalue
3214 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003215 if (E->getBase()->getType()->isVectorType() &&
3216 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003217 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003218 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003219 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003220 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003221 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
3222 LHS.getBaseInfo(), TBAAAccessInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003223 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003224
John McCall7f416cc2015-09-08 08:05:57 +00003225 // All the other cases basically behave like simple offsetting.
3226
John McCall7f416cc2015-09-08 08:05:57 +00003227 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003228 if (isa<ExtVectorElementExpr>(E->getBase())) {
3229 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003230 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003231 Address Addr = EmitExtVectorElementLValue(LV);
3232
3233 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
Vedant Kumara125eb52017-06-01 19:22:18 +00003234 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003235 SignedIndices, E->getExprLoc());
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00003236 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003237 CGM.getTBAAInfoForSubobject(LV, EltType));
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003238 }
John McCall7f416cc2015-09-08 08:05:57 +00003239
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003240 LValueBaseInfo EltBaseInfo;
3241 TBAAAccessInfo EltTBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003242 Address Addr = Address::invalid();
3243 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003244 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003245 // The base must be a pointer, which is not an aggregate. Emit
3246 // it. It needs to be emitted first in case it's what captures
3247 // the VLA bounds.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003248 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003249 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003250
John McCall23c29fe2011-06-24 21:55:10 +00003251 // The element count here is the total number of non-VLA elements.
3252 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003253
John McCall77527a82011-06-25 01:32:37 +00003254 // Effectively, the multiply by the VLA size is part of the GEP.
3255 // GEP indexes are signed, and scaling an index isn't permitted to
3256 // signed-overflow, so we use the same semantics for our explicit
3257 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003258 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003259 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003260 } else {
3261 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003262 }
John McCall7f416cc2015-09-08 08:05:57 +00003263
3264 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003265 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003266 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003267
Chris Lattner6c5abe82010-06-26 23:03:20 +00003268 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3269 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003270
John McCall7f416cc2015-09-08 08:05:57 +00003271 // Emit the base pointer.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003272 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003273 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3274
3275 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3276 llvm::Value *InterfaceSizeVal =
3277 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3278
3279 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003280
3281 // We don't necessarily build correct LLVM struct types for ObjC
3282 // interfaces, so we can't rely on GEP to do this scaling
3283 // correctly, so we need to cast to i8*. FIXME: is this actually
3284 // true? A lot of other things in the fragile ABI would break...
3285 llvm::Type *OrigBaseTy = Addr.getType();
3286 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3287
3288 // Do the GEP.
3289 CharUnits EltAlign =
3290 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003291 llvm::Value *EltPtr =
3292 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3293 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003294 Addr = Address(EltPtr, EltAlign);
3295
3296 // Cast back.
3297 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003298 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3299 // If this is A[i] where A is an array, the frontend will have decayed the
3300 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3301 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3302 // "gep x, i" here. Emit one "gep A, 0, i".
3303 assert(Array->getType()->isArrayType() &&
3304 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003305 LValue ArrayLV;
3306 // For simple multidimensional array indexing, set the 'accessed' flag for
3307 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003308 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003309 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3310 else
3311 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003312 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003313
Daniel Dunbar82634272011-04-01 00:49:43 +00003314 // Propagate the alignment from the array itself to the result.
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003315 Addr = emitArraySubscriptGEP(
3316 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3317 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3318 E->getExprLoc());
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003319 EltBaseInfo = ArrayLV.getBaseInfo();
3320 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003321 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003322 // The base must be a pointer; emit it with an estimate of its alignment.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003323 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003324 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003325 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003326 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003327 SignedIndices, E->getExprLoc());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003328 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003329
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003330 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
John McCall8ccfcb52009-09-24 19:53:00 +00003331
Richard Smith9c6890a2012-11-01 22:30:59 +00003332 if (getLangOpts().ObjC1 &&
3333 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003334 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003335 setObjCGCLValueClass(getContext(), E, LV);
3336 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003337 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003338}
3339
Alexey Bataev31300ed2016-02-04 11:27:03 +00003340static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003341 LValueBaseInfo &BaseInfo,
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003342 TBAAAccessInfo &TBAAInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003343 QualType BaseTy, QualType ElTy,
3344 bool IsLowerBound) {
3345 LValue BaseLVal;
3346 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3347 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3348 if (BaseTy->isArrayType()) {
3349 Address Addr = BaseLVal.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003350 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003351
3352 // If the array type was an incomplete type, we need to make sure
3353 // the decay ends up being the right type.
3354 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3355 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3356
3357 // Note that VLA pointers are always decayed, so we don't need to do
3358 // anything here.
3359 if (!BaseTy->isVariableArrayType()) {
3360 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3361 "Expected pointer to array");
3362 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3363 "arraydecay");
3364 }
3365
3366 return CGF.Builder.CreateElementBitCast(Addr,
3367 CGF.ConvertTypeForMem(ElTy));
3368 }
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003369 LValueBaseInfo TypeBaseInfo;
3370 TBAAAccessInfo TypeTBAAInfo;
3371 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeBaseInfo,
3372 &TypeTBAAInfo);
3373 BaseInfo.mergeForCast(TypeBaseInfo);
3374 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003375 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3376 }
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003377 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003378}
3379
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003380LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3381 bool IsLowerBound) {
Alexey Bataev7b0f1f02017-10-12 15:18:41 +00003382 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003383 QualType ResultExprTy;
3384 if (auto *AT = getContext().getAsArrayType(BaseTy))
3385 ResultExprTy = AT->getElementType();
3386 else
3387 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003388 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003389 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003390 // Requesting lower bound or upper bound, but without provided length and
3391 // without ':' symbol for the default length -> length = 1.
3392 // Idx = LowerBound ?: 0;
3393 if (auto *LowerBound = E->getLowerBound()) {
3394 Idx = Builder.CreateIntCast(
3395 EmitScalarExpr(LowerBound), IntPtrTy,
3396 LowerBound->getType()->hasSignedIntegerRepresentation());
3397 } else
3398 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3399 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003400 // Try to emit length or lower bound as constant. If this is possible, 1
3401 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3402 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003403 auto &C = CGM.getContext();
3404 auto *Length = E->getLength();
3405 llvm::APSInt ConstLength;
3406 if (Length) {
3407 // Idx = LowerBound + Length - 1;
3408 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3409 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3410 Length = nullptr;
3411 }
3412 auto *LowerBound = E->getLowerBound();
3413 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3414 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3415 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3416 LowerBound = nullptr;
3417 }
3418 if (!Length)
3419 --ConstLength;
3420 else if (!LowerBound)
3421 --ConstLowerBound;
3422
3423 if (Length || LowerBound) {
3424 auto *LowerBoundVal =
3425 LowerBound
3426 ? Builder.CreateIntCast(
3427 EmitScalarExpr(LowerBound), IntPtrTy,
3428 LowerBound->getType()->hasSignedIntegerRepresentation())
3429 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3430 auto *LengthVal =
3431 Length
3432 ? Builder.CreateIntCast(
3433 EmitScalarExpr(Length), IntPtrTy,
3434 Length->getType()->hasSignedIntegerRepresentation())
3435 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3436 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3437 /*HasNUW=*/false,
3438 !getLangOpts().isSignedOverflowDefined());
3439 if (Length && LowerBound) {
3440 Idx = Builder.CreateSub(
3441 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3442 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3443 }
3444 } else
3445 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3446 } else {
3447 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003448 QualType ArrayTy = BaseTy->isPointerType()
3449 ? E->getBase()->IgnoreParenImpCasts()->getType()
3450 : BaseTy;
3451 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003452 Length = VAT->getSizeExpr();
3453 if (Length->isIntegerConstantExpr(ConstLength, C))
3454 Length = nullptr;
3455 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003456 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003457 ConstLength = CAT->getSize();
3458 }
3459 if (Length) {
3460 auto *LengthVal = Builder.CreateIntCast(
3461 EmitScalarExpr(Length), IntPtrTy,
3462 Length->getType()->hasSignedIntegerRepresentation());
3463 Idx = Builder.CreateSub(
3464 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3465 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3466 } else {
3467 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3468 --ConstLength;
3469 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3470 }
3471 }
3472 }
3473 assert(Idx);
3474
Alexey Bataev31300ed2016-02-04 11:27:03 +00003475 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003476 LValueBaseInfo BaseInfo;
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003477 TBAAAccessInfo TBAAInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003478 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003479 // The base must be a pointer, which is not an aggregate. Emit
3480 // it. It needs to be emitted first in case it's what captures
3481 // the VLA bounds.
3482 Address Base =
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003483 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
3484 BaseTy, VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003485 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003486 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003487
3488 // Effectively, the multiply by the VLA size is part of the GEP.
3489 // GEP indexes are signed, and scaling an index isn't permitted to
3490 // signed-overflow, so we use the same semantics for our explicit
3491 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003492 if (getLangOpts().isSignedOverflowDefined())
3493 Idx = Builder.CreateMul(Idx, NumElements);
3494 else
3495 Idx = Builder.CreateNSWMul(Idx, NumElements);
3496 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003497 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003498 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003499 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3500 // If this is A[i] where A is an array, the frontend will have decayed the
3501 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3502 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3503 // "gep x, i" here. Emit one "gep A, 0, i".
3504 assert(Array->getType()->isArrayType() &&
3505 "Array to pointer decay must have array source type!");
3506 LValue ArrayLV;
3507 // For simple multidimensional array indexing, set the 'accessed' flag for
3508 // better bounds-checking of the base expression.
3509 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3510 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3511 else
3512 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003513
Alexey Bataev31300ed2016-02-04 11:27:03 +00003514 // Propagate the alignment from the array itself to the result.
3515 EltPtr = emitArraySubscriptGEP(
3516 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumara125eb52017-06-01 19:22:18 +00003517 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003518 /*SignedIndices=*/false, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003519 BaseInfo = ArrayLV.getBaseInfo();
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003520 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003521 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003522 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003523 TBAAInfo, BaseTy, ResultExprTy,
3524 IsLowerBound);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003525 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
Vedant Kumara125eb52017-06-01 19:22:18 +00003526 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003527 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003528 }
3529
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003530 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003531}
3532
Chris Lattner9e751ca2007-08-02 23:37:31 +00003533LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003534EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003535 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003536 LValue Base;
3537
3538 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003539 if (E->isArrow()) {
3540 // If it is a pointer to a vector, emit the address and form an lvalue with
3541 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003542 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003543 TBAAAccessInfo TBAAInfo;
3544 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003545 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003546 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003547 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003548 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003549 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3550 // emit the base as an lvalue.
3551 assert(E->getBase()->getType()->isVectorType());
3552 Base = EmitLValue(E->getBase());
3553 } else {
3554 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003555 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003556 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003557 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003558
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003559 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003560 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003561 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003562 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003563 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003564 }
John McCall1553b192011-06-16 04:16:24 +00003565
3566 QualType type =
3567 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003568
Nate Begemand3862152008-05-13 21:03:02 +00003569 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003570 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003571 E->getEncodedElementAccess(Indices);
3572
3573 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003574 llvm::Constant *CV =
3575 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003576 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003577 Base.getBaseInfo(), TBAAAccessInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003578 }
3579 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3580
3581 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003582 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003583
Chris Lattner595ba3a2012-01-30 06:20:36 +00003584 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3585 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003586 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003587 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003588 Base.getBaseInfo(), TBAAAccessInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003589}
3590
Devang Patel30efa2e2007-10-23 20:28:39 +00003591LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00003592 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3593 EmitIgnoredExpr(E->getBase());
3594 return EmitDeclRefLValue(DRE);
3595 }
3596
Devang Pateld68df202007-10-24 22:26:28 +00003597 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003598 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
Eli Friedman7f1ff602012-04-16 03:54:45 +00003599 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003600 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003601 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003602 TBAAAccessInfo TBAAInfo;
3603 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003604 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003605 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003606 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3607 if (IsBaseCXXThis)
3608 SkippedChecks.set(SanitizerKind::Alignment, true);
3609 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003610 SkippedChecks.set(SanitizerKind::Null, true);
3611 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3612 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003613 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003614 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003615 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003616
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003617 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003618 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003619 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003620 setObjCGCLValueClass(getContext(), E, LV);
3621 return LV;
3622 }
Craig Topper99e79272013-07-26 05:59:26 +00003623
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003624 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003625 return EmitFunctionDeclLValue(*this, E, FD);
3626
David Blaikie83d382b2011-09-23 05:06:16 +00003627 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003628}
Devang Patel30efa2e2007-10-23 20:28:39 +00003629
John McCalldec348f72013-05-03 07:33:41 +00003630/// Given that we are currently emitting a lambda, emit an l-value for
3631/// one of its members.
3632LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3633 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3634 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3635 QualType LambdaTagType =
3636 getContext().getTagDeclType(Field->getParent());
3637 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3638 return EmitLValueForField(LambdaLV, Field);
3639}
3640
John McCall7f416cc2015-09-08 08:05:57 +00003641/// Drill down to the storage of a field without walking into
3642/// reference types.
3643///
3644/// The resulting address doesn't necessarily have the right type.
3645static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3646 const FieldDecl *field) {
3647 const RecordDecl *rec = field->getParent();
3648
3649 unsigned idx =
3650 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3651
3652 CharUnits offset;
3653 // Adjust the alignment down to the given offset.
3654 // As a special case, if the LLVM field index is 0, we know that this
3655 // is zero.
3656 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3657 .getFieldOffset(field->getFieldIndex()) == 0) &&
3658 "LLVM field at index zero had non-zero offset?");
3659 if (idx != 0) {
3660 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3661 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3662 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3663 }
3664
3665 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3666}
3667
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003668static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3669 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3670 if (!RD)
3671 return false;
3672
3673 if (RD->isDynamicClass())
3674 return true;
3675
3676 for (const auto &Base : RD->bases())
3677 if (hasAnyVptr(Base.getType(), Context))
3678 return true;
3679
3680 for (const FieldDecl *Field : RD->fields())
3681 if (hasAnyVptr(Field->getType(), Context))
3682 return true;
3683
3684 return false;
3685}
3686
Eli Friedman7f1ff602012-04-16 03:54:45 +00003687LValue CodeGenFunction::EmitLValueForField(LValue base,
3688 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003689 LValueBaseInfo BaseInfo = base.getBaseInfo();
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003690
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003691 if (field->isBitField()) {
3692 const CGRecordLayout &RL =
3693 CGM.getTypes().getCGRecordLayout(field->getParent());
3694 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003695 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003696 unsigned Idx = RL.getLLVMFieldNo(field);
3697 if (Idx != 0)
3698 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003699 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3700 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003701 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003702 llvm::Type *FieldIntTy =
3703 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3704 if (Addr.getElementType() != FieldIntTy)
3705 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003706
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003707 QualType fieldType =
3708 field->getType().withCVRQualifiers(base.getVRQualifiers());
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003709 // TODO: Support TBAA for bit fields.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003710 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003711 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
3712 TBAAAccessInfo());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003713 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003714
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003715 // Fields of may-alias structures are may-alias themselves.
3716 // FIXME: this should get propagated down through anonymous structs
3717 // and unions.
3718 QualType FieldType = field->getType();
3719 const RecordDecl *rec = field->getParent();
3720 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003721 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003722 TBAAAccessInfo FieldTBAAInfo;
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003723 if (base.getTBAAInfo().isMayAlias() ||
3724 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
3725 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003726 } else {
3727 // If no base type been assigned for the base access, then try to generate
3728 // one for this base lvalue.
3729 FieldTBAAInfo = base.getTBAAInfo();
3730 if (!FieldTBAAInfo.BaseType) {
3731 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
3732 assert(!FieldTBAAInfo.Offset &&
3733 "Nonzero offset for an access with no base type!");
3734 }
3735
Ivan A. Kosarevda342472017-11-30 09:26:39 +00003736 // All union members are encoded to be of the same special type.
3737 if (FieldTBAAInfo.BaseType && rec->isUnion())
3738 FieldTBAAInfo = TBAAAccessInfo::getUnionMemberInfo(FieldTBAAInfo.BaseType,
3739 FieldTBAAInfo.Offset,
3740 FieldTBAAInfo.Size);
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003741
Ivan A. Kosarevda342472017-11-30 09:26:39 +00003742 // For now we describe accesses to direct and indirect union members as if
3743 // they were at the offset of their outermost enclosing union.
3744 if (!FieldTBAAInfo.isUnionMember()) {
3745 // Adjust offset to be relative to the base type.
3746 const ASTRecordLayout &Layout =
3747 getContext().getASTRecordLayout(field->getParent());
3748 unsigned CharWidth = getContext().getCharWidth();
3749 if (FieldTBAAInfo.BaseType)
3750 FieldTBAAInfo.Offset +=
3751 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
3752
3753 // Update the final access type.
3754 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
3755 }
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003756 }
3757
John McCall7f416cc2015-09-08 08:05:57 +00003758 Address addr = base.getAddress();
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003759 unsigned RecordCVR = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00003760 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003761 // For unions, there is no pointer adjustment.
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003762 assert(!FieldType->isReferenceType() && "union has reference member");
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003763 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3764 hasAnyVptr(FieldType, getContext()))
3765 // Because unions can easily skip invariant.barriers, we need to add
3766 // a barrier every time CXXRecord field with vptr is referenced.
3767 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3768 addr.getAlignment());
John McCall53fcbd22011-02-26 08:07:02 +00003769 } else {
3770 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003771 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003772
3773 // If this is a reference field, load the reference right now.
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003774 if (FieldType->isReferenceType()) {
3775 LValue RefLVal = MakeAddrLValue(addr, FieldType, FieldBaseInfo,
3776 FieldTBAAInfo);
3777 if (RecordCVR & Qualifiers::Volatile)
3778 RefLVal.getQuals().setVolatile(true);
3779 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003780
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003781 // Qualifiers on the struct don't apply to the referencee.
3782 RecordCVR = 0;
3783 FieldType = FieldType->getPointeeType();
John McCall53fcbd22011-02-26 08:07:02 +00003784 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003785 }
Craig Topper99e79272013-07-26 05:59:26 +00003786
Chris Lattner13ee4f42011-07-10 05:34:54 +00003787 // Make sure that the address is pointing to the right type. This is critical
3788 // for both unions and structs. A union needs a bitcast, a struct element
3789 // will need a bitcast if the LLVM type laid out doesn't match the desired
3790 // type.
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003791 addr = Builder.CreateElementBitCast(
3792 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003793
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003794 if (field->hasAttr<AnnotateAttr>())
3795 addr = EmitFieldAnnotations(field, addr);
3796
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003797 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003798 LV.getQuals().addCVRQualifiers(RecordCVR);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00003799
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003800 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003801 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3802 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003803
Daniel Dunbarf166a522010-08-21 03:44:13 +00003804 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003805}
3806
Craig Topper99e79272013-07-26 05:59:26 +00003807LValue
3808CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003809 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003810 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003811
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003812 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003813 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003814
John McCall7f416cc2015-09-08 08:05:57 +00003815 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003816
John McCall7f416cc2015-09-08 08:05:57 +00003817 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003818 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003819 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003820
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003821 // TODO: Generate TBAA information that describes this access as a structure
3822 // member access and not just an access to an object of the field's type. This
3823 // should be similar to what we do in EmitLValueForField().
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003824 LValueBaseInfo BaseInfo = Base.getBaseInfo();
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003825 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
3826 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00003827 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003828 CGM.getTBAAInfoForSubobject(Base, FieldType));
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003829}
3830
Chris Lattnerf53c0962010-09-06 00:11:41 +00003831LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003832 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003833 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003834 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003835 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003836 if (E->getType()->isVariablyModifiedType())
3837 // make sure to emit the VLA size.
3838 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003839
John McCall7f416cc2015-09-08 08:05:57 +00003840 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003841 const Expr *InitExpr = E->getInitializer();
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003842 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003843
Chad Rosier615ed1a2012-03-29 17:37:10 +00003844 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3845 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003846
3847 return Result;
3848}
3849
Richard Smithbb653bd2012-05-14 21:57:21 +00003850LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3851 if (!E->isGLValue())
3852 // Initializing an aggregate temporary in C++11: T{...}.
3853 return EmitAggExprToLValue(E);
3854
3855 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003856 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003857 return EmitLValue(E->getInit(0));
3858}
3859
Richard Smithf3076ff2014-06-20 18:43:47 +00003860/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3861/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3862/// LValue is returned and the current block has been terminated.
3863static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3864 const Expr *Operand) {
3865 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3866 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3867 return None;
3868 }
3869
3870 return CGF.EmitLValue(Operand);
3871}
3872
John McCallc07a0c72011-02-17 10:25:35 +00003873LValue CodeGenFunction::
3874EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3875 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003876 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003877 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003878 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003879 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003880 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003881
Eli Friedman59954892012-01-25 05:04:17 +00003882 OpaqueValueMapping binding(*this, expr);
3883
John McCallc07a0c72011-02-17 10:25:35 +00003884 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003885 bool CondExprBool;
3886 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003887 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003888 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003889
Justin Bogneref512b92014-01-06 22:27:43 +00003890 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003891 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003892 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003893 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003894 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003895 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003896 }
3897
John McCallc07a0c72011-02-17 10:25:35 +00003898 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3899 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3900 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003901
3902 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003903 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003904
John McCall0a6bf2e2011-01-26 19:21:13 +00003905 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003906 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003907 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003908 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003909 Optional<LValue> lhs =
3910 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003911 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003912
Richard Smithf3076ff2014-06-20 18:43:47 +00003913 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003914 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003915
John McCallc07a0c72011-02-17 10:25:35 +00003916 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003917 if (lhs)
3918 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003919
John McCall0a6bf2e2011-01-26 19:21:13 +00003920 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003921 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003922 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003923 Optional<LValue> rhs =
3924 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003925 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003926 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003927 return EmitUnsupportedLValue(expr, "conditional operator");
3928 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003929
John McCallc07a0c72011-02-17 10:25:35 +00003930 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003931
Richard Smithf3076ff2014-06-20 18:43:47 +00003932 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003933 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003934 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003935 phi->addIncoming(lhs->getPointer(), lhsBlock);
3936 phi->addIncoming(rhs->getPointer(), rhsBlock);
3937 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3938 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003939 std::max(lhs->getBaseInfo().getAlignmentSource(),
3940 rhs->getBaseInfo().getAlignmentSource());
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003941 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
3942 lhs->getTBAAInfo(), rhs->getTBAAInfo());
3943 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
3944 TBAAInfo);
Richard Smithf3076ff2014-06-20 18:43:47 +00003945 } else {
3946 assert((lhs || rhs) &&
3947 "both operands of glvalue conditional are throw-expressions?");
3948 return lhs ? *lhs : *rhs;
3949 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003950}
3951
Richard Smithbb653bd2012-05-14 21:57:21 +00003952/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3953/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003954/// otherwise if a cast is needed by the code generator in an lvalue context,
3955/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003956/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003957/// are permitted with aggregate result, including noop aggregate casts, and
3958/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003959LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003960 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003961 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003962 case CK_BitCast:
3963 case CK_ArrayToPointerDecay:
3964 case CK_FunctionToPointerDecay:
3965 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003966 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003967 case CK_IntegralToPointer:
3968 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003969 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003970 case CK_VectorSplat:
3971 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003972 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003973 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003974 case CK_IntegralToFloating:
3975 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003976 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003977 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003978 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003979 case CK_FloatingComplexToReal:
3980 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003981 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003982 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003983 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003984 case CK_IntegralComplexToReal:
3985 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003986 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003987 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003988 case CK_DerivedToBaseMemberPointer:
3989 case CK_BaseToDerivedMemberPointer:
3990 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003991 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003992 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003993 case CK_ARCProduceObject:
3994 case CK_ARCConsumeObject:
3995 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003996 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003997 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003998 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003999 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004000 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4001
4002 case CK_Dependent:
4003 llvm_unreachable("dependent cast kind in IR gen!");
4004
4005 case CK_BuiltinFnToFnPtr:
4006 llvm_unreachable("builtin functions are handled elsewhere");
4007
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004008 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004009 case CK_NonAtomicToAtomic:
4010 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004011 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00004012
Anders Carlsson8a01a752011-04-11 02:03:26 +00004013 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00004014 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004015 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004016 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00004017 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00004018 }
4019
John McCalle3027922010-08-25 11:45:40 +00004020 case CK_ConstructorConversion:
4021 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00004022 case CK_CPointerToObjCPointerCast:
4023 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004024 case CK_NoOp:
4025 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004026 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00004027
John McCalle3027922010-08-25 11:45:40 +00004028 case CK_UncheckedDerivedToBase:
4029 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00004030 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00004031 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004032 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004033
Anders Carlssond95f9602009-09-12 16:16:49 +00004034 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004035 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00004036
Anders Carlssond95f9602009-09-12 16:16:49 +00004037 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00004038 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00004039 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4040 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00004041
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004042 // TODO: Support accesses to members of base classes in TBAA. For now, we
4043 // conservatively pretend that the complete object is of the base class
4044 // type.
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004045 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004046 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Anders Carlssond95f9602009-09-12 16:16:49 +00004047 }
John McCalle3027922010-08-25 11:45:40 +00004048 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00004049 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00004050 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00004051 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004052 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004053
Anders Carlsson8c793172009-11-23 17:57:54 +00004054 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00004055
Anders Carlsson8c793172009-11-23 17:57:54 +00004056 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00004057 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00004058 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00004059 E->path_begin(), E->path_end(),
4060 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00004061
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004062 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4063 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00004064 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004065 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00004066 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004067
Peter Collingbourned2926c92015-03-14 02:42:25 +00004068 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004069 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4070 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004071 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004072
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004073 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004074 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Eli Friedman8c98dff2009-11-16 05:48:01 +00004075 }
John McCalle3027922010-08-25 11:45:40 +00004076 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00004077 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004078 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00004079
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00004080 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00004081 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004082 Address V = Builder.CreateBitCast(LV.getAddress(),
4083 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00004084
4085 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004086 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4087 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004088 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004089
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004090 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004091 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Anders Carlsson50cb3212009-11-14 21:21:42 +00004092 }
John McCalle3027922010-08-25 11:45:40 +00004093 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004094 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004095 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4096 ConvertType(E->getType()));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004097 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004098 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004099 }
Egor Churaev89831422016-12-23 14:55:49 +00004100 case CK_ZeroToOCLQueue:
4101 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004102 case CK_ZeroToOCLEvent:
4103 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00004104 }
Craig Topper99e79272013-07-26 05:59:26 +00004105
Douglas Gregorcdb466e2010-07-15 18:58:16 +00004106 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004107}
4108
John McCall1bf58462011-02-16 08:02:54 +00004109LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00004110 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00004111 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00004112}
4113
Eli Friedman7f1ff602012-04-16 03:54:45 +00004114RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004115 const FieldDecl *FD,
4116 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004117 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00004118 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00004119 switch (getEvaluationKind(FT)) {
4120 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004121 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00004122 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00004123 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00004124 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00004125 // This routine is used to load fields one-by-one to perform a copy, so
4126 // don't load reference fields.
4127 if (FD->getType()->isReferenceType())
4128 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00004129 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00004130 }
4131 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004132}
Douglas Gregorfe314812011-06-21 17:03:29 +00004133
Chris Lattnere47e4402007-06-01 18:02:12 +00004134//===--------------------------------------------------------------------===//
4135// Expression Emission
4136//===--------------------------------------------------------------------===//
4137
Craig Topper99e79272013-07-26 05:59:26 +00004138RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00004139 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00004140 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004141 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00004142 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004143
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004144 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004145 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004146
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004147 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00004148 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4149
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004150 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00004151 if (const CXXMethodDecl *MD =
4152 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004153 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004154
John McCallb92ab1a2016-10-26 23:46:34 +00004155 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00004156
John McCallb92ab1a2016-10-26 23:46:34 +00004157 if (callee.isBuiltin()) {
4158 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4159 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004160 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004161
John McCallb92ab1a2016-10-26 23:46:34 +00004162 if (callee.isPseudoDestructor()) {
4163 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4164 }
4165
4166 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4167}
4168
4169/// Emit a CallExpr without considering whether it might be a subclass.
4170RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4171 ReturnValueSlot ReturnValue) {
4172 CGCallee Callee = EmitCallee(E->getCallee());
4173 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4174}
4175
4176static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4177 if (auto builtinID = FD->getBuiltinID()) {
4178 return CGCallee::forBuiltin(builtinID, FD);
4179 }
4180
4181 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4182 return CGCallee::forDirect(calleePtr, FD);
4183}
4184
4185CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4186 E = E->IgnoreParens();
4187
4188 // Look through function-to-pointer decay.
4189 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4190 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4191 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4192 return EmitCallee(ICE->getSubExpr());
4193 }
4194
4195 // Resolve direct calls.
4196 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4197 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4198 return EmitDirectCallee(*this, FD);
4199 }
4200 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4201 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4202 EmitIgnoredExpr(ME->getBase());
4203 return EmitDirectCallee(*this, FD);
4204 }
4205
4206 // Look through template substitutions.
4207 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4208 return EmitCallee(NTTP->getReplacement());
4209
4210 // Treat pseudo-destructor calls differently.
4211 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4212 return CGCallee::forPseudoDestructor(PDE);
4213 }
4214
4215 // Otherwise, we have an indirect reference.
4216 llvm::Value *calleePtr;
4217 QualType functionType;
4218 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4219 calleePtr = EmitScalarExpr(E);
4220 functionType = ptrType->getPointeeType();
4221 } else {
4222 functionType = E->getType();
4223 calleePtr = EmitLValue(E).getPointer();
4224 }
4225 assert(functionType->isFunctionType());
4226 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4227 E->getReferencedDeclOfCallee());
4228 CGCallee callee(calleeInfo, calleePtr);
4229 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004230}
4231
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004232LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004233 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004234 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004235 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004236 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004237 return EmitLValue(E->getRHS());
4238 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004239
John McCalle3027922010-08-25 11:45:40 +00004240 if (E->getOpcode() == BO_PtrMemD ||
4241 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004242 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004243
John McCalla2342eb2010-12-05 02:00:02 +00004244 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004245
4246 // Note that in all of these cases, __block variables need the RHS
4247 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004248
4249 switch (getEvaluationKind(E->getType())) {
4250 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004251 switch (E->getLHS()->getType().getObjCLifetime()) {
4252 case Qualifiers::OCL_Strong:
4253 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4254
4255 case Qualifiers::OCL_Autoreleasing:
4256 return EmitARCStoreAutoreleasing(E).first;
4257
4258 // No reason to do any of these differently.
4259 case Qualifiers::OCL_None:
4260 case Qualifiers::OCL_ExplicitNone:
4261 case Qualifiers::OCL_Weak:
4262 break;
4263 }
4264
John McCalld0a30012010-12-06 06:10:02 +00004265 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004266 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004267 if (RV.isScalar())
4268 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004269 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004270 return LV;
4271 }
John McCall4f29b492010-11-16 23:07:28 +00004272
John McCall47fb9502013-03-07 21:37:08 +00004273 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004274 return EmitComplexAssignmentLValue(E);
4275
John McCall47fb9502013-03-07 21:37:08 +00004276 case TEK_Aggregate:
4277 return EmitAggExprToLValue(E);
4278 }
4279 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004280}
4281
Christopher Lambd91c3d42007-12-29 05:02:41 +00004282LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004283 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004284
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004285 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004286 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004287 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004288
David Majnemerced8bdf2015-02-25 17:36:15 +00004289 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004290 "Can't have a scalar return unless the return type is a "
4291 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004292
John McCall7f416cc2015-09-08 08:05:57 +00004293 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004294}
4295
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004296LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4297 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004298 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004299}
4300
Anders Carlsson3be22e22009-05-30 23:23:33 +00004301LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004302 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4303 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004304 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004305 EmitCXXConstructExpr(E, Slot);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004306 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00004307}
4308
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004309LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004310CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004311 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004312}
4313
John McCall7f416cc2015-09-08 08:05:57 +00004314Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4315 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4316 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004317}
4318
4319LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004320 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004321 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00004322}
4323
Mike Stumpc9b231c2009-11-15 08:09:41 +00004324LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004325CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004326 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004327 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004328 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004329 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004330 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004331}
4332
Eli Friedman5bc17122012-02-08 05:34:55 +00004333LValue
4334CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004335 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004336 EmitLambdaExpr(E, Slot);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004337 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00004338}
4339
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004340LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004341 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004342
Anders Carlsson280e61f12010-06-21 20:59:55 +00004343 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004344 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004345 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004346
Alp Toker314cc812014-01-25 16:55:45 +00004347 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004348 "Can't have a scalar return unless the return type is a "
4349 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004350
John McCall7f416cc2015-09-08 08:05:57 +00004351 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004352}
4353
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004354LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004355 Address V =
4356 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004357 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004358}
4359
Daniel Dunbar722f4242009-04-22 05:08:15 +00004360llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004361 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004362 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004363}
4364
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004365LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4366 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004367 const ObjCIvarDecl *Ivar,
4368 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004369 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004370 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004371}
4372
4373LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004374 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004375 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004376 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004377 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004378 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004379 if (E->isArrow()) {
4380 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004381 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004382 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004383 } else {
4384 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004385 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004386 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004387 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004388 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004389
Craig Topper99e79272013-07-26 05:59:26 +00004390 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004391 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4392 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004393 setObjCGCLValueClass(getContext(), E, LV);
4394 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004395}
4396
Chris Lattnera4185c52009-04-25 19:35:26 +00004397LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004398 // Can only get l-value for message expression returning aggregate type
4399 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004400 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004401 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00004402}
4403
John McCallb92ab1a2016-10-26 23:46:34 +00004404RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004405 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004406 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004407 // Get the actual function type. The callee type will always be a pointer to
4408 // function type or a block pointer type.
4409 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004410 "Call must have function pointer type!");
4411
John McCallb92ab1a2016-10-26 23:46:34 +00004412 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004413
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004414 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004415 // We can only guarantee that a function is called from the correct
4416 // context/function based on the appropriate target attributes,
4417 // so only check in the case where we have both always_inline and target
4418 // since otherwise we could be making a conditional call after a check for
4419 // the proper cpu features (and it won't cause code generation issues due to
4420 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004421 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4422 TargetDecl->hasAttr<TargetAttr>())
4423 checkTargetFeatures(E, FD);
4424
John McCall6fd4c232009-10-23 08:22:42 +00004425 CalleeType = getContext().getCanonicalType(CalleeType);
4426
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004427 const auto *FnType =
4428 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004429
John McCallb92ab1a2016-10-26 23:46:34 +00004430 CGCallee Callee = OrigCallee;
4431
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004432 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004433 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4434 if (llvm::Constant *PrefixSig =
4435 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004436 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004437 llvm::Constant *FTRTTIConst =
4438 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004439 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004440 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4441 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4442
John McCallb92ab1a2016-10-26 23:46:34 +00004443 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4444
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004445 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004446 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004447 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004448 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004449 llvm::Value *CalleeSig =
4450 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004451 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4452
4453 llvm::BasicBlock *Cont = createBasicBlock("cont");
4454 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4455 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4456
4457 EmitBlock(TypeCheck);
4458 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004459 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004460 llvm::Value *CalleeRTTIEncoded =
John McCall7f416cc2015-09-08 08:05:57 +00004461 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004462 llvm::Value *CalleeRTTI =
4463 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004464 llvm::Value *CalleeRTTIMatch =
4465 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4466 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004467 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004468 EmitCheckTypeDescriptor(CalleeType)
4469 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004470 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004471 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004472
4473 Builder.CreateBr(Cont);
4474 EmitBlock(Cont);
4475 }
4476 }
4477
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004478 // If we are checking indirect calls and this call is indirect, check that the
4479 // function pointer is a member of the bit set for the function type.
4480 if (SanOpts.has(SanitizerKind::CFIICall) &&
4481 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4482 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004483 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004484
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00004485 llvm::Metadata *MD;
4486 if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
4487 MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
4488 else
4489 MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4490
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004491 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004492
John McCallb92ab1a2016-10-26 23:46:34 +00004493 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4494 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004495 llvm::Value *TypeTest = Builder.CreateCall(
4496 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004497
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004498 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004499 llvm::Constant *StaticData[] = {
4500 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4501 EmitCheckSourceLocation(E->getLocStart()),
4502 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4503 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004504 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4505 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004506 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004507 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004508 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004509 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004510 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004511 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004512 }
4513
Daniel Dunbarc722b852008-08-30 03:02:31 +00004514 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004515 if (Chain)
4516 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4517 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004518
4519 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004520 // right-to-left, and that we evaluate arguments to certain other operators
4521 // left-to-right. Note that we allow this to override the order dictated by
4522 // the calling convention on the MS ABI, which means that parameter
4523 // destruction order is not necessarily reverse construction order.
4524 // FIXME: Revisit this based on C++ committee response to unimplementability.
4525 EvaluationOrder Order = EvaluationOrder::Default;
4526 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4527 if (OCE->isAssignmentOp())
4528 Order = EvaluationOrder::ForceRightToLeft;
4529 else {
4530 switch (OCE->getOperator()) {
4531 case OO_LessLess:
4532 case OO_GreaterGreater:
4533 case OO_AmpAmp:
4534 case OO_PipePipe:
4535 case OO_Comma:
4536 case OO_ArrowStar:
4537 Order = EvaluationOrder::ForceLeftToRight;
4538 break;
4539 default:
4540 break;
4541 }
4542 }
4543 }
Richard Smith762672a2016-09-28 19:09:10 +00004544
David Blaikief05779e2015-07-21 18:37:18 +00004545 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004546 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004547
Peter Collingbournef7706832014-12-12 23:41:25 +00004548 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4549 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004550
4551 // C99 6.5.2.2p6:
4552 // If the expression that denotes the called function has a type
4553 // that does not include a prototype, [the default argument
4554 // promotions are performed]. If the number of arguments does not
4555 // equal the number of parameters, the behavior is undefined. If
4556 // the function is defined with a type that includes a prototype,
4557 // and either the prototype ends with an ellipsis (, ...) or the
4558 // types of the arguments after promotion are not compatible with
4559 // the types of the parameters, the behavior is undefined. If the
4560 // function is defined with a type that does not include a
4561 // prototype, and the types of the arguments after promotion are
4562 // not compatible with those of the parameters after promotion,
4563 // the behavior is undefined [except in some trivial cases].
4564 // That is, in the general case, we should assume that a call
4565 // through an unprototyped function type works like a *non-variadic*
4566 // call. The way we make this work is to cast to the exact type
4567 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004568 //
4569 // Chain calls use this same code path to add the invisible chain parameter
4570 // to the function type.
4571 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004572 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004573 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004574
4575 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4576 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4577 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004578 }
4579
John McCallb92ab1a2016-10-26 23:46:34 +00004580 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004581}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004582
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004583LValue CodeGenFunction::
4584EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004585 Address BaseAddr = Address::invalid();
4586 if (E->getOpcode() == BO_PtrMemI) {
4587 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4588 } else {
4589 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4590 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004591
John McCallc134eb52010-08-31 21:07:20 +00004592 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4593
4594 const MemberPointerType *MPT
4595 = E->getRHS()->getType()->getAs<MemberPointerType>();
4596
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004597 LValueBaseInfo BaseInfo;
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004598 TBAAAccessInfo TBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00004599 Address MemberAddr =
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004600 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
4601 &TBAAInfo);
John McCallc134eb52010-08-31 21:07:20 +00004602
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004603 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004604}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004605
John McCall47fb9502013-03-07 21:37:08 +00004606/// Given the address of a temporary variable, produce an r-value of
4607/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004608RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004609 QualType type,
4610 SourceLocation loc) {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004611 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004612 switch (getEvaluationKind(type)) {
4613 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004614 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004615 case TEK_Aggregate:
4616 return lvalue.asAggregateRValue();
4617 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004618 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004619 }
4620 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004621}
4622
Duncan Sandse81111c2012-04-10 08:23:07 +00004623void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004624 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004625 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004626 return;
4627
Duncan Sands65229ed2012-04-16 16:29:47 +00004628 llvm::MDBuilder MDHelper(getLLVMContext());
4629 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004630
Duncan Sands6fc46192012-04-14 12:37:26 +00004631 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004632}
John McCallfe96e0b2011-11-06 09:01:30 +00004633
4634namespace {
4635 struct LValueOrRValue {
4636 LValue LV;
4637 RValue RV;
4638 };
4639}
4640
4641static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4642 const PseudoObjectExpr *E,
4643 bool forLValue,
4644 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004645 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004646
4647 // Find the result expression, if any.
4648 const Expr *resultExpr = E->getResultExpr();
4649 LValueOrRValue result;
4650
4651 for (PseudoObjectExpr::const_semantics_iterator
4652 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4653 const Expr *semantic = *i;
4654
4655 // If this semantic expression is an opaque value, bind it
4656 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004657 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004658
4659 // If this is the result expression, we may need to evaluate
4660 // directly into the slot.
4661 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4662 OVMA opaqueData;
4663 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004664 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004665 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
John McCall7f416cc2015-09-08 08:05:57 +00004666 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004667 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004668 opaqueData = OVMA::bind(CGF, ov, LV);
4669 result.RV = slot.asRValue();
4670
4671 // Otherwise, emit as normal.
4672 } else {
4673 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4674
4675 // If this is the result, also evaluate the result now.
4676 if (ov == resultExpr) {
4677 if (forLValue)
4678 result.LV = CGF.EmitLValue(ov);
4679 else
4680 result.RV = CGF.EmitAnyExpr(ov, slot);
4681 }
4682 }
4683
4684 opaques.push_back(opaqueData);
4685
4686 // Otherwise, if the expression is the result, evaluate it
4687 // and remember the result.
4688 } else if (semantic == resultExpr) {
4689 if (forLValue)
4690 result.LV = CGF.EmitLValue(semantic);
4691 else
4692 result.RV = CGF.EmitAnyExpr(semantic, slot);
4693
4694 // Otherwise, evaluate the expression in an ignored context.
4695 } else {
4696 CGF.EmitIgnoredExpr(semantic);
4697 }
4698 }
4699
4700 // Unbind all the opaques now.
4701 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4702 opaques[i].unbind(CGF);
4703
4704 return result;
4705}
4706
4707RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4708 AggValueSlot slot) {
4709 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4710}
4711
4712LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4713 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4714}