blob: cd7911a6046bca353cd57ca833e1b7c86e733114 [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 McCallcbc038a2011-09-21 08:08:30 +000023#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/ASTContext.h"
Renato Golin230c5eb2014-05-19 18:15:42 +000025#include "clang/AST/Attr.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "clang/AST/DeclObjC.h"
Vedant Kumar4593a462016-12-09 23:48:18 +000027#include "clang/AST/NSAPI.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000028#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000030#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000035#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000036#include "llvm/Support/MathExtras.h"
Filipe Cabecinhasab731f72016-05-12 16:51:36 +000037#include "llvm/Support/Path.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000038#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000039
Filipe Cabecinhas84171bd2016-12-12 16:43:40 +000040#include <string>
41
Chris Lattnere47e4402007-06-01 18:02:12 +000042using namespace clang;
43using namespace CodeGen;
44
Chris Lattnerd7f58862007-06-02 05:24:33 +000045//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000046// Miscellaneous Helper Methods
47//===--------------------------------------------------------------------===//
48
John McCallad7c5c12011-02-08 08:22:06 +000049llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
50 unsigned addressSpace =
Yaxun Liu39195062017-08-04 18:16:31 +000051 cast<llvm::PointerType>(value->getType())->getAddressSpace();
John McCallad7c5c12011-02-08 08:22:06 +000052
Chris Lattner2192fe52011-07-18 04:24:23 +000053 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000054 if (addressSpace)
55 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
56
57 if (value->getType() == destType) return value;
58 return Builder.CreateBitCast(value, destType);
59}
60
Chris Lattnere9a64532007-06-22 21:44:33 +000061/// CreateTempAlloca - This creates a alloca and inserts it into the entry
62/// block.
John McCall7f416cc2015-09-08 08:05:57 +000063Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +000064 const Twine &Name,
65 llvm::Value *ArraySize,
66 bool CastToDefaultAddrSpace) {
67 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
John McCall7f416cc2015-09-08 08:05:57 +000068 Alloca->setAlignment(Align.getQuantity());
Yaxun Liu84744c12017-06-19 17:03:41 +000069 llvm::Value *V = Alloca;
70 // Alloca always returns a pointer in alloca address space, which may
71 // be different from the type defined by the language. For example,
72 // in C++ the auto variables are in the default address space. Therefore
73 // cast alloca to the default address space when necessary.
74 if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
75 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
Yaxun Liu9d33fb12017-07-18 14:46:03 +000076 auto CurIP = Builder.saveIP();
77 Builder.SetInsertPoint(AllocaInsertPt);
Yaxun Liu84744c12017-06-19 17:03:41 +000078 V = getTargetHooks().performAddrSpaceCast(
79 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
80 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
Yaxun Liu9d33fb12017-07-18 14:46:03 +000081 Builder.restoreIP(CurIP);
Yaxun Liu84744c12017-06-19 17:03:41 +000082 }
83
84 return Address(V, Align);
John McCall7f416cc2015-09-08 08:05:57 +000085}
86
Yaxun Liu84744c12017-06-19 17:03:41 +000087/// CreateTempAlloca - This creates an alloca and inserts it into the entry
88/// block if \p ArraySize is nullptr, otherwise inserts it at the current
89/// insertion point of the builder.
Chris Lattner2192fe52011-07-18 04:24:23 +000090llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Yaxun Liu84744c12017-06-19 17:03:41 +000091 const Twine &Name,
92 llvm::Value *ArraySize) {
93 if (ArraySize)
94 return Builder.CreateAlloca(Ty, ArraySize, Name);
Matt Arsenault502ad602017-04-10 22:28:02 +000095 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
Yaxun Liu84744c12017-06-19 17:03:41 +000096 ArraySize, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000097}
Chris Lattner8394d792007-06-05 20:53:16 +000098
John McCall7f416cc2015-09-08 08:05:57 +000099/// CreateDefaultAlignTempAlloca - This creates an alloca with the
100/// default alignment of the corresponding LLVM type, which is *not*
101/// guaranteed to be related in any way to the expected alignment of
102/// an AST type that might have been lowered to Ty.
103Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
104 const Twine &Name) {
105 CharUnits Align =
106 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
107 return CreateTempAlloca(Ty, Align, Name);
108}
109
110void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
111 assert(isa<llvm::AllocaInst>(Var.getPointer()));
112 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
113 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +0000114 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000115 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +0000116}
117
John McCall7f416cc2015-09-08 08:05:57 +0000118Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +0000119 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +0000120 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +0000121}
122
Yaxun Liu84744c12017-06-19 17:03:41 +0000123Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
124 bool CastToDefaultAddrSpace) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000125 // FIXME: Should we prefer the preferred type alignment here?
Yaxun Liu84744c12017-06-19 17:03:41 +0000126 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
127 CastToDefaultAddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +0000128}
129
130Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +0000131 const Twine &Name,
132 bool CastToDefaultAddrSpace) {
133 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
134 CastToDefaultAddrSpace);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000135}
136
Chris Lattner8394d792007-06-05 20:53:16 +0000137/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
138/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000139llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000140 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000141 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000142 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000143 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000144 }
John McCall7a9aac22010-08-23 01:21:21 +0000145
146 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000147 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000148 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000149 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000150
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000151 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
152 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000153}
154
John McCalla2342eb2010-12-05 02:00:02 +0000155/// EmitIgnoredExpr - Emit code to compute the specified expression,
156/// ignoring the result.
157void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
158 if (E->isRValue())
159 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
160
161 // Just emit it as an l-value and drop the result.
162 EmitLValue(E);
163}
164
John McCall7a626f62010-09-15 10:14:12 +0000165/// EmitAnyExpr - Emit code to compute the specified expression which
166/// can have any type. The result is returned as an RValue struct.
167/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000168/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000169RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
170 AggValueSlot aggSlot,
171 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000172 switch (getEvaluationKind(E->getType())) {
173 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000174 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000175 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000176 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000177 case TEK_Aggregate:
178 if (!ignoreResult && aggSlot.isIgnored())
179 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
180 EmitAggExpr(E, aggSlot);
181 return aggSlot.asRValue();
182 }
183 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000184}
185
Mike Stump4a3999f2009-09-09 13:00:44 +0000186/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
187/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000188RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
189 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000190
John McCall47fb9502013-03-07 21:37:08 +0000191 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000192 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
193 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000194}
195
John McCall21886962010-04-21 10:05:39 +0000196/// EmitAnyExprToMem - Evaluate an expression into a given memory
197/// location.
198void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000199 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000200 Qualifiers Quals,
201 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000202 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000203 switch (getEvaluationKind(E->getType())) {
204 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000205 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000206 /*isInit*/ false);
207 return;
208
209 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000210 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000211 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000212 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000213 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000214 return;
215 }
216
217 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000218 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000219 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000220 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000221 return;
John McCall21886962010-04-21 10:05:39 +0000222 }
John McCall47fb9502013-03-07 21:37:08 +0000223 }
224 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000225}
226
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000227static void
228pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000229 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000230 // Objective-C++ ARC:
231 // If we are binding a reference to a temporary that has ownership, we
232 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000233 //
234 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000235 if (auto Lifetime = M->getType().getObjCLifetime()) {
236 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000237 case Qualifiers::OCL_None:
238 case Qualifiers::OCL_ExplicitNone:
239 // Carry on to normal cleanup handling.
240 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000241
Richard Smith736a9472013-06-12 20:42:33 +0000242 case Qualifiers::OCL_Autoreleasing:
243 // Nothing to do; cleaned up by an autorelease pool.
244 return;
245
246 case Qualifiers::OCL_Strong:
247 case Qualifiers::OCL_Weak:
248 switch (StorageDuration Duration = M->getStorageDuration()) {
249 case SD_Static:
250 // Note: we intentionally do not register a cleanup to release
251 // the object on program termination.
252 return;
253
254 case SD_Thread:
255 // FIXME: We should probably register a cleanup in this case.
256 return;
257
258 case SD_Automatic:
259 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000260 CodeGenFunction::Destroyer *Destroy;
261 CleanupKind CleanupKind;
262 if (Lifetime == Qualifiers::OCL_Strong) {
263 const ValueDecl *VD = M->getExtendingDecl();
264 bool Precise =
265 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
266 CleanupKind = CGF.getARCCleanupKind();
267 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
268 : &CodeGenFunction::destroyARCStrongImprecise;
269 } else {
270 // __weak objects always get EH cleanups; otherwise, exceptions
271 // could cause really nasty crashes instead of mere leaks.
272 CleanupKind = NormalAndEHCleanup;
273 Destroy = &CodeGenFunction::destroyARCWeak;
274 }
275 if (Duration == SD_FullExpression)
276 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000277 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000278 CleanupKind & EHCleanup);
279 else
280 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000281 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000282 *Destroy, CleanupKind & EHCleanup);
283 return;
284
285 case SD_Dynamic:
286 llvm_unreachable("temporary cannot have dynamic storage duration");
287 }
288 llvm_unreachable("unknown storage duration");
289 }
290 }
291
Craig Topper8a13c412014-05-21 05:09:00 +0000292 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000293 if (const RecordType *RT =
294 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
295 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000296 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000297 if (!ClassDecl->hasTrivialDestructor())
298 ReferenceTemporaryDtor = ClassDecl->getDestructor();
299 }
300
301 if (!ReferenceTemporaryDtor)
302 return;
303
304 // Call the destructor for the temporary.
305 switch (M->getStorageDuration()) {
306 case SD_Static:
307 case SD_Thread: {
308 llvm::Constant *CleanupFn;
309 llvm::Constant *CleanupArg;
310 if (E->getType()->isArrayType()) {
311 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000312 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000313 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
314 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000315 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
316 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000317 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
318 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000319 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000320 }
321 CGF.CGM.getCXXABI().registerGlobalDtor(
322 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
323 break;
324 }
325
326 case SD_FullExpression:
327 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
328 CodeGenFunction::destroyCXXObject,
329 CGF.getLangOpts().Exceptions);
330 break;
331
332 case SD_Automatic:
333 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
334 ReferenceTemporary, E->getType(),
335 CodeGenFunction::destroyCXXObject,
336 CGF.getLangOpts().Exceptions);
337 break;
338
339 case SD_Dynamic:
340 llvm_unreachable("temporary cannot have dynamic storage duration");
341 }
342}
343
Yaxun Liucbf647c2017-07-08 13:24:52 +0000344static Address createReferenceTemporary(CodeGenFunction &CGF,
345 const MaterializeTemporaryExpr *M,
346 const Expr *Inner) {
347 auto &TCG = CGF.getTargetHooks();
Richard Smith736a9472013-06-12 20:42:33 +0000348 switch (M->getStorageDuration()) {
349 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000350 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000351 // If we have a constant temporary array or record try to promote it into a
352 // constant global under the same rules a normal constant would've been
353 // promoted. This is easier on the optimizer and generally emits fewer
354 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000355 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000356 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000357 (Ty->isArrayType() || Ty->isRecordType()) &&
358 CGF.CGM.isTypeConstant(Ty, true))
359 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000360 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
361 auto AS = AddrSpace.getValue();
362 auto *GV = new llvm::GlobalVariable(
363 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
364 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
365 llvm::GlobalValue::NotThreadLocal,
366 CGF.getContext().getTargetAddressSpace(AS));
367 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
368 GV->setAlignment(alignment.getQuantity());
369 llvm::Constant *C = GV;
370 if (AS != LangAS::Default)
371 C = TCG.performAddrSpaceCast(
372 CGF.CGM, GV, AS, LangAS::Default,
373 GV->getValueType()->getPointerTo(
374 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
375 // FIXME: Should we put the new global into a COMDAT?
376 return Address(C, alignment);
377 }
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000378 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000379 return CGF.CreateMemTemp(Ty, "ref.tmp");
380 }
Richard Smith736a9472013-06-12 20:42:33 +0000381 case SD_Thread:
382 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000383 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000384
385 case SD_Dynamic:
386 llvm_unreachable("temporary can't have dynamic storage duration");
387 }
388 llvm_unreachable("unknown storage duration");
389}
390
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000391LValue CodeGenFunction::
392EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000393 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000394
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000395 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
396 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000397 auto ownership = M->getType().getObjCLifetime();
398 if (ownership != Qualifiers::OCL_None &&
399 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000400 Address Object = createReferenceTemporary(*this, M, E);
401 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
402 Object = Address(llvm::ConstantExpr::getBitCast(Var,
403 ConvertTypeForMem(E->getType())
404 ->getPointerTo(Object.getAddressSpace())),
405 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000406
407 // createReferenceTemporary will promote the temporary to a global with a
408 // constant initializer if it can. It can only do this to a value of
409 // ARC-manageable type if the value is global and therefore "immune" to
410 // ref-counting operations. Therefore we have no need to emit either a
411 // dynamic initialization or a cleanup and we can just return the address
412 // of the temporary.
413 if (Var->hasInitializer())
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000414 return MakeAddrLValue(Object, M->getType(),
415 LValueBaseInfo(AlignmentSource::Decl, false));
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000416
Richard Smitha509f2f2013-06-14 03:07:01 +0000417 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
418 }
John McCall7f416cc2015-09-08 08:05:57 +0000419 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000420 LValueBaseInfo(AlignmentSource::Decl,
421 false));
Richard Smitha509f2f2013-06-14 03:07:01 +0000422
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000423 switch (getEvaluationKind(E->getType())) {
424 default: llvm_unreachable("expected scalar or aggregate expression");
425 case TEK_Scalar:
426 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
427 break;
428 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000429 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000430 E->getType().getQualifiers(),
431 AggValueSlot::IsDestructed,
432 AggValueSlot::DoesNotNeedGCBarriers,
433 AggValueSlot::IsNotAliased));
434 break;
435 }
436 }
Richard Smith736a9472013-06-12 20:42:33 +0000437
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000438 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000439 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000440 }
441
Richard Smithf3fabd22013-06-03 00:17:11 +0000442 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000443 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000444 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
445
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000446 for (const auto &Ignored : CommaLHSs)
447 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000448
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000449 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000450 if (opaque->getType()->isRecordType()) {
451 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000452 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000453 }
454 }
455
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000456 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000457 Address Object = createReferenceTemporary(*this, M, E);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000458 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
459 Object.getPointer()->stripPointerCasts())) {
John McCall7f416cc2015-09-08 08:05:57 +0000460 Object = Address(llvm::ConstantExpr::getBitCast(
Yaxun Liucbf647c2017-07-08 13:24:52 +0000461 cast<llvm::Constant>(Object.getPointer()),
462 ConvertTypeForMem(E->getType())->getPointerTo()),
John McCall7f416cc2015-09-08 08:05:57 +0000463 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000464 // If the temporary is a global and has a constant initializer or is a
465 // constant temporary that we promoted to a global, we may have already
466 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000467 if (!Var->hasInitializer()) {
468 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
469 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
470 }
471 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000472 switch (M->getStorageDuration()) {
473 case SD_Automatic:
474 case SD_FullExpression:
475 if (auto *Size = EmitLifetimeStart(
476 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
477 Object.getPointer())) {
478 if (M->getStorageDuration() == SD_Automatic)
479 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
480 Object, Size);
481 else
482 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
483 Size);
484 }
485 break;
486 default:
487 break;
488 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000489 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
490 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000491 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000492
Richard Smith736a9472013-06-12 20:42:33 +0000493 // Perform derived-to-base casts and/or field accesses, to get from the
494 // temporary object we created (and, potentially, for which we extended
495 // the lifetime) to the subobject we're binding the reference to.
496 for (unsigned I = Adjustments.size(); I != 0; --I) {
497 SubobjectAdjustment &Adjustment = Adjustments[I-1];
498 switch (Adjustment.Kind) {
499 case SubobjectAdjustment::DerivedToBaseAdjustment:
500 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000501 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
502 Adjustment.DerivedToBase.BasePath->path_begin(),
503 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000504 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000505 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000506
Richard Smith736a9472013-06-12 20:42:33 +0000507 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000508 LValue LV = MakeAddrLValue(Object, E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000509 LValueBaseInfo(AlignmentSource::Decl, false));
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000510 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000511 assert(LV.isSimple() &&
512 "materialized temporary field is not a simple lvalue");
513 Object = LV.getAddress();
514 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000515 }
516
Richard Smith736a9472013-06-12 20:42:33 +0000517 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000518 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000519 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
520 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000521 break;
522 }
523 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000524 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000525
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000526 return MakeAddrLValue(Object, M->getType(),
527 LValueBaseInfo(AlignmentSource::Decl, false));
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
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000571bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000572 return SanOpts.has(SanitizerKind::Null) |
573 SanOpts.has(SanitizerKind::Alignment) |
574 SanOpts.has(SanitizerKind::ObjectSize) |
575 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000576}
577
Richard Smithe30752c2012-10-09 19:52:38 +0000578void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000579 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000580 CharUnits Alignment,
581 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000582 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000583 return;
584
Richard Smith2d8b2942012-11-01 07:22:08 +0000585 // Don't check pointers outside the default address space. The null check
586 // isn't correct, the object-size check isn't supported by LLVM, and we can't
587 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000588 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000589 return;
590
Vedant Kumarc420d142017-06-16 03:27:36 +0000591 // Don't check pointers to volatile data. The behavior here is implementation-
592 // defined.
593 if (Ty.isVolatileQualified())
594 return;
595
Alexey Samsonov24cad992014-07-17 18:46:27 +0000596 SanitizerScope SanScope(this);
597
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000598 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000599 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000600
Vedant Kumare859ebb2017-04-26 02:17:21 +0000601 // Quickly determine whether we have a pointer to an alloca. It's possible
602 // to skip null checks, and some alignment checks, for these pointers. This
603 // can reduce compile-time significantly.
604 auto PtrToAlloca =
605 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
606
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000607 llvm::Value *IsNonNull = nullptr;
608 bool IsGuaranteedNonNull =
609 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000610 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
611 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000612 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000613 !IsGuaranteedNonNull) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000614 // The glvalue must not be an empty glvalue.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000615 IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000616
Vedant Kumardbbdda42017-04-17 22:26:10 +0000617 // The IR builder can constant-fold the null check if the pointer points to
618 // a constant.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000619 IsGuaranteedNonNull =
Vedant Kumardbbdda42017-04-17 22:26:10 +0000620 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext());
621
622 // Skip the null check if the pointer is known to be non-null.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000623 if (!IsGuaranteedNonNull) {
Vedant Kumardbbdda42017-04-17 22:26:10 +0000624 if (AllowNullPointers) {
625 // When performing pointer casts, it's OK if the value is null.
626 // Skip the remaining checks in that case.
627 Done = createBasicBlock("null");
628 llvm::BasicBlock *Rest = createBasicBlock("not.null");
629 Builder.CreateCondBr(IsNonNull, Rest, Done);
630 EmitBlock(Rest);
631 } else {
632 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
633 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000634 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000635 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000636
Vedant Kumar18348ea2017-02-17 23:22:55 +0000637 if (SanOpts.has(SanitizerKind::ObjectSize) &&
638 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
639 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000640 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000641
Richard Smith69d0d262012-08-24 00:54:33 +0000642 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000643 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000644 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000645 // FIXME: Get object address space
646 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
647 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000648 llvm::Value *Min = Builder.getFalse();
George Burgess IVa63f9152017-03-21 20:09:35 +0000649 llvm::Value *NullIsUnknown = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000650 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
George Burgess IVa63f9152017-03-21 20:09:35 +0000651 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
652 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
653 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000654 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000655 }
Richard Smith69d0d262012-08-24 00:54:33 +0000656
Richard Smithb1b0ab42012-11-05 22:21:05 +0000657 uint64_t AlignVal = 0;
658
Vedant Kumar18348ea2017-02-17 23:22:55 +0000659 if (SanOpts.has(SanitizerKind::Alignment) &&
660 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000661 AlignVal = Alignment.getQuantity();
662 if (!Ty->isIncompleteType() && !AlignVal)
663 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
664
Richard Smith69d0d262012-08-24 00:54:33 +0000665 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000666 if (AlignVal > 1 &&
667 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000668 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000669 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000670 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
671 llvm::Value *Aligned =
672 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000673 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000674 }
Richard Smith69d0d262012-08-24 00:54:33 +0000675 }
676
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000677 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000678 // Make sure we're not losing information. Alignment needs to be a power of
679 // 2
680 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000681 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000682 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
683 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
684 llvm::ConstantInt::get(Int8Ty, TCK)};
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000685 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000686 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000687
Richard Smithb1b0ab42012-11-05 22:21:05 +0000688 // If possible, check that the vptr indicates that there is a subobject of
689 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000690 //
691 // C++11 [basic.life]p5,6:
692 // [For storage which does not refer to an object within its lifetime]
693 // The program has undefined behavior if:
694 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000695 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000696 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000697 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumara0c36712017-08-02 18:10:31 +0000698 !SkippedChecks.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000699 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000700 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
701 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000702 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000703 // Ensure that the pointer is non-null before loading it. If there is no
Vedant Kumara0c36712017-08-02 18:10:31 +0000704 // compile-time guarantee, reuse the run-time null check or emit a new one.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000705 if (!IsGuaranteedNonNull) {
Vedant Kumara0c36712017-08-02 18:10:31 +0000706 if (!IsNonNull)
707 IsNonNull = Builder.CreateIsNotNull(Ptr);
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000708 if (!Done)
709 Done = createBasicBlock("vptr.null");
710 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
711 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
712 EmitBlock(VptrNotNull);
713 }
714
Richard Smith4d3110a2012-10-25 02:14:12 +0000715 // Compute a hash of the mangled name of the type.
716 //
717 // FIXME: This is not guaranteed to be deterministic! Move to a
718 // fingerprinting mechanism once LLVM provides one. For the time
719 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000720 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000721 llvm::raw_svector_ostream Out(MangledName);
722 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
723 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000724
Alexey Samsonov84856012014-07-10 22:34:19 +0000725 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000726 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
727 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000728 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000729
Alexey Samsonov84856012014-07-10 22:34:19 +0000730 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
731 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
732 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000733 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000734 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
735 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000736
Alexey Samsonov84856012014-07-10 22:34:19 +0000737 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
738 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000739
Alexey Samsonov84856012014-07-10 22:34:19 +0000740 // Look the hash up in our cache.
741 const int CacheSize = 128;
742 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
743 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
744 "__ubsan_vptr_type_cache");
745 llvm::Value *Slot = Builder.CreateAnd(Hash,
746 llvm::ConstantInt::get(IntPtrTy,
747 CacheSize-1));
748 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
749 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000750 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
751 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000752
753 // If the hash isn't in the cache, call a runtime handler to perform the
754 // hard work of checking whether the vptr is for an object of the right
755 // type. This will either fill in the cache and return, or produce a
756 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000757 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000758 llvm::Constant *StaticData[] = {
759 EmitCheckSourceLocation(Loc),
760 EmitCheckTypeDescriptor(Ty),
761 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
762 llvm::ConstantInt::get(Int8Ty, TCK)
763 };
John McCall7f416cc2015-09-08 08:05:57 +0000764 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000765 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000766 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
767 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000768 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000769 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000770
771 if (Done) {
772 Builder.CreateBr(Done);
773 EmitBlock(Done);
774 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000775}
Chris Lattner4647a212007-08-31 22:49:20 +0000776
Richard Smith539e4a72013-02-23 02:53:19 +0000777/// Determine whether this expression refers to a flexible array member in a
778/// struct. We disable array bounds checks for such members.
779static bool isFlexibleArrayMemberExpr(const Expr *E) {
780 // For compatibility with existing code, we treat arrays of length 0 or
781 // 1 as flexible array members.
782 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000783 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000784 if (CAT->getSize().ugt(1))
785 return false;
786 } else if (!isa<IncompleteArrayType>(AT))
787 return false;
788
789 E = E->IgnoreParens();
790
791 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000792 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000793 // FIXME: If the base type of the member expr is not FD->getParent(),
794 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000795 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000796 RecordDecl::field_iterator FI(
797 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
798 return ++FI == FD->getParent()->field_end();
799 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000800 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
801 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000802 }
803
804 return false;
805}
806
807/// If Base is known to point to the start of an array, return the length of
808/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000809static llvm::Value *getArrayIndexingBound(
810 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000811 // For the vector indexing extension, the bound is the number of elements.
812 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
813 IndexedType = Base->getType();
814 return CGF.Builder.getInt32(VT->getNumElements());
815 }
816
817 Base = Base->IgnoreParens();
818
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000819 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000820 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
821 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
822 IndexedType = CE->getSubExpr()->getType();
823 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000824 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000825 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000826 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000827 return CGF.getVLASize(VAT).first;
828 }
829 }
830
Craig Topper8a13c412014-05-21 05:09:00 +0000831 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000832}
833
834void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
835 llvm::Value *Index, QualType IndexType,
836 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000837 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000838 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000839 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000840
Richard Smith539e4a72013-02-23 02:53:19 +0000841 QualType IndexedType;
842 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
843 if (!Bound)
844 return;
845
846 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
847 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
848 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
849
850 llvm::Constant *StaticData[] = {
851 EmitCheckSourceLocation(E->getExprLoc()),
852 EmitCheckTypeDescriptor(IndexedType),
853 EmitCheckTypeDescriptor(IndexType)
854 };
855 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
856 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000857 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
858 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000859}
860
Chris Lattner116ce8f2010-01-09 21:40:03 +0000861
Chris Lattner116ce8f2010-01-09 21:40:03 +0000862CodeGenFunction::ComplexPairTy CodeGenFunction::
863EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
864 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000865 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000866
Chris Lattner116ce8f2010-01-09 21:40:03 +0000867 llvm::Value *NextVal;
868 if (isa<llvm::IntegerType>(InVal.first->getType())) {
869 uint64_t AmountVal = isInc ? 1 : -1;
870 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000871
Chris Lattner116ce8f2010-01-09 21:40:03 +0000872 // Add the inc/dec to the real part.
873 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
874 } else {
875 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
876 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
877 if (!isInc)
878 FVal.changeSign();
879 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000880
Chris Lattner116ce8f2010-01-09 21:40:03 +0000881 // Add the inc/dec to the real part.
882 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
883 }
Craig Topper99e79272013-07-26 05:59:26 +0000884
Chris Lattner116ce8f2010-01-09 21:40:03 +0000885 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000886
Chris Lattner116ce8f2010-01-09 21:40:03 +0000887 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000888 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000889
Chris Lattner116ce8f2010-01-09 21:40:03 +0000890 // If this is a postinc, return the value read from memory, otherwise use the
891 // updated value.
892 return isPre ? IncVal : InVal;
893}
894
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000895void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
896 CodeGenFunction *CGF) {
897 // Bind VLAs in the cast type.
898 if (CGF && E->getType()->isVariablyModifiedType())
899 CGF->EmitVariablyModifiedType(E->getType());
900
901 if (CGDebugInfo *DI = getModuleDebugInfo())
902 DI->EmitExplicitCastType(E->getType());
903}
904
Chris Lattnera45c5af2007-06-02 19:47:04 +0000905//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000906// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000907//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000908
John McCall7f416cc2015-09-08 08:05:57 +0000909/// EmitPointerWithAlignment - Given an expression of pointer type, try to
910/// derive a more accurate bound on the alignment of the pointer.
911Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000912 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000913 // We allow this with ObjC object pointers because of fragile ABIs.
914 assert(E->getType()->isPointerType() ||
915 E->getType()->isObjCObjectPointerType());
916 E = E->IgnoreParens();
917
918 // Casts:
919 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000920 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
921 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000922
923 switch (CE->getCastKind()) {
924 // Non-converting casts (but not C's implicit conversion from void*).
925 case CK_BitCast:
926 case CK_NoOp:
927 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
928 if (PtrTy->getPointeeType()->isVoidType())
929 break;
930
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000931 LValueBaseInfo InnerInfo;
932 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo);
933 if (BaseInfo) *BaseInfo = InnerInfo;
John McCall7f416cc2015-09-08 08:05:57 +0000934
935 // If this is an explicit bitcast, and the source l-value is
936 // opaque, honor the alignment of the casted-to type.
937 if (isa<ExplicitCastExpr>(CE) &&
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000938 InnerInfo.getAlignmentSource() != AlignmentSource::Decl) {
939 LValueBaseInfo ExpInfo;
940 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
941 &ExpInfo);
942 if (BaseInfo)
943 BaseInfo->mergeForCast(ExpInfo);
944 Addr = Address(Addr.getPointer(), Align);
John McCall7f416cc2015-09-08 08:05:57 +0000945 }
946
Peter Collingbourne574975e2016-01-14 02:49:48 +0000947 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
948 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000949 if (auto PT = E->getType()->getAs<PointerType>())
950 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
951 /*MayBeNull=*/true,
952 CodeGenFunction::CFITCK_UnrelatedCast,
953 CE->getLocStart());
954 }
955
John McCall7f416cc2015-09-08 08:05:57 +0000956 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
957 }
958 break;
959
960 // Array-to-pointer decay.
961 case CK_ArrayToPointerDecay:
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000962 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000963
964 // Derived-to-base conversions.
965 case CK_UncheckedDerivedToBase:
966 case CK_DerivedToBase: {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000967 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000968 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
969 return GetAddressOfBaseClass(Addr, Derived,
970 CE->path_begin(), CE->path_end(),
971 ShouldNullCheckClassCastValue(CE),
972 CE->getExprLoc());
973 }
974
975 // TODO: Is there any reason to treat base-to-derived conversions
976 // specially?
977 default:
978 break;
979 }
980 }
981
982 // Unary &.
983 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
984 if (UO->getOpcode() == UO_AddrOf) {
985 LValue LV = EmitLValue(UO->getSubExpr());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000986 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +0000987 return LV.getAddress();
988 }
989 }
990
991 // TODO: conditional operators, comma.
992
993 // Otherwise, use the alignment of the type.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000994 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000995 return Address(EmitScalarExpr(E), Align);
996}
997
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000998RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000999 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001000 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +00001001
1002 switch (getEvaluationKind(Ty)) {
1003 case TEK_Complex: {
1004 llvm::Type *EltTy =
1005 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +00001006 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001007 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001008 }
Craig Topper99e79272013-07-26 05:59:26 +00001009
Chris Lattner65526f02010-08-23 05:26:13 +00001010 // If this is a use of an undefined aggregate type, the aggregate must have an
1011 // identifiable address. Just because the contents of the value are undefined
1012 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +00001013 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00001014 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +00001015 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001016 }
John McCall47fb9502013-03-07 21:37:08 +00001017
1018 case TEK_Scalar:
1019 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1020 }
1021 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +00001022}
1023
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001024RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1025 const char *Name) {
1026 ErrorUnsupported(E, Name);
1027 return GetUndefRValue(E->getType());
1028}
1029
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001030LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1031 const char *Name) {
1032 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001033 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001034 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1035 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001036}
1037
Vedant Kumarffd7c882017-04-14 22:03:34 +00001038bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001039 const Expr *Base = Obj;
1040 while (!isa<CXXThisExpr>(Base)) {
1041 // The result of a dynamic_cast can be null.
1042 if (isa<CXXDynamicCastExpr>(Base))
1043 return false;
1044
1045 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1046 Base = CE->getSubExpr();
1047 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1048 Base = PE->getSubExpr();
1049 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1050 if (UO->getOpcode() == UO_Extension)
1051 Base = UO->getSubExpr();
1052 else
1053 return false;
1054 } else {
1055 return false;
1056 }
1057 }
1058 return true;
1059}
1060
Richard Smith4d1458e2012-09-08 02:08:36 +00001061LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +00001062 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001063 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +00001064 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1065 else
1066 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001067 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1068 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001069 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1070 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1071 if (IsBaseCXXThis)
1072 SkippedChecks.set(SanitizerKind::Alignment, true);
1073 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001074 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001075 }
John McCall7f416cc2015-09-08 08:05:57 +00001076 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001077 E->getType(), LV.getAlignment(), SkippedChecks);
1078 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001079 return LV;
1080}
1081
Chris Lattner8394d792007-06-05 20:53:16 +00001082/// EmitLValue - Emit code to compute a designator that specifies the location
1083/// of the expression.
1084///
Mike Stump4a3999f2009-09-09 13:00:44 +00001085/// This can return one of two things: a simple address or a bitfield reference.
1086/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1087/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001088///
Mike Stump4a3999f2009-09-09 13:00:44 +00001089/// If this returns a bitfield reference, nothing about the pointee type of the
1090/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001091///
Mike Stump4a3999f2009-09-09 13:00:44 +00001092/// If this returns a normal address, and if the lvalue's C type is fixed size,
1093/// this method guarantees that the returned pointer type will point to an LLVM
1094/// type of the same size of the lvalue's type. If the lvalue has a variable
1095/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001096///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001097LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001098 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001099 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001100 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001101
John McCallc109a252011-11-07 03:59:57 +00001102 case Expr::ObjCPropertyRefExprClass:
1103 llvm_unreachable("cannot emit a property reference directly");
1104
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001105 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001106 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001107 case Expr::ObjCIsaExprClass:
1108 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001109 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001110 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001111 case Expr::CompoundAssignOperatorClass: {
1112 QualType Ty = E->getType();
1113 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1114 Ty = AT->getValueType();
1115 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001116 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1117 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001118 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001119 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001120 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001121 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001122 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001123 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001124 case Expr::VAArgExprClass:
1125 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001126 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001127 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001128 case Expr::ParenExprClass:
1129 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001130 case Expr::GenericSelectionExprClass:
1131 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001132 case Expr::PredefinedExprClass:
1133 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001134 case Expr::StringLiteralClass:
1135 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001136 case Expr::ObjCEncodeExprClass:
1137 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001138 case Expr::PseudoObjectExprClass:
1139 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001140 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001141 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001142 case Expr::CXXTemporaryObjectExprClass:
1143 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001144 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1145 case Expr::CXXBindTemporaryExprClass:
1146 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001147 case Expr::CXXUuidofExprClass:
1148 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001149 case Expr::LambdaExprClass:
1150 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001151
1152 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001153 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001154 enterFullExpression(cleanups);
1155 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001156 LValue LV = EmitLValue(cleanups->getSubExpr());
1157 if (LV.isSimple()) {
1158 // Defend against branches out of gnu statement expressions surrounded by
1159 // cleanups.
1160 llvm::Value *V = LV.getPointer();
1161 Scope.ForceCleanup({&V});
1162 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001163 getContext(), LV.getBaseInfo(),
Reid Kleckner092d0652017-03-06 22:18:34 +00001164 LV.getTBAAInfo());
1165 }
1166 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1167 // bitfield lvalue or some other non-simple lvalue?
1168 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001169 }
1170
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001171 case Expr::CXXDefaultArgExprClass:
1172 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001173 case Expr::CXXDefaultInitExprClass: {
1174 CXXDefaultInitExprScope Scope(*this);
1175 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1176 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001177 case Expr::CXXTypeidExprClass:
1178 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001179
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001180 case Expr::ObjCMessageExprClass:
1181 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001182 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001183 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001184 case Expr::StmtExprClass:
1185 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001186 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001187 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001188 case Expr::ArraySubscriptExprClass:
1189 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001190 case Expr::OMPArraySectionExprClass:
1191 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001192 case Expr::ExtVectorElementExprClass:
1193 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001194 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001195 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001196 case Expr::CompoundLiteralExprClass:
1197 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001198 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001199 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001200 case Expr::BinaryConditionalOperatorClass:
1201 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001202 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001203 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001204 case Expr::OpaqueValueExprClass:
1205 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001206 case Expr::SubstNonTypeTemplateParmExprClass:
1207 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001208 case Expr::ImplicitCastExprClass:
1209 case Expr::CStyleCastExprClass:
1210 case Expr::CXXFunctionalCastExprClass:
1211 case Expr::CXXStaticCastExprClass:
1212 case Expr::CXXDynamicCastExprClass:
1213 case Expr::CXXReinterpretCastExprClass:
1214 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001215 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001216 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001217
Douglas Gregorfe314812011-06-21 17:03:29 +00001218 case Expr::MaterializeTemporaryExprClass:
1219 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Eric Fiseliercddaf872017-06-15 19:43:36 +00001220
1221 case Expr::CoawaitExprClass:
1222 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1223 case Expr::CoyieldExprClass:
1224 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001225 }
1226}
1227
John McCall71335052012-03-10 03:05:10 +00001228/// Given an object of the given canonical type, can we safely copy a
1229/// value out of it based on its initializer?
1230static bool isConstantEmittableObjectType(QualType type) {
1231 assert(type.isCanonical());
1232 assert(!type->isReferenceType());
1233
1234 // Must be const-qualified but non-volatile.
1235 Qualifiers qs = type.getLocalQualifiers();
1236 if (!qs.hasConst() || qs.hasVolatile()) return false;
1237
1238 // Otherwise, all object types satisfy this except C++ classes with
1239 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001240 if (const auto *RT = dyn_cast<RecordType>(type))
1241 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001242 if (RD->hasMutableFields() || !RD->isTrivial())
1243 return false;
1244
1245 return true;
1246}
1247
1248/// Can we constant-emit a load of a reference to a variable of the
1249/// given type? This is different from predicates like
1250/// Decl::isUsableInConstantExpressions because we do want it to apply
1251/// in situations that don't necessarily satisfy the language's rules
1252/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1253/// to do this with const float variables even if those variables
1254/// aren't marked 'constexpr'.
1255enum ConstantEmissionKind {
1256 CEK_None,
1257 CEK_AsReferenceOnly,
1258 CEK_AsValueOrReference,
1259 CEK_AsValueOnly
1260};
1261static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1262 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001263 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001264 if (isConstantEmittableObjectType(ref->getPointeeType()))
1265 return CEK_AsValueOrReference;
1266 return CEK_AsReferenceOnly;
1267 }
1268 if (isConstantEmittableObjectType(type))
1269 return CEK_AsValueOnly;
1270 return CEK_None;
1271}
1272
1273/// Try to emit a reference to the given value without producing it as
1274/// an l-value. This is actually more than an optimization: we can't
1275/// produce an l-value for variables that we never actually captured
1276/// in a block or lambda, which means const int variables or constexpr
1277/// literals or similar.
1278CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001279CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1280 ValueDecl *value = refExpr->getDecl();
1281
John McCall71335052012-03-10 03:05:10 +00001282 // The value needs to be an enum constant or a constant variable.
1283 ConstantEmissionKind CEK;
1284 if (isa<ParmVarDecl>(value)) {
1285 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001286 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001287 CEK = checkVarTypeForConstantEmission(var->getType());
1288 } else if (isa<EnumConstantDecl>(value)) {
1289 CEK = CEK_AsValueOnly;
1290 } else {
1291 CEK = CEK_None;
1292 }
1293 if (CEK == CEK_None) return ConstantEmission();
1294
John McCall71335052012-03-10 03:05:10 +00001295 Expr::EvalResult result;
1296 bool resultIsReference;
1297 QualType resultType;
1298
1299 // It's best to evaluate all the way as an r-value if that's permitted.
1300 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001301 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001302 resultIsReference = false;
1303 resultType = refExpr->getType();
1304
1305 // Otherwise, try to evaluate as an l-value.
1306 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001307 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001308 resultIsReference = true;
1309 resultType = value->getType();
1310
1311 // Failure.
1312 } else {
1313 return ConstantEmission();
1314 }
1315
1316 // In any case, if the initializer has side-effects, abandon ship.
1317 if (result.HasSideEffects)
1318 return ConstantEmission();
1319
1320 // Emit as a constant.
1321 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1322
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001323 // Make sure we emit a debug reference to the global variable.
1324 // This should probably fire even for
1325 if (isa<VarDecl>(value)) {
1326 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001327 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001328 } else {
1329 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001330 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001331 }
John McCall71335052012-03-10 03:05:10 +00001332
1333 // If we emitted a reference constant, we need to dereference that.
1334 if (resultIsReference)
1335 return ConstantEmission::forReference(C);
1336
1337 return ConstantEmission::forValue(C);
1338}
1339
Nick Lewycky2d84e842013-10-02 02:29:49 +00001340llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1341 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001342 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001343 lvalue.getType(), Loc, lvalue.getBaseInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001344 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001345 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1346 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001347}
1348
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001349static bool hasBooleanRepresentation(QualType Ty) {
1350 if (Ty->isBooleanType())
1351 return true;
1352
1353 if (const EnumType *ET = Ty->getAs<EnumType>())
1354 return ET->getDecl()->getIntegerType()->isBooleanType();
1355
Douglas Gregor298f43d2012-04-12 20:42:30 +00001356 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1357 return hasBooleanRepresentation(AT->getValueType());
1358
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001359 return false;
1360}
1361
Richard Smith1629da92012-12-13 07:11:50 +00001362static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1363 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001364 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001365 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001366 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1367 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001368 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001369 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001370
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001371 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001372 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1373 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001374 } else {
1375 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001376 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001377 unsigned Bitwidth = LTy->getScalarSizeInBits();
1378 unsigned NumNegativeBits = ED->getNumNegativeBits();
1379 unsigned NumPositiveBits = ED->getNumPositiveBits();
1380
1381 if (NumNegativeBits) {
1382 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1383 assert(NumBits <= Bitwidth);
1384 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1385 Min = -End;
1386 } else {
1387 assert(NumPositiveBits <= Bitwidth);
1388 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1389 Min = llvm::APInt(Bitwidth, 0);
1390 }
1391 }
Richard Smith1629da92012-12-13 07:11:50 +00001392 return true;
1393}
1394
1395llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1396 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001397 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1398 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001399 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001400
Duncan Sandsc720e782012-04-15 18:04:54 +00001401 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001402 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001403}
1404
Vedant Kumar5a972652017-02-27 19:46:19 +00001405bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1406 SourceLocation Loc) {
1407 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1408 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1409 if (!HasBoolCheck && !HasEnumCheck)
1410 return false;
1411
1412 bool IsBool = hasBooleanRepresentation(Ty) ||
1413 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1414 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1415 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1416 if (!NeedsBoolCheck && !NeedsEnumCheck)
1417 return false;
1418
Vedant Kumar129edab2017-03-09 16:06:27 +00001419 // Single-bit booleans don't need to be checked. Special-case this to avoid
1420 // a bit width mismatch when handling bitfield values. This is handled by
1421 // EmitFromMemory for the non-bitfield case.
1422 if (IsBool &&
1423 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1424 return false;
1425
Vedant Kumar5a972652017-02-27 19:46:19 +00001426 llvm::APInt Min, End;
1427 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1428 return true;
1429
1430 SanitizerScope SanScope(this);
1431 llvm::Value *Check;
1432 --End;
1433 if (!Min) {
1434 Check = Builder.CreateICmpULE(
1435 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1436 } else {
1437 llvm::Value *Upper = Builder.CreateICmpSLE(
1438 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1439 llvm::Value *Lower = Builder.CreateICmpSGE(
1440 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1441 Check = Builder.CreateAnd(Upper, Lower);
1442 }
1443 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1444 EmitCheckTypeDescriptor(Ty)};
1445 SanitizerMask Kind =
1446 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1447 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1448 StaticArgs, EmitCheckValue(Value));
1449 return true;
1450}
1451
John McCall7f416cc2015-09-08 08:05:57 +00001452llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1453 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001454 SourceLocation Loc,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001455 LValueBaseInfo BaseInfo,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001456 llvm::MDNode *TBAAInfo,
1457 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001458 uint64_t TBAAOffset,
1459 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001460 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1461 // For better performance, handle vector loads differently.
1462 if (Ty->isVectorType()) {
1463 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001464
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001465 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001466
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001467 // Handle vectors of size 3 like size 4 for better performance.
1468 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001469
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001470 // Bitcast to vec4 type.
1471 llvm::VectorType *vec4Ty =
1472 llvm::VectorType::get(VTy->getElementType(), 4);
1473 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1474 // Now load value.
1475 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001476
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001477 // Shuffle vector to get vec3.
1478 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1479 {0, 1, 2}, "extractVec");
1480 return EmitFromMemory(V, Ty);
1481 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001482 }
1483 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001484
1485 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001486 LValue AtomicLValue =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001487 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001488 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1489 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001490 }
Craig Topper99e79272013-07-26 05:59:26 +00001491
John McCall7f416cc2015-09-08 08:05:57 +00001492 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001493 if (isNontemporal) {
1494 llvm::MDNode *Node = llvm::MDNode::get(
1495 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1496 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1497 }
Manman Renc451e572013-04-04 21:53:22 +00001498 if (TBAAInfo) {
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001499 bool MayAlias = BaseInfo.getMayAlias();
1500 llvm::MDNode *TBAA = MayAlias
1501 ? CGM.getTBAAInfo(getContext().CharTy)
1502 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1503 if (TBAA)
1504 CGM.DecorateInstructionWithTBAA(Load, TBAA, MayAlias);
Manman Renc451e572013-04-04 21:53:22 +00001505 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001506
Vedant Kumar5a972652017-02-27 19:46:19 +00001507 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1508 // In order to prevent the optimizer from throwing away the check, don't
1509 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001510 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001511 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1512 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001513
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001514 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001515}
1516
John McCall3a7f6922010-10-27 20:58:56 +00001517llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1518 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001519 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001520 // This should really always be an i1, but sometimes it's already
1521 // an i8, and it's awkward to track those cases down.
1522 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001523 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1524 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1525 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001526 }
1527
1528 return Value;
1529}
1530
1531llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1532 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001533 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001534 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1535 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001536 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1537 }
1538
1539 return Value;
1540}
1541
John McCall7f416cc2015-09-08 08:05:57 +00001542void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1543 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001544 LValueBaseInfo BaseInfo,
John McCall7f416cc2015-09-08 08:05:57 +00001545 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001546 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001547 uint64_t TBAAOffset,
1548 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001549
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001550 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1551 // Handle vectors differently to get better performance.
1552 if (Ty->isVectorType()) {
1553 llvm::Type *SrcTy = Value->getType();
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001554 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001555 // Handle vec3 special.
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001556 if (VecTy && VecTy->getNumElements() == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001557 // Our source is a vec3, do a shuffle vector to make it a vec4.
1558 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1559 Builder.getInt32(2),
1560 llvm::UndefValue::get(Builder.getInt32Ty())};
1561 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1562 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1563 MaskV, "extractVec");
1564 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1565 }
1566 if (Addr.getElementType() != SrcTy) {
1567 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1568 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001569 }
1570 }
Craig Topper99e79272013-07-26 05:59:26 +00001571
John McCall3a7f6922010-10-27 20:58:56 +00001572 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001573
David Majnemera38c9f12016-05-24 16:09:25 +00001574 LValue AtomicLValue =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001575 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001576 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001577 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1578 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001579 return;
1580 }
1581
Daniel Dunbar03816342010-08-21 02:24:36 +00001582 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001583 if (isNontemporal) {
1584 llvm::MDNode *Node =
1585 llvm::MDNode::get(Store->getContext(),
1586 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1587 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1588 }
Manman Renc451e572013-04-04 21:53:22 +00001589 if (TBAAInfo) {
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001590 bool MayAlias = BaseInfo.getMayAlias();
1591 llvm::MDNode *TBAA = MayAlias
1592 ? CGM.getTBAAInfo(getContext().CharTy)
1593 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1594 if (TBAA)
1595 CGM.DecorateInstructionWithTBAA(Store, TBAA, MayAlias);
Manman Renc451e572013-04-04 21:53:22 +00001596 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001597}
1598
David Chisnallfa35df62012-01-16 17:27:18 +00001599void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001600 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001601 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001602 lvalue.getType(), lvalue.getBaseInfo(),
Manman Renc451e572013-04-04 21:53:22 +00001603 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001604 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001605}
1606
Mike Stump4a3999f2009-09-09 13:00:44 +00001607/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1608/// method emits the address of the lvalue, then loads the result as an rvalue,
1609/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001610RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001611 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001612 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001613 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001614 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1615 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001616 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001617 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001618 // In MRC mode, we do a load+autorelease.
1619 if (!getLangOpts().ObjCAutoRefCount) {
1620 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1621 }
1622
1623 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001624 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1625 Object = EmitObjCConsumeObject(LV.getType(), Object);
1626 return RValue::get(Object);
1627 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001628
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001629 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001630 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001631
John McCalla1dee5302010-08-22 10:59:02 +00001632 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001633 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001634 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001635
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001636 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001637 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001638 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001639 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001640 "vecext"));
1641 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001642
1643 // If this is a reference to a subset of the elements of a vector, either
1644 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001645 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001646 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001647
Renato Golin230c5eb2014-05-19 18:15:42 +00001648 // Global Register variables always invoke intrinsics
1649 if (LV.isGlobalReg())
1650 return EmitLoadOfGlobalRegLValue(LV);
1651
John McCallc109a252011-11-07 03:59:57 +00001652 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001653 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001654}
1655
Vedant Kumar129edab2017-03-09 16:06:27 +00001656RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1657 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001658 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001659
Daniel Dunbar3447a022010-04-13 23:34:15 +00001660 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001661 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001662
John McCall7f416cc2015-09-08 08:05:57 +00001663 Address Ptr = LV.getBitFieldAddress();
1664 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001665
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001666 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001667 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001668 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1669 if (HighBits)
1670 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1671 if (Info.Offset + HighBits)
1672 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1673 } else {
1674 if (Info.Offset)
1675 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001676 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001677 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1678 Info.Size),
1679 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001680 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001681 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001682 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001683 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001684}
1685
Nate Begemanb699c9b2009-01-18 06:42:49 +00001686// If this is a reference to a subset of the elements of a vector, create an
1687// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001688RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001689 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1690 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001691
Nate Begemanf322eab2008-05-09 06:41:27 +00001692 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001693
1694 // If the result of the expression is a non-vector type, we must be extracting
1695 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001696 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001697 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001698 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001699 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001700 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001701 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001702
1703 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001704 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001705
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001706 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001707 for (unsigned i = 0; i != NumResultElts; ++i)
1708 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001709
Chris Lattner91c08ad2011-02-15 00:14:06 +00001710 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1711 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001712 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001713 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001714}
1715
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001716/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001717Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1718 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001719 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1720 QualType EQT = ExprVT->getElementType();
1721 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001722
John McCall7f416cc2015-09-08 08:05:57 +00001723 Address CastToPointerElement =
1724 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1725 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001726
1727 const llvm::Constant *Elts = LV.getExtVectorElts();
1728 unsigned ix = getAccessedFieldNo(0, Elts);
1729
John McCall7f416cc2015-09-08 08:05:57 +00001730 Address VectorBasePtrPlusIx =
1731 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1732 getContext().getTypeSizeInChars(EQT),
1733 "vector.elt");
1734
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001735 return VectorBasePtrPlusIx;
1736}
1737
Renato Golin230c5eb2014-05-19 18:15:42 +00001738/// @brief Load of global gamed gegisters are always calls to intrinsics.
1739RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001740 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1741 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001742 llvm::MDNode *RegName = cast<llvm::MDNode>(
1743 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001744
1745 // We accept integer and pointer types only
1746 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1747 llvm::Type *Ty = OrigTy;
1748 if (OrigTy->isPointerTy())
1749 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1750 llvm::Type *Types[] = { Ty };
1751
Renato Golin230c5eb2014-05-19 18:15:42 +00001752 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001753 llvm::Value *Call = Builder.CreateCall(
1754 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001755 if (OrigTy->isPointerTy())
1756 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001757 return RValue::get(Call);
1758}
Chris Lattner40ff7012007-08-03 16:18:34 +00001759
Chris Lattner9369a562007-06-29 16:31:29 +00001760
Chris Lattner8394d792007-06-05 20:53:16 +00001761/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1762/// lvalue, where both are guaranteed to the have the same type, and that type
1763/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001764void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001765 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001766 if (!Dst.isSimple()) {
1767 if (Dst.isVectorElt()) {
1768 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001769 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1770 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001771 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001772 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001773 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1774 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001775 return;
1776 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001777
Nate Begemance4d7fc2008-04-18 23:10:10 +00001778 // If this is an update of extended vector elements, insert them as
1779 // appropriate.
1780 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001781 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001782
Renato Golin230c5eb2014-05-19 18:15:42 +00001783 if (Dst.isGlobalReg())
1784 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1785
John McCallc109a252011-11-07 03:59:57 +00001786 assert(Dst.isBitField() && "Unknown LValue type");
1787 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001788 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001789
John McCall31168b02011-06-15 23:02:42 +00001790 // There's special magic for assigning into an ARC-qualified l-value.
1791 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1792 switch (Lifetime) {
1793 case Qualifiers::OCL_None:
1794 llvm_unreachable("present but none");
1795
1796 case Qualifiers::OCL_ExplicitNone:
1797 // nothing special
1798 break;
1799
1800 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001801 if (isInit) {
1802 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1803 break;
1804 }
John McCall55e1fbc2011-06-25 02:11:03 +00001805 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001806 return;
1807
1808 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001809 if (isInit)
1810 // Initialize and then skip the primitive store.
1811 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1812 else
1813 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001814 return;
1815
1816 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001817 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1818 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001819 // fall into the normal path
1820 break;
1821 }
1822 }
1823
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001824 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001825 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001826 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001827 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001828 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001829 return;
1830 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001831
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001832 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001833 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001834 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001835 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001836 if (Dst.isObjCIvar()) {
1837 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001838 llvm::Type *ResultType = IntPtrTy;
1839 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1840 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001841 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001842 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001843 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1844 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001845 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001846 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001847 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001848 } else if (Dst.isGlobalObjCRef()) {
1849 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1850 Dst.isThreadLocalRef());
1851 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001852 else
1853 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001854 return;
1855 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001856
Chris Lattner6278e6a2007-08-11 00:04:45 +00001857 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001858 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001859}
1860
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001861void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001862 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001863 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001864 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001865 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001866
Daniel Dunbar67aba792010-04-15 03:47:33 +00001867 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001868 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001869
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001870 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001871 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001872 /*IsSigned=*/false);
1873 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001874
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001875 // See if there are other bits in the bitfield's storage we'll need to load
1876 // and mask together with source before storing.
1877 if (Info.StorageSize != Info.Size) {
1878 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001879 llvm::Value *Val =
1880 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001881
1882 // Mask the source value as needed.
1883 if (!hasBooleanRepresentation(Dst.getType()))
1884 SrcVal = Builder.CreateAnd(SrcVal,
1885 llvm::APInt::getLowBitsSet(Info.StorageSize,
1886 Info.Size),
1887 "bf.value");
1888 MaskedVal = SrcVal;
1889 if (Info.Offset)
1890 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1891
1892 // Mask out the original value.
1893 Val = Builder.CreateAnd(Val,
1894 ~llvm::APInt::getBitsSet(Info.StorageSize,
1895 Info.Offset,
1896 Info.Offset + Info.Size),
1897 "bf.clear");
1898
1899 // Or together the unchanged values and the source value.
1900 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1901 } else {
1902 assert(Info.Offset == 0);
1903 }
1904
1905 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001906 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001907
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001908 // Return the new value of the bit-field, if requested.
1909 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001910 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001911
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001912 // Sign extend the value if needed.
1913 if (Info.IsSigned) {
1914 assert(Info.Size <= Info.StorageSize);
1915 unsigned HighBits = Info.StorageSize - Info.Size;
1916 if (HighBits) {
1917 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1918 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1919 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001920 }
1921
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001922 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1923 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001924 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001925 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001926}
1927
Nate Begemance4d7fc2008-04-18 23:10:10 +00001928void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001929 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001930 // This access turns into a read/modify/write of the vector. Load the input
1931 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001932 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1933 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001934 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001935
Chris Lattner4647a212007-08-31 22:49:20 +00001936 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001937
John McCall55e1fbc2011-06-25 02:11:03 +00001938 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001939 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001940 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001941 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001942 // Use shuffle vector is the src and destination are the same number of
1943 // elements and restore the vector mask since it is on the side it will be
1944 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001945 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001946 for (unsigned i = 0; i != NumSrcElts; ++i)
1947 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001948
Chris Lattner91c08ad2011-02-15 00:14:06 +00001949 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001950 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001951 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001952 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001953 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001954 // Extended the source vector to the same length and then shuffle it
1955 // into the destination.
1956 // FIXME: since we're shuffling with undef, can we just use the indices
1957 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001958 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001959 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001960 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001961 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001962 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001963 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001964 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001965 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001966 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001967 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001968 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001969 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001970 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001971
Joey Goulycf4143b2013-11-21 17:09:05 +00001972 // When the vector size is odd and .odd or .hi is used, the last element
1973 // of the Elts constant array will be one past the size of the vector.
1974 // Ignore the last element here, if it is greater than the mask size.
1975 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1976 NumSrcElts--;
1977
Nate Begemanb699c9b2009-01-18 06:42:49 +00001978 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001979 for (unsigned i = 0; i != NumSrcElts; ++i)
1980 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001981 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001982 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001983 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001984 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001985 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001986 }
1987 } else {
1988 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001989 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001990 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001991 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001992 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001993
John McCall7f416cc2015-09-08 08:05:57 +00001994 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1995 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001996}
1997
Renato Golin230c5eb2014-05-19 18:15:42 +00001998/// @brief Store of global named registers are always calls to intrinsics.
1999void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00002000 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2001 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002002 llvm::MDNode *RegName = cast<llvm::MDNode>(
2003 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00002004 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00002005
2006 // We accept integer and pointer types only
2007 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2008 llvm::Type *Ty = OrigTy;
2009 if (OrigTy->isPointerTy())
2010 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2011 llvm::Type *Types[] = { Ty };
2012
Renato Golin230c5eb2014-05-19 18:15:42 +00002013 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2014 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00002015 if (OrigTy->isPointerTy())
2016 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00002017 Builder.CreateCall(
2018 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00002019}
2020
Eric Christopherc9e2a682014-05-20 17:10:39 +00002021// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002022// generating write-barries API. It is currently a global, ivar,
2023// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002024static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002025 LValue &LV,
2026 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002027 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002028 return;
Craig Topper99e79272013-07-26 05:59:26 +00002029
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002030 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002031 QualType ExpTy = E->getType();
2032 if (IsMemberAccess && ExpTy->isPointerType()) {
2033 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00002034 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002035 // writer-barrier conservatively.
2036 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2037 if (ExpTy->isRecordType()) {
2038 LV.setObjCIvar(false);
2039 return;
2040 }
2041 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002042 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002043 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002044 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002045 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002046 return;
2047 }
Craig Topper99e79272013-07-26 05:59:26 +00002048
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002049 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2050 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00002051 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002052 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00002053 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002054 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002055 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002056 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002057 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002058 }
Craig Topper99e79272013-07-26 05:59:26 +00002059
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002060 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002061 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002062 return;
2063 }
Craig Topper99e79272013-07-26 05:59:26 +00002064
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002065 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002066 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002067 if (LV.isObjCIvar()) {
2068 // If cast is to a structure pointer, follow gcc's behavior and make it
2069 // a non-ivar write-barrier.
2070 QualType ExpTy = E->getType();
2071 if (ExpTy->isPointerType())
2072 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2073 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002074 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002075 }
2076 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002077 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002078
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002079 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002080 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2081 return;
2082 }
2083
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002084 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002085 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002086 return;
2087 }
Craig Topper99e79272013-07-26 05:59:26 +00002088
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002089 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002090 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002091 return;
2092 }
John McCall31168b02011-06-15 23:02:42 +00002093
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002094 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002095 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002096 return;
2097 }
2098
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002099 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002100 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002101 if (LV.isObjCIvar() && !LV.isObjCArray())
2102 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002103 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002104 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002105 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002106 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002107 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002108 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002109 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002110 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002111
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002112 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002113 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002114 // We don't know if member is an 'ivar', but this flag is looked at
2115 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002116 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002117 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002118 }
2119}
2120
Chris Lattner3f32d692011-07-12 06:52:18 +00002121static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002122EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002123 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002124 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002125 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002126 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002127}
2128
Alexey Bataev97720002014-11-11 04:05:39 +00002129static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002130 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2131 llvm::Type *RealVarTy, SourceLocation Loc) {
2132 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2133 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002134 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2135 return CGF.MakeAddrLValue(Addr, T, BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00002136}
2137
2138Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2139 const ReferenceType *RefTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002140 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002141 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2142 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002143 BaseInfo, /*forPointee*/ true));
John McCall7f416cc2015-09-08 08:05:57 +00002144}
2145
2146LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2147 const ReferenceType *RefTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002148 LValueBaseInfo BaseInfo;
2149 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2150 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002151}
2152
Alexey Bataev31300ed2016-02-04 11:27:03 +00002153Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2154 const PointerType *PtrTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002155 LValueBaseInfo *BaseInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002156 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002157 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2158 BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002159 /*forPointeeType=*/true));
2160}
2161
2162LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2163 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002164 LValueBaseInfo BaseInfo;
2165 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2166 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002167}
2168
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002169static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2170 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002171 QualType T = E->getType();
2172
2173 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002174 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2175 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002176 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2177
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002178 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002179 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2180 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002181 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002182 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002183 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002184 // Emit reference to the private copy of the variable if it is an OpenMP
2185 // threadprivate variable.
2186 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002187 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002188 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002189 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2190 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002191 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002192 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2193 LV = CGF.MakeAddrLValue(Addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002194 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002195 setObjCGCLValueClass(CGF.getContext(), E, LV);
2196 return LV;
2197}
2198
John McCallb92ab1a2016-10-26 23:46:34 +00002199static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2200 const FunctionDecl *FD) {
2201 if (FD->hasAttr<WeakRefAttr>()) {
2202 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2203 return aliasee.getPointer();
2204 }
2205
2206 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002207 if (!FD->hasPrototype()) {
2208 if (const FunctionProtoType *Proto =
2209 FD->getType()->getAs<FunctionProtoType>()) {
2210 // Ugly case: for a K&R-style definition, the type of the definition
2211 // isn't the same as the type of a use. Correct for this with a
2212 // bitcast.
2213 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002214 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2215 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2216 V = llvm::ConstantExpr::getBitCast(V,
2217 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002218 }
2219 }
John McCallb92ab1a2016-10-26 23:46:34 +00002220 return V;
2221}
2222
2223static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2224 const Expr *E, const FunctionDecl *FD) {
2225 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002226 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002227 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2228 return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002229}
2230
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002231static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2232 llvm::Value *ThisValue) {
2233 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2234 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2235 return CGF.EmitLValueForField(LV, FD);
2236}
2237
Renato Golin230c5eb2014-05-19 18:15:42 +00002238/// Named Registers are named metadata pointing to the register name
2239/// which will be read from/written to as an argument to the intrinsic
2240/// @llvm.read/write_register.
2241/// So far, only the name is being passed down, but other options such as
2242/// register type, allocation type or even optimization options could be
2243/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002244static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002245 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002246 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002247 assert(Asm->getLabel().size() < 64-Name.size() &&
2248 "Register name too big");
2249 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002250 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002251 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002252 if (M->getNumOperands() == 0) {
2253 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2254 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002255 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002256 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2257 }
John McCall7f416cc2015-09-08 08:05:57 +00002258
2259 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2260
2261 llvm::Value *Ptr =
2262 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2263 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002264}
2265
Chris Lattnerd7f58862007-06-02 05:24:33 +00002266LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002267 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002268 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002269
Renato Goline7b3d5d2014-05-27 16:46:27 +00002270 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2271 // Global Named registers access via intrinsics only
2272 if (VD->getStorageClass() == SC_Register &&
2273 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002274 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002275
Renato Goline7b3d5d2014-05-27 16:46:27 +00002276 // A DeclRefExpr for a reference initialized by a constant expression can
2277 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002278 const Expr *Init = VD->getAnyInitializer(VD);
2279 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2280 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002281 VD->checkInitIsICE() &&
2282 // Do not emit if it is private OpenMP variable.
2283 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2284 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002285 llvm::Constant *Val =
2286 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2287 assert(Val && "failed to emit reference constant expression");
2288 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002289
2290 // Should we be using the alignment of the constant pointer we emitted?
2291 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2292 /*pointee*/ true);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002293 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2294 return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo);
Richard Smith5a1104b2012-10-20 01:38:33 +00002295 }
David Majnemer602cfe72015-01-01 09:49:44 +00002296
2297 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002298 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002299 if (auto *FD = LambdaCaptureFields.lookup(VD))
2300 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2301 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002302 auto I = LocalDeclMap.find(VD);
2303 if (I != LocalDeclMap.end()) {
2304 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2305 return EmitLoadOfReferenceLValue(I->second, RefTy);
2306 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002307 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002308 LValue CapLVal =
2309 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2310 CapturedStmtInfo->getContextValue());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002311 bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002312 return MakeAddrLValue(
2313 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002314 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias));
David Majnemer602cfe72015-01-01 09:49:44 +00002315 }
John McCall7f416cc2015-09-08 08:05:57 +00002316
David Majnemer602cfe72015-01-01 09:49:44 +00002317 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002318 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002319 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2320 return MakeAddrLValue(addr, T, BaseInfo);
David Majnemer602cfe72015-01-01 09:49:44 +00002321 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002322 }
2323
Eli Friedman5720e342012-01-21 04:52:58 +00002324 // FIXME: We should be able to assert this for FunctionDecls as well!
2325 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2326 // those with a valid source location.
2327 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2328 !E->getLocation().isValid()) &&
2329 "Should not use decl without marking it used!");
2330
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002331 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002332 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002333 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002334 return MakeAddrLValue(Aliasee, T,
2335 LValueBaseInfo(AlignmentSource::Decl, false));
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002336 }
2337
Renato Goline7b3d5d2014-05-27 16:46:27 +00002338 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002339 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002340 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002341 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002342
John McCall7f416cc2015-09-08 08:05:57 +00002343 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002344
John McCall7f416cc2015-09-08 08:05:57 +00002345 // The variable should generally be present in the local decl map.
2346 auto iter = LocalDeclMap.find(VD);
2347 if (iter != LocalDeclMap.end()) {
2348 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002349
John McCall7f416cc2015-09-08 08:05:57 +00002350 // Otherwise, it might be static local we haven't emitted yet for
2351 // some reason; most likely, because it's in an outer function.
2352 } else if (VD->isStaticLocal()) {
2353 addr = Address(CGM.getOrCreateStaticVarDecl(
2354 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2355 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002356
John McCall7f416cc2015-09-08 08:05:57 +00002357 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002358 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002359 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2360 }
2361
2362
2363 // Check for OpenMP threadprivate variables.
2364 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2365 return EmitThreadPrivateVarDeclLValue(
2366 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2367 E->getExprLoc());
2368 }
2369
2370 // Drill into block byref variables.
2371 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2372 if (isBlockByref) {
2373 addr = emitBlockByrefAddress(addr, VD);
2374 }
2375
2376 // Drill into reference types.
2377 LValue LV;
2378 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2379 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2380 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002381 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2382 LV = MakeAddrLValue(addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002383 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002384
John McCallcdda29c2013-03-13 03:10:54 +00002385 bool isLocalStorage = VD->hasLocalStorage();
2386
2387 bool NonGCable = isLocalStorage &&
2388 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002389 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002390 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002391 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002392 LV.setNonGC(true);
2393 }
John McCallcdda29c2013-03-13 03:10:54 +00002394
2395 bool isImpreciseLifetime =
2396 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2397 if (isImpreciseLifetime)
2398 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002399 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002400 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002401 }
John McCallf3a88602011-02-03 08:15:49 +00002402
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002403 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002404 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002405
Richard Smithda383632016-08-15 01:33:41 +00002406 // FIXME: While we're emitting a binding from an enclosing scope, all other
2407 // DeclRefExprs we see should be implicitly treated as if they also refer to
2408 // an enclosing scope.
2409 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2410 return EmitLValue(BD->getBinding());
2411
David Blaikie83d382b2011-09-23 05:06:16 +00002412 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002413}
Chris Lattnere47e4402007-06-01 18:02:12 +00002414
Chris Lattner8394d792007-06-05 20:53:16 +00002415LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2416 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002417 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002418 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002419
Chris Lattner0f398c42008-07-26 22:37:01 +00002420 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002421 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002422 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002423 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002424 QualType T = E->getSubExpr()->getType()->getPointeeType();
2425 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002426
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002427 LValueBaseInfo BaseInfo;
2428 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo);
2429 LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002430 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002431
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002432 // We should not generate __weak write barrier on indirect reference
2433 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2434 // But, we continue to generate __strong write barrier on indirect write
2435 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002436 if (getLangOpts().ObjC1 &&
2437 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002438 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002439 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002440 return LV;
2441 }
John McCalle3027922010-08-25 11:45:40 +00002442 case UO_Real:
2443 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002444 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002445 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002446
Richard Smith0b6b8e42012-02-18 20:53:32 +00002447 // __real is valid on scalars. This is a faster way of testing that.
2448 // __imag can only produce an rvalue on scalars.
2449 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002450 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002451 assert(E->getSubExpr()->getType()->isArithmeticType());
2452 return LV;
2453 }
2454
Alexey Bataev611b0a12016-11-07 18:15:02 +00002455 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002456
John McCall7f416cc2015-09-08 08:05:57 +00002457 Address Component =
2458 (E->getOpcode() == UO_Real
2459 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2460 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002461 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo());
Alexey Bataev611b0a12016-11-07 18:15:02 +00002462 ElemLV.getQuals().addQualifiers(LV.getQuals());
2463 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002464 }
John McCalle3027922010-08-25 11:45:40 +00002465 case UO_PreInc:
2466 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002467 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002468 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002469
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002470 if (E->getType()->isAnyComplexType())
2471 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2472 else
2473 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2474 return LV;
2475 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002476 }
Chris Lattner8394d792007-06-05 20:53:16 +00002477}
2478
Chris Lattner4347e3692007-06-06 04:54:52 +00002479LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002480 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002481 E->getType(),
2482 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4347e3692007-06-06 04:54:52 +00002483}
2484
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002485LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002486 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002487 E->getType(),
2488 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002489}
2490
Mike Stump4a3999f2009-09-09 13:00:44 +00002491LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002492 auto SL = E->getFunctionName();
2493 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2494 StringRef FnName = CurFn->getName();
2495 if (FnName.startswith("\01"))
2496 FnName = FnName.substr(1);
2497 StringRef NameItems[] = {
2498 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2499 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002500 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002501 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2502 std::string Name = SL->getString();
2503 if (!Name.empty()) {
2504 unsigned Discriminator =
2505 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2506 if (Discriminator)
2507 Name += "_" + Twine(Discriminator + 1).str();
2508 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002509 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002510 } else {
2511 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002512 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002513 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002514 }
Alexey Bataevec474782014-10-09 08:45:04 +00002515 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002516 return MakeAddrLValue(C, E->getType(), BaseInfo);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002517}
2518
Richard Smithe30752c2012-10-09 19:52:38 +00002519/// Emit a type description suitable for use by a runtime sanitizer library. The
2520/// format of a type descriptor is
2521///
2522/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002523/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002524/// \endcode
2525///
Richard Smith683398a2012-10-09 23:55:19 +00002526/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2527/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002528llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002529 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002530 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002531 return C;
2532
Richard Smithe30752c2012-10-09 19:52:38 +00002533 uint16_t TypeKind = -1;
2534 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002535
Richard Smithe30752c2012-10-09 19:52:38 +00002536 if (T->isIntegerType()) {
2537 TypeKind = 0;
2538 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002539 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002540 } else if (T->isFloatingType()) {
2541 TypeKind = 1;
2542 TypeInfo = getContext().getTypeSize(T);
2543 }
2544
2545 // Format the type name as if for a diagnostic, including quotes and
2546 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002547 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002548 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2549 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002550 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002551 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002552
2553 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002554 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2555 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002556 };
2557 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2558
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002559 auto *GV = new llvm::GlobalVariable(
2560 CGM.getModule(), Descriptor->getType(),
2561 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002562 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002563 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002564
2565 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002566 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002567
Richard Smithe30752c2012-10-09 19:52:38 +00002568 return GV;
2569}
2570
2571llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2572 llvm::Type *TargetTy = IntPtrTy;
2573
Richard Smith48366f72013-03-22 00:47:07 +00002574 // Floating-point types which fit into intptr_t are bitcast to integers
2575 // and then passed directly (after zero-extension, if necessary).
2576 if (V->getType()->isFloatingPointTy()) {
2577 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2578 if (Bits <= TargetTy->getIntegerBitWidth())
2579 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2580 Bits));
2581 }
2582
Richard Smithe30752c2012-10-09 19:52:38 +00002583 // Integers which fit in intptr_t are zero-extended and passed directly.
2584 if (V->getType()->isIntegerTy() &&
2585 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2586 return Builder.CreateZExt(V, TargetTy);
2587
2588 // Pointers are passed directly, everything else is passed by address.
2589 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002590 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002591 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002592 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002593 }
2594 return Builder.CreatePtrToInt(V, TargetTy);
2595}
2596
2597/// \brief Emit a representation of a SourceLocation for passing to a handler
2598/// in a sanitizer runtime library. The format for this data is:
2599/// \code
2600/// struct SourceLocation {
2601/// const char *Filename;
2602/// int32_t Line, Column;
2603/// };
2604/// \endcode
2605/// For an invalid SourceLocation, the Filename pointer is null.
2606llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002607 llvm::Constant *Filename;
2608 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002609
Alexey Samsonov6c124142014-07-18 17:50:06 +00002610 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2611 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002612 StringRef FilenameString = PLoc.getFilename();
2613
2614 int PathComponentsToStrip =
2615 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2616 if (PathComponentsToStrip < 0) {
2617 assert(PathComponentsToStrip != INT_MIN);
2618 int PathComponentsToKeep = -PathComponentsToStrip;
2619 auto I = llvm::sys::path::rbegin(FilenameString);
2620 auto E = llvm::sys::path::rend(FilenameString);
2621 while (I != E && --PathComponentsToKeep)
2622 ++I;
2623
2624 FilenameString = FilenameString.substr(I - E);
2625 } else if (PathComponentsToStrip > 0) {
2626 auto I = llvm::sys::path::begin(FilenameString);
2627 auto E = llvm::sys::path::end(FilenameString);
2628 while (I != E && PathComponentsToStrip--)
2629 ++I;
2630
2631 if (I != E)
2632 FilenameString =
2633 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2634 else
2635 FilenameString = llvm::sys::path::filename(FilenameString);
2636 }
2637
2638 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002639 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2640 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2641 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002642 Line = PLoc.getLine();
2643 Column = PLoc.getColumn();
2644 } else {
2645 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2646 Line = Column = 0;
2647 }
2648
2649 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2650 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002651
2652 return llvm::ConstantStruct::getAnon(Data);
2653}
2654
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002655namespace {
2656/// \brief Specify under what conditions this check can be recovered
2657enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002658 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002659 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002660 /// Check supports recovering, runtime has both fatal (noreturn) and
2661 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002662 Recoverable,
2663 /// Runtime conditionally aborts, always need to support recovery.
2664 AlwaysRecoverable
2665};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002666}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002667
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002668static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2669 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002670 switch (Kind) {
2671 case SanitizerKind::Vptr:
2672 return CheckRecoverableKind::AlwaysRecoverable;
2673 case SanitizerKind::Return:
2674 case SanitizerKind::Unreachable:
2675 return CheckRecoverableKind::Unrecoverable;
2676 default:
2677 return CheckRecoverableKind::Recoverable;
2678 }
2679}
2680
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002681namespace {
2682struct SanitizerHandlerInfo {
2683 char const *const Name;
2684 unsigned Version;
2685};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002686}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002687
2688const SanitizerHandlerInfo SanitizerHandlers[] = {
2689#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2690 LIST_SANITIZER_CHECKS
2691#undef SANITIZER_CHECK
2692};
2693
Alexey Samsonov88459522015-01-12 22:39:12 +00002694static void emitCheckHandlerCall(CodeGenFunction &CGF,
2695 llvm::FunctionType *FnType,
2696 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002697 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002698 CheckRecoverableKind RecoverKind, bool IsFatal,
2699 llvm::BasicBlock *ContBB) {
2700 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2701 bool NeedsAbortSuffix =
2702 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002703 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2704 const StringRef CheckName = CheckInfo.Name;
2705 std::string FnName =
2706 ("__ubsan_handle_" + CheckName +
Vedant Kumar4881bdf2016-12-12 18:47:33 +00002707 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002708 (NeedsAbortSuffix ? "_abort" : ""))
2709 .str();
Alexey Samsonov88459522015-01-12 22:39:12 +00002710 bool MayReturn =
2711 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2712
2713 llvm::AttrBuilder B;
2714 if (!MayReturn) {
2715 B.addAttribute(llvm::Attribute::NoReturn)
2716 .addAttribute(llvm::Attribute::NoUnwind);
2717 }
2718 B.addAttribute(llvm::Attribute::UWTable);
2719
2720 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2721 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002722 llvm::AttributeList::get(CGF.getLLVMContext(),
2723 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002724 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002725 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2726 if (!MayReturn) {
2727 HandlerCall->setDoesNotReturn();
2728 CGF.Builder.CreateUnreachable();
2729 } else {
2730 CGF.Builder.CreateBr(ContBB);
2731 }
2732}
2733
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002734void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002735 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002736 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002737 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002738 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002739 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002740 assert(CheckHandler >= 0 &&
2741 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2742 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002743
2744 llvm::Value *FatalCond = nullptr;
2745 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002746 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002747 for (int i = 0, n = Checked.size(); i < n; ++i) {
2748 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002749 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002750 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002751 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2752 ? TrapCond
2753 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2754 ? RecoverableCond
2755 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002756 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2757 }
2758
Peter Collingbourne9881b782015-06-18 23:59:22 +00002759 if (TrapCond)
2760 EmitTrapCheck(TrapCond);
2761 if (!FatalCond && !RecoverableCond)
2762 return;
2763
Alexey Samsonov88459522015-01-12 22:39:12 +00002764 llvm::Value *JointCond;
2765 if (FatalCond && RecoverableCond)
2766 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2767 else
2768 JointCond = FatalCond ? FatalCond : RecoverableCond;
2769 assert(JointCond);
2770
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002771 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002772 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002773#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002774 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002775 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002776 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002777 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002778 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002779#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002780
Richard Smith4d1458e2012-09-08 02:08:36 +00002781 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002782 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2783 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002784 // Give hint that we very much don't expect to execute the handler
2785 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2786 llvm::MDBuilder MDHelper(getLLVMContext());
2787 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2788 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002789 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002790
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002791 // Handler functions take an i8* pointing to the (handler-specific) static
2792 // information block, followed by a sequence of intptr_t arguments
2793 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002794 SmallVector<llvm::Value *, 4> Args;
2795 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002796 Args.reserve(DynamicArgs.size() + 1);
2797 ArgTypes.reserve(DynamicArgs.size() + 1);
2798
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002799 // Emit handler arguments and create handler function type.
2800 if (!StaticArgs.empty()) {
2801 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2802 auto *InfoPtr =
2803 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2804 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002805 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002806 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2807 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2808 ArgTypes.push_back(Int8PtrTy);
2809 }
2810
Richard Smithe30752c2012-10-09 19:52:38 +00002811 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2812 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2813 ArgTypes.push_back(IntPtrTy);
2814 }
2815
2816 llvm::FunctionType *FnType =
2817 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002818
Alexey Samsonov88459522015-01-12 22:39:12 +00002819 if (!FatalCond || !RecoverableCond) {
2820 // Simple case: we need to generate a single handler call, either
2821 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002822 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002823 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002824 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002825 // Emit two handler calls: first one for set of unrecoverable checks,
2826 // another one for recoverable.
2827 llvm::BasicBlock *NonFatalHandlerBB =
2828 createBasicBlock("non_fatal." + CheckName);
2829 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2830 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2831 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002832 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002833 NonFatalHandlerBB);
2834 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002835 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002836 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002837 }
Richard Smithe30752c2012-10-09 19:52:38 +00002838
Richard Smith4d1458e2012-09-08 02:08:36 +00002839 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002840}
2841
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002842void CodeGenFunction::EmitCfiSlowPathCheck(
2843 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2844 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002845 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2846
2847 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2848 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2849
2850 llvm::MDBuilder MDHelper(getLLVMContext());
2851 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2852 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2853
2854 EmitBlock(CheckBB);
2855
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002856 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2857
2858 llvm::CallInst *CheckCall;
2859 if (WithDiag) {
2860 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2861 auto *InfoPtr =
2862 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2863 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002864 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002865 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2866
2867 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2868 "__cfi_slowpath_diag",
2869 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2870 false));
2871 CheckCall = Builder.CreateCall(
2872 SlowPathDiagFn,
2873 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2874 } else {
2875 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2876 "__cfi_slowpath",
2877 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2878 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2879 }
2880
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002881 CheckCall->setDoesNotThrow();
2882
2883 EmitBlock(Cont);
2884}
2885
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00002886// Emit a stub for __cfi_check function so that the linker knows about this
2887// symbol in LTO mode.
2888void CodeGenFunction::EmitCfiCheckStub() {
2889 llvm::Module *M = &CGM.getModule();
2890 auto &Ctx = M->getContext();
2891 llvm::Function *F = llvm::Function::Create(
2892 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2893 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2894 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2895 // FIXME: consider emitting an intrinsic call like
2896 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2897 // which can be lowered in CrossDSOCFI pass to the actual contents of
2898 // __cfi_check. This would allow inlining of __cfi_check calls.
2899 llvm::CallInst::Create(
2900 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2901 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2902}
2903
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002904// This function is basically a switch over the CFI failure kind, which is
2905// extracted from CFICheckFailData (1st function argument). Each case is either
2906// llvm.trap or a call to one of the two runtime handlers, based on
2907// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2908// failure kind) traps, but this should really never happen. CFICheckFailData
2909// can be nullptr if the calling module has -fsanitize-trap behavior for this
2910// check kind; in this case __cfi_check_fail traps as well.
2911void CodeGenFunction::EmitCfiCheckFail() {
2912 SanitizerScope SanScope(this);
2913 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002914 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2915 ImplicitParamDecl::Other);
2916 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2917 ImplicitParamDecl::Other);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002918 Args.push_back(&ArgData);
2919 Args.push_back(&ArgAddr);
2920
John McCallc56a8b32016-03-11 04:30:31 +00002921 const CGFunctionInfo &FI =
2922 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002923
2924 llvm::Function *F = llvm::Function::Create(
2925 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2926 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2927 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2928
2929 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2930 SourceLocation());
2931
2932 llvm::Value *Data =
2933 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2934 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2935 llvm::Value *Addr =
2936 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2937 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2938
2939 // Data == nullptr means the calling module has trap behaviour for this check.
2940 llvm::Value *DataIsNotNullPtr =
2941 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2942 EmitTrapCheck(DataIsNotNullPtr);
2943
2944 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002945 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002946 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002947 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002948
2949 llvm::Value *V = Builder.CreateConstGEP2_32(
2950 CfiCheckFailDataTy,
2951 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2952 0);
2953 Address CheckKindAddr(V, getIntAlign());
2954 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2955
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002956 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2957 CGM.getLLVMContext(),
2958 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2959 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002960 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002961 {Addr, AllVtables}),
2962 IntPtrTy);
2963
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002964 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002965 {CFITCK_VCall, SanitizerKind::CFIVCall},
2966 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2967 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2968 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2969 {CFITCK_ICall, SanitizerKind::CFIICall}};
2970
2971 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2972 for (auto CheckKindMaskPair : CheckKinds) {
2973 int Kind = CheckKindMaskPair.first;
2974 SanitizerMask Mask = CheckKindMaskPair.second;
2975 llvm::Value *Cond =
2976 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002977 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002978 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002979 {Data, Addr, ValidVtable});
2980 else
2981 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002982 }
2983
2984 FinishFunction();
2985 // The only reference to this function will be created during LTO link.
2986 // Make sure it survives until then.
2987 CGM.addUsedGlobal(F);
2988}
2989
Chad Rosierae229d52013-01-29 23:31:22 +00002990void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002991 llvm::BasicBlock *Cont = createBasicBlock("cont");
2992
2993 // If we're optimizing, collapse all calls to trap down to just one per
2994 // function to save on code size.
2995 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2996 TrapBB = createBasicBlock("trap");
2997 Builder.CreateCondBr(Checked, Cont, TrapBB);
2998 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002999 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00003000 TrapCall->setDoesNotReturn();
3001 TrapCall->setDoesNotThrow();
3002 Builder.CreateUnreachable();
3003 } else {
3004 Builder.CreateCondBr(Checked, Cont, TrapBB);
3005 }
3006
3007 EmitBlock(Cont);
3008}
3009
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003010llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00003011 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003012
Amaury Sechet21f51b32016-09-09 04:42:49 +00003013 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3014 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3015 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00003016 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00003017 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003018
3019 return TrapCall;
3020}
3021
John McCall7f416cc2015-09-08 08:05:57 +00003022Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003023 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00003024 assert(E->getType()->isArrayType() &&
3025 "Array to pointer decay must have array source type!");
3026
3027 // Expressions of array type can't be bitfields or vector elements.
3028 LValue LV = EmitLValue(E);
3029 Address Addr = LV.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003030 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003031
3032 // If the array type was an incomplete type, we need to make sure
3033 // the decay ends up being the right type.
3034 llvm::Type *NewTy = ConvertType(E->getType());
3035 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3036
3037 // Note that VLA pointers are always decayed, so we don't need to do
3038 // anything here.
3039 if (!E->getType()->isVariableArrayType()) {
3040 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3041 "Expected pointer to array");
3042 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3043 }
3044
3045 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3046 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3047}
3048
Chris Lattner6c5abe82010-06-26 23:03:20 +00003049/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3050/// array to pointer, return the array subexpression.
3051static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3052 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003053 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00003054 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00003055 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003056
Chris Lattner6c5abe82010-06-26 23:03:20 +00003057 // If this is a decay from variable width array, bail out.
3058 const Expr *SubExpr = CE->getSubExpr();
3059 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00003060 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003061
Chris Lattner6c5abe82010-06-26 23:03:20 +00003062 return SubExpr;
3063}
3064
John McCall7f416cc2015-09-08 08:05:57 +00003065static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3066 llvm::Value *ptr,
3067 ArrayRef<llvm::Value*> indices,
3068 bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003069 bool signedIndices,
Vedant Kumara125eb52017-06-01 19:22:18 +00003070 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003071 const llvm::Twine &name = "arrayidx") {
3072 if (inbounds) {
Vedant Kumar175b6d12017-07-13 20:55:26 +00003073 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3074 CodeGenFunction::NotSubtraction, loc,
3075 name);
John McCall7f416cc2015-09-08 08:05:57 +00003076 } else {
3077 return CGF.Builder.CreateGEP(ptr, indices, name);
3078 }
3079}
3080
3081static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3082 llvm::Value *idx,
3083 CharUnits eltSize) {
3084 // If we have a constant index, we can use the exact offset of the
3085 // element we're accessing.
3086 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3087 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3088 return arrayAlign.alignmentAtOffset(offset);
3089
3090 // Otherwise, use the worst-case alignment for any element.
3091 } else {
3092 return arrayAlign.alignmentOfArrayElement(eltSize);
3093 }
3094}
3095
3096static QualType getFixedSizeElementType(const ASTContext &ctx,
3097 const VariableArrayType *vla) {
3098 QualType eltType;
3099 do {
3100 eltType = vla->getElementType();
3101 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3102 return eltType;
3103}
3104
3105static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
Vedant Kumara125eb52017-06-01 19:22:18 +00003106 ArrayRef<llvm::Value *> indices,
John McCall7f416cc2015-09-08 08:05:57 +00003107 QualType eltType, bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003108 bool signedIndices, SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003109 const llvm::Twine &name = "arrayidx") {
3110 // All the indices except that last must be zero.
3111#ifndef NDEBUG
3112 for (auto idx : indices.drop_back())
3113 assert(isa<llvm::ConstantInt>(idx) &&
3114 cast<llvm::ConstantInt>(idx)->isZero());
3115#endif
3116
3117 // Determine the element size of the statically-sized base. This is
3118 // the thing that the indices are expressed in terms of.
3119 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3120 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3121 }
3122
3123 // We can use that to compute the best alignment of the element.
3124 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3125 CharUnits eltAlign =
3126 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3127
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003128 llvm::Value *eltPtr = emitArraySubscriptGEP(
3129 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
John McCall7f416cc2015-09-08 08:05:57 +00003130 return Address(eltPtr, eltAlign);
3131}
3132
Richard Smith539e4a72013-02-23 02:53:19 +00003133LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3134 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003135 // The index must always be an integer, which is not an aggregate. Emit it
3136 // in lexical order (this complexity is, sadly, required by C++17).
3137 llvm::Value *IdxPre =
3138 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003139 bool SignedIndices = false;
Richard Smith40885712016-09-27 00:53:24 +00003140 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003141 auto *Idx = IdxPre;
3142 if (E->getLHS() != E->getIdx()) {
3143 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3144 Idx = EmitScalarExpr(E->getIdx());
3145 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003146
Richard Smith9e67b992016-09-26 23:49:47 +00003147 QualType IdxTy = E->getIdx()->getType();
3148 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003149 SignedIndices |= IdxSigned;
Richard Smith9e67b992016-09-26 23:49:47 +00003150
3151 if (SanOpts.has(SanitizerKind::ArrayBounds))
3152 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3153
3154 // Extend or truncate the index type to 32 or 64-bits.
3155 if (Promote && Idx->getType() != IntPtrTy)
3156 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3157
3158 return Idx;
3159 };
3160 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003161
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003162 // If the base is a vector type, then we are forming a vector element lvalue
3163 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003164 if (E->getBase()->getType()->isVectorType() &&
3165 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003166 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003167 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003168 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003169 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00003170 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00003171 E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003172 LHS.getBaseInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003173 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003174
John McCall7f416cc2015-09-08 08:05:57 +00003175 // All the other cases basically behave like simple offsetting.
3176
John McCall7f416cc2015-09-08 08:05:57 +00003177 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003178 if (isa<ExtVectorElementExpr>(E->getBase())) {
3179 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003180 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003181 Address Addr = EmitExtVectorElementLValue(LV);
3182
3183 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
Vedant Kumara125eb52017-06-01 19:22:18 +00003184 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003185 SignedIndices, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003186 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003187 }
John McCall7f416cc2015-09-08 08:05:57 +00003188
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003189 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003190 Address Addr = Address::invalid();
3191 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003192 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003193 // The base must be a pointer, which is not an aggregate. Emit
3194 // it. It needs to be emitted first in case it's what captures
3195 // the VLA bounds.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003196 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003197 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003198
John McCall23c29fe2011-06-24 21:55:10 +00003199 // The element count here is the total number of non-VLA elements.
3200 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003201
John McCall77527a82011-06-25 01:32:37 +00003202 // Effectively, the multiply by the VLA size is part of the GEP.
3203 // GEP indexes are signed, and scaling an index isn't permitted to
3204 // signed-overflow, so we use the same semantics for our explicit
3205 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003206 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003207 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003208 } else {
3209 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003210 }
John McCall7f416cc2015-09-08 08:05:57 +00003211
3212 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003213 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003214 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003215
Chris Lattner6c5abe82010-06-26 23:03:20 +00003216 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3217 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003218
John McCall7f416cc2015-09-08 08:05:57 +00003219 // Emit the base pointer.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003220 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003221 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3222
3223 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3224 llvm::Value *InterfaceSizeVal =
3225 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3226
3227 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003228
3229 // We don't necessarily build correct LLVM struct types for ObjC
3230 // interfaces, so we can't rely on GEP to do this scaling
3231 // correctly, so we need to cast to i8*. FIXME: is this actually
3232 // true? A lot of other things in the fragile ABI would break...
3233 llvm::Type *OrigBaseTy = Addr.getType();
3234 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3235
3236 // Do the GEP.
3237 CharUnits EltAlign =
3238 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003239 llvm::Value *EltPtr =
3240 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3241 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003242 Addr = Address(EltPtr, EltAlign);
3243
3244 // Cast back.
3245 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003246 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3247 // If this is A[i] where A is an array, the frontend will have decayed the
3248 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3249 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3250 // "gep x, i" here. Emit one "gep A, 0, i".
3251 assert(Array->getType()->isArrayType() &&
3252 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003253 LValue ArrayLV;
3254 // For simple multidimensional array indexing, set the 'accessed' flag for
3255 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003256 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003257 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3258 else
3259 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003260 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003261
Daniel Dunbar82634272011-04-01 00:49:43 +00003262 // Propagate the alignment from the array itself to the result.
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003263 Addr = emitArraySubscriptGEP(
3264 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3265 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3266 E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003267 BaseInfo = ArrayLV.getBaseInfo();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003268 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003269 // The base must be a pointer; emit it with an estimate of its alignment.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003270 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003271 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003272 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003273 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003274 SignedIndices, E->getExprLoc());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003275 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003276
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003277 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo);
Mike Stump4a3999f2009-09-09 13:00:44 +00003278
John McCall7f416cc2015-09-08 08:05:57 +00003279 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003280
Richard Smith9c6890a2012-11-01 22:30:59 +00003281 if (getLangOpts().ObjC1 &&
3282 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003283 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003284 setObjCGCLValueClass(getContext(), E, LV);
3285 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003286 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003287}
3288
Alexey Bataev31300ed2016-02-04 11:27:03 +00003289static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003290 LValueBaseInfo &BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003291 QualType BaseTy, QualType ElTy,
3292 bool IsLowerBound) {
3293 LValue BaseLVal;
3294 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3295 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3296 if (BaseTy->isArrayType()) {
3297 Address Addr = BaseLVal.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003298 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003299
3300 // If the array type was an incomplete type, we need to make sure
3301 // the decay ends up being the right type.
3302 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3303 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3304
3305 // Note that VLA pointers are always decayed, so we don't need to do
3306 // anything here.
3307 if (!BaseTy->isVariableArrayType()) {
3308 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3309 "Expected pointer to array");
3310 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3311 "arraydecay");
3312 }
3313
3314 return CGF.Builder.CreateElementBitCast(Addr,
3315 CGF.ConvertTypeForMem(ElTy));
3316 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003317 LValueBaseInfo TypeInfo;
3318 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3319 BaseInfo.mergeForCast(TypeInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003320 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3321 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003322 return CGF.EmitPointerWithAlignment(Base, &BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003323}
3324
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003325LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3326 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003327 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003328 if (auto *ASE =
3329 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003330 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003331 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003332 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003333 QualType ResultExprTy;
3334 if (auto *AT = getContext().getAsArrayType(BaseTy))
3335 ResultExprTy = AT->getElementType();
3336 else
3337 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003338 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003339 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003340 // Requesting lower bound or upper bound, but without provided length and
3341 // without ':' symbol for the default length -> length = 1.
3342 // Idx = LowerBound ?: 0;
3343 if (auto *LowerBound = E->getLowerBound()) {
3344 Idx = Builder.CreateIntCast(
3345 EmitScalarExpr(LowerBound), IntPtrTy,
3346 LowerBound->getType()->hasSignedIntegerRepresentation());
3347 } else
3348 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3349 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003350 // Try to emit length or lower bound as constant. If this is possible, 1
3351 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3352 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003353 auto &C = CGM.getContext();
3354 auto *Length = E->getLength();
3355 llvm::APSInt ConstLength;
3356 if (Length) {
3357 // Idx = LowerBound + Length - 1;
3358 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3359 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3360 Length = nullptr;
3361 }
3362 auto *LowerBound = E->getLowerBound();
3363 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3364 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3365 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3366 LowerBound = nullptr;
3367 }
3368 if (!Length)
3369 --ConstLength;
3370 else if (!LowerBound)
3371 --ConstLowerBound;
3372
3373 if (Length || LowerBound) {
3374 auto *LowerBoundVal =
3375 LowerBound
3376 ? Builder.CreateIntCast(
3377 EmitScalarExpr(LowerBound), IntPtrTy,
3378 LowerBound->getType()->hasSignedIntegerRepresentation())
3379 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3380 auto *LengthVal =
3381 Length
3382 ? Builder.CreateIntCast(
3383 EmitScalarExpr(Length), IntPtrTy,
3384 Length->getType()->hasSignedIntegerRepresentation())
3385 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3386 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3387 /*HasNUW=*/false,
3388 !getLangOpts().isSignedOverflowDefined());
3389 if (Length && LowerBound) {
3390 Idx = Builder.CreateSub(
3391 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3392 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3393 }
3394 } else
3395 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3396 } else {
3397 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003398 QualType ArrayTy = BaseTy->isPointerType()
3399 ? E->getBase()->IgnoreParenImpCasts()->getType()
3400 : BaseTy;
3401 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003402 Length = VAT->getSizeExpr();
3403 if (Length->isIntegerConstantExpr(ConstLength, C))
3404 Length = nullptr;
3405 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003406 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003407 ConstLength = CAT->getSize();
3408 }
3409 if (Length) {
3410 auto *LengthVal = Builder.CreateIntCast(
3411 EmitScalarExpr(Length), IntPtrTy,
3412 Length->getType()->hasSignedIntegerRepresentation());
3413 Idx = Builder.CreateSub(
3414 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3415 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3416 } else {
3417 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3418 --ConstLength;
3419 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3420 }
3421 }
3422 }
3423 assert(Idx);
3424
Alexey Bataev31300ed2016-02-04 11:27:03 +00003425 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003426 LValueBaseInfo BaseInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003427 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003428 // The base must be a pointer, which is not an aggregate. Emit
3429 // it. It needs to be emitted first in case it's what captures
3430 // the VLA bounds.
3431 Address Base =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003432 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003433 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003434 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003435 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003436
3437 // Effectively, the multiply by the VLA size is part of the GEP.
3438 // GEP indexes are signed, and scaling an index isn't permitted to
3439 // signed-overflow, so we use the same semantics for our explicit
3440 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003441 if (getLangOpts().isSignedOverflowDefined())
3442 Idx = Builder.CreateMul(Idx, NumElements);
3443 else
3444 Idx = Builder.CreateNSWMul(Idx, NumElements);
3445 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003446 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003447 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003448 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3449 // If this is A[i] where A is an array, the frontend will have decayed the
3450 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3451 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3452 // "gep x, i" here. Emit one "gep A, 0, i".
3453 assert(Array->getType()->isArrayType() &&
3454 "Array to pointer decay must have array source type!");
3455 LValue ArrayLV;
3456 // For simple multidimensional array indexing, set the 'accessed' flag for
3457 // better bounds-checking of the base expression.
3458 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3459 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3460 else
3461 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003462
Alexey Bataev31300ed2016-02-04 11:27:03 +00003463 // Propagate the alignment from the array itself to the result.
3464 EltPtr = emitArraySubscriptGEP(
3465 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumara125eb52017-06-01 19:22:18 +00003466 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003467 /*SignedIndices=*/false, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003468 BaseInfo = ArrayLV.getBaseInfo();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003469 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003470 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003471 BaseTy, ResultExprTy, IsLowerBound);
3472 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
Vedant Kumara125eb52017-06-01 19:22:18 +00003473 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003474 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003475 }
3476
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003477 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003478}
3479
Chris Lattner9e751ca2007-08-02 23:37:31 +00003480LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003481EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003482 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003483 LValue Base;
3484
3485 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003486 if (E->isArrow()) {
3487 // If it is a pointer to a vector, emit the address and form an lvalue with
3488 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003489 LValueBaseInfo BaseInfo;
3490 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003491 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003492 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003493 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003494 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003495 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3496 // emit the base as an lvalue.
3497 assert(E->getBase()->getType()->isVectorType());
3498 Base = EmitLValue(E->getBase());
3499 } else {
3500 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003501 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003502 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003503 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003504
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003505 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003506 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003507 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003508 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003509 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4e1a3232009-12-23 21:31:11 +00003510 }
John McCall1553b192011-06-16 04:16:24 +00003511
3512 QualType type =
3513 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003514
Nate Begemand3862152008-05-13 21:03:02 +00003515 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003516 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003517 E->getEncodedElementAccess(Indices);
3518
3519 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003520 llvm::Constant *CV =
3521 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003522 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003523 Base.getBaseInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003524 }
3525 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3526
3527 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003528 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003529
Chris Lattner595ba3a2012-01-30 06:20:36 +00003530 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3531 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003532 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003533 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003534 Base.getBaseInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003535}
3536
Devang Patel30efa2e2007-10-23 20:28:39 +00003537LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003538 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003539 // 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 +00003540 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003541 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003542 LValueBaseInfo BaseInfo;
3543 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003544 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003545 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003546 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3547 if (IsBaseCXXThis)
3548 SkippedChecks.set(SanitizerKind::Alignment, true);
3549 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003550 SkippedChecks.set(SanitizerKind::Null, true);
3551 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3552 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003553 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003554 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003555 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003556
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003557 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003558 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003559 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003560 setObjCGCLValueClass(getContext(), E, LV);
3561 return LV;
3562 }
Craig Topper99e79272013-07-26 05:59:26 +00003563
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003564 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003565 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003566
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003567 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003568 return EmitFunctionDeclLValue(*this, E, FD);
3569
David Blaikie83d382b2011-09-23 05:06:16 +00003570 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003571}
Devang Patel30efa2e2007-10-23 20:28:39 +00003572
John McCalldec348f72013-05-03 07:33:41 +00003573/// Given that we are currently emitting a lambda, emit an l-value for
3574/// one of its members.
3575LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3576 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3577 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3578 QualType LambdaTagType =
3579 getContext().getTagDeclType(Field->getParent());
3580 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3581 return EmitLValueForField(LambdaLV, Field);
3582}
3583
John McCall7f416cc2015-09-08 08:05:57 +00003584/// Drill down to the storage of a field without walking into
3585/// reference types.
3586///
3587/// The resulting address doesn't necessarily have the right type.
3588static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3589 const FieldDecl *field) {
3590 const RecordDecl *rec = field->getParent();
3591
3592 unsigned idx =
3593 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3594
3595 CharUnits offset;
3596 // Adjust the alignment down to the given offset.
3597 // As a special case, if the LLVM field index is 0, we know that this
3598 // is zero.
3599 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3600 .getFieldOffset(field->getFieldIndex()) == 0) &&
3601 "LLVM field at index zero had non-zero offset?");
3602 if (idx != 0) {
3603 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3604 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3605 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3606 }
3607
3608 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3609}
3610
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003611static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3612 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3613 if (!RD)
3614 return false;
3615
3616 if (RD->isDynamicClass())
3617 return true;
3618
3619 for (const auto &Base : RD->bases())
3620 if (hasAnyVptr(Base.getType(), Context))
3621 return true;
3622
3623 for (const FieldDecl *Field : RD->fields())
3624 if (hasAnyVptr(Field->getType(), Context))
3625 return true;
3626
3627 return false;
3628}
3629
Eli Friedman7f1ff602012-04-16 03:54:45 +00003630LValue CodeGenFunction::EmitLValueForField(LValue base,
3631 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003632 LValueBaseInfo BaseInfo = base.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003633 AlignmentSource fieldAlignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003634 getFieldAlignmentSource(BaseInfo.getAlignmentSource());
3635 LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias());
John McCall7f416cc2015-09-08 08:05:57 +00003636
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003637 const RecordDecl *rec = field->getParent();
3638 if (rec->isUnion() || rec->hasAttr<MayAliasAttr>())
3639 FieldBaseInfo.setMayAlias(true);
3640 bool mayAlias = FieldBaseInfo.getMayAlias();
3641
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003642 if (field->isBitField()) {
3643 const CGRecordLayout &RL =
3644 CGM.getTypes().getCGRecordLayout(field->getParent());
3645 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003646 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003647 unsigned Idx = RL.getLLVMFieldNo(field);
3648 if (Idx != 0)
3649 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003650 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3651 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003652 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003653 llvm::Type *FieldIntTy =
3654 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3655 if (Addr.getElementType() != FieldIntTy)
3656 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003657
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003658 QualType fieldType =
3659 field->getType().withCVRQualifiers(base.getVRQualifiers());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003660 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003661 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003662
John McCall53fcbd22011-02-26 08:07:02 +00003663 QualType type = field->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003664 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003665 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003666 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003667 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003668 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003669 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003670 // TODO: handle path-aware TBAA for union.
3671 TBAAPath = false;
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003672
3673 const auto FieldType = field->getType();
3674 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3675 hasAnyVptr(FieldType, getContext()))
3676 // Because unions can easily skip invariant.barriers, we need to add
3677 // a barrier every time CXXRecord field with vptr is referenced.
3678 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3679 addr.getAlignment());
John McCall53fcbd22011-02-26 08:07:02 +00003680 } else {
3681 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003682 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003683
3684 // If this is a reference field, load the reference right now.
3685 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3686 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3687 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3688
Manman Renc451e572013-04-04 21:53:22 +00003689 // Loading the reference will disable path-aware TBAA.
3690 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003691 if (CGM.shouldUseTBAA()) {
3692 llvm::MDNode *tbaa;
3693 if (mayAlias)
3694 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3695 else
3696 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003697 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003698 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003699 }
3700
John McCall53fcbd22011-02-26 08:07:02 +00003701 mayAlias = false;
3702 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003703
3704 CharUnits alignment =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003705 getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true);
3706 FieldBaseInfo.setMayAlias(false);
John McCall7f416cc2015-09-08 08:05:57 +00003707 addr = Address(load, alignment);
3708
3709 // Qualifiers on the struct don't apply to the referencee, and
3710 // we'll pick up CVR from the actual type later, so reset these
3711 // additional qualifiers now.
3712 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003713 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003714 }
Craig Topper99e79272013-07-26 05:59:26 +00003715
Chris Lattner13ee4f42011-07-10 05:34:54 +00003716 // Make sure that the address is pointing to the right type. This is critical
3717 // for both unions and structs. A union needs a bitcast, a struct element
3718 // will need a bitcast if the LLVM type laid out doesn't match the desired
3719 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003720 addr = Builder.CreateElementBitCast(addr,
3721 CGM.getTypes().ConvertTypeForMem(type),
3722 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003723
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003724 if (field->hasAttr<AnnotateAttr>())
3725 addr = EmitFieldAnnotations(field, addr);
3726
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003727 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003728 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003729 if (TBAAPath) {
3730 const ASTRecordLayout &Layout =
3731 getContext().getASTRecordLayout(field->getParent());
3732 // Set the base type to be the base type of the base LValue and
3733 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003734 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3735 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003736 Layout.getFieldOffset(field->getFieldIndex()) /
3737 getContext().getCharWidth());
3738 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003739
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003740 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003741 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3742 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003743
3744 // Fields of may_alias structs act like 'char' for TBAA purposes.
3745 // FIXME: this should get propagated down through anonymous structs
3746 // and unions.
3747 if (mayAlias && LV.getTBAAInfo())
3748 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3749
Daniel Dunbarf166a522010-08-21 03:44:13 +00003750 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003751}
3752
Craig Topper99e79272013-07-26 05:59:26 +00003753LValue
3754CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003755 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003756 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003757
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003758 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003759 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003760
John McCall7f416cc2015-09-08 08:05:57 +00003761 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003762
John McCall7f416cc2015-09-08 08:05:57 +00003763 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003764 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003765 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003766
John McCall7f416cc2015-09-08 08:05:57 +00003767 // TODO: access-path TBAA?
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003768 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3769 LValueBaseInfo FieldBaseInfo(
3770 getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3771 BaseInfo.getMayAlias());
3772 return MakeAddrLValue(V, FieldType, FieldBaseInfo);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003773}
3774
Chris Lattnerf53c0962010-09-06 00:11:41 +00003775LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003776 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Richard Smith2d988f02011-11-22 22:48:32 +00003777 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003778 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003779 return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo);
Richard Smith2d988f02011-11-22 22:48:32 +00003780 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003781 if (E->getType()->isVariablyModifiedType())
3782 // make sure to emit the VLA size.
3783 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003784
John McCall7f416cc2015-09-08 08:05:57 +00003785 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003786 const Expr *InitExpr = E->getInitializer();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003787 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003788
Chad Rosier615ed1a2012-03-29 17:37:10 +00003789 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3790 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003791
3792 return Result;
3793}
3794
Richard Smithbb653bd2012-05-14 21:57:21 +00003795LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3796 if (!E->isGLValue())
3797 // Initializing an aggregate temporary in C++11: T{...}.
3798 return EmitAggExprToLValue(E);
3799
3800 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003801 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003802 return EmitLValue(E->getInit(0));
3803}
3804
Richard Smithf3076ff2014-06-20 18:43:47 +00003805/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3806/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3807/// LValue is returned and the current block has been terminated.
3808static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3809 const Expr *Operand) {
3810 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3811 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3812 return None;
3813 }
3814
3815 return CGF.EmitLValue(Operand);
3816}
3817
John McCallc07a0c72011-02-17 10:25:35 +00003818LValue CodeGenFunction::
3819EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3820 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003821 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003822 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003823 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003824 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003825 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003826
Eli Friedman59954892012-01-25 05:04:17 +00003827 OpaqueValueMapping binding(*this, expr);
3828
John McCallc07a0c72011-02-17 10:25:35 +00003829 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003830 bool CondExprBool;
3831 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003832 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003833 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003834
Justin Bogneref512b92014-01-06 22:27:43 +00003835 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003836 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003837 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003838 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003839 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003840 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003841 }
3842
John McCallc07a0c72011-02-17 10:25:35 +00003843 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3844 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3845 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003846
3847 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003848 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003849
John McCall0a6bf2e2011-01-26 19:21:13 +00003850 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003851 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003852 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003853 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003854 Optional<LValue> lhs =
3855 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003856 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003857
Richard Smithf3076ff2014-06-20 18:43:47 +00003858 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003859 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003860
John McCallc07a0c72011-02-17 10:25:35 +00003861 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003862 if (lhs)
3863 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003864
John McCall0a6bf2e2011-01-26 19:21:13 +00003865 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003866 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003867 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003868 Optional<LValue> rhs =
3869 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003870 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003871 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003872 return EmitUnsupportedLValue(expr, "conditional operator");
3873 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003874
John McCallc07a0c72011-02-17 10:25:35 +00003875 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003876
Richard Smithf3076ff2014-06-20 18:43:47 +00003877 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003878 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003879 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003880 phi->addIncoming(lhs->getPointer(), lhsBlock);
3881 phi->addIncoming(rhs->getPointer(), rhsBlock);
3882 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3883 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003884 std::max(lhs->getBaseInfo().getAlignmentSource(),
3885 rhs->getBaseInfo().getAlignmentSource());
3886 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3887 rhs->getBaseInfo().getMayAlias();
3888 return MakeAddrLValue(result, expr->getType(),
3889 LValueBaseInfo(alignSource, MayAlias));
Richard Smithf3076ff2014-06-20 18:43:47 +00003890 } else {
3891 assert((lhs || rhs) &&
3892 "both operands of glvalue conditional are throw-expressions?");
3893 return lhs ? *lhs : *rhs;
3894 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003895}
3896
Richard Smithbb653bd2012-05-14 21:57:21 +00003897/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3898/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003899/// otherwise if a cast is needed by the code generator in an lvalue context,
3900/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003901/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003902/// are permitted with aggregate result, including noop aggregate casts, and
3903/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003904LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003905 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003906 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003907 case CK_BitCast:
3908 case CK_ArrayToPointerDecay:
3909 case CK_FunctionToPointerDecay:
3910 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003911 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003912 case CK_IntegralToPointer:
3913 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003914 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003915 case CK_VectorSplat:
3916 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003917 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003918 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003919 case CK_IntegralToFloating:
3920 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003921 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003922 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003923 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003924 case CK_FloatingComplexToReal:
3925 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003926 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003927 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003928 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003929 case CK_IntegralComplexToReal:
3930 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003931 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003932 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003933 case CK_DerivedToBaseMemberPointer:
3934 case CK_BaseToDerivedMemberPointer:
3935 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003936 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003937 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003938 case CK_ARCProduceObject:
3939 case CK_ARCConsumeObject:
3940 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003941 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003942 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003943 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003944 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003945 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3946
3947 case CK_Dependent:
3948 llvm_unreachable("dependent cast kind in IR gen!");
3949
3950 case CK_BuiltinFnToFnPtr:
3951 llvm_unreachable("builtin functions are handled elsewhere");
3952
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003953 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003954 case CK_NonAtomicToAtomic:
3955 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003956 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003957
Anders Carlsson8a01a752011-04-11 02:03:26 +00003958 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003959 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003960 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003961 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003962 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003963 }
3964
John McCalle3027922010-08-25 11:45:40 +00003965 case CK_ConstructorConversion:
3966 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003967 case CK_CPointerToObjCPointerCast:
3968 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003969 case CK_NoOp:
3970 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003971 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003972
John McCalle3027922010-08-25 11:45:40 +00003973 case CK_UncheckedDerivedToBase:
3974 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003975 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003976 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003977 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003978
Anders Carlssond95f9602009-09-12 16:16:49 +00003979 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003980 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003981
Anders Carlssond95f9602009-09-12 16:16:49 +00003982 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003983 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003984 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3985 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003986
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003987 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo());
Anders Carlssond95f9602009-09-12 16:16:49 +00003988 }
John McCalle3027922010-08-25 11:45:40 +00003989 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003990 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003991 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003992 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003993 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003994
Anders Carlsson8c793172009-11-23 17:57:54 +00003995 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003996
Anders Carlsson8c793172009-11-23 17:57:54 +00003997 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003998 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003999 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00004000 E->path_begin(), E->path_end(),
4001 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00004002
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004003 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4004 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00004005 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004006 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00004007 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004008
Peter Collingbourned2926c92015-03-14 02:42:25 +00004009 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004010 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4011 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004012 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004013
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004014 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo());
Eli Friedman8c98dff2009-11-16 05:48:01 +00004015 }
John McCalle3027922010-08-25 11:45:40 +00004016 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00004017 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004018 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00004019
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00004020 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00004021 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004022 Address V = Builder.CreateBitCast(LV.getAddress(),
4023 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00004024
4025 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004026 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4027 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004028 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004029
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004030 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Anders Carlsson50cb3212009-11-14 21:21:42 +00004031 }
John McCalle3027922010-08-25 11:45:40 +00004032 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004033 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004034 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4035 ConvertType(E->getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004036 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004037 }
Egor Churaev89831422016-12-23 14:55:49 +00004038 case CK_ZeroToOCLQueue:
4039 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004040 case CK_ZeroToOCLEvent:
4041 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00004042 }
Craig Topper99e79272013-07-26 05:59:26 +00004043
Douglas Gregorcdb466e2010-07-15 18:58:16 +00004044 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004045}
4046
John McCall1bf58462011-02-16 08:02:54 +00004047LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00004048 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00004049 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00004050}
4051
Eli Friedman7f1ff602012-04-16 03:54:45 +00004052RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004053 const FieldDecl *FD,
4054 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004055 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00004056 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00004057 switch (getEvaluationKind(FT)) {
4058 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004059 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00004060 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00004061 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00004062 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00004063 // This routine is used to load fields one-by-one to perform a copy, so
4064 // don't load reference fields.
4065 if (FD->getType()->isReferenceType())
4066 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00004067 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00004068 }
4069 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004070}
Douglas Gregorfe314812011-06-21 17:03:29 +00004071
Chris Lattnere47e4402007-06-01 18:02:12 +00004072//===--------------------------------------------------------------------===//
4073// Expression Emission
4074//===--------------------------------------------------------------------===//
4075
Craig Topper99e79272013-07-26 05:59:26 +00004076RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00004077 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00004078 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004079 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00004080 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004081
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004082 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004083 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004084
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004085 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00004086 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4087
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004088 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00004089 if (const CXXMethodDecl *MD =
4090 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004091 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004092
John McCallb92ab1a2016-10-26 23:46:34 +00004093 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00004094
John McCallb92ab1a2016-10-26 23:46:34 +00004095 if (callee.isBuiltin()) {
4096 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4097 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004098 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004099
John McCallb92ab1a2016-10-26 23:46:34 +00004100 if (callee.isPseudoDestructor()) {
4101 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4102 }
4103
4104 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4105}
4106
4107/// Emit a CallExpr without considering whether it might be a subclass.
4108RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4109 ReturnValueSlot ReturnValue) {
4110 CGCallee Callee = EmitCallee(E->getCallee());
4111 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4112}
4113
4114static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4115 if (auto builtinID = FD->getBuiltinID()) {
4116 return CGCallee::forBuiltin(builtinID, FD);
4117 }
4118
4119 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4120 return CGCallee::forDirect(calleePtr, FD);
4121}
4122
4123CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4124 E = E->IgnoreParens();
4125
4126 // Look through function-to-pointer decay.
4127 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4128 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4129 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4130 return EmitCallee(ICE->getSubExpr());
4131 }
4132
4133 // Resolve direct calls.
4134 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4135 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4136 return EmitDirectCallee(*this, FD);
4137 }
4138 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4139 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4140 EmitIgnoredExpr(ME->getBase());
4141 return EmitDirectCallee(*this, FD);
4142 }
4143
4144 // Look through template substitutions.
4145 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4146 return EmitCallee(NTTP->getReplacement());
4147
4148 // Treat pseudo-destructor calls differently.
4149 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4150 return CGCallee::forPseudoDestructor(PDE);
4151 }
4152
4153 // Otherwise, we have an indirect reference.
4154 llvm::Value *calleePtr;
4155 QualType functionType;
4156 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4157 calleePtr = EmitScalarExpr(E);
4158 functionType = ptrType->getPointeeType();
4159 } else {
4160 functionType = E->getType();
4161 calleePtr = EmitLValue(E).getPointer();
4162 }
4163 assert(functionType->isFunctionType());
4164 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4165 E->getReferencedDeclOfCallee());
4166 CGCallee callee(calleeInfo, calleePtr);
4167 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004168}
4169
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004170LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004171 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004172 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004173 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004174 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004175 return EmitLValue(E->getRHS());
4176 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004177
John McCalle3027922010-08-25 11:45:40 +00004178 if (E->getOpcode() == BO_PtrMemD ||
4179 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004180 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004181
John McCalla2342eb2010-12-05 02:00:02 +00004182 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004183
4184 // Note that in all of these cases, __block variables need the RHS
4185 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004186
4187 switch (getEvaluationKind(E->getType())) {
4188 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004189 switch (E->getLHS()->getType().getObjCLifetime()) {
4190 case Qualifiers::OCL_Strong:
4191 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4192
4193 case Qualifiers::OCL_Autoreleasing:
4194 return EmitARCStoreAutoreleasing(E).first;
4195
4196 // No reason to do any of these differently.
4197 case Qualifiers::OCL_None:
4198 case Qualifiers::OCL_ExplicitNone:
4199 case Qualifiers::OCL_Weak:
4200 break;
4201 }
4202
John McCalld0a30012010-12-06 06:10:02 +00004203 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004204 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004205 if (RV.isScalar())
4206 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004207 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004208 return LV;
4209 }
John McCall4f29b492010-11-16 23:07:28 +00004210
John McCall47fb9502013-03-07 21:37:08 +00004211 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004212 return EmitComplexAssignmentLValue(E);
4213
John McCall47fb9502013-03-07 21:37:08 +00004214 case TEK_Aggregate:
4215 return EmitAggExprToLValue(E);
4216 }
4217 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004218}
4219
Christopher Lambd91c3d42007-12-29 05:02:41 +00004220LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004221 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004222
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004223 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004224 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004225 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004226
David Majnemerced8bdf2015-02-25 17:36:15 +00004227 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004228 "Can't have a scalar return unless the return type is a "
4229 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004230
John McCall7f416cc2015-09-08 08:05:57 +00004231 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004232}
4233
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004234LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4235 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004236 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004237}
4238
Anders Carlsson3be22e22009-05-30 23:23:33 +00004239LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004240 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4241 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004242 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004243 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004244 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004245 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlsson3be22e22009-05-30 23:23:33 +00004246}
4247
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004248LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004249CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004250 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004251}
4252
John McCall7f416cc2015-09-08 08:05:57 +00004253Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4254 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4255 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004256}
4257
4258LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004259 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004260 LValueBaseInfo(AlignmentSource::Decl, false));
Nico Webercf4ff5862012-10-11 10:13:44 +00004261}
4262
Mike Stumpc9b231c2009-11-15 08:09:41 +00004263LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004264CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004265 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004266 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004267 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004268 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4269 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004270 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004271}
4272
Eli Friedman5bc17122012-02-08 05:34:55 +00004273LValue
4274CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004275 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004276 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004277 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004278 LValueBaseInfo(AlignmentSource::Decl, false));
Eli Friedman5bc17122012-02-08 05:34:55 +00004279}
4280
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004281LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004282 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004283
Anders Carlsson280e61f12010-06-21 20:59:55 +00004284 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004285 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004286 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004287
Alp Toker314cc812014-01-25 16:55:45 +00004288 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004289 "Can't have a scalar return unless the return type is a "
4290 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004291
John McCall7f416cc2015-09-08 08:05:57 +00004292 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004293}
4294
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004295LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004296 Address V =
4297 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004298 return MakeAddrLValue(V, E->getType(),
4299 LValueBaseInfo(AlignmentSource::Decl, false));
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004300}
4301
Daniel Dunbar722f4242009-04-22 05:08:15 +00004302llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004303 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004304 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004305}
4306
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004307LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4308 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004309 const ObjCIvarDecl *Ivar,
4310 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004311 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004312 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004313}
4314
4315LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004316 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004317 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004318 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004319 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004320 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004321 if (E->isArrow()) {
4322 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004323 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004324 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004325 } else {
4326 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004327 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004328 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004329 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004330 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004331
Craig Topper99e79272013-07-26 05:59:26 +00004332 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004333 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4334 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004335 setObjCGCLValueClass(getContext(), E, LV);
4336 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004337}
4338
Chris Lattnera4185c52009-04-25 19:35:26 +00004339LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004340 // Can only get l-value for message expression returning aggregate type
4341 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004342 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004343 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnera4185c52009-04-25 19:35:26 +00004344}
4345
John McCallb92ab1a2016-10-26 23:46:34 +00004346RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004347 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004348 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004349 // Get the actual function type. The callee type will always be a pointer to
4350 // function type or a block pointer type.
4351 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004352 "Call must have function pointer type!");
4353
John McCallb92ab1a2016-10-26 23:46:34 +00004354 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004355
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004356 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004357 // We can only guarantee that a function is called from the correct
4358 // context/function based on the appropriate target attributes,
4359 // so only check in the case where we have both always_inline and target
4360 // since otherwise we could be making a conditional call after a check for
4361 // the proper cpu features (and it won't cause code generation issues due to
4362 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004363 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4364 TargetDecl->hasAttr<TargetAttr>())
4365 checkTargetFeatures(E, FD);
4366
John McCall6fd4c232009-10-23 08:22:42 +00004367 CalleeType = getContext().getCanonicalType(CalleeType);
4368
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004369 const auto *FnType =
4370 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004371
John McCallb92ab1a2016-10-26 23:46:34 +00004372 CGCallee Callee = OrigCallee;
4373
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004374 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004375 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4376 if (llvm::Constant *PrefixSig =
4377 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004378 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004379 llvm::Constant *FTRTTIConst =
4380 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4381 llvm::Type *PrefixStructTyElems[] = {
4382 PrefixSig->getType(),
4383 FTRTTIConst->getType()
4384 };
4385 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4386 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4387
John McCallb92ab1a2016-10-26 23:46:34 +00004388 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4389
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004390 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004391 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004392 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004393 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004394 llvm::Value *CalleeSig =
4395 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004396 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4397
4398 llvm::BasicBlock *Cont = createBasicBlock("cont");
4399 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4400 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4401
4402 EmitBlock(TypeCheck);
4403 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004404 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004405 llvm::Value *CalleeRTTI =
4406 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004407 llvm::Value *CalleeRTTIMatch =
4408 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4409 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004410 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004411 EmitCheckTypeDescriptor(CalleeType)
4412 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004413 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004414 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004415
4416 Builder.CreateBr(Cont);
4417 EmitBlock(Cont);
4418 }
4419 }
4420
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004421 // If we are checking indirect calls and this call is indirect, check that the
4422 // function pointer is a member of the bit set for the function type.
4423 if (SanOpts.has(SanitizerKind::CFIICall) &&
4424 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4425 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004426 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004427
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004428 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004429 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004430
John McCallb92ab1a2016-10-26 23:46:34 +00004431 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4432 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004433 llvm::Value *TypeTest = Builder.CreateCall(
4434 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004435
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004436 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004437 llvm::Constant *StaticData[] = {
4438 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4439 EmitCheckSourceLocation(E->getLocStart()),
4440 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4441 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004442 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4443 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004444 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004445 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004446 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004447 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004448 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004449 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004450 }
4451
Daniel Dunbarc722b852008-08-30 03:02:31 +00004452 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004453 if (Chain)
4454 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4455 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004456
4457 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004458 // right-to-left, and that we evaluate arguments to certain other operators
4459 // left-to-right. Note that we allow this to override the order dictated by
4460 // the calling convention on the MS ABI, which means that parameter
4461 // destruction order is not necessarily reverse construction order.
4462 // FIXME: Revisit this based on C++ committee response to unimplementability.
4463 EvaluationOrder Order = EvaluationOrder::Default;
4464 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4465 if (OCE->isAssignmentOp())
4466 Order = EvaluationOrder::ForceRightToLeft;
4467 else {
4468 switch (OCE->getOperator()) {
4469 case OO_LessLess:
4470 case OO_GreaterGreater:
4471 case OO_AmpAmp:
4472 case OO_PipePipe:
4473 case OO_Comma:
4474 case OO_ArrowStar:
4475 Order = EvaluationOrder::ForceLeftToRight;
4476 break;
4477 default:
4478 break;
4479 }
4480 }
4481 }
Richard Smith762672a2016-09-28 19:09:10 +00004482
David Blaikief05779e2015-07-21 18:37:18 +00004483 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004484 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004485
Peter Collingbournef7706832014-12-12 23:41:25 +00004486 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4487 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004488
4489 // C99 6.5.2.2p6:
4490 // If the expression that denotes the called function has a type
4491 // that does not include a prototype, [the default argument
4492 // promotions are performed]. If the number of arguments does not
4493 // equal the number of parameters, the behavior is undefined. If
4494 // the function is defined with a type that includes a prototype,
4495 // and either the prototype ends with an ellipsis (, ...) or the
4496 // types of the arguments after promotion are not compatible with
4497 // the types of the parameters, the behavior is undefined. If the
4498 // function is defined with a type that does not include a
4499 // prototype, and the types of the arguments after promotion are
4500 // not compatible with those of the parameters after promotion,
4501 // the behavior is undefined [except in some trivial cases].
4502 // That is, in the general case, we should assume that a call
4503 // through an unprototyped function type works like a *non-variadic*
4504 // call. The way we make this work is to cast to the exact type
4505 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004506 //
4507 // Chain calls use this same code path to add the invisible chain parameter
4508 // to the function type.
4509 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004510 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004511 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004512
4513 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4514 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4515 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004516 }
4517
John McCallb92ab1a2016-10-26 23:46:34 +00004518 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004519}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004520
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004521LValue CodeGenFunction::
4522EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004523 Address BaseAddr = Address::invalid();
4524 if (E->getOpcode() == BO_PtrMemI) {
4525 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4526 } else {
4527 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4528 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004529
John McCallc134eb52010-08-31 21:07:20 +00004530 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4531
4532 const MemberPointerType *MPT
4533 = E->getRHS()->getType()->getAs<MemberPointerType>();
4534
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004535 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00004536 Address MemberAddr =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004537 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
John McCallc134eb52010-08-31 21:07:20 +00004538
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004539 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004540}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004541
John McCall47fb9502013-03-07 21:37:08 +00004542/// Given the address of a temporary variable, produce an r-value of
4543/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004544RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004545 QualType type,
4546 SourceLocation loc) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004547 LValue lvalue = MakeAddrLValue(addr, type,
4548 LValueBaseInfo(AlignmentSource::Decl, false));
John McCall47fb9502013-03-07 21:37:08 +00004549 switch (getEvaluationKind(type)) {
4550 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004551 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004552 case TEK_Aggregate:
4553 return lvalue.asAggregateRValue();
4554 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004555 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004556 }
4557 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004558}
4559
Duncan Sandse81111c2012-04-10 08:23:07 +00004560void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004561 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004562 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004563 return;
4564
Duncan Sands65229ed2012-04-16 16:29:47 +00004565 llvm::MDBuilder MDHelper(getLLVMContext());
4566 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004567
Duncan Sands6fc46192012-04-14 12:37:26 +00004568 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004569}
John McCallfe96e0b2011-11-06 09:01:30 +00004570
4571namespace {
4572 struct LValueOrRValue {
4573 LValue LV;
4574 RValue RV;
4575 };
4576}
4577
4578static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4579 const PseudoObjectExpr *E,
4580 bool forLValue,
4581 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004582 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004583
4584 // Find the result expression, if any.
4585 const Expr *resultExpr = E->getResultExpr();
4586 LValueOrRValue result;
4587
4588 for (PseudoObjectExpr::const_semantics_iterator
4589 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4590 const Expr *semantic = *i;
4591
4592 // If this semantic expression is an opaque value, bind it
4593 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004594 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004595
4596 // If this is the result expression, we may need to evaluate
4597 // directly into the slot.
4598 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4599 OVMA opaqueData;
4600 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004601 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004602 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004603 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
John McCall7f416cc2015-09-08 08:05:57 +00004604 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004605 BaseInfo);
John McCallfe96e0b2011-11-06 09:01:30 +00004606 opaqueData = OVMA::bind(CGF, ov, LV);
4607 result.RV = slot.asRValue();
4608
4609 // Otherwise, emit as normal.
4610 } else {
4611 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4612
4613 // If this is the result, also evaluate the result now.
4614 if (ov == resultExpr) {
4615 if (forLValue)
4616 result.LV = CGF.EmitLValue(ov);
4617 else
4618 result.RV = CGF.EmitAnyExpr(ov, slot);
4619 }
4620 }
4621
4622 opaques.push_back(opaqueData);
4623
4624 // Otherwise, if the expression is the result, evaluate it
4625 // and remember the result.
4626 } else if (semantic == resultExpr) {
4627 if (forLValue)
4628 result.LV = CGF.EmitLValue(semantic);
4629 else
4630 result.RV = CGF.EmitAnyExpr(semantic, slot);
4631
4632 // Otherwise, evaluate the expression in an ignored context.
4633 } else {
4634 CGF.EmitIgnoredExpr(semantic);
4635 }
4636 }
4637
4638 // Unbind all the opaques now.
4639 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4640 opaques[i].unbind(CGF);
4641
4642 return result;
4643}
4644
4645RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4646 AggValueSlot slot) {
4647 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4648}
4649
4650LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4651 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4652}