blob: a6d5dd85c234c234272f744c020918ae7be1a139 [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 =
51 cast<llvm::PointerType>(value->getType())->getAddressSpace();
52
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,
64 const Twine &Name) {
65 auto Alloca = CreateTempAlloca(Ty, Name);
66 Alloca->setAlignment(Align.getQuantity());
67 return Address(Alloca, Align);
68}
69
70/// CreateTempAlloca - This creates a alloca and inserts it into the entry
71/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000072llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000073 const Twine &Name) {
Matt Arsenault502ad602017-04-10 22:28:02 +000074 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
75 nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000076}
Chris Lattner8394d792007-06-05 20:53:16 +000077
John McCall7f416cc2015-09-08 08:05:57 +000078/// CreateDefaultAlignTempAlloca - This creates an alloca with the
79/// default alignment of the corresponding LLVM type, which is *not*
80/// guaranteed to be related in any way to the expected alignment of
81/// an AST type that might have been lowered to Ty.
82Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
83 const Twine &Name) {
84 CharUnits Align =
85 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
86 return CreateTempAlloca(Ty, Align, Name);
87}
88
89void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
90 assert(isa<llvm::AllocaInst>(Var.getPointer()));
91 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
92 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000093 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +000094 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +000095}
96
John McCall7f416cc2015-09-08 08:05:57 +000097Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000098 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000099 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +0000100}
101
John McCall7f416cc2015-09-08 08:05:57 +0000102Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000103 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +0000104 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
105}
106
107Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
108 const Twine &Name) {
109 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000110}
111
Chris Lattner8394d792007-06-05 20:53:16 +0000112/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
113/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000114llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000115 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000116 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000117 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000118 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000119 }
John McCall7a9aac22010-08-23 01:21:21 +0000120
121 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000122 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000123 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000124 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000125
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000126 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
127 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000128}
129
John McCalla2342eb2010-12-05 02:00:02 +0000130/// EmitIgnoredExpr - Emit code to compute the specified expression,
131/// ignoring the result.
132void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
133 if (E->isRValue())
134 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
135
136 // Just emit it as an l-value and drop the result.
137 EmitLValue(E);
138}
139
John McCall7a626f62010-09-15 10:14:12 +0000140/// EmitAnyExpr - Emit code to compute the specified expression which
141/// can have any type. The result is returned as an RValue struct.
142/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000143/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000144RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
145 AggValueSlot aggSlot,
146 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000147 switch (getEvaluationKind(E->getType())) {
148 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000149 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000150 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000151 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000152 case TEK_Aggregate:
153 if (!ignoreResult && aggSlot.isIgnored())
154 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
155 EmitAggExpr(E, aggSlot);
156 return aggSlot.asRValue();
157 }
158 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000159}
160
Mike Stump4a3999f2009-09-09 13:00:44 +0000161/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
162/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000163RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
164 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000165
John McCall47fb9502013-03-07 21:37:08 +0000166 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000167 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
168 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000169}
170
John McCall21886962010-04-21 10:05:39 +0000171/// EmitAnyExprToMem - Evaluate an expression into a given memory
172/// location.
173void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000174 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000175 Qualifiers Quals,
176 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000177 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000178 switch (getEvaluationKind(E->getType())) {
179 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000180 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000181 /*isInit*/ false);
182 return;
183
184 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000185 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000186 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000187 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000188 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000189 return;
190 }
191
192 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000193 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000194 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000195 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000196 return;
John McCall21886962010-04-21 10:05:39 +0000197 }
John McCall47fb9502013-03-07 21:37:08 +0000198 }
199 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000200}
201
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000202static void
203pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000204 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000205 // Objective-C++ ARC:
206 // If we are binding a reference to a temporary that has ownership, we
207 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000208 //
209 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000210 if (auto Lifetime = M->getType().getObjCLifetime()) {
211 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000212 case Qualifiers::OCL_None:
213 case Qualifiers::OCL_ExplicitNone:
214 // Carry on to normal cleanup handling.
215 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000216
Richard Smith736a9472013-06-12 20:42:33 +0000217 case Qualifiers::OCL_Autoreleasing:
218 // Nothing to do; cleaned up by an autorelease pool.
219 return;
220
221 case Qualifiers::OCL_Strong:
222 case Qualifiers::OCL_Weak:
223 switch (StorageDuration Duration = M->getStorageDuration()) {
224 case SD_Static:
225 // Note: we intentionally do not register a cleanup to release
226 // the object on program termination.
227 return;
228
229 case SD_Thread:
230 // FIXME: We should probably register a cleanup in this case.
231 return;
232
233 case SD_Automatic:
234 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000235 CodeGenFunction::Destroyer *Destroy;
236 CleanupKind CleanupKind;
237 if (Lifetime == Qualifiers::OCL_Strong) {
238 const ValueDecl *VD = M->getExtendingDecl();
239 bool Precise =
240 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
241 CleanupKind = CGF.getARCCleanupKind();
242 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
243 : &CodeGenFunction::destroyARCStrongImprecise;
244 } else {
245 // __weak objects always get EH cleanups; otherwise, exceptions
246 // could cause really nasty crashes instead of mere leaks.
247 CleanupKind = NormalAndEHCleanup;
248 Destroy = &CodeGenFunction::destroyARCWeak;
249 }
250 if (Duration == SD_FullExpression)
251 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000252 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000253 CleanupKind & EHCleanup);
254 else
255 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000256 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000257 *Destroy, CleanupKind & EHCleanup);
258 return;
259
260 case SD_Dynamic:
261 llvm_unreachable("temporary cannot have dynamic storage duration");
262 }
263 llvm_unreachable("unknown storage duration");
264 }
265 }
266
Craig Topper8a13c412014-05-21 05:09:00 +0000267 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000268 if (const RecordType *RT =
269 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
270 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000271 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000272 if (!ClassDecl->hasTrivialDestructor())
273 ReferenceTemporaryDtor = ClassDecl->getDestructor();
274 }
275
276 if (!ReferenceTemporaryDtor)
277 return;
278
279 // Call the destructor for the temporary.
280 switch (M->getStorageDuration()) {
281 case SD_Static:
282 case SD_Thread: {
283 llvm::Constant *CleanupFn;
284 llvm::Constant *CleanupArg;
285 if (E->getType()->isArrayType()) {
286 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000287 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000288 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
289 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000290 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
291 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000292 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
293 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000294 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000295 }
296 CGF.CGM.getCXXABI().registerGlobalDtor(
297 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
298 break;
299 }
300
301 case SD_FullExpression:
302 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
303 CodeGenFunction::destroyCXXObject,
304 CGF.getLangOpts().Exceptions);
305 break;
306
307 case SD_Automatic:
308 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
309 ReferenceTemporary, E->getType(),
310 CodeGenFunction::destroyCXXObject,
311 CGF.getLangOpts().Exceptions);
312 break;
313
314 case SD_Dynamic:
315 llvm_unreachable("temporary cannot have dynamic storage duration");
316 }
317}
318
John McCall7f416cc2015-09-08 08:05:57 +0000319static Address
Richard Smith736a9472013-06-12 20:42:33 +0000320createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000321 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000322 switch (M->getStorageDuration()) {
323 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000324 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000325 // If we have a constant temporary array or record try to promote it into a
326 // constant global under the same rules a normal constant would've been
327 // promoted. This is easier on the optimizer and generally emits fewer
328 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000329 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000330 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000331 (Ty->isArrayType() || Ty->isRecordType()) &&
332 CGF.CGM.isTypeConstant(Ty, true))
333 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000334 auto *GV = new llvm::GlobalVariable(
335 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
336 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000337 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
338 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000339 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000340 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000341 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000342 return CGF.CreateMemTemp(Ty, "ref.tmp");
343 }
Richard Smith736a9472013-06-12 20:42:33 +0000344 case SD_Thread:
345 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000346 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000347
348 case SD_Dynamic:
349 llvm_unreachable("temporary can't have dynamic storage duration");
350 }
351 llvm_unreachable("unknown storage duration");
352}
353
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000354LValue CodeGenFunction::
355EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000356 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000357
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000358 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
359 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000360 auto ownership = M->getType().getObjCLifetime();
361 if (ownership != Qualifiers::OCL_None &&
362 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000363 Address Object = createReferenceTemporary(*this, M, E);
364 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
365 Object = Address(llvm::ConstantExpr::getBitCast(Var,
366 ConvertTypeForMem(E->getType())
367 ->getPointerTo(Object.getAddressSpace())),
368 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000369
370 // createReferenceTemporary will promote the temporary to a global with a
371 // constant initializer if it can. It can only do this to a value of
372 // ARC-manageable type if the value is global and therefore "immune" to
373 // ref-counting operations. Therefore we have no need to emit either a
374 // dynamic initialization or a cleanup and we can just return the address
375 // of the temporary.
376 if (Var->hasInitializer())
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000377 return MakeAddrLValue(Object, M->getType(),
378 LValueBaseInfo(AlignmentSource::Decl, false));
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000379
Richard Smitha509f2f2013-06-14 03:07:01 +0000380 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
381 }
John McCall7f416cc2015-09-08 08:05:57 +0000382 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000383 LValueBaseInfo(AlignmentSource::Decl,
384 false));
Richard Smitha509f2f2013-06-14 03:07:01 +0000385
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000386 switch (getEvaluationKind(E->getType())) {
387 default: llvm_unreachable("expected scalar or aggregate expression");
388 case TEK_Scalar:
389 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
390 break;
391 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000392 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000393 E->getType().getQualifiers(),
394 AggValueSlot::IsDestructed,
395 AggValueSlot::DoesNotNeedGCBarriers,
396 AggValueSlot::IsNotAliased));
397 break;
398 }
399 }
Richard Smith736a9472013-06-12 20:42:33 +0000400
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000401 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000402 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000403 }
404
Richard Smithf3fabd22013-06-03 00:17:11 +0000405 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000406 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000407 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
408
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000409 for (const auto &Ignored : CommaLHSs)
410 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000411
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000412 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000413 if (opaque->getType()->isRecordType()) {
414 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000415 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000416 }
417 }
418
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000419 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000420 Address Object = createReferenceTemporary(*this, M, E);
421 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
422 Object = Address(llvm::ConstantExpr::getBitCast(
423 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
424 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000425 // If the temporary is a global and has a constant initializer or is a
426 // constant temporary that we promoted to a global, we may have already
427 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000428 if (!Var->hasInitializer()) {
429 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
430 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
431 }
432 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000433 switch (M->getStorageDuration()) {
434 case SD_Automatic:
435 case SD_FullExpression:
436 if (auto *Size = EmitLifetimeStart(
437 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
438 Object.getPointer())) {
439 if (M->getStorageDuration() == SD_Automatic)
440 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
441 Object, Size);
442 else
443 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
444 Size);
445 }
446 break;
447 default:
448 break;
449 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000450 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
451 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000452 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000453
Richard Smith736a9472013-06-12 20:42:33 +0000454 // Perform derived-to-base casts and/or field accesses, to get from the
455 // temporary object we created (and, potentially, for which we extended
456 // the lifetime) to the subobject we're binding the reference to.
457 for (unsigned I = Adjustments.size(); I != 0; --I) {
458 SubobjectAdjustment &Adjustment = Adjustments[I-1];
459 switch (Adjustment.Kind) {
460 case SubobjectAdjustment::DerivedToBaseAdjustment:
461 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000462 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
463 Adjustment.DerivedToBase.BasePath->path_begin(),
464 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000465 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000466 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000467
Richard Smith736a9472013-06-12 20:42:33 +0000468 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000469 LValue LV = MakeAddrLValue(Object, E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000470 LValueBaseInfo(AlignmentSource::Decl, false));
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000471 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000472 assert(LV.isSimple() &&
473 "materialized temporary field is not a simple lvalue");
474 Object = LV.getAddress();
475 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000476 }
477
Richard Smith736a9472013-06-12 20:42:33 +0000478 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000479 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000480 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
481 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000482 break;
483 }
484 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000485 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000486
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000487 return MakeAddrLValue(Object, M->getType(),
488 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000489}
490
491RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000492CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
493 // Emit the expression as an lvalue.
494 LValue LV = EmitLValue(E);
495 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000496 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000497
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000498 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000499 // C++11 [dcl.ref]p5 (as amended by core issue 453):
500 // If a glvalue to which a reference is directly bound designates neither
501 // an existing object or function of an appropriate type nor a region of
502 // storage of suitable size and alignment to contain an object of the
503 // reference's type, the behavior is undefined.
504 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000505 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000506 }
John McCall8680f872010-07-21 06:29:51 +0000507
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000508 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000509}
510
511
Mike Stump4a3999f2009-09-09 13:00:44 +0000512/// getAccessedFieldNo - Given an encoded value and a result number, return the
513/// input field number being accessed.
514unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000515 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000516 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
517 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000518}
519
Richard Smith4d3110a2012-10-25 02:14:12 +0000520/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
521static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
522 llvm::Value *High) {
523 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
524 llvm::Value *K47 = Builder.getInt64(47);
525 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
526 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
527 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
528 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
529 return Builder.CreateMul(B1, KMul);
530}
531
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000532bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000533 return SanOpts.has(SanitizerKind::Null) |
534 SanOpts.has(SanitizerKind::Alignment) |
535 SanOpts.has(SanitizerKind::ObjectSize) |
536 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000537}
538
Richard Smithe30752c2012-10-09 19:52:38 +0000539void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000540 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000541 CharUnits Alignment,
542 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000543 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000544 return;
545
Richard Smith2d8b2942012-11-01 07:22:08 +0000546 // Don't check pointers outside the default address space. The null check
547 // isn't correct, the object-size check isn't supported by LLVM, and we can't
548 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000549 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000550 return;
551
Alexey Samsonov24cad992014-07-17 18:46:27 +0000552 SanitizerScope SanScope(this);
553
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000554 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000555 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000556
Vedant Kumare859ebb2017-04-26 02:17:21 +0000557 // Quickly determine whether we have a pointer to an alloca. It's possible
558 // to skip null checks, and some alignment checks, for these pointers. This
559 // can reduce compile-time significantly.
560 auto PtrToAlloca =
561 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
562
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000563 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
564 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000565 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumare859ebb2017-04-26 02:17:21 +0000566 !SkippedChecks.has(SanitizerKind::Null) && !PtrToAlloca) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000567 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000568 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000569
Vedant Kumardbbdda42017-04-17 22:26:10 +0000570 // The IR builder can constant-fold the null check if the pointer points to
571 // a constant.
572 bool PtrIsNonNull =
573 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext());
574
575 // Skip the null check if the pointer is known to be non-null.
576 if (!PtrIsNonNull) {
577 if (AllowNullPointers) {
578 // When performing pointer casts, it's OK if the value is null.
579 // Skip the remaining checks in that case.
580 Done = createBasicBlock("null");
581 llvm::BasicBlock *Rest = createBasicBlock("not.null");
582 Builder.CreateCondBr(IsNonNull, Rest, Done);
583 EmitBlock(Rest);
584 } else {
585 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
586 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000587 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000588 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000589
Vedant Kumar18348ea2017-02-17 23:22:55 +0000590 if (SanOpts.has(SanitizerKind::ObjectSize) &&
591 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
592 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000593 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000594
Richard Smith69d0d262012-08-24 00:54:33 +0000595 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000596 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000597 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000598 // FIXME: Get object address space
599 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
600 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000601 llvm::Value *Min = Builder.getFalse();
George Burgess IVa63f9152017-03-21 20:09:35 +0000602 llvm::Value *NullIsUnknown = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000603 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
George Burgess IVa63f9152017-03-21 20:09:35 +0000604 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
605 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
606 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000607 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000608 }
Richard Smith69d0d262012-08-24 00:54:33 +0000609
Richard Smithb1b0ab42012-11-05 22:21:05 +0000610 uint64_t AlignVal = 0;
611
Vedant Kumar18348ea2017-02-17 23:22:55 +0000612 if (SanOpts.has(SanitizerKind::Alignment) &&
613 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000614 AlignVal = Alignment.getQuantity();
615 if (!Ty->isIncompleteType() && !AlignVal)
616 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
617
Richard Smith69d0d262012-08-24 00:54:33 +0000618 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000619 if (AlignVal > 1 &&
620 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000621 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000622 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000623 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
624 llvm::Value *Aligned =
625 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000626 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000627 }
Richard Smith69d0d262012-08-24 00:54:33 +0000628 }
629
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000630 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000631 // Make sure we're not losing information. Alignment needs to be a power of
632 // 2
633 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000634 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000635 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
636 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
637 llvm::ConstantInt::get(Int8Ty, TCK)};
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000638 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000639 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000640
Richard Smithb1b0ab42012-11-05 22:21:05 +0000641 // If possible, check that the vptr indicates that there is a subobject of
642 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000643 //
644 // C++11 [basic.life]p5,6:
645 // [For storage which does not refer to an object within its lifetime]
646 // The program has undefined behavior if:
647 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000648 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000649 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000650 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumar18348ea2017-02-17 23:22:55 +0000651 !SkippedChecks.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000652 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000653 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
654 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000655 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000656 // Compute a hash of the mangled name of the type.
657 //
658 // FIXME: This is not guaranteed to be deterministic! Move to a
659 // fingerprinting mechanism once LLVM provides one. For the time
660 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000661 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000662 llvm::raw_svector_ostream Out(MangledName);
663 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
664 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000665
Alexey Samsonov84856012014-07-10 22:34:19 +0000666 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000667 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
668 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000669 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000670
Alexey Samsonov84856012014-07-10 22:34:19 +0000671 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
672 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
673 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000674 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000675 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
676 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000677
Alexey Samsonov84856012014-07-10 22:34:19 +0000678 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
679 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000680
Alexey Samsonov84856012014-07-10 22:34:19 +0000681 // Look the hash up in our cache.
682 const int CacheSize = 128;
683 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
684 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
685 "__ubsan_vptr_type_cache");
686 llvm::Value *Slot = Builder.CreateAnd(Hash,
687 llvm::ConstantInt::get(IntPtrTy,
688 CacheSize-1));
689 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
690 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000691 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
692 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000693
694 // If the hash isn't in the cache, call a runtime handler to perform the
695 // hard work of checking whether the vptr is for an object of the right
696 // type. This will either fill in the cache and return, or produce a
697 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000698 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000699 llvm::Constant *StaticData[] = {
700 EmitCheckSourceLocation(Loc),
701 EmitCheckTypeDescriptor(Ty),
702 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
703 llvm::ConstantInt::get(Int8Ty, TCK)
704 };
John McCall7f416cc2015-09-08 08:05:57 +0000705 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000706 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000707 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
708 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000709 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000710 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000711
712 if (Done) {
713 Builder.CreateBr(Done);
714 EmitBlock(Done);
715 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000716}
Chris Lattner4647a212007-08-31 22:49:20 +0000717
Richard Smith539e4a72013-02-23 02:53:19 +0000718/// Determine whether this expression refers to a flexible array member in a
719/// struct. We disable array bounds checks for such members.
720static bool isFlexibleArrayMemberExpr(const Expr *E) {
721 // For compatibility with existing code, we treat arrays of length 0 or
722 // 1 as flexible array members.
723 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000724 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000725 if (CAT->getSize().ugt(1))
726 return false;
727 } else if (!isa<IncompleteArrayType>(AT))
728 return false;
729
730 E = E->IgnoreParens();
731
732 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000733 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000734 // FIXME: If the base type of the member expr is not FD->getParent(),
735 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000736 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000737 RecordDecl::field_iterator FI(
738 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
739 return ++FI == FD->getParent()->field_end();
740 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000741 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
742 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000743 }
744
745 return false;
746}
747
748/// If Base is known to point to the start of an array, return the length of
749/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000750static llvm::Value *getArrayIndexingBound(
751 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000752 // For the vector indexing extension, the bound is the number of elements.
753 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
754 IndexedType = Base->getType();
755 return CGF.Builder.getInt32(VT->getNumElements());
756 }
757
758 Base = Base->IgnoreParens();
759
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000760 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000761 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
762 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
763 IndexedType = CE->getSubExpr()->getType();
764 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000765 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000766 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000767 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000768 return CGF.getVLASize(VAT).first;
769 }
770 }
771
Craig Topper8a13c412014-05-21 05:09:00 +0000772 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000773}
774
775void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
776 llvm::Value *Index, QualType IndexType,
777 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000778 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000779 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000780 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000781
Richard Smith539e4a72013-02-23 02:53:19 +0000782 QualType IndexedType;
783 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
784 if (!Bound)
785 return;
786
787 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
788 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
789 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
790
791 llvm::Constant *StaticData[] = {
792 EmitCheckSourceLocation(E->getExprLoc()),
793 EmitCheckTypeDescriptor(IndexedType),
794 EmitCheckTypeDescriptor(IndexType)
795 };
796 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
797 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000798 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
799 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000800}
801
Chris Lattner116ce8f2010-01-09 21:40:03 +0000802
Chris Lattner116ce8f2010-01-09 21:40:03 +0000803CodeGenFunction::ComplexPairTy CodeGenFunction::
804EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
805 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000806 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000807
Chris Lattner116ce8f2010-01-09 21:40:03 +0000808 llvm::Value *NextVal;
809 if (isa<llvm::IntegerType>(InVal.first->getType())) {
810 uint64_t AmountVal = isInc ? 1 : -1;
811 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000812
Chris Lattner116ce8f2010-01-09 21:40:03 +0000813 // Add the inc/dec to the real part.
814 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
815 } else {
816 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
817 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
818 if (!isInc)
819 FVal.changeSign();
820 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000821
Chris Lattner116ce8f2010-01-09 21:40:03 +0000822 // Add the inc/dec to the real part.
823 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
824 }
Craig Topper99e79272013-07-26 05:59:26 +0000825
Chris Lattner116ce8f2010-01-09 21:40:03 +0000826 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000827
Chris Lattner116ce8f2010-01-09 21:40:03 +0000828 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000829 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000830
Chris Lattner116ce8f2010-01-09 21:40:03 +0000831 // If this is a postinc, return the value read from memory, otherwise use the
832 // updated value.
833 return isPre ? IncVal : InVal;
834}
835
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000836void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
837 CodeGenFunction *CGF) {
838 // Bind VLAs in the cast type.
839 if (CGF && E->getType()->isVariablyModifiedType())
840 CGF->EmitVariablyModifiedType(E->getType());
841
842 if (CGDebugInfo *DI = getModuleDebugInfo())
843 DI->EmitExplicitCastType(E->getType());
844}
845
Chris Lattnera45c5af2007-06-02 19:47:04 +0000846//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000847// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000848//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000849
John McCall7f416cc2015-09-08 08:05:57 +0000850/// EmitPointerWithAlignment - Given an expression of pointer type, try to
851/// derive a more accurate bound on the alignment of the pointer.
852Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000853 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000854 // We allow this with ObjC object pointers because of fragile ABIs.
855 assert(E->getType()->isPointerType() ||
856 E->getType()->isObjCObjectPointerType());
857 E = E->IgnoreParens();
858
859 // Casts:
860 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000861 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
862 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000863
864 switch (CE->getCastKind()) {
865 // Non-converting casts (but not C's implicit conversion from void*).
866 case CK_BitCast:
867 case CK_NoOp:
868 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
869 if (PtrTy->getPointeeType()->isVoidType())
870 break;
871
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000872 LValueBaseInfo InnerInfo;
873 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo);
874 if (BaseInfo) *BaseInfo = InnerInfo;
John McCall7f416cc2015-09-08 08:05:57 +0000875
876 // If this is an explicit bitcast, and the source l-value is
877 // opaque, honor the alignment of the casted-to type.
878 if (isa<ExplicitCastExpr>(CE) &&
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000879 InnerInfo.getAlignmentSource() != AlignmentSource::Decl) {
880 LValueBaseInfo ExpInfo;
881 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
882 &ExpInfo);
883 if (BaseInfo)
884 BaseInfo->mergeForCast(ExpInfo);
885 Addr = Address(Addr.getPointer(), Align);
John McCall7f416cc2015-09-08 08:05:57 +0000886 }
887
Peter Collingbourne574975e2016-01-14 02:49:48 +0000888 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
889 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000890 if (auto PT = E->getType()->getAs<PointerType>())
891 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
892 /*MayBeNull=*/true,
893 CodeGenFunction::CFITCK_UnrelatedCast,
894 CE->getLocStart());
895 }
896
John McCall7f416cc2015-09-08 08:05:57 +0000897 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
898 }
899 break;
900
901 // Array-to-pointer decay.
902 case CK_ArrayToPointerDecay:
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000903 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000904
905 // Derived-to-base conversions.
906 case CK_UncheckedDerivedToBase:
907 case CK_DerivedToBase: {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000908 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000909 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
910 return GetAddressOfBaseClass(Addr, Derived,
911 CE->path_begin(), CE->path_end(),
912 ShouldNullCheckClassCastValue(CE),
913 CE->getExprLoc());
914 }
915
916 // TODO: Is there any reason to treat base-to-derived conversions
917 // specially?
918 default:
919 break;
920 }
921 }
922
923 // Unary &.
924 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
925 if (UO->getOpcode() == UO_AddrOf) {
926 LValue LV = EmitLValue(UO->getSubExpr());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000927 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +0000928 return LV.getAddress();
929 }
930 }
931
932 // TODO: conditional operators, comma.
933
934 // Otherwise, use the alignment of the type.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000935 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000936 return Address(EmitScalarExpr(E), Align);
937}
938
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000939RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000940 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000941 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000942
943 switch (getEvaluationKind(Ty)) {
944 case TEK_Complex: {
945 llvm::Type *EltTy =
946 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000947 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000948 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000949 }
Craig Topper99e79272013-07-26 05:59:26 +0000950
Chris Lattner65526f02010-08-23 05:26:13 +0000951 // If this is a use of an undefined aggregate type, the aggregate must have an
952 // identifiable address. Just because the contents of the value are undefined
953 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000954 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000955 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000956 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000957 }
John McCall47fb9502013-03-07 21:37:08 +0000958
959 case TEK_Scalar:
960 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
961 }
962 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000963}
964
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000965RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
966 const char *Name) {
967 ErrorUnsupported(E, Name);
968 return GetUndefRValue(E->getType());
969}
970
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000971LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
972 const char *Name) {
973 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000974 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000975 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
976 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000977}
978
Vedant Kumarffd7c882017-04-14 22:03:34 +0000979bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000980 const Expr *Base = Obj;
981 while (!isa<CXXThisExpr>(Base)) {
982 // The result of a dynamic_cast can be null.
983 if (isa<CXXDynamicCastExpr>(Base))
984 return false;
985
986 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
987 Base = CE->getSubExpr();
988 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
989 Base = PE->getSubExpr();
990 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
991 if (UO->getOpcode() == UO_Extension)
992 Base = UO->getSubExpr();
993 else
994 return false;
995 } else {
996 return false;
997 }
998 }
999 return true;
1000}
1001
Richard Smith4d1458e2012-09-08 02:08:36 +00001002LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +00001003 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001004 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +00001005 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1006 else
1007 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001008 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1009 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001010 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1011 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1012 if (IsBaseCXXThis)
1013 SkippedChecks.set(SanitizerKind::Alignment, true);
1014 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001015 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001016 }
John McCall7f416cc2015-09-08 08:05:57 +00001017 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001018 E->getType(), LV.getAlignment(), SkippedChecks);
1019 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001020 return LV;
1021}
1022
Chris Lattner8394d792007-06-05 20:53:16 +00001023/// EmitLValue - Emit code to compute a designator that specifies the location
1024/// of the expression.
1025///
Mike Stump4a3999f2009-09-09 13:00:44 +00001026/// This can return one of two things: a simple address or a bitfield reference.
1027/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1028/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001029///
Mike Stump4a3999f2009-09-09 13:00:44 +00001030/// If this returns a bitfield reference, nothing about the pointee type of the
1031/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001032///
Mike Stump4a3999f2009-09-09 13:00:44 +00001033/// If this returns a normal address, and if the lvalue's C type is fixed size,
1034/// this method guarantees that the returned pointer type will point to an LLVM
1035/// type of the same size of the lvalue's type. If the lvalue has a variable
1036/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001037///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001038LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001039 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001040 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001041 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001042
John McCallc109a252011-11-07 03:59:57 +00001043 case Expr::ObjCPropertyRefExprClass:
1044 llvm_unreachable("cannot emit a property reference directly");
1045
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001046 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001047 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001048 case Expr::ObjCIsaExprClass:
1049 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001050 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001051 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001052 case Expr::CompoundAssignOperatorClass: {
1053 QualType Ty = E->getType();
1054 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1055 Ty = AT->getValueType();
1056 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001057 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1058 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001059 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001060 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001061 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001062 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001063 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001064 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001065 case Expr::VAArgExprClass:
1066 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001067 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001068 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001069 case Expr::ParenExprClass:
1070 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001071 case Expr::GenericSelectionExprClass:
1072 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001073 case Expr::PredefinedExprClass:
1074 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001075 case Expr::StringLiteralClass:
1076 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001077 case Expr::ObjCEncodeExprClass:
1078 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001079 case Expr::PseudoObjectExprClass:
1080 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001081 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001082 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001083 case Expr::CXXTemporaryObjectExprClass:
1084 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001085 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1086 case Expr::CXXBindTemporaryExprClass:
1087 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001088 case Expr::CXXUuidofExprClass:
1089 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001090 case Expr::LambdaExprClass:
1091 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001092
1093 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001094 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001095 enterFullExpression(cleanups);
1096 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001097 LValue LV = EmitLValue(cleanups->getSubExpr());
1098 if (LV.isSimple()) {
1099 // Defend against branches out of gnu statement expressions surrounded by
1100 // cleanups.
1101 llvm::Value *V = LV.getPointer();
1102 Scope.ForceCleanup({&V});
1103 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001104 getContext(), LV.getBaseInfo(),
Reid Kleckner092d0652017-03-06 22:18:34 +00001105 LV.getTBAAInfo());
1106 }
1107 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1108 // bitfield lvalue or some other non-simple lvalue?
1109 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001110 }
1111
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001112 case Expr::CXXDefaultArgExprClass:
1113 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001114 case Expr::CXXDefaultInitExprClass: {
1115 CXXDefaultInitExprScope Scope(*this);
1116 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1117 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001118 case Expr::CXXTypeidExprClass:
1119 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001120
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001121 case Expr::ObjCMessageExprClass:
1122 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001123 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001124 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001125 case Expr::StmtExprClass:
1126 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001127 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001128 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001129 case Expr::ArraySubscriptExprClass:
1130 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001131 case Expr::OMPArraySectionExprClass:
1132 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001133 case Expr::ExtVectorElementExprClass:
1134 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001135 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001136 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001137 case Expr::CompoundLiteralExprClass:
1138 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001139 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001140 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001141 case Expr::BinaryConditionalOperatorClass:
1142 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001143 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001144 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001145 case Expr::OpaqueValueExprClass:
1146 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001147 case Expr::SubstNonTypeTemplateParmExprClass:
1148 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001149 case Expr::ImplicitCastExprClass:
1150 case Expr::CStyleCastExprClass:
1151 case Expr::CXXFunctionalCastExprClass:
1152 case Expr::CXXStaticCastExprClass:
1153 case Expr::CXXDynamicCastExprClass:
1154 case Expr::CXXReinterpretCastExprClass:
1155 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001156 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001157 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001158
Douglas Gregorfe314812011-06-21 17:03:29 +00001159 case Expr::MaterializeTemporaryExprClass:
1160 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001161 }
1162}
1163
John McCall71335052012-03-10 03:05:10 +00001164/// Given an object of the given canonical type, can we safely copy a
1165/// value out of it based on its initializer?
1166static bool isConstantEmittableObjectType(QualType type) {
1167 assert(type.isCanonical());
1168 assert(!type->isReferenceType());
1169
1170 // Must be const-qualified but non-volatile.
1171 Qualifiers qs = type.getLocalQualifiers();
1172 if (!qs.hasConst() || qs.hasVolatile()) return false;
1173
1174 // Otherwise, all object types satisfy this except C++ classes with
1175 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001176 if (const auto *RT = dyn_cast<RecordType>(type))
1177 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001178 if (RD->hasMutableFields() || !RD->isTrivial())
1179 return false;
1180
1181 return true;
1182}
1183
1184/// Can we constant-emit a load of a reference to a variable of the
1185/// given type? This is different from predicates like
1186/// Decl::isUsableInConstantExpressions because we do want it to apply
1187/// in situations that don't necessarily satisfy the language's rules
1188/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1189/// to do this with const float variables even if those variables
1190/// aren't marked 'constexpr'.
1191enum ConstantEmissionKind {
1192 CEK_None,
1193 CEK_AsReferenceOnly,
1194 CEK_AsValueOrReference,
1195 CEK_AsValueOnly
1196};
1197static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1198 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001199 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001200 if (isConstantEmittableObjectType(ref->getPointeeType()))
1201 return CEK_AsValueOrReference;
1202 return CEK_AsReferenceOnly;
1203 }
1204 if (isConstantEmittableObjectType(type))
1205 return CEK_AsValueOnly;
1206 return CEK_None;
1207}
1208
1209/// Try to emit a reference to the given value without producing it as
1210/// an l-value. This is actually more than an optimization: we can't
1211/// produce an l-value for variables that we never actually captured
1212/// in a block or lambda, which means const int variables or constexpr
1213/// literals or similar.
1214CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001215CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1216 ValueDecl *value = refExpr->getDecl();
1217
John McCall71335052012-03-10 03:05:10 +00001218 // The value needs to be an enum constant or a constant variable.
1219 ConstantEmissionKind CEK;
1220 if (isa<ParmVarDecl>(value)) {
1221 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001222 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001223 CEK = checkVarTypeForConstantEmission(var->getType());
1224 } else if (isa<EnumConstantDecl>(value)) {
1225 CEK = CEK_AsValueOnly;
1226 } else {
1227 CEK = CEK_None;
1228 }
1229 if (CEK == CEK_None) return ConstantEmission();
1230
John McCall71335052012-03-10 03:05:10 +00001231 Expr::EvalResult result;
1232 bool resultIsReference;
1233 QualType resultType;
1234
1235 // It's best to evaluate all the way as an r-value if that's permitted.
1236 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001237 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001238 resultIsReference = false;
1239 resultType = refExpr->getType();
1240
1241 // Otherwise, try to evaluate as an l-value.
1242 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001243 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001244 resultIsReference = true;
1245 resultType = value->getType();
1246
1247 // Failure.
1248 } else {
1249 return ConstantEmission();
1250 }
1251
1252 // In any case, if the initializer has side-effects, abandon ship.
1253 if (result.HasSideEffects)
1254 return ConstantEmission();
1255
1256 // Emit as a constant.
1257 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1258
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001259 // Make sure we emit a debug reference to the global variable.
1260 // This should probably fire even for
1261 if (isa<VarDecl>(value)) {
1262 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001263 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001264 } else {
1265 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001266 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001267 }
John McCall71335052012-03-10 03:05:10 +00001268
1269 // If we emitted a reference constant, we need to dereference that.
1270 if (resultIsReference)
1271 return ConstantEmission::forReference(C);
1272
1273 return ConstantEmission::forValue(C);
1274}
1275
Nick Lewycky2d84e842013-10-02 02:29:49 +00001276llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1277 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001278 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001279 lvalue.getType(), Loc, lvalue.getBaseInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001280 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001281 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1282 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001283}
1284
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001285static bool hasBooleanRepresentation(QualType Ty) {
1286 if (Ty->isBooleanType())
1287 return true;
1288
1289 if (const EnumType *ET = Ty->getAs<EnumType>())
1290 return ET->getDecl()->getIntegerType()->isBooleanType();
1291
Douglas Gregor298f43d2012-04-12 20:42:30 +00001292 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1293 return hasBooleanRepresentation(AT->getValueType());
1294
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001295 return false;
1296}
1297
Richard Smith1629da92012-12-13 07:11:50 +00001298static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1299 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001300 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001301 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001302 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1303 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001304 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001305 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001306
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001307 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001308 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1309 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001310 } else {
1311 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001312 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001313 unsigned Bitwidth = LTy->getScalarSizeInBits();
1314 unsigned NumNegativeBits = ED->getNumNegativeBits();
1315 unsigned NumPositiveBits = ED->getNumPositiveBits();
1316
1317 if (NumNegativeBits) {
1318 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1319 assert(NumBits <= Bitwidth);
1320 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1321 Min = -End;
1322 } else {
1323 assert(NumPositiveBits <= Bitwidth);
1324 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1325 Min = llvm::APInt(Bitwidth, 0);
1326 }
1327 }
Richard Smith1629da92012-12-13 07:11:50 +00001328 return true;
1329}
1330
1331llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1332 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001333 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1334 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001335 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001336
Duncan Sandsc720e782012-04-15 18:04:54 +00001337 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001338 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001339}
1340
Vedant Kumar5a972652017-02-27 19:46:19 +00001341bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1342 SourceLocation Loc) {
1343 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1344 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1345 if (!HasBoolCheck && !HasEnumCheck)
1346 return false;
1347
1348 bool IsBool = hasBooleanRepresentation(Ty) ||
1349 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1350 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1351 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1352 if (!NeedsBoolCheck && !NeedsEnumCheck)
1353 return false;
1354
Vedant Kumar129edab2017-03-09 16:06:27 +00001355 // Single-bit booleans don't need to be checked. Special-case this to avoid
1356 // a bit width mismatch when handling bitfield values. This is handled by
1357 // EmitFromMemory for the non-bitfield case.
1358 if (IsBool &&
1359 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1360 return false;
1361
Vedant Kumar5a972652017-02-27 19:46:19 +00001362 llvm::APInt Min, End;
1363 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1364 return true;
1365
1366 SanitizerScope SanScope(this);
1367 llvm::Value *Check;
1368 --End;
1369 if (!Min) {
1370 Check = Builder.CreateICmpULE(
1371 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1372 } else {
1373 llvm::Value *Upper = Builder.CreateICmpSLE(
1374 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1375 llvm::Value *Lower = Builder.CreateICmpSGE(
1376 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1377 Check = Builder.CreateAnd(Upper, Lower);
1378 }
1379 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1380 EmitCheckTypeDescriptor(Ty)};
1381 SanitizerMask Kind =
1382 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1383 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1384 StaticArgs, EmitCheckValue(Value));
1385 return true;
1386}
1387
John McCall7f416cc2015-09-08 08:05:57 +00001388llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1389 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001390 SourceLocation Loc,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001391 LValueBaseInfo BaseInfo,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001392 llvm::MDNode *TBAAInfo,
1393 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001394 uint64_t TBAAOffset,
1395 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001396 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1397 // For better performance, handle vector loads differently.
1398 if (Ty->isVectorType()) {
1399 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001400
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001401 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001402
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001403 // Handle vectors of size 3 like size 4 for better performance.
1404 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001405
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001406 // Bitcast to vec4 type.
1407 llvm::VectorType *vec4Ty =
1408 llvm::VectorType::get(VTy->getElementType(), 4);
1409 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1410 // Now load value.
1411 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001412
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001413 // Shuffle vector to get vec3.
1414 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1415 {0, 1, 2}, "extractVec");
1416 return EmitFromMemory(V, Ty);
1417 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001418 }
1419 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001420
1421 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001422 LValue AtomicLValue =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001423 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001424 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1425 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001426 }
Craig Topper99e79272013-07-26 05:59:26 +00001427
John McCall7f416cc2015-09-08 08:05:57 +00001428 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001429 if (isNontemporal) {
1430 llvm::MDNode *Node = llvm::MDNode::get(
1431 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1432 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1433 }
Manman Renc451e572013-04-04 21:53:22 +00001434 if (TBAAInfo) {
1435 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1436 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001437 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001438 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1439 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001440 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001441
Vedant Kumar5a972652017-02-27 19:46:19 +00001442 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1443 // In order to prevent the optimizer from throwing away the check, don't
1444 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001445 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001446 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1447 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001448
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001449 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001450}
1451
John McCall3a7f6922010-10-27 20:58:56 +00001452llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1453 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001454 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001455 // This should really always be an i1, but sometimes it's already
1456 // an i8, and it's awkward to track those cases down.
1457 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001458 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1459 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1460 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001461 }
1462
1463 return Value;
1464}
1465
1466llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1467 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001468 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001469 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1470 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001471 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1472 }
1473
1474 return Value;
1475}
1476
John McCall7f416cc2015-09-08 08:05:57 +00001477void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1478 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001479 LValueBaseInfo BaseInfo,
John McCall7f416cc2015-09-08 08:05:57 +00001480 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001481 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001482 uint64_t TBAAOffset,
1483 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001484
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001485 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1486 // Handle vectors differently to get better performance.
1487 if (Ty->isVectorType()) {
1488 llvm::Type *SrcTy = Value->getType();
1489 auto *VecTy = cast<llvm::VectorType>(SrcTy);
1490 // Handle vec3 special.
1491 if (VecTy->getNumElements() == 3) {
1492 // Our source is a vec3, do a shuffle vector to make it a vec4.
1493 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1494 Builder.getInt32(2),
1495 llvm::UndefValue::get(Builder.getInt32Ty())};
1496 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1497 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1498 MaskV, "extractVec");
1499 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1500 }
1501 if (Addr.getElementType() != SrcTy) {
1502 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1503 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001504 }
1505 }
Craig Topper99e79272013-07-26 05:59:26 +00001506
John McCall3a7f6922010-10-27 20:58:56 +00001507 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001508
David Majnemera38c9f12016-05-24 16:09:25 +00001509 LValue AtomicLValue =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001510 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001511 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001512 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1513 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001514 return;
1515 }
1516
Daniel Dunbar03816342010-08-21 02:24:36 +00001517 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001518 if (isNontemporal) {
1519 llvm::MDNode *Node =
1520 llvm::MDNode::get(Store->getContext(),
1521 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1522 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1523 }
Manman Renc451e572013-04-04 21:53:22 +00001524 if (TBAAInfo) {
1525 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1526 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001527 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001528 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1529 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001530 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001531}
1532
David Chisnallfa35df62012-01-16 17:27:18 +00001533void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001534 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001535 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001536 lvalue.getType(), lvalue.getBaseInfo(),
Manman Renc451e572013-04-04 21:53:22 +00001537 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001538 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001539}
1540
Mike Stump4a3999f2009-09-09 13:00:44 +00001541/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1542/// method emits the address of the lvalue, then loads the result as an rvalue,
1543/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001544RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001545 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001546 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001547 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001548 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1549 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001550 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001551 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001552 // In MRC mode, we do a load+autorelease.
1553 if (!getLangOpts().ObjCAutoRefCount) {
1554 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1555 }
1556
1557 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001558 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1559 Object = EmitObjCConsumeObject(LV.getType(), Object);
1560 return RValue::get(Object);
1561 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001562
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001563 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001564 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001565
John McCalla1dee5302010-08-22 10:59:02 +00001566 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001567 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001568 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001569
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001570 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001571 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001572 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001573 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001574 "vecext"));
1575 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001576
1577 // If this is a reference to a subset of the elements of a vector, either
1578 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001579 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001580 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001581
Renato Golin230c5eb2014-05-19 18:15:42 +00001582 // Global Register variables always invoke intrinsics
1583 if (LV.isGlobalReg())
1584 return EmitLoadOfGlobalRegLValue(LV);
1585
John McCallc109a252011-11-07 03:59:57 +00001586 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001587 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001588}
1589
Vedant Kumar129edab2017-03-09 16:06:27 +00001590RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1591 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001592 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001593
Daniel Dunbar3447a022010-04-13 23:34:15 +00001594 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001595 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001596
John McCall7f416cc2015-09-08 08:05:57 +00001597 Address Ptr = LV.getBitFieldAddress();
1598 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001599
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001600 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001601 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001602 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1603 if (HighBits)
1604 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1605 if (Info.Offset + HighBits)
1606 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1607 } else {
1608 if (Info.Offset)
1609 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001610 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001611 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1612 Info.Size),
1613 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001614 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001615 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001616 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001617 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001618}
1619
Nate Begemanb699c9b2009-01-18 06:42:49 +00001620// If this is a reference to a subset of the elements of a vector, create an
1621// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001622RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001623 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1624 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001625
Nate Begemanf322eab2008-05-09 06:41:27 +00001626 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001627
1628 // If the result of the expression is a non-vector type, we must be extracting
1629 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001630 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001631 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001632 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001633 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001634 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001635 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001636
1637 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001638 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001639
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001640 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001641 for (unsigned i = 0; i != NumResultElts; ++i)
1642 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001643
Chris Lattner91c08ad2011-02-15 00:14:06 +00001644 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1645 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001646 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001647 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001648}
1649
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001650/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001651Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1652 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001653 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1654 QualType EQT = ExprVT->getElementType();
1655 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001656
John McCall7f416cc2015-09-08 08:05:57 +00001657 Address CastToPointerElement =
1658 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1659 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001660
1661 const llvm::Constant *Elts = LV.getExtVectorElts();
1662 unsigned ix = getAccessedFieldNo(0, Elts);
1663
John McCall7f416cc2015-09-08 08:05:57 +00001664 Address VectorBasePtrPlusIx =
1665 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1666 getContext().getTypeSizeInChars(EQT),
1667 "vector.elt");
1668
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001669 return VectorBasePtrPlusIx;
1670}
1671
Renato Golin230c5eb2014-05-19 18:15:42 +00001672/// @brief Load of global gamed gegisters are always calls to intrinsics.
1673RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001674 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1675 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001676 llvm::MDNode *RegName = cast<llvm::MDNode>(
1677 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001678
1679 // We accept integer and pointer types only
1680 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1681 llvm::Type *Ty = OrigTy;
1682 if (OrigTy->isPointerTy())
1683 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1684 llvm::Type *Types[] = { Ty };
1685
Renato Golin230c5eb2014-05-19 18:15:42 +00001686 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001687 llvm::Value *Call = Builder.CreateCall(
1688 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001689 if (OrigTy->isPointerTy())
1690 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001691 return RValue::get(Call);
1692}
Chris Lattner40ff7012007-08-03 16:18:34 +00001693
Chris Lattner9369a562007-06-29 16:31:29 +00001694
Chris Lattner8394d792007-06-05 20:53:16 +00001695/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1696/// lvalue, where both are guaranteed to the have the same type, and that type
1697/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001698void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001699 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001700 if (!Dst.isSimple()) {
1701 if (Dst.isVectorElt()) {
1702 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001703 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1704 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001705 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001706 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001707 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1708 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001709 return;
1710 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001711
Nate Begemance4d7fc2008-04-18 23:10:10 +00001712 // If this is an update of extended vector elements, insert them as
1713 // appropriate.
1714 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001715 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001716
Renato Golin230c5eb2014-05-19 18:15:42 +00001717 if (Dst.isGlobalReg())
1718 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1719
John McCallc109a252011-11-07 03:59:57 +00001720 assert(Dst.isBitField() && "Unknown LValue type");
1721 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001722 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001723
John McCall31168b02011-06-15 23:02:42 +00001724 // There's special magic for assigning into an ARC-qualified l-value.
1725 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1726 switch (Lifetime) {
1727 case Qualifiers::OCL_None:
1728 llvm_unreachable("present but none");
1729
1730 case Qualifiers::OCL_ExplicitNone:
1731 // nothing special
1732 break;
1733
1734 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001735 if (isInit) {
1736 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1737 break;
1738 }
John McCall55e1fbc2011-06-25 02:11:03 +00001739 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001740 return;
1741
1742 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001743 if (isInit)
1744 // Initialize and then skip the primitive store.
1745 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1746 else
1747 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001748 return;
1749
1750 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001751 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1752 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001753 // fall into the normal path
1754 break;
1755 }
1756 }
1757
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001758 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001759 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001760 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001761 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001762 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001763 return;
1764 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001765
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001766 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001767 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001768 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001769 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001770 if (Dst.isObjCIvar()) {
1771 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001772 llvm::Type *ResultType = IntPtrTy;
1773 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1774 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001775 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001776 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001777 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1778 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001779 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001780 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001781 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001782 } else if (Dst.isGlobalObjCRef()) {
1783 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1784 Dst.isThreadLocalRef());
1785 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001786 else
1787 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001788 return;
1789 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001790
Chris Lattner6278e6a2007-08-11 00:04:45 +00001791 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001792 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001793}
1794
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001795void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001796 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001797 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001798 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001799 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001800
Daniel Dunbar67aba792010-04-15 03:47:33 +00001801 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001802 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001803
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001804 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001805 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001806 /*IsSigned=*/false);
1807 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001808
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001809 // See if there are other bits in the bitfield's storage we'll need to load
1810 // and mask together with source before storing.
1811 if (Info.StorageSize != Info.Size) {
1812 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001813 llvm::Value *Val =
1814 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001815
1816 // Mask the source value as needed.
1817 if (!hasBooleanRepresentation(Dst.getType()))
1818 SrcVal = Builder.CreateAnd(SrcVal,
1819 llvm::APInt::getLowBitsSet(Info.StorageSize,
1820 Info.Size),
1821 "bf.value");
1822 MaskedVal = SrcVal;
1823 if (Info.Offset)
1824 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1825
1826 // Mask out the original value.
1827 Val = Builder.CreateAnd(Val,
1828 ~llvm::APInt::getBitsSet(Info.StorageSize,
1829 Info.Offset,
1830 Info.Offset + Info.Size),
1831 "bf.clear");
1832
1833 // Or together the unchanged values and the source value.
1834 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1835 } else {
1836 assert(Info.Offset == 0);
1837 }
1838
1839 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001840 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001841
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001842 // Return the new value of the bit-field, if requested.
1843 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001844 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001845
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001846 // Sign extend the value if needed.
1847 if (Info.IsSigned) {
1848 assert(Info.Size <= Info.StorageSize);
1849 unsigned HighBits = Info.StorageSize - Info.Size;
1850 if (HighBits) {
1851 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1852 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1853 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001854 }
1855
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001856 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1857 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001858 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001859 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001860}
1861
Nate Begemance4d7fc2008-04-18 23:10:10 +00001862void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001863 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001864 // This access turns into a read/modify/write of the vector. Load the input
1865 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001866 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1867 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001868 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001869
Chris Lattner4647a212007-08-31 22:49:20 +00001870 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001871
John McCall55e1fbc2011-06-25 02:11:03 +00001872 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001873 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001874 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001875 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001876 // Use shuffle vector is the src and destination are the same number of
1877 // elements and restore the vector mask since it is on the side it will be
1878 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001879 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001880 for (unsigned i = 0; i != NumSrcElts; ++i)
1881 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001882
Chris Lattner91c08ad2011-02-15 00:14:06 +00001883 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001884 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001885 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001886 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001887 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001888 // Extended the source vector to the same length and then shuffle it
1889 // into the destination.
1890 // FIXME: since we're shuffling with undef, can we just use the indices
1891 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001892 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001893 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001894 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001895 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001896 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001897 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001898 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001899 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001900 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001901 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001902 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001903 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001904 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001905
Joey Goulycf4143b2013-11-21 17:09:05 +00001906 // When the vector size is odd and .odd or .hi is used, the last element
1907 // of the Elts constant array will be one past the size of the vector.
1908 // Ignore the last element here, if it is greater than the mask size.
1909 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1910 NumSrcElts--;
1911
Nate Begemanb699c9b2009-01-18 06:42:49 +00001912 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001913 for (unsigned i = 0; i != NumSrcElts; ++i)
1914 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001915 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001916 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001917 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001918 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001919 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001920 }
1921 } else {
1922 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001923 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001924 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001925 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001926 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001927
John McCall7f416cc2015-09-08 08:05:57 +00001928 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1929 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001930}
1931
Renato Golin230c5eb2014-05-19 18:15:42 +00001932/// @brief Store of global named registers are always calls to intrinsics.
1933void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001934 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1935 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001936 llvm::MDNode *RegName = cast<llvm::MDNode>(
1937 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001938 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001939
1940 // We accept integer and pointer types only
1941 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1942 llvm::Type *Ty = OrigTy;
1943 if (OrigTy->isPointerTy())
1944 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1945 llvm::Type *Types[] = { Ty };
1946
Renato Golin230c5eb2014-05-19 18:15:42 +00001947 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1948 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001949 if (OrigTy->isPointerTy())
1950 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001951 Builder.CreateCall(
1952 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001953}
1954
Eric Christopherc9e2a682014-05-20 17:10:39 +00001955// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001956// generating write-barries API. It is currently a global, ivar,
1957// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001958static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001959 LValue &LV,
1960 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001961 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001962 return;
Craig Topper99e79272013-07-26 05:59:26 +00001963
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001964 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001965 QualType ExpTy = E->getType();
1966 if (IsMemberAccess && ExpTy->isPointerType()) {
1967 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001968 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001969 // writer-barrier conservatively.
1970 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1971 if (ExpTy->isRecordType()) {
1972 LV.setObjCIvar(false);
1973 return;
1974 }
1975 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001976 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001977 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001978 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001979 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001980 return;
1981 }
Craig Topper99e79272013-07-26 05:59:26 +00001982
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001983 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1984 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001985 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001986 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001987 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001988 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001989 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001990 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001991 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001992 }
Craig Topper99e79272013-07-26 05:59:26 +00001993
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001994 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001995 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001996 return;
1997 }
Craig Topper99e79272013-07-26 05:59:26 +00001998
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001999 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002000 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002001 if (LV.isObjCIvar()) {
2002 // If cast is to a structure pointer, follow gcc's behavior and make it
2003 // a non-ivar write-barrier.
2004 QualType ExpTy = E->getType();
2005 if (ExpTy->isPointerType())
2006 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2007 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002008 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002009 }
2010 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002011 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002012
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002013 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002014 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2015 return;
2016 }
2017
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002018 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002019 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002020 return;
2021 }
Craig Topper99e79272013-07-26 05:59:26 +00002022
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002023 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002024 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002025 return;
2026 }
John McCall31168b02011-06-15 23:02:42 +00002027
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002028 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002029 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002030 return;
2031 }
2032
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002033 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002034 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002035 if (LV.isObjCIvar() && !LV.isObjCArray())
2036 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002037 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002038 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002039 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002040 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002041 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002042 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002043 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002044 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002045
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002046 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002047 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002048 // We don't know if member is an 'ivar', but this flag is looked at
2049 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002050 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002051 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002052 }
2053}
2054
Chris Lattner3f32d692011-07-12 06:52:18 +00002055static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002056EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002057 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002058 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002059 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002060 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002061}
2062
Alexey Bataev97720002014-11-11 04:05:39 +00002063static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002064 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2065 llvm::Type *RealVarTy, SourceLocation Loc) {
2066 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2067 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002068 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2069 return CGF.MakeAddrLValue(Addr, T, BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00002070}
2071
2072Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2073 const ReferenceType *RefTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002074 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002075 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2076 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002077 BaseInfo, /*forPointee*/ true));
John McCall7f416cc2015-09-08 08:05:57 +00002078}
2079
2080LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2081 const ReferenceType *RefTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002082 LValueBaseInfo BaseInfo;
2083 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2084 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002085}
2086
Alexey Bataev31300ed2016-02-04 11:27:03 +00002087Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2088 const PointerType *PtrTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002089 LValueBaseInfo *BaseInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002090 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002091 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2092 BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002093 /*forPointeeType=*/true));
2094}
2095
2096LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2097 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002098 LValueBaseInfo BaseInfo;
2099 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2100 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002101}
2102
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002103static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2104 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002105 QualType T = E->getType();
2106
2107 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002108 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2109 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002110 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2111
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002112 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002113 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2114 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002115 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002116 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002117 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002118 // Emit reference to the private copy of the variable if it is an OpenMP
2119 // threadprivate variable.
2120 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002121 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002122 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002123 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2124 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002125 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002126 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2127 LV = CGF.MakeAddrLValue(Addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002128 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002129 setObjCGCLValueClass(CGF.getContext(), E, LV);
2130 return LV;
2131}
2132
John McCallb92ab1a2016-10-26 23:46:34 +00002133static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2134 const FunctionDecl *FD) {
2135 if (FD->hasAttr<WeakRefAttr>()) {
2136 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2137 return aliasee.getPointer();
2138 }
2139
2140 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002141 if (!FD->hasPrototype()) {
2142 if (const FunctionProtoType *Proto =
2143 FD->getType()->getAs<FunctionProtoType>()) {
2144 // Ugly case: for a K&R-style definition, the type of the definition
2145 // isn't the same as the type of a use. Correct for this with a
2146 // bitcast.
2147 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002148 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2149 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2150 V = llvm::ConstantExpr::getBitCast(V,
2151 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002152 }
2153 }
John McCallb92ab1a2016-10-26 23:46:34 +00002154 return V;
2155}
2156
2157static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2158 const Expr *E, const FunctionDecl *FD) {
2159 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002160 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002161 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2162 return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002163}
2164
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002165static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2166 llvm::Value *ThisValue) {
2167 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2168 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2169 return CGF.EmitLValueForField(LV, FD);
2170}
2171
Renato Golin230c5eb2014-05-19 18:15:42 +00002172/// Named Registers are named metadata pointing to the register name
2173/// which will be read from/written to as an argument to the intrinsic
2174/// @llvm.read/write_register.
2175/// So far, only the name is being passed down, but other options such as
2176/// register type, allocation type or even optimization options could be
2177/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002178static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002179 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002180 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002181 assert(Asm->getLabel().size() < 64-Name.size() &&
2182 "Register name too big");
2183 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002184 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002185 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002186 if (M->getNumOperands() == 0) {
2187 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2188 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002189 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002190 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2191 }
John McCall7f416cc2015-09-08 08:05:57 +00002192
2193 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2194
2195 llvm::Value *Ptr =
2196 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2197 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002198}
2199
Chris Lattnerd7f58862007-06-02 05:24:33 +00002200LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002201 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002202 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002203
Renato Goline7b3d5d2014-05-27 16:46:27 +00002204 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2205 // Global Named registers access via intrinsics only
2206 if (VD->getStorageClass() == SC_Register &&
2207 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002208 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002209
Renato Goline7b3d5d2014-05-27 16:46:27 +00002210 // A DeclRefExpr for a reference initialized by a constant expression can
2211 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002212 const Expr *Init = VD->getAnyInitializer(VD);
2213 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2214 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002215 VD->checkInitIsICE() &&
2216 // Do not emit if it is private OpenMP variable.
2217 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2218 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002219 llvm::Constant *Val =
2220 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2221 assert(Val && "failed to emit reference constant expression");
2222 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002223
2224 // Should we be using the alignment of the constant pointer we emitted?
2225 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2226 /*pointee*/ true);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002227 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2228 return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo);
Richard Smith5a1104b2012-10-20 01:38:33 +00002229 }
David Majnemer602cfe72015-01-01 09:49:44 +00002230
2231 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002232 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002233 if (auto *FD = LambdaCaptureFields.lookup(VD))
2234 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2235 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002236 auto I = LocalDeclMap.find(VD);
2237 if (I != LocalDeclMap.end()) {
2238 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2239 return EmitLoadOfReferenceLValue(I->second, RefTy);
2240 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002241 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002242 LValue CapLVal =
2243 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2244 CapturedStmtInfo->getContextValue());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002245 bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002246 return MakeAddrLValue(
2247 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002248 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias));
David Majnemer602cfe72015-01-01 09:49:44 +00002249 }
John McCall7f416cc2015-09-08 08:05:57 +00002250
David Majnemer602cfe72015-01-01 09:49:44 +00002251 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002252 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002253 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2254 return MakeAddrLValue(addr, T, BaseInfo);
David Majnemer602cfe72015-01-01 09:49:44 +00002255 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002256 }
2257
Eli Friedman5720e342012-01-21 04:52:58 +00002258 // FIXME: We should be able to assert this for FunctionDecls as well!
2259 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2260 // those with a valid source location.
2261 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2262 !E->getLocation().isValid()) &&
2263 "Should not use decl without marking it used!");
2264
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002265 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002266 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002267 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002268 return MakeAddrLValue(Aliasee, T,
2269 LValueBaseInfo(AlignmentSource::Decl, false));
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002270 }
2271
Renato Goline7b3d5d2014-05-27 16:46:27 +00002272 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002273 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002274 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002275 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002276
John McCall7f416cc2015-09-08 08:05:57 +00002277 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002278
John McCall7f416cc2015-09-08 08:05:57 +00002279 // The variable should generally be present in the local decl map.
2280 auto iter = LocalDeclMap.find(VD);
2281 if (iter != LocalDeclMap.end()) {
2282 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002283
John McCall7f416cc2015-09-08 08:05:57 +00002284 // Otherwise, it might be static local we haven't emitted yet for
2285 // some reason; most likely, because it's in an outer function.
2286 } else if (VD->isStaticLocal()) {
2287 addr = Address(CGM.getOrCreateStaticVarDecl(
2288 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2289 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002290
John McCall7f416cc2015-09-08 08:05:57 +00002291 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002292 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002293 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2294 }
2295
2296
2297 // Check for OpenMP threadprivate variables.
2298 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2299 return EmitThreadPrivateVarDeclLValue(
2300 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2301 E->getExprLoc());
2302 }
2303
2304 // Drill into block byref variables.
2305 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2306 if (isBlockByref) {
2307 addr = emitBlockByrefAddress(addr, VD);
2308 }
2309
2310 // Drill into reference types.
2311 LValue LV;
2312 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2313 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2314 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002315 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2316 LV = MakeAddrLValue(addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002317 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002318
John McCallcdda29c2013-03-13 03:10:54 +00002319 bool isLocalStorage = VD->hasLocalStorage();
2320
2321 bool NonGCable = isLocalStorage &&
2322 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002323 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002324 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002325 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002326 LV.setNonGC(true);
2327 }
John McCallcdda29c2013-03-13 03:10:54 +00002328
2329 bool isImpreciseLifetime =
2330 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2331 if (isImpreciseLifetime)
2332 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002333 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002334 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002335 }
John McCallf3a88602011-02-03 08:15:49 +00002336
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002337 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002338 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002339
Richard Smithda383632016-08-15 01:33:41 +00002340 // FIXME: While we're emitting a binding from an enclosing scope, all other
2341 // DeclRefExprs we see should be implicitly treated as if they also refer to
2342 // an enclosing scope.
2343 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2344 return EmitLValue(BD->getBinding());
2345
David Blaikie83d382b2011-09-23 05:06:16 +00002346 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002347}
Chris Lattnere47e4402007-06-01 18:02:12 +00002348
Chris Lattner8394d792007-06-05 20:53:16 +00002349LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2350 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002351 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002352 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002353
Chris Lattner0f398c42008-07-26 22:37:01 +00002354 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002355 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002356 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002357 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002358 QualType T = E->getSubExpr()->getType()->getPointeeType();
2359 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002360
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002361 LValueBaseInfo BaseInfo;
2362 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo);
2363 LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002364 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002365
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002366 // We should not generate __weak write barrier on indirect reference
2367 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2368 // But, we continue to generate __strong write barrier on indirect write
2369 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002370 if (getLangOpts().ObjC1 &&
2371 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002372 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002373 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002374 return LV;
2375 }
John McCalle3027922010-08-25 11:45:40 +00002376 case UO_Real:
2377 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002378 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002379 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002380
Richard Smith0b6b8e42012-02-18 20:53:32 +00002381 // __real is valid on scalars. This is a faster way of testing that.
2382 // __imag can only produce an rvalue on scalars.
2383 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002384 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002385 assert(E->getSubExpr()->getType()->isArithmeticType());
2386 return LV;
2387 }
2388
Alexey Bataev611b0a12016-11-07 18:15:02 +00002389 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002390
John McCall7f416cc2015-09-08 08:05:57 +00002391 Address Component =
2392 (E->getOpcode() == UO_Real
2393 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2394 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002395 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo());
Alexey Bataev611b0a12016-11-07 18:15:02 +00002396 ElemLV.getQuals().addQualifiers(LV.getQuals());
2397 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002398 }
John McCalle3027922010-08-25 11:45:40 +00002399 case UO_PreInc:
2400 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002401 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002402 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002403
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002404 if (E->getType()->isAnyComplexType())
2405 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2406 else
2407 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2408 return LV;
2409 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002410 }
Chris Lattner8394d792007-06-05 20:53:16 +00002411}
2412
Chris Lattner4347e3692007-06-06 04:54:52 +00002413LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002414 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002415 E->getType(),
2416 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4347e3692007-06-06 04:54:52 +00002417}
2418
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002419LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002420 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002421 E->getType(),
2422 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002423}
2424
Mike Stump4a3999f2009-09-09 13:00:44 +00002425LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002426 auto SL = E->getFunctionName();
2427 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2428 StringRef FnName = CurFn->getName();
2429 if (FnName.startswith("\01"))
2430 FnName = FnName.substr(1);
2431 StringRef NameItems[] = {
2432 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2433 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002434 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002435 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2436 std::string Name = SL->getString();
2437 if (!Name.empty()) {
2438 unsigned Discriminator =
2439 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2440 if (Discriminator)
2441 Name += "_" + Twine(Discriminator + 1).str();
2442 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002443 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002444 } else {
2445 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002446 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002447 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002448 }
Alexey Bataevec474782014-10-09 08:45:04 +00002449 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002450 return MakeAddrLValue(C, E->getType(), BaseInfo);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002451}
2452
Richard Smithe30752c2012-10-09 19:52:38 +00002453/// Emit a type description suitable for use by a runtime sanitizer library. The
2454/// format of a type descriptor is
2455///
2456/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002457/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002458/// \endcode
2459///
Richard Smith683398a2012-10-09 23:55:19 +00002460/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2461/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002462llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002463 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002464 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002465 return C;
2466
Richard Smithe30752c2012-10-09 19:52:38 +00002467 uint16_t TypeKind = -1;
2468 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002469
Richard Smithe30752c2012-10-09 19:52:38 +00002470 if (T->isIntegerType()) {
2471 TypeKind = 0;
2472 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002473 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002474 } else if (T->isFloatingType()) {
2475 TypeKind = 1;
2476 TypeInfo = getContext().getTypeSize(T);
2477 }
2478
2479 // Format the type name as if for a diagnostic, including quotes and
2480 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002481 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002482 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2483 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002484 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002485 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002486
2487 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002488 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2489 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002490 };
2491 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2492
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002493 auto *GV = new llvm::GlobalVariable(
2494 CGM.getModule(), Descriptor->getType(),
2495 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002496 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002497 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002498
2499 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002500 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002501
Richard Smithe30752c2012-10-09 19:52:38 +00002502 return GV;
2503}
2504
2505llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2506 llvm::Type *TargetTy = IntPtrTy;
2507
Richard Smith48366f72013-03-22 00:47:07 +00002508 // Floating-point types which fit into intptr_t are bitcast to integers
2509 // and then passed directly (after zero-extension, if necessary).
2510 if (V->getType()->isFloatingPointTy()) {
2511 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2512 if (Bits <= TargetTy->getIntegerBitWidth())
2513 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2514 Bits));
2515 }
2516
Richard Smithe30752c2012-10-09 19:52:38 +00002517 // Integers which fit in intptr_t are zero-extended and passed directly.
2518 if (V->getType()->isIntegerTy() &&
2519 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2520 return Builder.CreateZExt(V, TargetTy);
2521
2522 // Pointers are passed directly, everything else is passed by address.
2523 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002524 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002525 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002526 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002527 }
2528 return Builder.CreatePtrToInt(V, TargetTy);
2529}
2530
2531/// \brief Emit a representation of a SourceLocation for passing to a handler
2532/// in a sanitizer runtime library. The format for this data is:
2533/// \code
2534/// struct SourceLocation {
2535/// const char *Filename;
2536/// int32_t Line, Column;
2537/// };
2538/// \endcode
2539/// For an invalid SourceLocation, the Filename pointer is null.
2540llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002541 llvm::Constant *Filename;
2542 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002543
Alexey Samsonov6c124142014-07-18 17:50:06 +00002544 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2545 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002546 StringRef FilenameString = PLoc.getFilename();
2547
2548 int PathComponentsToStrip =
2549 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2550 if (PathComponentsToStrip < 0) {
2551 assert(PathComponentsToStrip != INT_MIN);
2552 int PathComponentsToKeep = -PathComponentsToStrip;
2553 auto I = llvm::sys::path::rbegin(FilenameString);
2554 auto E = llvm::sys::path::rend(FilenameString);
2555 while (I != E && --PathComponentsToKeep)
2556 ++I;
2557
2558 FilenameString = FilenameString.substr(I - E);
2559 } else if (PathComponentsToStrip > 0) {
2560 auto I = llvm::sys::path::begin(FilenameString);
2561 auto E = llvm::sys::path::end(FilenameString);
2562 while (I != E && PathComponentsToStrip--)
2563 ++I;
2564
2565 if (I != E)
2566 FilenameString =
2567 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2568 else
2569 FilenameString = llvm::sys::path::filename(FilenameString);
2570 }
2571
2572 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002573 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2574 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2575 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002576 Line = PLoc.getLine();
2577 Column = PLoc.getColumn();
2578 } else {
2579 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2580 Line = Column = 0;
2581 }
2582
2583 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2584 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002585
2586 return llvm::ConstantStruct::getAnon(Data);
2587}
2588
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002589namespace {
2590/// \brief Specify under what conditions this check can be recovered
2591enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002592 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002593 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002594 /// Check supports recovering, runtime has both fatal (noreturn) and
2595 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002596 Recoverable,
2597 /// Runtime conditionally aborts, always need to support recovery.
2598 AlwaysRecoverable
2599};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002600}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002601
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002602static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2603 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002604 switch (Kind) {
2605 case SanitizerKind::Vptr:
2606 return CheckRecoverableKind::AlwaysRecoverable;
2607 case SanitizerKind::Return:
2608 case SanitizerKind::Unreachable:
2609 return CheckRecoverableKind::Unrecoverable;
2610 default:
2611 return CheckRecoverableKind::Recoverable;
2612 }
2613}
2614
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002615namespace {
2616struct SanitizerHandlerInfo {
2617 char const *const Name;
2618 unsigned Version;
2619};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002620}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002621
2622const SanitizerHandlerInfo SanitizerHandlers[] = {
2623#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2624 LIST_SANITIZER_CHECKS
2625#undef SANITIZER_CHECK
2626};
2627
Alexey Samsonov88459522015-01-12 22:39:12 +00002628static void emitCheckHandlerCall(CodeGenFunction &CGF,
2629 llvm::FunctionType *FnType,
2630 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002631 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002632 CheckRecoverableKind RecoverKind, bool IsFatal,
2633 llvm::BasicBlock *ContBB) {
2634 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2635 bool NeedsAbortSuffix =
2636 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002637 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2638 const StringRef CheckName = CheckInfo.Name;
2639 std::string FnName =
2640 ("__ubsan_handle_" + CheckName +
Vedant Kumar4881bdf2016-12-12 18:47:33 +00002641 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002642 (NeedsAbortSuffix ? "_abort" : ""))
2643 .str();
Alexey Samsonov88459522015-01-12 22:39:12 +00002644 bool MayReturn =
2645 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2646
2647 llvm::AttrBuilder B;
2648 if (!MayReturn) {
2649 B.addAttribute(llvm::Attribute::NoReturn)
2650 .addAttribute(llvm::Attribute::NoUnwind);
2651 }
2652 B.addAttribute(llvm::Attribute::UWTable);
2653
2654 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2655 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002656 llvm::AttributeList::get(CGF.getLLVMContext(),
2657 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002658 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002659 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2660 if (!MayReturn) {
2661 HandlerCall->setDoesNotReturn();
2662 CGF.Builder.CreateUnreachable();
2663 } else {
2664 CGF.Builder.CreateBr(ContBB);
2665 }
2666}
2667
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002668void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002669 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002670 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002671 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002672 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002673 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002674 assert(CheckHandler >= 0 &&
2675 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2676 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002677
2678 llvm::Value *FatalCond = nullptr;
2679 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002680 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002681 for (int i = 0, n = Checked.size(); i < n; ++i) {
2682 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002683 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002684 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002685 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2686 ? TrapCond
2687 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2688 ? RecoverableCond
2689 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002690 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2691 }
2692
Peter Collingbourne9881b782015-06-18 23:59:22 +00002693 if (TrapCond)
2694 EmitTrapCheck(TrapCond);
2695 if (!FatalCond && !RecoverableCond)
2696 return;
2697
Alexey Samsonov88459522015-01-12 22:39:12 +00002698 llvm::Value *JointCond;
2699 if (FatalCond && RecoverableCond)
2700 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2701 else
2702 JointCond = FatalCond ? FatalCond : RecoverableCond;
2703 assert(JointCond);
2704
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002705 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002706 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002707#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002708 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002709 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002710 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002711 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002712 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002713#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002714
Richard Smith4d1458e2012-09-08 02:08:36 +00002715 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002716 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2717 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002718 // Give hint that we very much don't expect to execute the handler
2719 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2720 llvm::MDBuilder MDHelper(getLLVMContext());
2721 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2722 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002723 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002724
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002725 // Handler functions take an i8* pointing to the (handler-specific) static
2726 // information block, followed by a sequence of intptr_t arguments
2727 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002728 SmallVector<llvm::Value *, 4> Args;
2729 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002730 Args.reserve(DynamicArgs.size() + 1);
2731 ArgTypes.reserve(DynamicArgs.size() + 1);
2732
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002733 // Emit handler arguments and create handler function type.
2734 if (!StaticArgs.empty()) {
2735 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2736 auto *InfoPtr =
2737 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2738 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002739 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002740 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2741 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2742 ArgTypes.push_back(Int8PtrTy);
2743 }
2744
Richard Smithe30752c2012-10-09 19:52:38 +00002745 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2746 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2747 ArgTypes.push_back(IntPtrTy);
2748 }
2749
2750 llvm::FunctionType *FnType =
2751 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002752
Alexey Samsonov88459522015-01-12 22:39:12 +00002753 if (!FatalCond || !RecoverableCond) {
2754 // Simple case: we need to generate a single handler call, either
2755 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002756 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002757 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002758 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002759 // Emit two handler calls: first one for set of unrecoverable checks,
2760 // another one for recoverable.
2761 llvm::BasicBlock *NonFatalHandlerBB =
2762 createBasicBlock("non_fatal." + CheckName);
2763 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2764 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2765 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002766 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002767 NonFatalHandlerBB);
2768 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002769 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002770 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002771 }
Richard Smithe30752c2012-10-09 19:52:38 +00002772
Richard Smith4d1458e2012-09-08 02:08:36 +00002773 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002774}
2775
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002776void CodeGenFunction::EmitCfiSlowPathCheck(
2777 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2778 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002779 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2780
2781 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2782 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2783
2784 llvm::MDBuilder MDHelper(getLLVMContext());
2785 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2786 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2787
2788 EmitBlock(CheckBB);
2789
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002790 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2791
2792 llvm::CallInst *CheckCall;
2793 if (WithDiag) {
2794 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2795 auto *InfoPtr =
2796 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2797 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002798 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002799 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2800
2801 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2802 "__cfi_slowpath_diag",
2803 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2804 false));
2805 CheckCall = Builder.CreateCall(
2806 SlowPathDiagFn,
2807 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2808 } else {
2809 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2810 "__cfi_slowpath",
2811 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2812 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2813 }
2814
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002815 CheckCall->setDoesNotThrow();
2816
2817 EmitBlock(Cont);
2818}
2819
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00002820// Emit a stub for __cfi_check function so that the linker knows about this
2821// symbol in LTO mode.
2822void CodeGenFunction::EmitCfiCheckStub() {
2823 llvm::Module *M = &CGM.getModule();
2824 auto &Ctx = M->getContext();
2825 llvm::Function *F = llvm::Function::Create(
2826 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2827 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2828 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2829 // FIXME: consider emitting an intrinsic call like
2830 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2831 // which can be lowered in CrossDSOCFI pass to the actual contents of
2832 // __cfi_check. This would allow inlining of __cfi_check calls.
2833 llvm::CallInst::Create(
2834 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2835 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2836}
2837
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002838// This function is basically a switch over the CFI failure kind, which is
2839// extracted from CFICheckFailData (1st function argument). Each case is either
2840// llvm.trap or a call to one of the two runtime handlers, based on
2841// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2842// failure kind) traps, but this should really never happen. CFICheckFailData
2843// can be nullptr if the calling module has -fsanitize-trap behavior for this
2844// check kind; in this case __cfi_check_fail traps as well.
2845void CodeGenFunction::EmitCfiCheckFail() {
2846 SanitizerScope SanScope(this);
2847 FunctionArgList Args;
2848 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2849 getContext().VoidPtrTy);
2850 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2851 getContext().VoidPtrTy);
2852 Args.push_back(&ArgData);
2853 Args.push_back(&ArgAddr);
2854
John McCallc56a8b32016-03-11 04:30:31 +00002855 const CGFunctionInfo &FI =
2856 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002857
2858 llvm::Function *F = llvm::Function::Create(
2859 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2860 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2861 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2862
2863 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2864 SourceLocation());
2865
2866 llvm::Value *Data =
2867 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2868 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2869 llvm::Value *Addr =
2870 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2871 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2872
2873 // Data == nullptr means the calling module has trap behaviour for this check.
2874 llvm::Value *DataIsNotNullPtr =
2875 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2876 EmitTrapCheck(DataIsNotNullPtr);
2877
2878 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002879 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002880 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002881 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002882
2883 llvm::Value *V = Builder.CreateConstGEP2_32(
2884 CfiCheckFailDataTy,
2885 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2886 0);
2887 Address CheckKindAddr(V, getIntAlign());
2888 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2889
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002890 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2891 CGM.getLLVMContext(),
2892 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2893 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002894 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002895 {Addr, AllVtables}),
2896 IntPtrTy);
2897
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002898 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002899 {CFITCK_VCall, SanitizerKind::CFIVCall},
2900 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2901 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2902 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2903 {CFITCK_ICall, SanitizerKind::CFIICall}};
2904
2905 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2906 for (auto CheckKindMaskPair : CheckKinds) {
2907 int Kind = CheckKindMaskPair.first;
2908 SanitizerMask Mask = CheckKindMaskPair.second;
2909 llvm::Value *Cond =
2910 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002911 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002912 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002913 {Data, Addr, ValidVtable});
2914 else
2915 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002916 }
2917
2918 FinishFunction();
2919 // The only reference to this function will be created during LTO link.
2920 // Make sure it survives until then.
2921 CGM.addUsedGlobal(F);
2922}
2923
Chad Rosierae229d52013-01-29 23:31:22 +00002924void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002925 llvm::BasicBlock *Cont = createBasicBlock("cont");
2926
2927 // If we're optimizing, collapse all calls to trap down to just one per
2928 // function to save on code size.
2929 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2930 TrapBB = createBasicBlock("trap");
2931 Builder.CreateCondBr(Checked, Cont, TrapBB);
2932 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002933 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002934 TrapCall->setDoesNotReturn();
2935 TrapCall->setDoesNotThrow();
2936 Builder.CreateUnreachable();
2937 } else {
2938 Builder.CreateCondBr(Checked, Cont, TrapBB);
2939 }
2940
2941 EmitBlock(Cont);
2942}
2943
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002944llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002945 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002946
Amaury Sechet21f51b32016-09-09 04:42:49 +00002947 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2948 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2949 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00002950 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00002951 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002952
2953 return TrapCall;
2954}
2955
John McCall7f416cc2015-09-08 08:05:57 +00002956Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002957 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002958 assert(E->getType()->isArrayType() &&
2959 "Array to pointer decay must have array source type!");
2960
2961 // Expressions of array type can't be bitfields or vector elements.
2962 LValue LV = EmitLValue(E);
2963 Address Addr = LV.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002964 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00002965
2966 // If the array type was an incomplete type, we need to make sure
2967 // the decay ends up being the right type.
2968 llvm::Type *NewTy = ConvertType(E->getType());
2969 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2970
2971 // Note that VLA pointers are always decayed, so we don't need to do
2972 // anything here.
2973 if (!E->getType()->isVariableArrayType()) {
2974 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2975 "Expected pointer to array");
2976 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2977 }
2978
2979 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2980 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2981}
2982
Chris Lattner6c5abe82010-06-26 23:03:20 +00002983/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2984/// array to pointer, return the array subexpression.
2985static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2986 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002987 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002988 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002989 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002990
Chris Lattner6c5abe82010-06-26 23:03:20 +00002991 // If this is a decay from variable width array, bail out.
2992 const Expr *SubExpr = CE->getSubExpr();
2993 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002994 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002995
Chris Lattner6c5abe82010-06-26 23:03:20 +00002996 return SubExpr;
2997}
2998
John McCall7f416cc2015-09-08 08:05:57 +00002999static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3000 llvm::Value *ptr,
3001 ArrayRef<llvm::Value*> indices,
3002 bool inbounds,
3003 const llvm::Twine &name = "arrayidx") {
3004 if (inbounds) {
3005 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
3006 } else {
3007 return CGF.Builder.CreateGEP(ptr, indices, name);
3008 }
3009}
3010
3011static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3012 llvm::Value *idx,
3013 CharUnits eltSize) {
3014 // If we have a constant index, we can use the exact offset of the
3015 // element we're accessing.
3016 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3017 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3018 return arrayAlign.alignmentAtOffset(offset);
3019
3020 // Otherwise, use the worst-case alignment for any element.
3021 } else {
3022 return arrayAlign.alignmentOfArrayElement(eltSize);
3023 }
3024}
3025
3026static QualType getFixedSizeElementType(const ASTContext &ctx,
3027 const VariableArrayType *vla) {
3028 QualType eltType;
3029 do {
3030 eltType = vla->getElementType();
3031 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3032 return eltType;
3033}
3034
3035static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3036 ArrayRef<llvm::Value*> indices,
3037 QualType eltType, bool inbounds,
3038 const llvm::Twine &name = "arrayidx") {
3039 // All the indices except that last must be zero.
3040#ifndef NDEBUG
3041 for (auto idx : indices.drop_back())
3042 assert(isa<llvm::ConstantInt>(idx) &&
3043 cast<llvm::ConstantInt>(idx)->isZero());
3044#endif
3045
3046 // Determine the element size of the statically-sized base. This is
3047 // the thing that the indices are expressed in terms of.
3048 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3049 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3050 }
3051
3052 // We can use that to compute the best alignment of the element.
3053 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3054 CharUnits eltAlign =
3055 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3056
3057 llvm::Value *eltPtr =
3058 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
3059 return Address(eltPtr, eltAlign);
3060}
3061
Richard Smith539e4a72013-02-23 02:53:19 +00003062LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3063 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003064 // The index must always be an integer, which is not an aggregate. Emit it
3065 // in lexical order (this complexity is, sadly, required by C++17).
3066 llvm::Value *IdxPre =
3067 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Richard Smith40885712016-09-27 00:53:24 +00003068 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003069 auto *Idx = IdxPre;
3070 if (E->getLHS() != E->getIdx()) {
3071 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3072 Idx = EmitScalarExpr(E->getIdx());
3073 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003074
Richard Smith9e67b992016-09-26 23:49:47 +00003075 QualType IdxTy = E->getIdx()->getType();
3076 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3077
3078 if (SanOpts.has(SanitizerKind::ArrayBounds))
3079 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3080
3081 // Extend or truncate the index type to 32 or 64-bits.
3082 if (Promote && Idx->getType() != IntPtrTy)
3083 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3084
3085 return Idx;
3086 };
3087 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003088
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003089 // If the base is a vector type, then we are forming a vector element lvalue
3090 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003091 if (E->getBase()->getType()->isVectorType() &&
3092 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003093 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003094 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003095 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003096 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00003097 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00003098 E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003099 LHS.getBaseInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003100 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003101
John McCall7f416cc2015-09-08 08:05:57 +00003102 // All the other cases basically behave like simple offsetting.
3103
John McCall7f416cc2015-09-08 08:05:57 +00003104 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003105 if (isa<ExtVectorElementExpr>(E->getBase())) {
3106 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003107 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003108 Address Addr = EmitExtVectorElementLValue(LV);
3109
3110 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3111 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003112 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003113 }
John McCall7f416cc2015-09-08 08:05:57 +00003114
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003115 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003116 Address Addr = Address::invalid();
3117 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003118 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003119 // The base must be a pointer, which is not an aggregate. Emit
3120 // it. It needs to be emitted first in case it's what captures
3121 // the VLA bounds.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003122 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003123 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003124
John McCall23c29fe2011-06-24 21:55:10 +00003125 // The element count here is the total number of non-VLA elements.
3126 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003127
John McCall77527a82011-06-25 01:32:37 +00003128 // Effectively, the multiply by the VLA size is part of the GEP.
3129 // GEP indexes are signed, and scaling an index isn't permitted to
3130 // signed-overflow, so we use the same semantics for our explicit
3131 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003132 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003133 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003134 } else {
3135 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003136 }
John McCall7f416cc2015-09-08 08:05:57 +00003137
3138 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3139 !getLangOpts().isSignedOverflowDefined());
3140
Chris Lattner6c5abe82010-06-26 23:03:20 +00003141 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3142 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003143
John McCall7f416cc2015-09-08 08:05:57 +00003144 // Emit the base pointer.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003145 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003146 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3147
3148 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3149 llvm::Value *InterfaceSizeVal =
3150 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3151
3152 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003153
3154 // We don't necessarily build correct LLVM struct types for ObjC
3155 // interfaces, so we can't rely on GEP to do this scaling
3156 // correctly, so we need to cast to i8*. FIXME: is this actually
3157 // true? A lot of other things in the fragile ABI would break...
3158 llvm::Type *OrigBaseTy = Addr.getType();
3159 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3160
3161 // Do the GEP.
3162 CharUnits EltAlign =
3163 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3164 llvm::Value *EltPtr =
3165 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3166 Addr = Address(EltPtr, EltAlign);
3167
3168 // Cast back.
3169 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003170 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3171 // If this is A[i] where A is an array, the frontend will have decayed the
3172 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3173 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3174 // "gep x, i" here. Emit one "gep A, 0, i".
3175 assert(Array->getType()->isArrayType() &&
3176 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003177 LValue ArrayLV;
3178 // For simple multidimensional array indexing, set the 'accessed' flag for
3179 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003180 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003181 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3182 else
3183 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003184 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003185
Daniel Dunbar82634272011-04-01 00:49:43 +00003186 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00003187 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3188 {CGM.getSize(CharUnits::Zero()), Idx},
3189 E->getType(),
3190 !getLangOpts().isSignedOverflowDefined());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003191 BaseInfo = ArrayLV.getBaseInfo();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003192 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003193 // The base must be a pointer; emit it with an estimate of its alignment.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003194 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003195 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003196 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3197 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003198 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003199
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003200 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo);
Mike Stump4a3999f2009-09-09 13:00:44 +00003201
John McCall7f416cc2015-09-08 08:05:57 +00003202 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003203
Richard Smith9c6890a2012-11-01 22:30:59 +00003204 if (getLangOpts().ObjC1 &&
3205 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003206 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003207 setObjCGCLValueClass(getContext(), E, LV);
3208 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003209 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003210}
3211
Alexey Bataev31300ed2016-02-04 11:27:03 +00003212static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003213 LValueBaseInfo &BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003214 QualType BaseTy, QualType ElTy,
3215 bool IsLowerBound) {
3216 LValue BaseLVal;
3217 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3218 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3219 if (BaseTy->isArrayType()) {
3220 Address Addr = BaseLVal.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003221 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003222
3223 // If the array type was an incomplete type, we need to make sure
3224 // the decay ends up being the right type.
3225 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3226 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3227
3228 // Note that VLA pointers are always decayed, so we don't need to do
3229 // anything here.
3230 if (!BaseTy->isVariableArrayType()) {
3231 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3232 "Expected pointer to array");
3233 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3234 "arraydecay");
3235 }
3236
3237 return CGF.Builder.CreateElementBitCast(Addr,
3238 CGF.ConvertTypeForMem(ElTy));
3239 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003240 LValueBaseInfo TypeInfo;
3241 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3242 BaseInfo.mergeForCast(TypeInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003243 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3244 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003245 return CGF.EmitPointerWithAlignment(Base, &BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003246}
3247
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003248LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3249 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003250 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003251 if (auto *ASE =
3252 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003253 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003254 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003255 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003256 QualType ResultExprTy;
3257 if (auto *AT = getContext().getAsArrayType(BaseTy))
3258 ResultExprTy = AT->getElementType();
3259 else
3260 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003261 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003262 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003263 // Requesting lower bound or upper bound, but without provided length and
3264 // without ':' symbol for the default length -> length = 1.
3265 // Idx = LowerBound ?: 0;
3266 if (auto *LowerBound = E->getLowerBound()) {
3267 Idx = Builder.CreateIntCast(
3268 EmitScalarExpr(LowerBound), IntPtrTy,
3269 LowerBound->getType()->hasSignedIntegerRepresentation());
3270 } else
3271 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3272 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003273 // Try to emit length or lower bound as constant. If this is possible, 1
3274 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3275 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003276 auto &C = CGM.getContext();
3277 auto *Length = E->getLength();
3278 llvm::APSInt ConstLength;
3279 if (Length) {
3280 // Idx = LowerBound + Length - 1;
3281 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3282 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3283 Length = nullptr;
3284 }
3285 auto *LowerBound = E->getLowerBound();
3286 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3287 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3288 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3289 LowerBound = nullptr;
3290 }
3291 if (!Length)
3292 --ConstLength;
3293 else if (!LowerBound)
3294 --ConstLowerBound;
3295
3296 if (Length || LowerBound) {
3297 auto *LowerBoundVal =
3298 LowerBound
3299 ? Builder.CreateIntCast(
3300 EmitScalarExpr(LowerBound), IntPtrTy,
3301 LowerBound->getType()->hasSignedIntegerRepresentation())
3302 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3303 auto *LengthVal =
3304 Length
3305 ? Builder.CreateIntCast(
3306 EmitScalarExpr(Length), IntPtrTy,
3307 Length->getType()->hasSignedIntegerRepresentation())
3308 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3309 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3310 /*HasNUW=*/false,
3311 !getLangOpts().isSignedOverflowDefined());
3312 if (Length && LowerBound) {
3313 Idx = Builder.CreateSub(
3314 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3315 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3316 }
3317 } else
3318 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3319 } else {
3320 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003321 QualType ArrayTy = BaseTy->isPointerType()
3322 ? E->getBase()->IgnoreParenImpCasts()->getType()
3323 : BaseTy;
3324 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003325 Length = VAT->getSizeExpr();
3326 if (Length->isIntegerConstantExpr(ConstLength, C))
3327 Length = nullptr;
3328 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003329 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003330 ConstLength = CAT->getSize();
3331 }
3332 if (Length) {
3333 auto *LengthVal = Builder.CreateIntCast(
3334 EmitScalarExpr(Length), IntPtrTy,
3335 Length->getType()->hasSignedIntegerRepresentation());
3336 Idx = Builder.CreateSub(
3337 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3338 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3339 } else {
3340 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3341 --ConstLength;
3342 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3343 }
3344 }
3345 }
3346 assert(Idx);
3347
Alexey Bataev31300ed2016-02-04 11:27:03 +00003348 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003349 LValueBaseInfo BaseInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003350 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003351 // The base must be a pointer, which is not an aggregate. Emit
3352 // it. It needs to be emitted first in case it's what captures
3353 // the VLA bounds.
3354 Address Base =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003355 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003356 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003357 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003358 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003359
3360 // Effectively, the multiply by the VLA size is part of the GEP.
3361 // GEP indexes are signed, and scaling an index isn't permitted to
3362 // signed-overflow, so we use the same semantics for our explicit
3363 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003364 if (getLangOpts().isSignedOverflowDefined())
3365 Idx = Builder.CreateMul(Idx, NumElements);
3366 else
3367 Idx = Builder.CreateNSWMul(Idx, NumElements);
3368 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3369 !getLangOpts().isSignedOverflowDefined());
3370 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3371 // If this is A[i] where A is an array, the frontend will have decayed the
3372 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3373 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3374 // "gep x, i" here. Emit one "gep A, 0, i".
3375 assert(Array->getType()->isArrayType() &&
3376 "Array to pointer decay must have array source type!");
3377 LValue ArrayLV;
3378 // For simple multidimensional array indexing, set the 'accessed' flag for
3379 // better bounds-checking of the base expression.
3380 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3381 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3382 else
3383 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003384
Alexey Bataev31300ed2016-02-04 11:27:03 +00003385 // Propagate the alignment from the array itself to the result.
3386 EltPtr = emitArraySubscriptGEP(
3387 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3388 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003389 BaseInfo = ArrayLV.getBaseInfo();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003390 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003391 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003392 BaseTy, ResultExprTy, IsLowerBound);
3393 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3394 !getLangOpts().isSignedOverflowDefined());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003395 }
3396
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003397 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003398}
3399
Chris Lattner9e751ca2007-08-02 23:37:31 +00003400LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003401EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003402 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003403 LValue Base;
3404
3405 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003406 if (E->isArrow()) {
3407 // If it is a pointer to a vector, emit the address and form an lvalue with
3408 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003409 LValueBaseInfo BaseInfo;
3410 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003411 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003412 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003413 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003414 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003415 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3416 // emit the base as an lvalue.
3417 assert(E->getBase()->getType()->isVectorType());
3418 Base = EmitLValue(E->getBase());
3419 } else {
3420 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003421 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003422 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003423 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003424
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003425 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003426 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003427 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003428 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003429 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4e1a3232009-12-23 21:31:11 +00003430 }
John McCall1553b192011-06-16 04:16:24 +00003431
3432 QualType type =
3433 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003434
Nate Begemand3862152008-05-13 21:03:02 +00003435 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003436 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003437 E->getEncodedElementAccess(Indices);
3438
3439 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003440 llvm::Constant *CV =
3441 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003442 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003443 Base.getBaseInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003444 }
3445 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3446
3447 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003448 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003449
Chris Lattner595ba3a2012-01-30 06:20:36 +00003450 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3451 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003452 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003453 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003454 Base.getBaseInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003455}
3456
Devang Patel30efa2e2007-10-23 20:28:39 +00003457LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003458 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003459 // 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 +00003460 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003461 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003462 LValueBaseInfo BaseInfo;
3463 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003464 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003465 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003466 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3467 if (IsBaseCXXThis)
3468 SkippedChecks.set(SanitizerKind::Alignment, true);
3469 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003470 SkippedChecks.set(SanitizerKind::Null, true);
3471 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3472 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003473 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003474 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003475 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003476
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003477 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003478 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003479 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003480 setObjCGCLValueClass(getContext(), E, LV);
3481 return LV;
3482 }
Craig Topper99e79272013-07-26 05:59:26 +00003483
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003484 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003485 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003486
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003487 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003488 return EmitFunctionDeclLValue(*this, E, FD);
3489
David Blaikie83d382b2011-09-23 05:06:16 +00003490 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003491}
Devang Patel30efa2e2007-10-23 20:28:39 +00003492
John McCalldec348f72013-05-03 07:33:41 +00003493/// Given that we are currently emitting a lambda, emit an l-value for
3494/// one of its members.
3495LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3496 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3497 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3498 QualType LambdaTagType =
3499 getContext().getTagDeclType(Field->getParent());
3500 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3501 return EmitLValueForField(LambdaLV, Field);
3502}
3503
John McCall7f416cc2015-09-08 08:05:57 +00003504/// Drill down to the storage of a field without walking into
3505/// reference types.
3506///
3507/// The resulting address doesn't necessarily have the right type.
3508static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3509 const FieldDecl *field) {
3510 const RecordDecl *rec = field->getParent();
3511
3512 unsigned idx =
3513 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3514
3515 CharUnits offset;
3516 // Adjust the alignment down to the given offset.
3517 // As a special case, if the LLVM field index is 0, we know that this
3518 // is zero.
3519 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3520 .getFieldOffset(field->getFieldIndex()) == 0) &&
3521 "LLVM field at index zero had non-zero offset?");
3522 if (idx != 0) {
3523 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3524 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3525 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3526 }
3527
3528 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3529}
3530
Eli Friedman7f1ff602012-04-16 03:54:45 +00003531LValue CodeGenFunction::EmitLValueForField(LValue base,
3532 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003533 LValueBaseInfo BaseInfo = base.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003534 AlignmentSource fieldAlignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003535 getFieldAlignmentSource(BaseInfo.getAlignmentSource());
3536 LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias());
John McCall7f416cc2015-09-08 08:05:57 +00003537
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003538 if (field->isBitField()) {
3539 const CGRecordLayout &RL =
3540 CGM.getTypes().getCGRecordLayout(field->getParent());
3541 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003542 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003543 unsigned Idx = RL.getLLVMFieldNo(field);
3544 if (Idx != 0)
3545 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003546 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3547 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003548 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003549 llvm::Type *FieldIntTy =
3550 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3551 if (Addr.getElementType() != FieldIntTy)
3552 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003553
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003554 QualType fieldType =
3555 field->getType().withCVRQualifiers(base.getVRQualifiers());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003556 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003557 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003558
John McCall53fcbd22011-02-26 08:07:02 +00003559 const RecordDecl *rec = field->getParent();
3560 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003561
John McCall53fcbd22011-02-26 08:07:02 +00003562 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3563
John McCall7f416cc2015-09-08 08:05:57 +00003564 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003565 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003566 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003567 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003568 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003569 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003570 // TODO: handle path-aware TBAA for union.
3571 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003572 } else {
3573 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003574 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003575
3576 // If this is a reference field, load the reference right now.
3577 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3578 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3579 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3580
Manman Renc451e572013-04-04 21:53:22 +00003581 // Loading the reference will disable path-aware TBAA.
3582 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003583 if (CGM.shouldUseTBAA()) {
3584 llvm::MDNode *tbaa;
3585 if (mayAlias)
3586 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3587 else
3588 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003589 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003590 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003591 }
3592
John McCall53fcbd22011-02-26 08:07:02 +00003593 mayAlias = false;
3594 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003595
3596 CharUnits alignment =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003597 getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true);
3598 FieldBaseInfo.setMayAlias(false);
John McCall7f416cc2015-09-08 08:05:57 +00003599 addr = Address(load, alignment);
3600
3601 // Qualifiers on the struct don't apply to the referencee, and
3602 // we'll pick up CVR from the actual type later, so reset these
3603 // additional qualifiers now.
3604 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003605 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003606 }
Craig Topper99e79272013-07-26 05:59:26 +00003607
Chris Lattner13ee4f42011-07-10 05:34:54 +00003608 // Make sure that the address is pointing to the right type. This is critical
3609 // for both unions and structs. A union needs a bitcast, a struct element
3610 // will need a bitcast if the LLVM type laid out doesn't match the desired
3611 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003612 addr = Builder.CreateElementBitCast(addr,
3613 CGM.getTypes().ConvertTypeForMem(type),
3614 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003615
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003616 if (field->hasAttr<AnnotateAttr>())
3617 addr = EmitFieldAnnotations(field, addr);
3618
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003619 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003620 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003621 if (TBAAPath) {
3622 const ASTRecordLayout &Layout =
3623 getContext().getASTRecordLayout(field->getParent());
3624 // Set the base type to be the base type of the base LValue and
3625 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003626 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3627 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003628 Layout.getFieldOffset(field->getFieldIndex()) /
3629 getContext().getCharWidth());
3630 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003631
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003632 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003633 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3634 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003635
3636 // Fields of may_alias structs act like 'char' for TBAA purposes.
3637 // FIXME: this should get propagated down through anonymous structs
3638 // and unions.
3639 if (mayAlias && LV.getTBAAInfo())
3640 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3641
Daniel Dunbarf166a522010-08-21 03:44:13 +00003642 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003643}
3644
Craig Topper99e79272013-07-26 05:59:26 +00003645LValue
3646CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003647 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003648 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003649
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003650 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003651 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003652
John McCall7f416cc2015-09-08 08:05:57 +00003653 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003654
John McCall7f416cc2015-09-08 08:05:57 +00003655 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003656 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003657 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003658
John McCall7f416cc2015-09-08 08:05:57 +00003659 // TODO: access-path TBAA?
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003660 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3661 LValueBaseInfo FieldBaseInfo(
3662 getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3663 BaseInfo.getMayAlias());
3664 return MakeAddrLValue(V, FieldType, FieldBaseInfo);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003665}
3666
Chris Lattnerf53c0962010-09-06 00:11:41 +00003667LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003668 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Richard Smith2d988f02011-11-22 22:48:32 +00003669 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003670 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003671 return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo);
Richard Smith2d988f02011-11-22 22:48:32 +00003672 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003673 if (E->getType()->isVariablyModifiedType())
3674 // make sure to emit the VLA size.
3675 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003676
John McCall7f416cc2015-09-08 08:05:57 +00003677 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003678 const Expr *InitExpr = E->getInitializer();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003679 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003680
Chad Rosier615ed1a2012-03-29 17:37:10 +00003681 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3682 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003683
3684 return Result;
3685}
3686
Richard Smithbb653bd2012-05-14 21:57:21 +00003687LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3688 if (!E->isGLValue())
3689 // Initializing an aggregate temporary in C++11: T{...}.
3690 return EmitAggExprToLValue(E);
3691
3692 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003693 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003694 return EmitLValue(E->getInit(0));
3695}
3696
Richard Smithf3076ff2014-06-20 18:43:47 +00003697/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3698/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3699/// LValue is returned and the current block has been terminated.
3700static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3701 const Expr *Operand) {
3702 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3703 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3704 return None;
3705 }
3706
3707 return CGF.EmitLValue(Operand);
3708}
3709
John McCallc07a0c72011-02-17 10:25:35 +00003710LValue CodeGenFunction::
3711EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3712 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003713 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003714 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003715 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003716 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003717 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003718
Eli Friedman59954892012-01-25 05:04:17 +00003719 OpaqueValueMapping binding(*this, expr);
3720
John McCallc07a0c72011-02-17 10:25:35 +00003721 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003722 bool CondExprBool;
3723 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003724 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003725 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003726
Justin Bogneref512b92014-01-06 22:27:43 +00003727 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003728 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003729 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003730 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003731 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003732 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003733 }
3734
John McCallc07a0c72011-02-17 10:25:35 +00003735 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3736 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3737 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003738
3739 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003740 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003741
John McCall0a6bf2e2011-01-26 19:21:13 +00003742 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003743 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003744 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003745 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003746 Optional<LValue> lhs =
3747 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003748 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003749
Richard Smithf3076ff2014-06-20 18:43:47 +00003750 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003751 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003752
John McCallc07a0c72011-02-17 10:25:35 +00003753 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003754 if (lhs)
3755 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003756
John McCall0a6bf2e2011-01-26 19:21:13 +00003757 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003758 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003759 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003760 Optional<LValue> rhs =
3761 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003762 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003763 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003764 return EmitUnsupportedLValue(expr, "conditional operator");
3765 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003766
John McCallc07a0c72011-02-17 10:25:35 +00003767 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003768
Richard Smithf3076ff2014-06-20 18:43:47 +00003769 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003770 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003771 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003772 phi->addIncoming(lhs->getPointer(), lhsBlock);
3773 phi->addIncoming(rhs->getPointer(), rhsBlock);
3774 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3775 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003776 std::max(lhs->getBaseInfo().getAlignmentSource(),
3777 rhs->getBaseInfo().getAlignmentSource());
3778 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3779 rhs->getBaseInfo().getMayAlias();
3780 return MakeAddrLValue(result, expr->getType(),
3781 LValueBaseInfo(alignSource, MayAlias));
Richard Smithf3076ff2014-06-20 18:43:47 +00003782 } else {
3783 assert((lhs || rhs) &&
3784 "both operands of glvalue conditional are throw-expressions?");
3785 return lhs ? *lhs : *rhs;
3786 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003787}
3788
Richard Smithbb653bd2012-05-14 21:57:21 +00003789/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3790/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003791/// otherwise if a cast is needed by the code generator in an lvalue context,
3792/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003793/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003794/// are permitted with aggregate result, including noop aggregate casts, and
3795/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003796LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003797 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003798 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003799 case CK_BitCast:
3800 case CK_ArrayToPointerDecay:
3801 case CK_FunctionToPointerDecay:
3802 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003803 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003804 case CK_IntegralToPointer:
3805 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003806 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003807 case CK_VectorSplat:
3808 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003809 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003810 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003811 case CK_IntegralToFloating:
3812 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003813 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003814 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003815 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003816 case CK_FloatingComplexToReal:
3817 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003818 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003819 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003820 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003821 case CK_IntegralComplexToReal:
3822 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003823 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003824 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003825 case CK_DerivedToBaseMemberPointer:
3826 case CK_BaseToDerivedMemberPointer:
3827 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003828 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003829 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003830 case CK_ARCProduceObject:
3831 case CK_ARCConsumeObject:
3832 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003833 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003834 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003835 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003836 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003837 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3838
3839 case CK_Dependent:
3840 llvm_unreachable("dependent cast kind in IR gen!");
3841
3842 case CK_BuiltinFnToFnPtr:
3843 llvm_unreachable("builtin functions are handled elsewhere");
3844
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003845 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003846 case CK_NonAtomicToAtomic:
3847 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003848 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003849
Anders Carlsson8a01a752011-04-11 02:03:26 +00003850 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003851 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003852 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003853 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003854 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003855 }
3856
John McCalle3027922010-08-25 11:45:40 +00003857 case CK_ConstructorConversion:
3858 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003859 case CK_CPointerToObjCPointerCast:
3860 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003861 case CK_NoOp:
3862 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003863 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003864
John McCalle3027922010-08-25 11:45:40 +00003865 case CK_UncheckedDerivedToBase:
3866 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003867 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003868 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003869 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003870
Anders Carlssond95f9602009-09-12 16:16:49 +00003871 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003872 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003873
Anders Carlssond95f9602009-09-12 16:16:49 +00003874 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003875 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003876 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3877 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003878
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003879 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo());
Anders Carlssond95f9602009-09-12 16:16:49 +00003880 }
John McCalle3027922010-08-25 11:45:40 +00003881 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003882 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003883 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003884 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003885 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003886
Anders Carlsson8c793172009-11-23 17:57:54 +00003887 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003888
Anders Carlsson8c793172009-11-23 17:57:54 +00003889 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003890 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003891 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003892 E->path_begin(), E->path_end(),
3893 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003894
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003895 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3896 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003897 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003898 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003899 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003900
Peter Collingbourned2926c92015-03-14 02:42:25 +00003901 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003902 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3903 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003904 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003905
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003906 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003907 }
John McCalle3027922010-08-25 11:45:40 +00003908 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003909 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003910 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003911
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003912 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003913 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003914 Address V = Builder.CreateBitCast(LV.getAddress(),
3915 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003916
3917 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003918 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3919 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003920 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003921
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003922 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003923 }
John McCalle3027922010-08-25 11:45:40 +00003924 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003925 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003926 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3927 ConvertType(E->getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003928 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003929 }
Egor Churaev89831422016-12-23 14:55:49 +00003930 case CK_ZeroToOCLQueue:
3931 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003932 case CK_ZeroToOCLEvent:
3933 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003934 }
Craig Topper99e79272013-07-26 05:59:26 +00003935
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003936 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003937}
3938
John McCall1bf58462011-02-16 08:02:54 +00003939LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003940 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003941 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003942}
3943
Eli Friedman7f1ff602012-04-16 03:54:45 +00003944RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003945 const FieldDecl *FD,
3946 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003947 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003948 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003949 switch (getEvaluationKind(FT)) {
3950 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003951 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003952 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003953 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003954 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00003955 // This routine is used to load fields one-by-one to perform a copy, so
3956 // don't load reference fields.
3957 if (FD->getType()->isReferenceType())
3958 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00003959 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003960 }
3961 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003962}
Douglas Gregorfe314812011-06-21 17:03:29 +00003963
Chris Lattnere47e4402007-06-01 18:02:12 +00003964//===--------------------------------------------------------------------===//
3965// Expression Emission
3966//===--------------------------------------------------------------------===//
3967
Craig Topper99e79272013-07-26 05:59:26 +00003968RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003969 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003970 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003971 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003972 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003973
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003974 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003975 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003976
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003977 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003978 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3979
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003980 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00003981 if (const CXXMethodDecl *MD =
3982 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003983 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003984
John McCallb92ab1a2016-10-26 23:46:34 +00003985 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00003986
John McCallb92ab1a2016-10-26 23:46:34 +00003987 if (callee.isBuiltin()) {
3988 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3989 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003990 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003991
John McCallb92ab1a2016-10-26 23:46:34 +00003992 if (callee.isPseudoDestructor()) {
3993 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3994 }
3995
3996 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3997}
3998
3999/// Emit a CallExpr without considering whether it might be a subclass.
4000RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4001 ReturnValueSlot ReturnValue) {
4002 CGCallee Callee = EmitCallee(E->getCallee());
4003 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4004}
4005
4006static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4007 if (auto builtinID = FD->getBuiltinID()) {
4008 return CGCallee::forBuiltin(builtinID, FD);
4009 }
4010
4011 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4012 return CGCallee::forDirect(calleePtr, FD);
4013}
4014
4015CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4016 E = E->IgnoreParens();
4017
4018 // Look through function-to-pointer decay.
4019 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4020 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4021 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4022 return EmitCallee(ICE->getSubExpr());
4023 }
4024
4025 // Resolve direct calls.
4026 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4027 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4028 return EmitDirectCallee(*this, FD);
4029 }
4030 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4031 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4032 EmitIgnoredExpr(ME->getBase());
4033 return EmitDirectCallee(*this, FD);
4034 }
4035
4036 // Look through template substitutions.
4037 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4038 return EmitCallee(NTTP->getReplacement());
4039
4040 // Treat pseudo-destructor calls differently.
4041 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4042 return CGCallee::forPseudoDestructor(PDE);
4043 }
4044
4045 // Otherwise, we have an indirect reference.
4046 llvm::Value *calleePtr;
4047 QualType functionType;
4048 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4049 calleePtr = EmitScalarExpr(E);
4050 functionType = ptrType->getPointeeType();
4051 } else {
4052 functionType = E->getType();
4053 calleePtr = EmitLValue(E).getPointer();
4054 }
4055 assert(functionType->isFunctionType());
4056 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4057 E->getReferencedDeclOfCallee());
4058 CGCallee callee(calleeInfo, calleePtr);
4059 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004060}
4061
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004062LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004063 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004064 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004065 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004066 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004067 return EmitLValue(E->getRHS());
4068 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004069
John McCalle3027922010-08-25 11:45:40 +00004070 if (E->getOpcode() == BO_PtrMemD ||
4071 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004072 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004073
John McCalla2342eb2010-12-05 02:00:02 +00004074 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004075
4076 // Note that in all of these cases, __block variables need the RHS
4077 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004078
4079 switch (getEvaluationKind(E->getType())) {
4080 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004081 switch (E->getLHS()->getType().getObjCLifetime()) {
4082 case Qualifiers::OCL_Strong:
4083 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4084
4085 case Qualifiers::OCL_Autoreleasing:
4086 return EmitARCStoreAutoreleasing(E).first;
4087
4088 // No reason to do any of these differently.
4089 case Qualifiers::OCL_None:
4090 case Qualifiers::OCL_ExplicitNone:
4091 case Qualifiers::OCL_Weak:
4092 break;
4093 }
4094
John McCalld0a30012010-12-06 06:10:02 +00004095 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004096 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004097 if (RV.isScalar())
4098 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004099 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004100 return LV;
4101 }
John McCall4f29b492010-11-16 23:07:28 +00004102
John McCall47fb9502013-03-07 21:37:08 +00004103 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004104 return EmitComplexAssignmentLValue(E);
4105
John McCall47fb9502013-03-07 21:37:08 +00004106 case TEK_Aggregate:
4107 return EmitAggExprToLValue(E);
4108 }
4109 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004110}
4111
Christopher Lambd91c3d42007-12-29 05:02:41 +00004112LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004113 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004114
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004115 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004116 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004117 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004118
David Majnemerced8bdf2015-02-25 17:36:15 +00004119 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004120 "Can't have a scalar return unless the return type is a "
4121 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004122
John McCall7f416cc2015-09-08 08:05:57 +00004123 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004124}
4125
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004126LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4127 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004128 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004129}
4130
Anders Carlsson3be22e22009-05-30 23:23:33 +00004131LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004132 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4133 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004134 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004135 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004136 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004137 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlsson3be22e22009-05-30 23:23:33 +00004138}
4139
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004140LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004141CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004142 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004143}
4144
John McCall7f416cc2015-09-08 08:05:57 +00004145Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4146 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4147 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004148}
4149
4150LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004151 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004152 LValueBaseInfo(AlignmentSource::Decl, false));
Nico Webercf4ff5862012-10-11 10:13:44 +00004153}
4154
Mike Stumpc9b231c2009-11-15 08:09:41 +00004155LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004156CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004157 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004158 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004159 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004160 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4161 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004162 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004163}
4164
Eli Friedman5bc17122012-02-08 05:34:55 +00004165LValue
4166CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004167 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004168 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004169 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004170 LValueBaseInfo(AlignmentSource::Decl, false));
Eli Friedman5bc17122012-02-08 05:34:55 +00004171}
4172
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004173LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004174 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004175
Anders Carlsson280e61f12010-06-21 20:59:55 +00004176 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004177 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004178 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004179
Alp Toker314cc812014-01-25 16:55:45 +00004180 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004181 "Can't have a scalar return unless the return type is a "
4182 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004183
John McCall7f416cc2015-09-08 08:05:57 +00004184 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004185}
4186
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004187LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004188 Address V =
4189 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004190 return MakeAddrLValue(V, E->getType(),
4191 LValueBaseInfo(AlignmentSource::Decl, false));
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004192}
4193
Daniel Dunbar722f4242009-04-22 05:08:15 +00004194llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004195 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004196 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004197}
4198
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004199LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4200 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004201 const ObjCIvarDecl *Ivar,
4202 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004203 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004204 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004205}
4206
4207LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004208 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004209 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004210 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004211 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004212 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004213 if (E->isArrow()) {
4214 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004215 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004216 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004217 } else {
4218 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004219 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004220 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004221 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004222 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004223
Craig Topper99e79272013-07-26 05:59:26 +00004224 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004225 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4226 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004227 setObjCGCLValueClass(getContext(), E, LV);
4228 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004229}
4230
Chris Lattnera4185c52009-04-25 19:35:26 +00004231LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004232 // Can only get l-value for message expression returning aggregate type
4233 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004234 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004235 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnera4185c52009-04-25 19:35:26 +00004236}
4237
John McCallb92ab1a2016-10-26 23:46:34 +00004238RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004239 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004240 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004241 // Get the actual function type. The callee type will always be a pointer to
4242 // function type or a block pointer type.
4243 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004244 "Call must have function pointer type!");
4245
John McCallb92ab1a2016-10-26 23:46:34 +00004246 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004247
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004248 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004249 // We can only guarantee that a function is called from the correct
4250 // context/function based on the appropriate target attributes,
4251 // so only check in the case where we have both always_inline and target
4252 // since otherwise we could be making a conditional call after a check for
4253 // the proper cpu features (and it won't cause code generation issues due to
4254 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004255 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4256 TargetDecl->hasAttr<TargetAttr>())
4257 checkTargetFeatures(E, FD);
4258
John McCall6fd4c232009-10-23 08:22:42 +00004259 CalleeType = getContext().getCanonicalType(CalleeType);
4260
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004261 const auto *FnType =
4262 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004263
John McCallb92ab1a2016-10-26 23:46:34 +00004264 CGCallee Callee = OrigCallee;
4265
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004266 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004267 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4268 if (llvm::Constant *PrefixSig =
4269 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004270 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004271 llvm::Constant *FTRTTIConst =
4272 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4273 llvm::Type *PrefixStructTyElems[] = {
4274 PrefixSig->getType(),
4275 FTRTTIConst->getType()
4276 };
4277 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4278 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4279
John McCallb92ab1a2016-10-26 23:46:34 +00004280 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4281
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004282 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004283 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004284 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004285 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004286 llvm::Value *CalleeSig =
4287 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004288 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4289
4290 llvm::BasicBlock *Cont = createBasicBlock("cont");
4291 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4292 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4293
4294 EmitBlock(TypeCheck);
4295 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004296 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004297 llvm::Value *CalleeRTTI =
4298 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004299 llvm::Value *CalleeRTTIMatch =
4300 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4301 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004302 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004303 EmitCheckTypeDescriptor(CalleeType)
4304 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004305 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004306 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004307
4308 Builder.CreateBr(Cont);
4309 EmitBlock(Cont);
4310 }
4311 }
4312
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004313 // If we are checking indirect calls and this call is indirect, check that the
4314 // function pointer is a member of the bit set for the function type.
4315 if (SanOpts.has(SanitizerKind::CFIICall) &&
4316 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4317 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004318 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004319
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004320 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004321 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004322
John McCallb92ab1a2016-10-26 23:46:34 +00004323 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4324 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004325 llvm::Value *TypeTest = Builder.CreateCall(
4326 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004327
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004328 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004329 llvm::Constant *StaticData[] = {
4330 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4331 EmitCheckSourceLocation(E->getLocStart()),
4332 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4333 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004334 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4335 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004336 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004337 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004338 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004339 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004340 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004341 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004342 }
4343
Daniel Dunbarc722b852008-08-30 03:02:31 +00004344 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004345 if (Chain)
4346 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4347 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004348
4349 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004350 // right-to-left, and that we evaluate arguments to certain other operators
4351 // left-to-right. Note that we allow this to override the order dictated by
4352 // the calling convention on the MS ABI, which means that parameter
4353 // destruction order is not necessarily reverse construction order.
4354 // FIXME: Revisit this based on C++ committee response to unimplementability.
4355 EvaluationOrder Order = EvaluationOrder::Default;
4356 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4357 if (OCE->isAssignmentOp())
4358 Order = EvaluationOrder::ForceRightToLeft;
4359 else {
4360 switch (OCE->getOperator()) {
4361 case OO_LessLess:
4362 case OO_GreaterGreater:
4363 case OO_AmpAmp:
4364 case OO_PipePipe:
4365 case OO_Comma:
4366 case OO_ArrowStar:
4367 Order = EvaluationOrder::ForceLeftToRight;
4368 break;
4369 default:
4370 break;
4371 }
4372 }
4373 }
Richard Smith762672a2016-09-28 19:09:10 +00004374
David Blaikief05779e2015-07-21 18:37:18 +00004375 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004376 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004377
Peter Collingbournef7706832014-12-12 23:41:25 +00004378 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4379 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004380
4381 // C99 6.5.2.2p6:
4382 // If the expression that denotes the called function has a type
4383 // that does not include a prototype, [the default argument
4384 // promotions are performed]. If the number of arguments does not
4385 // equal the number of parameters, the behavior is undefined. If
4386 // the function is defined with a type that includes a prototype,
4387 // and either the prototype ends with an ellipsis (, ...) or the
4388 // types of the arguments after promotion are not compatible with
4389 // the types of the parameters, the behavior is undefined. If the
4390 // function is defined with a type that does not include a
4391 // prototype, and the types of the arguments after promotion are
4392 // not compatible with those of the parameters after promotion,
4393 // the behavior is undefined [except in some trivial cases].
4394 // That is, in the general case, we should assume that a call
4395 // through an unprototyped function type works like a *non-variadic*
4396 // call. The way we make this work is to cast to the exact type
4397 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004398 //
4399 // Chain calls use this same code path to add the invisible chain parameter
4400 // to the function type.
4401 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004402 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004403 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004404
4405 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4406 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4407 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004408 }
4409
John McCallb92ab1a2016-10-26 23:46:34 +00004410 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004411}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004412
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004413LValue CodeGenFunction::
4414EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004415 Address BaseAddr = Address::invalid();
4416 if (E->getOpcode() == BO_PtrMemI) {
4417 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4418 } else {
4419 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4420 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004421
John McCallc134eb52010-08-31 21:07:20 +00004422 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4423
4424 const MemberPointerType *MPT
4425 = E->getRHS()->getType()->getAs<MemberPointerType>();
4426
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004427 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00004428 Address MemberAddr =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004429 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
John McCallc134eb52010-08-31 21:07:20 +00004430
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004431 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004432}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004433
John McCall47fb9502013-03-07 21:37:08 +00004434/// Given the address of a temporary variable, produce an r-value of
4435/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004436RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004437 QualType type,
4438 SourceLocation loc) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004439 LValue lvalue = MakeAddrLValue(addr, type,
4440 LValueBaseInfo(AlignmentSource::Decl, false));
John McCall47fb9502013-03-07 21:37:08 +00004441 switch (getEvaluationKind(type)) {
4442 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004443 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004444 case TEK_Aggregate:
4445 return lvalue.asAggregateRValue();
4446 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004447 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004448 }
4449 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004450}
4451
Duncan Sandse81111c2012-04-10 08:23:07 +00004452void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004453 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004454 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004455 return;
4456
Duncan Sands65229ed2012-04-16 16:29:47 +00004457 llvm::MDBuilder MDHelper(getLLVMContext());
4458 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004459
Duncan Sands6fc46192012-04-14 12:37:26 +00004460 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004461}
John McCallfe96e0b2011-11-06 09:01:30 +00004462
4463namespace {
4464 struct LValueOrRValue {
4465 LValue LV;
4466 RValue RV;
4467 };
4468}
4469
4470static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4471 const PseudoObjectExpr *E,
4472 bool forLValue,
4473 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004474 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004475
4476 // Find the result expression, if any.
4477 const Expr *resultExpr = E->getResultExpr();
4478 LValueOrRValue result;
4479
4480 for (PseudoObjectExpr::const_semantics_iterator
4481 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4482 const Expr *semantic = *i;
4483
4484 // If this semantic expression is an opaque value, bind it
4485 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004486 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004487
4488 // If this is the result expression, we may need to evaluate
4489 // directly into the slot.
4490 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4491 OVMA opaqueData;
4492 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004493 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004494 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004495 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
John McCall7f416cc2015-09-08 08:05:57 +00004496 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004497 BaseInfo);
John McCallfe96e0b2011-11-06 09:01:30 +00004498 opaqueData = OVMA::bind(CGF, ov, LV);
4499 result.RV = slot.asRValue();
4500
4501 // Otherwise, emit as normal.
4502 } else {
4503 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4504
4505 // If this is the result, also evaluate the result now.
4506 if (ov == resultExpr) {
4507 if (forLValue)
4508 result.LV = CGF.EmitLValue(ov);
4509 else
4510 result.RV = CGF.EmitAnyExpr(ov, slot);
4511 }
4512 }
4513
4514 opaques.push_back(opaqueData);
4515
4516 // Otherwise, if the expression is the result, evaluate it
4517 // and remember the result.
4518 } else if (semantic == resultExpr) {
4519 if (forLValue)
4520 result.LV = CGF.EmitLValue(semantic);
4521 else
4522 result.RV = CGF.EmitAnyExpr(semantic, slot);
4523
4524 // Otherwise, evaluate the expression in an ignored context.
4525 } else {
4526 CGF.EmitIgnoredExpr(semantic);
4527 }
4528 }
4529
4530 // Unbind all the opaques now.
4531 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4532 opaques[i].unbind(CGF);
4533
4534 return result;
4535}
4536
4537RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4538 AggValueSlot slot) {
4539 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4540}
4541
4542LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4543 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4544}