blob: 9f800a75b5bc89bd5217d94c35152a27f3c63191 [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) {
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001435 bool MayAlias = BaseInfo.getMayAlias();
1436 llvm::MDNode *TBAA = MayAlias
1437 ? CGM.getTBAAInfo(getContext().CharTy)
1438 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1439 if (TBAA)
1440 CGM.DecorateInstructionWithTBAA(Load, TBAA, MayAlias);
Manman Renc451e572013-04-04 21:53:22 +00001441 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001442
Vedant Kumar5a972652017-02-27 19:46:19 +00001443 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1444 // In order to prevent the optimizer from throwing away the check, don't
1445 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001446 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001447 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1448 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001449
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001450 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001451}
1452
John McCall3a7f6922010-10-27 20:58:56 +00001453llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1454 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001455 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001456 // This should really always be an i1, but sometimes it's already
1457 // an i8, and it's awkward to track those cases down.
1458 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001459 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1460 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1461 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001462 }
1463
1464 return Value;
1465}
1466
1467llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1468 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001469 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001470 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1471 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001472 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1473 }
1474
1475 return Value;
1476}
1477
John McCall7f416cc2015-09-08 08:05:57 +00001478void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1479 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001480 LValueBaseInfo BaseInfo,
John McCall7f416cc2015-09-08 08:05:57 +00001481 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001482 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001483 uint64_t TBAAOffset,
1484 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001485
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001486 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1487 // Handle vectors differently to get better performance.
1488 if (Ty->isVectorType()) {
1489 llvm::Type *SrcTy = Value->getType();
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001490 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001491 // Handle vec3 special.
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001492 if (VecTy && VecTy->getNumElements() == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001493 // Our source is a vec3, do a shuffle vector to make it a vec4.
1494 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1495 Builder.getInt32(2),
1496 llvm::UndefValue::get(Builder.getInt32Ty())};
1497 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1498 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1499 MaskV, "extractVec");
1500 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1501 }
1502 if (Addr.getElementType() != SrcTy) {
1503 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1504 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001505 }
1506 }
Craig Topper99e79272013-07-26 05:59:26 +00001507
John McCall3a7f6922010-10-27 20:58:56 +00001508 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001509
David Majnemera38c9f12016-05-24 16:09:25 +00001510 LValue AtomicLValue =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001511 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001512 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001513 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1514 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001515 return;
1516 }
1517
Daniel Dunbar03816342010-08-21 02:24:36 +00001518 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001519 if (isNontemporal) {
1520 llvm::MDNode *Node =
1521 llvm::MDNode::get(Store->getContext(),
1522 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1523 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1524 }
Manman Renc451e572013-04-04 21:53:22 +00001525 if (TBAAInfo) {
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001526 bool MayAlias = BaseInfo.getMayAlias();
1527 llvm::MDNode *TBAA = MayAlias
1528 ? CGM.getTBAAInfo(getContext().CharTy)
1529 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1530 if (TBAA)
1531 CGM.DecorateInstructionWithTBAA(Store, TBAA, MayAlias);
Manman Renc451e572013-04-04 21:53:22 +00001532 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001533}
1534
David Chisnallfa35df62012-01-16 17:27:18 +00001535void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001536 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001537 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001538 lvalue.getType(), lvalue.getBaseInfo(),
Manman Renc451e572013-04-04 21:53:22 +00001539 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001540 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001541}
1542
Mike Stump4a3999f2009-09-09 13:00:44 +00001543/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1544/// method emits the address of the lvalue, then loads the result as an rvalue,
1545/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001546RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001547 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001548 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001549 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001550 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1551 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001552 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001553 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001554 // In MRC mode, we do a load+autorelease.
1555 if (!getLangOpts().ObjCAutoRefCount) {
1556 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1557 }
1558
1559 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001560 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1561 Object = EmitObjCConsumeObject(LV.getType(), Object);
1562 return RValue::get(Object);
1563 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001564
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001565 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001566 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001567
John McCalla1dee5302010-08-22 10:59:02 +00001568 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001569 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001570 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001571
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001572 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001573 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001574 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001575 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001576 "vecext"));
1577 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001578
1579 // If this is a reference to a subset of the elements of a vector, either
1580 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001581 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001582 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001583
Renato Golin230c5eb2014-05-19 18:15:42 +00001584 // Global Register variables always invoke intrinsics
1585 if (LV.isGlobalReg())
1586 return EmitLoadOfGlobalRegLValue(LV);
1587
John McCallc109a252011-11-07 03:59:57 +00001588 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001589 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001590}
1591
Vedant Kumar129edab2017-03-09 16:06:27 +00001592RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1593 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001594 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001595
Daniel Dunbar3447a022010-04-13 23:34:15 +00001596 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001597 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001598
John McCall7f416cc2015-09-08 08:05:57 +00001599 Address Ptr = LV.getBitFieldAddress();
1600 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001601
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001602 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001603 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001604 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1605 if (HighBits)
1606 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1607 if (Info.Offset + HighBits)
1608 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1609 } else {
1610 if (Info.Offset)
1611 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001612 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001613 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1614 Info.Size),
1615 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001616 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001617 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001618 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001619 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001620}
1621
Nate Begemanb699c9b2009-01-18 06:42:49 +00001622// If this is a reference to a subset of the elements of a vector, create an
1623// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001624RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001625 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1626 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001627
Nate Begemanf322eab2008-05-09 06:41:27 +00001628 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001629
1630 // If the result of the expression is a non-vector type, we must be extracting
1631 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001632 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001633 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001634 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001635 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001636 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001637 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001638
1639 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001640 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001641
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001642 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001643 for (unsigned i = 0; i != NumResultElts; ++i)
1644 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001645
Chris Lattner91c08ad2011-02-15 00:14:06 +00001646 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1647 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001648 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001649 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001650}
1651
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001652/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001653Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1654 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001655 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1656 QualType EQT = ExprVT->getElementType();
1657 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001658
John McCall7f416cc2015-09-08 08:05:57 +00001659 Address CastToPointerElement =
1660 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1661 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001662
1663 const llvm::Constant *Elts = LV.getExtVectorElts();
1664 unsigned ix = getAccessedFieldNo(0, Elts);
1665
John McCall7f416cc2015-09-08 08:05:57 +00001666 Address VectorBasePtrPlusIx =
1667 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1668 getContext().getTypeSizeInChars(EQT),
1669 "vector.elt");
1670
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001671 return VectorBasePtrPlusIx;
1672}
1673
Renato Golin230c5eb2014-05-19 18:15:42 +00001674/// @brief Load of global gamed gegisters are always calls to intrinsics.
1675RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001676 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1677 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001678 llvm::MDNode *RegName = cast<llvm::MDNode>(
1679 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001680
1681 // We accept integer and pointer types only
1682 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1683 llvm::Type *Ty = OrigTy;
1684 if (OrigTy->isPointerTy())
1685 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1686 llvm::Type *Types[] = { Ty };
1687
Renato Golin230c5eb2014-05-19 18:15:42 +00001688 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001689 llvm::Value *Call = Builder.CreateCall(
1690 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001691 if (OrigTy->isPointerTy())
1692 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001693 return RValue::get(Call);
1694}
Chris Lattner40ff7012007-08-03 16:18:34 +00001695
Chris Lattner9369a562007-06-29 16:31:29 +00001696
Chris Lattner8394d792007-06-05 20:53:16 +00001697/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1698/// lvalue, where both are guaranteed to the have the same type, and that type
1699/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001700void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001701 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001702 if (!Dst.isSimple()) {
1703 if (Dst.isVectorElt()) {
1704 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001705 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1706 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001707 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001708 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001709 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1710 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001711 return;
1712 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001713
Nate Begemance4d7fc2008-04-18 23:10:10 +00001714 // If this is an update of extended vector elements, insert them as
1715 // appropriate.
1716 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001717 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001718
Renato Golin230c5eb2014-05-19 18:15:42 +00001719 if (Dst.isGlobalReg())
1720 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1721
John McCallc109a252011-11-07 03:59:57 +00001722 assert(Dst.isBitField() && "Unknown LValue type");
1723 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001724 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001725
John McCall31168b02011-06-15 23:02:42 +00001726 // There's special magic for assigning into an ARC-qualified l-value.
1727 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1728 switch (Lifetime) {
1729 case Qualifiers::OCL_None:
1730 llvm_unreachable("present but none");
1731
1732 case Qualifiers::OCL_ExplicitNone:
1733 // nothing special
1734 break;
1735
1736 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001737 if (isInit) {
1738 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1739 break;
1740 }
John McCall55e1fbc2011-06-25 02:11:03 +00001741 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001742 return;
1743
1744 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001745 if (isInit)
1746 // Initialize and then skip the primitive store.
1747 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1748 else
1749 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001750 return;
1751
1752 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001753 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1754 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001755 // fall into the normal path
1756 break;
1757 }
1758 }
1759
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001760 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001761 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001762 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001763 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001764 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001765 return;
1766 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001767
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001768 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001769 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001770 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001771 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001772 if (Dst.isObjCIvar()) {
1773 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001774 llvm::Type *ResultType = IntPtrTy;
1775 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1776 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001777 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001778 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001779 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1780 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001781 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001782 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001783 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001784 } else if (Dst.isGlobalObjCRef()) {
1785 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1786 Dst.isThreadLocalRef());
1787 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001788 else
1789 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001790 return;
1791 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001792
Chris Lattner6278e6a2007-08-11 00:04:45 +00001793 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001794 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001795}
1796
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001797void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001798 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001799 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001800 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001801 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001802
Daniel Dunbar67aba792010-04-15 03:47:33 +00001803 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001804 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001805
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001806 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001807 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001808 /*IsSigned=*/false);
1809 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001810
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001811 // See if there are other bits in the bitfield's storage we'll need to load
1812 // and mask together with source before storing.
1813 if (Info.StorageSize != Info.Size) {
1814 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001815 llvm::Value *Val =
1816 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001817
1818 // Mask the source value as needed.
1819 if (!hasBooleanRepresentation(Dst.getType()))
1820 SrcVal = Builder.CreateAnd(SrcVal,
1821 llvm::APInt::getLowBitsSet(Info.StorageSize,
1822 Info.Size),
1823 "bf.value");
1824 MaskedVal = SrcVal;
1825 if (Info.Offset)
1826 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1827
1828 // Mask out the original value.
1829 Val = Builder.CreateAnd(Val,
1830 ~llvm::APInt::getBitsSet(Info.StorageSize,
1831 Info.Offset,
1832 Info.Offset + Info.Size),
1833 "bf.clear");
1834
1835 // Or together the unchanged values and the source value.
1836 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1837 } else {
1838 assert(Info.Offset == 0);
1839 }
1840
1841 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001842 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001843
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001844 // Return the new value of the bit-field, if requested.
1845 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001846 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001847
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001848 // Sign extend the value if needed.
1849 if (Info.IsSigned) {
1850 assert(Info.Size <= Info.StorageSize);
1851 unsigned HighBits = Info.StorageSize - Info.Size;
1852 if (HighBits) {
1853 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1854 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1855 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001856 }
1857
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001858 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1859 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001860 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001861 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001862}
1863
Nate Begemance4d7fc2008-04-18 23:10:10 +00001864void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001865 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001866 // This access turns into a read/modify/write of the vector. Load the input
1867 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001868 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1869 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001870 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001871
Chris Lattner4647a212007-08-31 22:49:20 +00001872 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001873
John McCall55e1fbc2011-06-25 02:11:03 +00001874 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001875 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001876 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001877 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001878 // Use shuffle vector is the src and destination are the same number of
1879 // elements and restore the vector mask since it is on the side it will be
1880 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001881 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001882 for (unsigned i = 0; i != NumSrcElts; ++i)
1883 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001884
Chris Lattner91c08ad2011-02-15 00:14:06 +00001885 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001886 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001887 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001888 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001889 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001890 // Extended the source vector to the same length and then shuffle it
1891 // into the destination.
1892 // FIXME: since we're shuffling with undef, can we just use the indices
1893 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001894 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001895 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001896 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001897 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001898 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001899 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001900 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001901 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001902 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001903 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001904 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001905 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001906 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001907
Joey Goulycf4143b2013-11-21 17:09:05 +00001908 // When the vector size is odd and .odd or .hi is used, the last element
1909 // of the Elts constant array will be one past the size of the vector.
1910 // Ignore the last element here, if it is greater than the mask size.
1911 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1912 NumSrcElts--;
1913
Nate Begemanb699c9b2009-01-18 06:42:49 +00001914 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001915 for (unsigned i = 0; i != NumSrcElts; ++i)
1916 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001917 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001918 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001919 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001920 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001921 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001922 }
1923 } else {
1924 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001925 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001926 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001927 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001928 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001929
John McCall7f416cc2015-09-08 08:05:57 +00001930 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1931 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001932}
1933
Renato Golin230c5eb2014-05-19 18:15:42 +00001934/// @brief Store of global named registers are always calls to intrinsics.
1935void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001936 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1937 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001938 llvm::MDNode *RegName = cast<llvm::MDNode>(
1939 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001940 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001941
1942 // We accept integer and pointer types only
1943 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1944 llvm::Type *Ty = OrigTy;
1945 if (OrigTy->isPointerTy())
1946 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1947 llvm::Type *Types[] = { Ty };
1948
Renato Golin230c5eb2014-05-19 18:15:42 +00001949 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1950 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001951 if (OrigTy->isPointerTy())
1952 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001953 Builder.CreateCall(
1954 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001955}
1956
Eric Christopherc9e2a682014-05-20 17:10:39 +00001957// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001958// generating write-barries API. It is currently a global, ivar,
1959// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001960static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001961 LValue &LV,
1962 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001963 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001964 return;
Craig Topper99e79272013-07-26 05:59:26 +00001965
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001966 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001967 QualType ExpTy = E->getType();
1968 if (IsMemberAccess && ExpTy->isPointerType()) {
1969 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001970 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001971 // writer-barrier conservatively.
1972 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1973 if (ExpTy->isRecordType()) {
1974 LV.setObjCIvar(false);
1975 return;
1976 }
1977 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001978 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001979 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001980 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001981 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001982 return;
1983 }
Craig Topper99e79272013-07-26 05:59:26 +00001984
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001985 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1986 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001987 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001988 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001989 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001990 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001991 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001992 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001993 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001994 }
Craig Topper99e79272013-07-26 05:59:26 +00001995
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001996 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001997 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001998 return;
1999 }
Craig Topper99e79272013-07-26 05:59:26 +00002000
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002001 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002002 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002003 if (LV.isObjCIvar()) {
2004 // If cast is to a structure pointer, follow gcc's behavior and make it
2005 // a non-ivar write-barrier.
2006 QualType ExpTy = E->getType();
2007 if (ExpTy->isPointerType())
2008 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2009 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002010 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002011 }
2012 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002013 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002014
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002015 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002016 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2017 return;
2018 }
2019
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002020 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002021 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002022 return;
2023 }
Craig Topper99e79272013-07-26 05:59:26 +00002024
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002025 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002026 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002027 return;
2028 }
John McCall31168b02011-06-15 23:02:42 +00002029
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002030 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002031 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002032 return;
2033 }
2034
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002035 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002036 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002037 if (LV.isObjCIvar() && !LV.isObjCArray())
2038 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002039 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002040 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002041 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002042 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002043 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002044 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002045 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002046 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002047
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002048 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002049 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002050 // We don't know if member is an 'ivar', but this flag is looked at
2051 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002052 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002053 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002054 }
2055}
2056
Chris Lattner3f32d692011-07-12 06:52:18 +00002057static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002058EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002059 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002060 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002061 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002062 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002063}
2064
Alexey Bataev97720002014-11-11 04:05:39 +00002065static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002066 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2067 llvm::Type *RealVarTy, SourceLocation Loc) {
2068 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2069 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002070 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2071 return CGF.MakeAddrLValue(Addr, T, BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00002072}
2073
2074Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2075 const ReferenceType *RefTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002076 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002077 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2078 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002079 BaseInfo, /*forPointee*/ true));
John McCall7f416cc2015-09-08 08:05:57 +00002080}
2081
2082LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2083 const ReferenceType *RefTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002084 LValueBaseInfo BaseInfo;
2085 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2086 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002087}
2088
Alexey Bataev31300ed2016-02-04 11:27:03 +00002089Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2090 const PointerType *PtrTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002091 LValueBaseInfo *BaseInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002092 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002093 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2094 BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002095 /*forPointeeType=*/true));
2096}
2097
2098LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2099 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002100 LValueBaseInfo BaseInfo;
2101 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2102 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002103}
2104
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002105static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2106 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002107 QualType T = E->getType();
2108
2109 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002110 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2111 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002112 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2113
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002114 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002115 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2116 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002117 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002118 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002119 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002120 // Emit reference to the private copy of the variable if it is an OpenMP
2121 // threadprivate variable.
2122 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002123 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002124 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002125 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2126 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002127 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002128 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2129 LV = CGF.MakeAddrLValue(Addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002130 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002131 setObjCGCLValueClass(CGF.getContext(), E, LV);
2132 return LV;
2133}
2134
John McCallb92ab1a2016-10-26 23:46:34 +00002135static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2136 const FunctionDecl *FD) {
2137 if (FD->hasAttr<WeakRefAttr>()) {
2138 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2139 return aliasee.getPointer();
2140 }
2141
2142 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002143 if (!FD->hasPrototype()) {
2144 if (const FunctionProtoType *Proto =
2145 FD->getType()->getAs<FunctionProtoType>()) {
2146 // Ugly case: for a K&R-style definition, the type of the definition
2147 // isn't the same as the type of a use. Correct for this with a
2148 // bitcast.
2149 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002150 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2151 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2152 V = llvm::ConstantExpr::getBitCast(V,
2153 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002154 }
2155 }
John McCallb92ab1a2016-10-26 23:46:34 +00002156 return V;
2157}
2158
2159static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2160 const Expr *E, const FunctionDecl *FD) {
2161 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002162 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002163 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2164 return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002165}
2166
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002167static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2168 llvm::Value *ThisValue) {
2169 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2170 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2171 return CGF.EmitLValueForField(LV, FD);
2172}
2173
Renato Golin230c5eb2014-05-19 18:15:42 +00002174/// Named Registers are named metadata pointing to the register name
2175/// which will be read from/written to as an argument to the intrinsic
2176/// @llvm.read/write_register.
2177/// So far, only the name is being passed down, but other options such as
2178/// register type, allocation type or even optimization options could be
2179/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002180static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002181 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002182 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002183 assert(Asm->getLabel().size() < 64-Name.size() &&
2184 "Register name too big");
2185 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002186 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002187 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002188 if (M->getNumOperands() == 0) {
2189 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2190 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002191 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002192 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2193 }
John McCall7f416cc2015-09-08 08:05:57 +00002194
2195 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2196
2197 llvm::Value *Ptr =
2198 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2199 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002200}
2201
Chris Lattnerd7f58862007-06-02 05:24:33 +00002202LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002203 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002204 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002205
Renato Goline7b3d5d2014-05-27 16:46:27 +00002206 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2207 // Global Named registers access via intrinsics only
2208 if (VD->getStorageClass() == SC_Register &&
2209 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002210 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002211
Renato Goline7b3d5d2014-05-27 16:46:27 +00002212 // A DeclRefExpr for a reference initialized by a constant expression can
2213 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002214 const Expr *Init = VD->getAnyInitializer(VD);
2215 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2216 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002217 VD->checkInitIsICE() &&
2218 // Do not emit if it is private OpenMP variable.
2219 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2220 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002221 llvm::Constant *Val =
2222 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2223 assert(Val && "failed to emit reference constant expression");
2224 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002225
2226 // Should we be using the alignment of the constant pointer we emitted?
2227 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2228 /*pointee*/ true);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002229 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2230 return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo);
Richard Smith5a1104b2012-10-20 01:38:33 +00002231 }
David Majnemer602cfe72015-01-01 09:49:44 +00002232
2233 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002234 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002235 if (auto *FD = LambdaCaptureFields.lookup(VD))
2236 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2237 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002238 auto I = LocalDeclMap.find(VD);
2239 if (I != LocalDeclMap.end()) {
2240 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2241 return EmitLoadOfReferenceLValue(I->second, RefTy);
2242 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002243 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002244 LValue CapLVal =
2245 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2246 CapturedStmtInfo->getContextValue());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002247 bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002248 return MakeAddrLValue(
2249 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002250 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias));
David Majnemer602cfe72015-01-01 09:49:44 +00002251 }
John McCall7f416cc2015-09-08 08:05:57 +00002252
David Majnemer602cfe72015-01-01 09:49:44 +00002253 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002254 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002255 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2256 return MakeAddrLValue(addr, T, BaseInfo);
David Majnemer602cfe72015-01-01 09:49:44 +00002257 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002258 }
2259
Eli Friedman5720e342012-01-21 04:52:58 +00002260 // FIXME: We should be able to assert this for FunctionDecls as well!
2261 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2262 // those with a valid source location.
2263 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2264 !E->getLocation().isValid()) &&
2265 "Should not use decl without marking it used!");
2266
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002267 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002268 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002269 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002270 return MakeAddrLValue(Aliasee, T,
2271 LValueBaseInfo(AlignmentSource::Decl, false));
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002272 }
2273
Renato Goline7b3d5d2014-05-27 16:46:27 +00002274 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002275 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002276 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002277 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002278
John McCall7f416cc2015-09-08 08:05:57 +00002279 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002280
John McCall7f416cc2015-09-08 08:05:57 +00002281 // The variable should generally be present in the local decl map.
2282 auto iter = LocalDeclMap.find(VD);
2283 if (iter != LocalDeclMap.end()) {
2284 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002285
John McCall7f416cc2015-09-08 08:05:57 +00002286 // Otherwise, it might be static local we haven't emitted yet for
2287 // some reason; most likely, because it's in an outer function.
2288 } else if (VD->isStaticLocal()) {
2289 addr = Address(CGM.getOrCreateStaticVarDecl(
2290 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2291 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002292
John McCall7f416cc2015-09-08 08:05:57 +00002293 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002294 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002295 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2296 }
2297
2298
2299 // Check for OpenMP threadprivate variables.
2300 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2301 return EmitThreadPrivateVarDeclLValue(
2302 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2303 E->getExprLoc());
2304 }
2305
2306 // Drill into block byref variables.
2307 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2308 if (isBlockByref) {
2309 addr = emitBlockByrefAddress(addr, VD);
2310 }
2311
2312 // Drill into reference types.
2313 LValue LV;
2314 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2315 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2316 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002317 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2318 LV = MakeAddrLValue(addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002319 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002320
John McCallcdda29c2013-03-13 03:10:54 +00002321 bool isLocalStorage = VD->hasLocalStorage();
2322
2323 bool NonGCable = isLocalStorage &&
2324 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002325 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002326 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002327 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002328 LV.setNonGC(true);
2329 }
John McCallcdda29c2013-03-13 03:10:54 +00002330
2331 bool isImpreciseLifetime =
2332 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2333 if (isImpreciseLifetime)
2334 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002335 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002336 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002337 }
John McCallf3a88602011-02-03 08:15:49 +00002338
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002339 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002340 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002341
Richard Smithda383632016-08-15 01:33:41 +00002342 // FIXME: While we're emitting a binding from an enclosing scope, all other
2343 // DeclRefExprs we see should be implicitly treated as if they also refer to
2344 // an enclosing scope.
2345 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2346 return EmitLValue(BD->getBinding());
2347
David Blaikie83d382b2011-09-23 05:06:16 +00002348 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002349}
Chris Lattnere47e4402007-06-01 18:02:12 +00002350
Chris Lattner8394d792007-06-05 20:53:16 +00002351LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2352 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002353 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002354 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002355
Chris Lattner0f398c42008-07-26 22:37:01 +00002356 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002357 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002358 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002359 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002360 QualType T = E->getSubExpr()->getType()->getPointeeType();
2361 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002362
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002363 LValueBaseInfo BaseInfo;
2364 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo);
2365 LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002366 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002367
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002368 // We should not generate __weak write barrier on indirect reference
2369 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2370 // But, we continue to generate __strong write barrier on indirect write
2371 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002372 if (getLangOpts().ObjC1 &&
2373 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002374 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002375 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002376 return LV;
2377 }
John McCalle3027922010-08-25 11:45:40 +00002378 case UO_Real:
2379 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002380 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002381 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002382
Richard Smith0b6b8e42012-02-18 20:53:32 +00002383 // __real is valid on scalars. This is a faster way of testing that.
2384 // __imag can only produce an rvalue on scalars.
2385 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002386 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002387 assert(E->getSubExpr()->getType()->isArithmeticType());
2388 return LV;
2389 }
2390
Alexey Bataev611b0a12016-11-07 18:15:02 +00002391 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002392
John McCall7f416cc2015-09-08 08:05:57 +00002393 Address Component =
2394 (E->getOpcode() == UO_Real
2395 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2396 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002397 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo());
Alexey Bataev611b0a12016-11-07 18:15:02 +00002398 ElemLV.getQuals().addQualifiers(LV.getQuals());
2399 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002400 }
John McCalle3027922010-08-25 11:45:40 +00002401 case UO_PreInc:
2402 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002403 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002404 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002405
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002406 if (E->getType()->isAnyComplexType())
2407 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2408 else
2409 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2410 return LV;
2411 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002412 }
Chris Lattner8394d792007-06-05 20:53:16 +00002413}
2414
Chris Lattner4347e3692007-06-06 04:54:52 +00002415LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002416 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002417 E->getType(),
2418 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4347e3692007-06-06 04:54:52 +00002419}
2420
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002421LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002422 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002423 E->getType(),
2424 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002425}
2426
Mike Stump4a3999f2009-09-09 13:00:44 +00002427LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002428 auto SL = E->getFunctionName();
2429 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2430 StringRef FnName = CurFn->getName();
2431 if (FnName.startswith("\01"))
2432 FnName = FnName.substr(1);
2433 StringRef NameItems[] = {
2434 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2435 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002436 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002437 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2438 std::string Name = SL->getString();
2439 if (!Name.empty()) {
2440 unsigned Discriminator =
2441 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2442 if (Discriminator)
2443 Name += "_" + Twine(Discriminator + 1).str();
2444 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002445 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002446 } else {
2447 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002448 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002449 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002450 }
Alexey Bataevec474782014-10-09 08:45:04 +00002451 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002452 return MakeAddrLValue(C, E->getType(), BaseInfo);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002453}
2454
Richard Smithe30752c2012-10-09 19:52:38 +00002455/// Emit a type description suitable for use by a runtime sanitizer library. The
2456/// format of a type descriptor is
2457///
2458/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002459/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002460/// \endcode
2461///
Richard Smith683398a2012-10-09 23:55:19 +00002462/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2463/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002464llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002465 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002466 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002467 return C;
2468
Richard Smithe30752c2012-10-09 19:52:38 +00002469 uint16_t TypeKind = -1;
2470 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002471
Richard Smithe30752c2012-10-09 19:52:38 +00002472 if (T->isIntegerType()) {
2473 TypeKind = 0;
2474 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002475 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002476 } else if (T->isFloatingType()) {
2477 TypeKind = 1;
2478 TypeInfo = getContext().getTypeSize(T);
2479 }
2480
2481 // Format the type name as if for a diagnostic, including quotes and
2482 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002483 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002484 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2485 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002486 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002487 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002488
2489 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002490 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2491 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002492 };
2493 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2494
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002495 auto *GV = new llvm::GlobalVariable(
2496 CGM.getModule(), Descriptor->getType(),
2497 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002498 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002499 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002500
2501 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002502 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002503
Richard Smithe30752c2012-10-09 19:52:38 +00002504 return GV;
2505}
2506
2507llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2508 llvm::Type *TargetTy = IntPtrTy;
2509
Richard Smith48366f72013-03-22 00:47:07 +00002510 // Floating-point types which fit into intptr_t are bitcast to integers
2511 // and then passed directly (after zero-extension, if necessary).
2512 if (V->getType()->isFloatingPointTy()) {
2513 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2514 if (Bits <= TargetTy->getIntegerBitWidth())
2515 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2516 Bits));
2517 }
2518
Richard Smithe30752c2012-10-09 19:52:38 +00002519 // Integers which fit in intptr_t are zero-extended and passed directly.
2520 if (V->getType()->isIntegerTy() &&
2521 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2522 return Builder.CreateZExt(V, TargetTy);
2523
2524 // Pointers are passed directly, everything else is passed by address.
2525 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002526 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002527 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002528 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002529 }
2530 return Builder.CreatePtrToInt(V, TargetTy);
2531}
2532
2533/// \brief Emit a representation of a SourceLocation for passing to a handler
2534/// in a sanitizer runtime library. The format for this data is:
2535/// \code
2536/// struct SourceLocation {
2537/// const char *Filename;
2538/// int32_t Line, Column;
2539/// };
2540/// \endcode
2541/// For an invalid SourceLocation, the Filename pointer is null.
2542llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002543 llvm::Constant *Filename;
2544 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002545
Alexey Samsonov6c124142014-07-18 17:50:06 +00002546 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2547 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002548 StringRef FilenameString = PLoc.getFilename();
2549
2550 int PathComponentsToStrip =
2551 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2552 if (PathComponentsToStrip < 0) {
2553 assert(PathComponentsToStrip != INT_MIN);
2554 int PathComponentsToKeep = -PathComponentsToStrip;
2555 auto I = llvm::sys::path::rbegin(FilenameString);
2556 auto E = llvm::sys::path::rend(FilenameString);
2557 while (I != E && --PathComponentsToKeep)
2558 ++I;
2559
2560 FilenameString = FilenameString.substr(I - E);
2561 } else if (PathComponentsToStrip > 0) {
2562 auto I = llvm::sys::path::begin(FilenameString);
2563 auto E = llvm::sys::path::end(FilenameString);
2564 while (I != E && PathComponentsToStrip--)
2565 ++I;
2566
2567 if (I != E)
2568 FilenameString =
2569 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2570 else
2571 FilenameString = llvm::sys::path::filename(FilenameString);
2572 }
2573
2574 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002575 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2576 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2577 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002578 Line = PLoc.getLine();
2579 Column = PLoc.getColumn();
2580 } else {
2581 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2582 Line = Column = 0;
2583 }
2584
2585 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2586 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002587
2588 return llvm::ConstantStruct::getAnon(Data);
2589}
2590
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002591namespace {
2592/// \brief Specify under what conditions this check can be recovered
2593enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002594 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002595 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002596 /// Check supports recovering, runtime has both fatal (noreturn) and
2597 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002598 Recoverable,
2599 /// Runtime conditionally aborts, always need to support recovery.
2600 AlwaysRecoverable
2601};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002602}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002603
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002604static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2605 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002606 switch (Kind) {
2607 case SanitizerKind::Vptr:
2608 return CheckRecoverableKind::AlwaysRecoverable;
2609 case SanitizerKind::Return:
2610 case SanitizerKind::Unreachable:
2611 return CheckRecoverableKind::Unrecoverable;
2612 default:
2613 return CheckRecoverableKind::Recoverable;
2614 }
2615}
2616
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002617namespace {
2618struct SanitizerHandlerInfo {
2619 char const *const Name;
2620 unsigned Version;
2621};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002622}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002623
2624const SanitizerHandlerInfo SanitizerHandlers[] = {
2625#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2626 LIST_SANITIZER_CHECKS
2627#undef SANITIZER_CHECK
2628};
2629
Alexey Samsonov88459522015-01-12 22:39:12 +00002630static void emitCheckHandlerCall(CodeGenFunction &CGF,
2631 llvm::FunctionType *FnType,
2632 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002633 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002634 CheckRecoverableKind RecoverKind, bool IsFatal,
2635 llvm::BasicBlock *ContBB) {
2636 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2637 bool NeedsAbortSuffix =
2638 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002639 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2640 const StringRef CheckName = CheckInfo.Name;
2641 std::string FnName =
2642 ("__ubsan_handle_" + CheckName +
Vedant Kumar4881bdf2016-12-12 18:47:33 +00002643 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002644 (NeedsAbortSuffix ? "_abort" : ""))
2645 .str();
Alexey Samsonov88459522015-01-12 22:39:12 +00002646 bool MayReturn =
2647 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2648
2649 llvm::AttrBuilder B;
2650 if (!MayReturn) {
2651 B.addAttribute(llvm::Attribute::NoReturn)
2652 .addAttribute(llvm::Attribute::NoUnwind);
2653 }
2654 B.addAttribute(llvm::Attribute::UWTable);
2655
2656 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2657 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002658 llvm::AttributeList::get(CGF.getLLVMContext(),
2659 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002660 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002661 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2662 if (!MayReturn) {
2663 HandlerCall->setDoesNotReturn();
2664 CGF.Builder.CreateUnreachable();
2665 } else {
2666 CGF.Builder.CreateBr(ContBB);
2667 }
2668}
2669
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002670void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002671 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002672 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002673 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002674 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002675 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002676 assert(CheckHandler >= 0 &&
2677 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2678 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002679
2680 llvm::Value *FatalCond = nullptr;
2681 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002682 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002683 for (int i = 0, n = Checked.size(); i < n; ++i) {
2684 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002685 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002686 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002687 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2688 ? TrapCond
2689 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2690 ? RecoverableCond
2691 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002692 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2693 }
2694
Peter Collingbourne9881b782015-06-18 23:59:22 +00002695 if (TrapCond)
2696 EmitTrapCheck(TrapCond);
2697 if (!FatalCond && !RecoverableCond)
2698 return;
2699
Alexey Samsonov88459522015-01-12 22:39:12 +00002700 llvm::Value *JointCond;
2701 if (FatalCond && RecoverableCond)
2702 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2703 else
2704 JointCond = FatalCond ? FatalCond : RecoverableCond;
2705 assert(JointCond);
2706
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002707 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002708 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002709#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002710 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002711 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002712 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002713 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002714 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002715#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002716
Richard Smith4d1458e2012-09-08 02:08:36 +00002717 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002718 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2719 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002720 // Give hint that we very much don't expect to execute the handler
2721 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2722 llvm::MDBuilder MDHelper(getLLVMContext());
2723 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2724 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002725 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002726
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002727 // Handler functions take an i8* pointing to the (handler-specific) static
2728 // information block, followed by a sequence of intptr_t arguments
2729 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002730 SmallVector<llvm::Value *, 4> Args;
2731 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002732 Args.reserve(DynamicArgs.size() + 1);
2733 ArgTypes.reserve(DynamicArgs.size() + 1);
2734
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002735 // Emit handler arguments and create handler function type.
2736 if (!StaticArgs.empty()) {
2737 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2738 auto *InfoPtr =
2739 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2740 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002741 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002742 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2743 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2744 ArgTypes.push_back(Int8PtrTy);
2745 }
2746
Richard Smithe30752c2012-10-09 19:52:38 +00002747 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2748 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2749 ArgTypes.push_back(IntPtrTy);
2750 }
2751
2752 llvm::FunctionType *FnType =
2753 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002754
Alexey Samsonov88459522015-01-12 22:39:12 +00002755 if (!FatalCond || !RecoverableCond) {
2756 // Simple case: we need to generate a single handler call, either
2757 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002758 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002759 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002760 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002761 // Emit two handler calls: first one for set of unrecoverable checks,
2762 // another one for recoverable.
2763 llvm::BasicBlock *NonFatalHandlerBB =
2764 createBasicBlock("non_fatal." + CheckName);
2765 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2766 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2767 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002768 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002769 NonFatalHandlerBB);
2770 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002771 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002772 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002773 }
Richard Smithe30752c2012-10-09 19:52:38 +00002774
Richard Smith4d1458e2012-09-08 02:08:36 +00002775 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002776}
2777
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002778void CodeGenFunction::EmitCfiSlowPathCheck(
2779 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2780 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002781 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2782
2783 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2784 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2785
2786 llvm::MDBuilder MDHelper(getLLVMContext());
2787 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2788 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2789
2790 EmitBlock(CheckBB);
2791
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002792 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2793
2794 llvm::CallInst *CheckCall;
2795 if (WithDiag) {
2796 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2797 auto *InfoPtr =
2798 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2799 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002800 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002801 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2802
2803 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2804 "__cfi_slowpath_diag",
2805 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2806 false));
2807 CheckCall = Builder.CreateCall(
2808 SlowPathDiagFn,
2809 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2810 } else {
2811 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2812 "__cfi_slowpath",
2813 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2814 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2815 }
2816
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002817 CheckCall->setDoesNotThrow();
2818
2819 EmitBlock(Cont);
2820}
2821
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00002822// Emit a stub for __cfi_check function so that the linker knows about this
2823// symbol in LTO mode.
2824void CodeGenFunction::EmitCfiCheckStub() {
2825 llvm::Module *M = &CGM.getModule();
2826 auto &Ctx = M->getContext();
2827 llvm::Function *F = llvm::Function::Create(
2828 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2829 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2830 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2831 // FIXME: consider emitting an intrinsic call like
2832 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2833 // which can be lowered in CrossDSOCFI pass to the actual contents of
2834 // __cfi_check. This would allow inlining of __cfi_check calls.
2835 llvm::CallInst::Create(
2836 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2837 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2838}
2839
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002840// This function is basically a switch over the CFI failure kind, which is
2841// extracted from CFICheckFailData (1st function argument). Each case is either
2842// llvm.trap or a call to one of the two runtime handlers, based on
2843// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2844// failure kind) traps, but this should really never happen. CFICheckFailData
2845// can be nullptr if the calling module has -fsanitize-trap behavior for this
2846// check kind; in this case __cfi_check_fail traps as well.
2847void CodeGenFunction::EmitCfiCheckFail() {
2848 SanitizerScope SanScope(this);
2849 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002850 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2851 ImplicitParamDecl::Other);
2852 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2853 ImplicitParamDecl::Other);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002854 Args.push_back(&ArgData);
2855 Args.push_back(&ArgAddr);
2856
John McCallc56a8b32016-03-11 04:30:31 +00002857 const CGFunctionInfo &FI =
2858 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002859
2860 llvm::Function *F = llvm::Function::Create(
2861 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2862 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2863 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2864
2865 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2866 SourceLocation());
2867
2868 llvm::Value *Data =
2869 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2870 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2871 llvm::Value *Addr =
2872 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2873 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2874
2875 // Data == nullptr means the calling module has trap behaviour for this check.
2876 llvm::Value *DataIsNotNullPtr =
2877 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2878 EmitTrapCheck(DataIsNotNullPtr);
2879
2880 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002881 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002882 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002883 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002884
2885 llvm::Value *V = Builder.CreateConstGEP2_32(
2886 CfiCheckFailDataTy,
2887 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2888 0);
2889 Address CheckKindAddr(V, getIntAlign());
2890 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2891
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002892 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2893 CGM.getLLVMContext(),
2894 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2895 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002896 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002897 {Addr, AllVtables}),
2898 IntPtrTy);
2899
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002900 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002901 {CFITCK_VCall, SanitizerKind::CFIVCall},
2902 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2903 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2904 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2905 {CFITCK_ICall, SanitizerKind::CFIICall}};
2906
2907 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2908 for (auto CheckKindMaskPair : CheckKinds) {
2909 int Kind = CheckKindMaskPair.first;
2910 SanitizerMask Mask = CheckKindMaskPair.second;
2911 llvm::Value *Cond =
2912 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002913 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002914 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002915 {Data, Addr, ValidVtable});
2916 else
2917 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002918 }
2919
2920 FinishFunction();
2921 // The only reference to this function will be created during LTO link.
2922 // Make sure it survives until then.
2923 CGM.addUsedGlobal(F);
2924}
2925
Chad Rosierae229d52013-01-29 23:31:22 +00002926void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002927 llvm::BasicBlock *Cont = createBasicBlock("cont");
2928
2929 // If we're optimizing, collapse all calls to trap down to just one per
2930 // function to save on code size.
2931 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2932 TrapBB = createBasicBlock("trap");
2933 Builder.CreateCondBr(Checked, Cont, TrapBB);
2934 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002935 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002936 TrapCall->setDoesNotReturn();
2937 TrapCall->setDoesNotThrow();
2938 Builder.CreateUnreachable();
2939 } else {
2940 Builder.CreateCondBr(Checked, Cont, TrapBB);
2941 }
2942
2943 EmitBlock(Cont);
2944}
2945
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002946llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002947 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002948
Amaury Sechet21f51b32016-09-09 04:42:49 +00002949 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2950 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2951 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00002952 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00002953 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002954
2955 return TrapCall;
2956}
2957
John McCall7f416cc2015-09-08 08:05:57 +00002958Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002959 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002960 assert(E->getType()->isArrayType() &&
2961 "Array to pointer decay must have array source type!");
2962
2963 // Expressions of array type can't be bitfields or vector elements.
2964 LValue LV = EmitLValue(E);
2965 Address Addr = LV.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002966 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00002967
2968 // If the array type was an incomplete type, we need to make sure
2969 // the decay ends up being the right type.
2970 llvm::Type *NewTy = ConvertType(E->getType());
2971 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2972
2973 // Note that VLA pointers are always decayed, so we don't need to do
2974 // anything here.
2975 if (!E->getType()->isVariableArrayType()) {
2976 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2977 "Expected pointer to array");
2978 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2979 }
2980
2981 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2982 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2983}
2984
Chris Lattner6c5abe82010-06-26 23:03:20 +00002985/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2986/// array to pointer, return the array subexpression.
2987static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2988 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002989 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002990 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002991 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002992
Chris Lattner6c5abe82010-06-26 23:03:20 +00002993 // If this is a decay from variable width array, bail out.
2994 const Expr *SubExpr = CE->getSubExpr();
2995 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002996 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002997
Chris Lattner6c5abe82010-06-26 23:03:20 +00002998 return SubExpr;
2999}
3000
John McCall7f416cc2015-09-08 08:05:57 +00003001static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3002 llvm::Value *ptr,
3003 ArrayRef<llvm::Value*> indices,
3004 bool inbounds,
Vedant Kumara125eb52017-06-01 19:22:18 +00003005 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003006 const llvm::Twine &name = "arrayidx") {
3007 if (inbounds) {
Vedant Kumara125eb52017-06-01 19:22:18 +00003008 return CGF.EmitCheckedInBoundsGEP(ptr, indices, loc, name);
John McCall7f416cc2015-09-08 08:05:57 +00003009 } else {
3010 return CGF.Builder.CreateGEP(ptr, indices, name);
3011 }
3012}
3013
3014static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3015 llvm::Value *idx,
3016 CharUnits eltSize) {
3017 // If we have a constant index, we can use the exact offset of the
3018 // element we're accessing.
3019 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3020 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3021 return arrayAlign.alignmentAtOffset(offset);
3022
3023 // Otherwise, use the worst-case alignment for any element.
3024 } else {
3025 return arrayAlign.alignmentOfArrayElement(eltSize);
3026 }
3027}
3028
3029static QualType getFixedSizeElementType(const ASTContext &ctx,
3030 const VariableArrayType *vla) {
3031 QualType eltType;
3032 do {
3033 eltType = vla->getElementType();
3034 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3035 return eltType;
3036}
3037
3038static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
Vedant Kumara125eb52017-06-01 19:22:18 +00003039 ArrayRef<llvm::Value *> indices,
John McCall7f416cc2015-09-08 08:05:57 +00003040 QualType eltType, bool inbounds,
Vedant Kumara125eb52017-06-01 19:22:18 +00003041 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003042 const llvm::Twine &name = "arrayidx") {
3043 // All the indices except that last must be zero.
3044#ifndef NDEBUG
3045 for (auto idx : indices.drop_back())
3046 assert(isa<llvm::ConstantInt>(idx) &&
3047 cast<llvm::ConstantInt>(idx)->isZero());
3048#endif
3049
3050 // Determine the element size of the statically-sized base. This is
3051 // the thing that the indices are expressed in terms of.
3052 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3053 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3054 }
3055
3056 // We can use that to compute the best alignment of the element.
3057 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3058 CharUnits eltAlign =
3059 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3060
3061 llvm::Value *eltPtr =
Vedant Kumara125eb52017-06-01 19:22:18 +00003062 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, loc, name);
John McCall7f416cc2015-09-08 08:05:57 +00003063 return Address(eltPtr, eltAlign);
3064}
3065
Richard Smith539e4a72013-02-23 02:53:19 +00003066LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3067 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003068 // The index must always be an integer, which is not an aggregate. Emit it
3069 // in lexical order (this complexity is, sadly, required by C++17).
3070 llvm::Value *IdxPre =
3071 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Richard Smith40885712016-09-27 00:53:24 +00003072 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003073 auto *Idx = IdxPre;
3074 if (E->getLHS() != E->getIdx()) {
3075 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3076 Idx = EmitScalarExpr(E->getIdx());
3077 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003078
Richard Smith9e67b992016-09-26 23:49:47 +00003079 QualType IdxTy = E->getIdx()->getType();
3080 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3081
3082 if (SanOpts.has(SanitizerKind::ArrayBounds))
3083 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3084
3085 // Extend or truncate the index type to 32 or 64-bits.
3086 if (Promote && Idx->getType() != IntPtrTy)
3087 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3088
3089 return Idx;
3090 };
3091 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003092
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003093 // If the base is a vector type, then we are forming a vector element lvalue
3094 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003095 if (E->getBase()->getType()->isVectorType() &&
3096 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003097 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003098 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003099 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003100 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00003101 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00003102 E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003103 LHS.getBaseInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003104 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003105
John McCall7f416cc2015-09-08 08:05:57 +00003106 // All the other cases basically behave like simple offsetting.
3107
John McCall7f416cc2015-09-08 08:05:57 +00003108 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003109 if (isa<ExtVectorElementExpr>(E->getBase())) {
3110 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003111 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003112 Address Addr = EmitExtVectorElementLValue(LV);
3113
3114 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
Vedant Kumara125eb52017-06-01 19:22:18 +00003115 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3116 E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003117 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003118 }
John McCall7f416cc2015-09-08 08:05:57 +00003119
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003120 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003121 Address Addr = Address::invalid();
3122 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003123 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003124 // The base must be a pointer, which is not an aggregate. Emit
3125 // it. It needs to be emitted first in case it's what captures
3126 // the VLA bounds.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003127 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003128 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003129
John McCall23c29fe2011-06-24 21:55:10 +00003130 // The element count here is the total number of non-VLA elements.
3131 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003132
John McCall77527a82011-06-25 01:32:37 +00003133 // Effectively, the multiply by the VLA size is part of the GEP.
3134 // GEP indexes are signed, and scaling an index isn't permitted to
3135 // signed-overflow, so we use the same semantics for our explicit
3136 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003137 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003138 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003139 } else {
3140 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003141 }
John McCall7f416cc2015-09-08 08:05:57 +00003142
3143 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003144 !getLangOpts().isSignedOverflowDefined(),
3145 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003146
Chris Lattner6c5abe82010-06-26 23:03:20 +00003147 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3148 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003149
John McCall7f416cc2015-09-08 08:05:57 +00003150 // Emit the base pointer.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003151 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003152 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3153
3154 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3155 llvm::Value *InterfaceSizeVal =
3156 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3157
3158 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003159
3160 // We don't necessarily build correct LLVM struct types for ObjC
3161 // interfaces, so we can't rely on GEP to do this scaling
3162 // correctly, so we need to cast to i8*. FIXME: is this actually
3163 // true? A lot of other things in the fragile ABI would break...
3164 llvm::Type *OrigBaseTy = Addr.getType();
3165 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3166
3167 // Do the GEP.
3168 CharUnits EltAlign =
3169 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
Vedant Kumara125eb52017-06-01 19:22:18 +00003170 llvm::Value *EltPtr = emitArraySubscriptGEP(
3171 *this, Addr.getPointer(), ScaledIdx, false, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003172 Addr = Address(EltPtr, EltAlign);
3173
3174 // Cast back.
3175 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003176 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3177 // If this is A[i] where A is an array, the frontend will have decayed the
3178 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3179 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3180 // "gep x, i" here. Emit one "gep A, 0, i".
3181 assert(Array->getType()->isArrayType() &&
3182 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003183 LValue ArrayLV;
3184 // For simple multidimensional array indexing, set the 'accessed' flag for
3185 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003186 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003187 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3188 else
3189 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003190 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003191
Daniel Dunbar82634272011-04-01 00:49:43 +00003192 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00003193 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3194 {CGM.getSize(CharUnits::Zero()), Idx},
3195 E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003196 !getLangOpts().isSignedOverflowDefined(),
3197 E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003198 BaseInfo = ArrayLV.getBaseInfo();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003199 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003200 // The base must be a pointer; emit it with an estimate of its alignment.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003201 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003202 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003203 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003204 !getLangOpts().isSignedOverflowDefined(),
3205 E->getExprLoc());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003206 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003207
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003208 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo);
Mike Stump4a3999f2009-09-09 13:00:44 +00003209
John McCall7f416cc2015-09-08 08:05:57 +00003210 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003211
Richard Smith9c6890a2012-11-01 22:30:59 +00003212 if (getLangOpts().ObjC1 &&
3213 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003214 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003215 setObjCGCLValueClass(getContext(), E, LV);
3216 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003217 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003218}
3219
Alexey Bataev31300ed2016-02-04 11:27:03 +00003220static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003221 LValueBaseInfo &BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003222 QualType BaseTy, QualType ElTy,
3223 bool IsLowerBound) {
3224 LValue BaseLVal;
3225 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3226 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3227 if (BaseTy->isArrayType()) {
3228 Address Addr = BaseLVal.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003229 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003230
3231 // If the array type was an incomplete type, we need to make sure
3232 // the decay ends up being the right type.
3233 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3234 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3235
3236 // Note that VLA pointers are always decayed, so we don't need to do
3237 // anything here.
3238 if (!BaseTy->isVariableArrayType()) {
3239 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3240 "Expected pointer to array");
3241 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3242 "arraydecay");
3243 }
3244
3245 return CGF.Builder.CreateElementBitCast(Addr,
3246 CGF.ConvertTypeForMem(ElTy));
3247 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003248 LValueBaseInfo TypeInfo;
3249 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3250 BaseInfo.mergeForCast(TypeInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003251 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3252 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003253 return CGF.EmitPointerWithAlignment(Base, &BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003254}
3255
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003256LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3257 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003258 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003259 if (auto *ASE =
3260 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003261 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003262 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003263 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003264 QualType ResultExprTy;
3265 if (auto *AT = getContext().getAsArrayType(BaseTy))
3266 ResultExprTy = AT->getElementType();
3267 else
3268 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003269 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003270 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003271 // Requesting lower bound or upper bound, but without provided length and
3272 // without ':' symbol for the default length -> length = 1.
3273 // Idx = LowerBound ?: 0;
3274 if (auto *LowerBound = E->getLowerBound()) {
3275 Idx = Builder.CreateIntCast(
3276 EmitScalarExpr(LowerBound), IntPtrTy,
3277 LowerBound->getType()->hasSignedIntegerRepresentation());
3278 } else
3279 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3280 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003281 // Try to emit length or lower bound as constant. If this is possible, 1
3282 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3283 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003284 auto &C = CGM.getContext();
3285 auto *Length = E->getLength();
3286 llvm::APSInt ConstLength;
3287 if (Length) {
3288 // Idx = LowerBound + Length - 1;
3289 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3290 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3291 Length = nullptr;
3292 }
3293 auto *LowerBound = E->getLowerBound();
3294 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3295 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3296 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3297 LowerBound = nullptr;
3298 }
3299 if (!Length)
3300 --ConstLength;
3301 else if (!LowerBound)
3302 --ConstLowerBound;
3303
3304 if (Length || LowerBound) {
3305 auto *LowerBoundVal =
3306 LowerBound
3307 ? Builder.CreateIntCast(
3308 EmitScalarExpr(LowerBound), IntPtrTy,
3309 LowerBound->getType()->hasSignedIntegerRepresentation())
3310 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3311 auto *LengthVal =
3312 Length
3313 ? Builder.CreateIntCast(
3314 EmitScalarExpr(Length), IntPtrTy,
3315 Length->getType()->hasSignedIntegerRepresentation())
3316 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3317 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3318 /*HasNUW=*/false,
3319 !getLangOpts().isSignedOverflowDefined());
3320 if (Length && LowerBound) {
3321 Idx = Builder.CreateSub(
3322 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3323 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3324 }
3325 } else
3326 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3327 } else {
3328 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003329 QualType ArrayTy = BaseTy->isPointerType()
3330 ? E->getBase()->IgnoreParenImpCasts()->getType()
3331 : BaseTy;
3332 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003333 Length = VAT->getSizeExpr();
3334 if (Length->isIntegerConstantExpr(ConstLength, C))
3335 Length = nullptr;
3336 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003337 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003338 ConstLength = CAT->getSize();
3339 }
3340 if (Length) {
3341 auto *LengthVal = Builder.CreateIntCast(
3342 EmitScalarExpr(Length), IntPtrTy,
3343 Length->getType()->hasSignedIntegerRepresentation());
3344 Idx = Builder.CreateSub(
3345 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3346 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3347 } else {
3348 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3349 --ConstLength;
3350 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3351 }
3352 }
3353 }
3354 assert(Idx);
3355
Alexey Bataev31300ed2016-02-04 11:27:03 +00003356 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003357 LValueBaseInfo BaseInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003358 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003359 // The base must be a pointer, which is not an aggregate. Emit
3360 // it. It needs to be emitted first in case it's what captures
3361 // the VLA bounds.
3362 Address Base =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003363 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003364 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003365 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003366 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003367
3368 // Effectively, the multiply by the VLA size is part of the GEP.
3369 // GEP indexes are signed, and scaling an index isn't permitted to
3370 // signed-overflow, so we use the same semantics for our explicit
3371 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003372 if (getLangOpts().isSignedOverflowDefined())
3373 Idx = Builder.CreateMul(Idx, NumElements);
3374 else
3375 Idx = Builder.CreateNSWMul(Idx, NumElements);
3376 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003377 !getLangOpts().isSignedOverflowDefined(),
3378 E->getExprLoc());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003379 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3380 // If this is A[i] where A is an array, the frontend will have decayed the
3381 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3382 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3383 // "gep x, i" here. Emit one "gep A, 0, i".
3384 assert(Array->getType()->isArrayType() &&
3385 "Array to pointer decay must have array source type!");
3386 LValue ArrayLV;
3387 // For simple multidimensional array indexing, set the 'accessed' flag for
3388 // better bounds-checking of the base expression.
3389 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3390 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3391 else
3392 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003393
Alexey Bataev31300ed2016-02-04 11:27:03 +00003394 // Propagate the alignment from the array itself to the result.
3395 EltPtr = emitArraySubscriptGEP(
3396 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumara125eb52017-06-01 19:22:18 +00003397 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
3398 E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003399 BaseInfo = ArrayLV.getBaseInfo();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003400 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003401 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003402 BaseTy, ResultExprTy, IsLowerBound);
3403 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
Vedant Kumara125eb52017-06-01 19:22:18 +00003404 !getLangOpts().isSignedOverflowDefined(),
3405 E->getExprLoc());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003406 }
3407
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003408 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003409}
3410
Chris Lattner9e751ca2007-08-02 23:37:31 +00003411LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003412EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003413 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003414 LValue Base;
3415
3416 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003417 if (E->isArrow()) {
3418 // If it is a pointer to a vector, emit the address and form an lvalue with
3419 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003420 LValueBaseInfo BaseInfo;
3421 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003422 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003423 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003424 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003425 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003426 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3427 // emit the base as an lvalue.
3428 assert(E->getBase()->getType()->isVectorType());
3429 Base = EmitLValue(E->getBase());
3430 } else {
3431 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003432 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003433 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003434 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003435
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003436 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003437 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003438 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003439 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003440 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4e1a3232009-12-23 21:31:11 +00003441 }
John McCall1553b192011-06-16 04:16:24 +00003442
3443 QualType type =
3444 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003445
Nate Begemand3862152008-05-13 21:03:02 +00003446 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003447 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003448 E->getEncodedElementAccess(Indices);
3449
3450 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003451 llvm::Constant *CV =
3452 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003453 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003454 Base.getBaseInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003455 }
3456 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3457
3458 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003459 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003460
Chris Lattner595ba3a2012-01-30 06:20:36 +00003461 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3462 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003463 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003464 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003465 Base.getBaseInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003466}
3467
Devang Patel30efa2e2007-10-23 20:28:39 +00003468LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003469 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003470 // 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 +00003471 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003472 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003473 LValueBaseInfo BaseInfo;
3474 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003475 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003476 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003477 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3478 if (IsBaseCXXThis)
3479 SkippedChecks.set(SanitizerKind::Alignment, true);
3480 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003481 SkippedChecks.set(SanitizerKind::Null, true);
3482 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3483 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003484 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003485 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003486 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003487
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003488 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003489 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003490 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003491 setObjCGCLValueClass(getContext(), E, LV);
3492 return LV;
3493 }
Craig Topper99e79272013-07-26 05:59:26 +00003494
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003495 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003496 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003497
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003498 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003499 return EmitFunctionDeclLValue(*this, E, FD);
3500
David Blaikie83d382b2011-09-23 05:06:16 +00003501 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003502}
Devang Patel30efa2e2007-10-23 20:28:39 +00003503
John McCalldec348f72013-05-03 07:33:41 +00003504/// Given that we are currently emitting a lambda, emit an l-value for
3505/// one of its members.
3506LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3507 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3508 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3509 QualType LambdaTagType =
3510 getContext().getTagDeclType(Field->getParent());
3511 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3512 return EmitLValueForField(LambdaLV, Field);
3513}
3514
John McCall7f416cc2015-09-08 08:05:57 +00003515/// Drill down to the storage of a field without walking into
3516/// reference types.
3517///
3518/// The resulting address doesn't necessarily have the right type.
3519static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3520 const FieldDecl *field) {
3521 const RecordDecl *rec = field->getParent();
3522
3523 unsigned idx =
3524 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3525
3526 CharUnits offset;
3527 // Adjust the alignment down to the given offset.
3528 // As a special case, if the LLVM field index is 0, we know that this
3529 // is zero.
3530 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3531 .getFieldOffset(field->getFieldIndex()) == 0) &&
3532 "LLVM field at index zero had non-zero offset?");
3533 if (idx != 0) {
3534 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3535 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3536 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3537 }
3538
3539 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3540}
3541
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003542static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3543 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3544 if (!RD)
3545 return false;
3546
3547 if (RD->isDynamicClass())
3548 return true;
3549
3550 for (const auto &Base : RD->bases())
3551 if (hasAnyVptr(Base.getType(), Context))
3552 return true;
3553
3554 for (const FieldDecl *Field : RD->fields())
3555 if (hasAnyVptr(Field->getType(), Context))
3556 return true;
3557
3558 return false;
3559}
3560
Eli Friedman7f1ff602012-04-16 03:54:45 +00003561LValue CodeGenFunction::EmitLValueForField(LValue base,
3562 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003563 LValueBaseInfo BaseInfo = base.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003564 AlignmentSource fieldAlignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003565 getFieldAlignmentSource(BaseInfo.getAlignmentSource());
3566 LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias());
John McCall7f416cc2015-09-08 08:05:57 +00003567
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003568 const RecordDecl *rec = field->getParent();
3569 if (rec->isUnion() || rec->hasAttr<MayAliasAttr>())
3570 FieldBaseInfo.setMayAlias(true);
3571 bool mayAlias = FieldBaseInfo.getMayAlias();
3572
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003573 if (field->isBitField()) {
3574 const CGRecordLayout &RL =
3575 CGM.getTypes().getCGRecordLayout(field->getParent());
3576 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003577 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003578 unsigned Idx = RL.getLLVMFieldNo(field);
3579 if (Idx != 0)
3580 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003581 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3582 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003583 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003584 llvm::Type *FieldIntTy =
3585 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3586 if (Addr.getElementType() != FieldIntTy)
3587 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003588
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003589 QualType fieldType =
3590 field->getType().withCVRQualifiers(base.getVRQualifiers());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003591 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003592 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003593
John McCall53fcbd22011-02-26 08:07:02 +00003594 QualType type = field->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003595 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003596 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003597 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003598 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003599 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003600 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003601 // TODO: handle path-aware TBAA for union.
3602 TBAAPath = false;
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003603
3604 const auto FieldType = field->getType();
3605 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3606 hasAnyVptr(FieldType, getContext()))
3607 // Because unions can easily skip invariant.barriers, we need to add
3608 // a barrier every time CXXRecord field with vptr is referenced.
3609 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3610 addr.getAlignment());
John McCall53fcbd22011-02-26 08:07:02 +00003611 } else {
3612 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003613 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003614
3615 // If this is a reference field, load the reference right now.
3616 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3617 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3618 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3619
Manman Renc451e572013-04-04 21:53:22 +00003620 // Loading the reference will disable path-aware TBAA.
3621 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003622 if (CGM.shouldUseTBAA()) {
3623 llvm::MDNode *tbaa;
3624 if (mayAlias)
3625 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3626 else
3627 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003628 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003629 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003630 }
3631
John McCall53fcbd22011-02-26 08:07:02 +00003632 mayAlias = false;
3633 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003634
3635 CharUnits alignment =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003636 getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true);
3637 FieldBaseInfo.setMayAlias(false);
John McCall7f416cc2015-09-08 08:05:57 +00003638 addr = Address(load, alignment);
3639
3640 // Qualifiers on the struct don't apply to the referencee, and
3641 // we'll pick up CVR from the actual type later, so reset these
3642 // additional qualifiers now.
3643 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003644 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003645 }
Craig Topper99e79272013-07-26 05:59:26 +00003646
Chris Lattner13ee4f42011-07-10 05:34:54 +00003647 // Make sure that the address is pointing to the right type. This is critical
3648 // for both unions and structs. A union needs a bitcast, a struct element
3649 // will need a bitcast if the LLVM type laid out doesn't match the desired
3650 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003651 addr = Builder.CreateElementBitCast(addr,
3652 CGM.getTypes().ConvertTypeForMem(type),
3653 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003654
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003655 if (field->hasAttr<AnnotateAttr>())
3656 addr = EmitFieldAnnotations(field, addr);
3657
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003658 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003659 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003660 if (TBAAPath) {
3661 const ASTRecordLayout &Layout =
3662 getContext().getASTRecordLayout(field->getParent());
3663 // Set the base type to be the base type of the base LValue and
3664 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003665 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3666 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003667 Layout.getFieldOffset(field->getFieldIndex()) /
3668 getContext().getCharWidth());
3669 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003670
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003671 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003672 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3673 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003674
3675 // Fields of may_alias structs act like 'char' for TBAA purposes.
3676 // FIXME: this should get propagated down through anonymous structs
3677 // and unions.
3678 if (mayAlias && LV.getTBAAInfo())
3679 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3680
Daniel Dunbarf166a522010-08-21 03:44:13 +00003681 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003682}
3683
Craig Topper99e79272013-07-26 05:59:26 +00003684LValue
3685CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003686 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003687 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003688
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003689 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003690 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003691
John McCall7f416cc2015-09-08 08:05:57 +00003692 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003693
John McCall7f416cc2015-09-08 08:05:57 +00003694 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003695 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003696 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003697
John McCall7f416cc2015-09-08 08:05:57 +00003698 // TODO: access-path TBAA?
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003699 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3700 LValueBaseInfo FieldBaseInfo(
3701 getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3702 BaseInfo.getMayAlias());
3703 return MakeAddrLValue(V, FieldType, FieldBaseInfo);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003704}
3705
Chris Lattnerf53c0962010-09-06 00:11:41 +00003706LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003707 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Richard Smith2d988f02011-11-22 22:48:32 +00003708 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003709 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003710 return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo);
Richard Smith2d988f02011-11-22 22:48:32 +00003711 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003712 if (E->getType()->isVariablyModifiedType())
3713 // make sure to emit the VLA size.
3714 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003715
John McCall7f416cc2015-09-08 08:05:57 +00003716 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003717 const Expr *InitExpr = E->getInitializer();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003718 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003719
Chad Rosier615ed1a2012-03-29 17:37:10 +00003720 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3721 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003722
3723 return Result;
3724}
3725
Richard Smithbb653bd2012-05-14 21:57:21 +00003726LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3727 if (!E->isGLValue())
3728 // Initializing an aggregate temporary in C++11: T{...}.
3729 return EmitAggExprToLValue(E);
3730
3731 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003732 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003733 return EmitLValue(E->getInit(0));
3734}
3735
Richard Smithf3076ff2014-06-20 18:43:47 +00003736/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3737/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3738/// LValue is returned and the current block has been terminated.
3739static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3740 const Expr *Operand) {
3741 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3742 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3743 return None;
3744 }
3745
3746 return CGF.EmitLValue(Operand);
3747}
3748
John McCallc07a0c72011-02-17 10:25:35 +00003749LValue CodeGenFunction::
3750EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3751 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003752 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003753 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003754 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003755 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003756 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003757
Eli Friedman59954892012-01-25 05:04:17 +00003758 OpaqueValueMapping binding(*this, expr);
3759
John McCallc07a0c72011-02-17 10:25:35 +00003760 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003761 bool CondExprBool;
3762 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003763 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003764 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003765
Justin Bogneref512b92014-01-06 22:27:43 +00003766 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003767 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003768 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003769 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003770 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003771 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003772 }
3773
John McCallc07a0c72011-02-17 10:25:35 +00003774 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3775 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3776 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003777
3778 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003779 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003780
John McCall0a6bf2e2011-01-26 19:21:13 +00003781 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003782 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003783 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003784 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003785 Optional<LValue> lhs =
3786 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003787 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003788
Richard Smithf3076ff2014-06-20 18:43:47 +00003789 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003790 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003791
John McCallc07a0c72011-02-17 10:25:35 +00003792 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003793 if (lhs)
3794 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003795
John McCall0a6bf2e2011-01-26 19:21:13 +00003796 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003797 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003798 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003799 Optional<LValue> rhs =
3800 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003801 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003802 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003803 return EmitUnsupportedLValue(expr, "conditional operator");
3804 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003805
John McCallc07a0c72011-02-17 10:25:35 +00003806 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003807
Richard Smithf3076ff2014-06-20 18:43:47 +00003808 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003809 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003810 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003811 phi->addIncoming(lhs->getPointer(), lhsBlock);
3812 phi->addIncoming(rhs->getPointer(), rhsBlock);
3813 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3814 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003815 std::max(lhs->getBaseInfo().getAlignmentSource(),
3816 rhs->getBaseInfo().getAlignmentSource());
3817 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3818 rhs->getBaseInfo().getMayAlias();
3819 return MakeAddrLValue(result, expr->getType(),
3820 LValueBaseInfo(alignSource, MayAlias));
Richard Smithf3076ff2014-06-20 18:43:47 +00003821 } else {
3822 assert((lhs || rhs) &&
3823 "both operands of glvalue conditional are throw-expressions?");
3824 return lhs ? *lhs : *rhs;
3825 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003826}
3827
Richard Smithbb653bd2012-05-14 21:57:21 +00003828/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3829/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003830/// otherwise if a cast is needed by the code generator in an lvalue context,
3831/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003832/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003833/// are permitted with aggregate result, including noop aggregate casts, and
3834/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003835LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003836 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003837 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003838 case CK_BitCast:
3839 case CK_ArrayToPointerDecay:
3840 case CK_FunctionToPointerDecay:
3841 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003842 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003843 case CK_IntegralToPointer:
3844 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003845 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003846 case CK_VectorSplat:
3847 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003848 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003849 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003850 case CK_IntegralToFloating:
3851 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003852 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003853 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003854 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003855 case CK_FloatingComplexToReal:
3856 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003857 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003858 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003859 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003860 case CK_IntegralComplexToReal:
3861 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003862 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003863 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003864 case CK_DerivedToBaseMemberPointer:
3865 case CK_BaseToDerivedMemberPointer:
3866 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003867 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003868 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003869 case CK_ARCProduceObject:
3870 case CK_ARCConsumeObject:
3871 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003872 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003873 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003874 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003875 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003876 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3877
3878 case CK_Dependent:
3879 llvm_unreachable("dependent cast kind in IR gen!");
3880
3881 case CK_BuiltinFnToFnPtr:
3882 llvm_unreachable("builtin functions are handled elsewhere");
3883
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003884 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003885 case CK_NonAtomicToAtomic:
3886 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003887 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003888
Anders Carlsson8a01a752011-04-11 02:03:26 +00003889 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003890 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003891 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003892 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003893 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003894 }
3895
John McCalle3027922010-08-25 11:45:40 +00003896 case CK_ConstructorConversion:
3897 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003898 case CK_CPointerToObjCPointerCast:
3899 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003900 case CK_NoOp:
3901 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003902 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003903
John McCalle3027922010-08-25 11:45:40 +00003904 case CK_UncheckedDerivedToBase:
3905 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003906 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003907 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003908 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003909
Anders Carlssond95f9602009-09-12 16:16:49 +00003910 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003911 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003912
Anders Carlssond95f9602009-09-12 16:16:49 +00003913 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003914 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003915 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3916 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003917
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003918 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo());
Anders Carlssond95f9602009-09-12 16:16:49 +00003919 }
John McCalle3027922010-08-25 11:45:40 +00003920 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003921 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003922 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003923 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003924 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003925
Anders Carlsson8c793172009-11-23 17:57:54 +00003926 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003927
Anders Carlsson8c793172009-11-23 17:57:54 +00003928 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003929 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003930 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003931 E->path_begin(), E->path_end(),
3932 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003933
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003934 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3935 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003936 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003937 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003938 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003939
Peter Collingbourned2926c92015-03-14 02:42:25 +00003940 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003941 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3942 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003943 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003944
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003945 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003946 }
John McCalle3027922010-08-25 11:45:40 +00003947 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003948 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003949 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003950
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003951 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003952 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003953 Address V = Builder.CreateBitCast(LV.getAddress(),
3954 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003955
3956 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003957 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3958 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003959 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003960
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003961 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003962 }
John McCalle3027922010-08-25 11:45:40 +00003963 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003964 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003965 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3966 ConvertType(E->getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003967 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003968 }
Egor Churaev89831422016-12-23 14:55:49 +00003969 case CK_ZeroToOCLQueue:
3970 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003971 case CK_ZeroToOCLEvent:
3972 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003973 }
Craig Topper99e79272013-07-26 05:59:26 +00003974
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003975 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003976}
3977
John McCall1bf58462011-02-16 08:02:54 +00003978LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003979 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003980 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003981}
3982
Eli Friedman7f1ff602012-04-16 03:54:45 +00003983RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003984 const FieldDecl *FD,
3985 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003986 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003987 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003988 switch (getEvaluationKind(FT)) {
3989 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003990 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003991 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003992 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003993 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00003994 // This routine is used to load fields one-by-one to perform a copy, so
3995 // don't load reference fields.
3996 if (FD->getType()->isReferenceType())
3997 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00003998 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003999 }
4000 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004001}
Douglas Gregorfe314812011-06-21 17:03:29 +00004002
Chris Lattnere47e4402007-06-01 18:02:12 +00004003//===--------------------------------------------------------------------===//
4004// Expression Emission
4005//===--------------------------------------------------------------------===//
4006
Craig Topper99e79272013-07-26 05:59:26 +00004007RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00004008 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00004009 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004010 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00004011 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004012
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004013 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004014 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004015
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004016 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00004017 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4018
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004019 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00004020 if (const CXXMethodDecl *MD =
4021 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004022 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004023
John McCallb92ab1a2016-10-26 23:46:34 +00004024 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00004025
John McCallb92ab1a2016-10-26 23:46:34 +00004026 if (callee.isBuiltin()) {
4027 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4028 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004029 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004030
John McCallb92ab1a2016-10-26 23:46:34 +00004031 if (callee.isPseudoDestructor()) {
4032 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4033 }
4034
4035 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4036}
4037
4038/// Emit a CallExpr without considering whether it might be a subclass.
4039RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4040 ReturnValueSlot ReturnValue) {
4041 CGCallee Callee = EmitCallee(E->getCallee());
4042 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4043}
4044
4045static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4046 if (auto builtinID = FD->getBuiltinID()) {
4047 return CGCallee::forBuiltin(builtinID, FD);
4048 }
4049
4050 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4051 return CGCallee::forDirect(calleePtr, FD);
4052}
4053
4054CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4055 E = E->IgnoreParens();
4056
4057 // Look through function-to-pointer decay.
4058 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4059 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4060 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4061 return EmitCallee(ICE->getSubExpr());
4062 }
4063
4064 // Resolve direct calls.
4065 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4066 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4067 return EmitDirectCallee(*this, FD);
4068 }
4069 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4070 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4071 EmitIgnoredExpr(ME->getBase());
4072 return EmitDirectCallee(*this, FD);
4073 }
4074
4075 // Look through template substitutions.
4076 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4077 return EmitCallee(NTTP->getReplacement());
4078
4079 // Treat pseudo-destructor calls differently.
4080 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4081 return CGCallee::forPseudoDestructor(PDE);
4082 }
4083
4084 // Otherwise, we have an indirect reference.
4085 llvm::Value *calleePtr;
4086 QualType functionType;
4087 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4088 calleePtr = EmitScalarExpr(E);
4089 functionType = ptrType->getPointeeType();
4090 } else {
4091 functionType = E->getType();
4092 calleePtr = EmitLValue(E).getPointer();
4093 }
4094 assert(functionType->isFunctionType());
4095 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4096 E->getReferencedDeclOfCallee());
4097 CGCallee callee(calleeInfo, calleePtr);
4098 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004099}
4100
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004101LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004102 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004103 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004104 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004105 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004106 return EmitLValue(E->getRHS());
4107 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004108
John McCalle3027922010-08-25 11:45:40 +00004109 if (E->getOpcode() == BO_PtrMemD ||
4110 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004111 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004112
John McCalla2342eb2010-12-05 02:00:02 +00004113 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004114
4115 // Note that in all of these cases, __block variables need the RHS
4116 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004117
4118 switch (getEvaluationKind(E->getType())) {
4119 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004120 switch (E->getLHS()->getType().getObjCLifetime()) {
4121 case Qualifiers::OCL_Strong:
4122 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4123
4124 case Qualifiers::OCL_Autoreleasing:
4125 return EmitARCStoreAutoreleasing(E).first;
4126
4127 // No reason to do any of these differently.
4128 case Qualifiers::OCL_None:
4129 case Qualifiers::OCL_ExplicitNone:
4130 case Qualifiers::OCL_Weak:
4131 break;
4132 }
4133
John McCalld0a30012010-12-06 06:10:02 +00004134 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004135 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004136 if (RV.isScalar())
4137 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004138 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004139 return LV;
4140 }
John McCall4f29b492010-11-16 23:07:28 +00004141
John McCall47fb9502013-03-07 21:37:08 +00004142 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004143 return EmitComplexAssignmentLValue(E);
4144
John McCall47fb9502013-03-07 21:37:08 +00004145 case TEK_Aggregate:
4146 return EmitAggExprToLValue(E);
4147 }
4148 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004149}
4150
Christopher Lambd91c3d42007-12-29 05:02:41 +00004151LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004152 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004153
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004154 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004155 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004156 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004157
David Majnemerced8bdf2015-02-25 17:36:15 +00004158 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004159 "Can't have a scalar return unless the return type is a "
4160 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004161
John McCall7f416cc2015-09-08 08:05:57 +00004162 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004163}
4164
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004165LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4166 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004167 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004168}
4169
Anders Carlsson3be22e22009-05-30 23:23:33 +00004170LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004171 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4172 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004173 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004174 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004175 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004176 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlsson3be22e22009-05-30 23:23:33 +00004177}
4178
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004179LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004180CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004181 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004182}
4183
John McCall7f416cc2015-09-08 08:05:57 +00004184Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4185 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4186 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004187}
4188
4189LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004190 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004191 LValueBaseInfo(AlignmentSource::Decl, false));
Nico Webercf4ff5862012-10-11 10:13:44 +00004192}
4193
Mike Stumpc9b231c2009-11-15 08:09:41 +00004194LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004195CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004196 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004197 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004198 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004199 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4200 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004201 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004202}
4203
Eli Friedman5bc17122012-02-08 05:34:55 +00004204LValue
4205CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004206 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004207 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004208 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004209 LValueBaseInfo(AlignmentSource::Decl, false));
Eli Friedman5bc17122012-02-08 05:34:55 +00004210}
4211
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004212LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004213 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004214
Anders Carlsson280e61f12010-06-21 20:59:55 +00004215 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004216 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004217 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004218
Alp Toker314cc812014-01-25 16:55:45 +00004219 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004220 "Can't have a scalar return unless the return type is a "
4221 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004222
John McCall7f416cc2015-09-08 08:05:57 +00004223 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004224}
4225
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004226LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004227 Address V =
4228 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004229 return MakeAddrLValue(V, E->getType(),
4230 LValueBaseInfo(AlignmentSource::Decl, false));
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004231}
4232
Daniel Dunbar722f4242009-04-22 05:08:15 +00004233llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004234 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004235 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004236}
4237
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004238LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4239 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004240 const ObjCIvarDecl *Ivar,
4241 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004242 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004243 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004244}
4245
4246LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004247 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004248 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004249 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004250 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004251 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004252 if (E->isArrow()) {
4253 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004254 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004255 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004256 } else {
4257 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004258 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004259 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004260 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004261 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004262
Craig Topper99e79272013-07-26 05:59:26 +00004263 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004264 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4265 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004266 setObjCGCLValueClass(getContext(), E, LV);
4267 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004268}
4269
Chris Lattnera4185c52009-04-25 19:35:26 +00004270LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004271 // Can only get l-value for message expression returning aggregate type
4272 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004273 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004274 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnera4185c52009-04-25 19:35:26 +00004275}
4276
John McCallb92ab1a2016-10-26 23:46:34 +00004277RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004278 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004279 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004280 // Get the actual function type. The callee type will always be a pointer to
4281 // function type or a block pointer type.
4282 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004283 "Call must have function pointer type!");
4284
John McCallb92ab1a2016-10-26 23:46:34 +00004285 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004286
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004287 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004288 // We can only guarantee that a function is called from the correct
4289 // context/function based on the appropriate target attributes,
4290 // so only check in the case where we have both always_inline and target
4291 // since otherwise we could be making a conditional call after a check for
4292 // the proper cpu features (and it won't cause code generation issues due to
4293 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004294 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4295 TargetDecl->hasAttr<TargetAttr>())
4296 checkTargetFeatures(E, FD);
4297
John McCall6fd4c232009-10-23 08:22:42 +00004298 CalleeType = getContext().getCanonicalType(CalleeType);
4299
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004300 const auto *FnType =
4301 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004302
John McCallb92ab1a2016-10-26 23:46:34 +00004303 CGCallee Callee = OrigCallee;
4304
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004305 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004306 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4307 if (llvm::Constant *PrefixSig =
4308 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004309 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004310 llvm::Constant *FTRTTIConst =
4311 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4312 llvm::Type *PrefixStructTyElems[] = {
4313 PrefixSig->getType(),
4314 FTRTTIConst->getType()
4315 };
4316 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4317 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4318
John McCallb92ab1a2016-10-26 23:46:34 +00004319 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4320
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004321 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004322 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004323 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004324 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004325 llvm::Value *CalleeSig =
4326 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004327 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4328
4329 llvm::BasicBlock *Cont = createBasicBlock("cont");
4330 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4331 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4332
4333 EmitBlock(TypeCheck);
4334 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004335 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004336 llvm::Value *CalleeRTTI =
4337 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004338 llvm::Value *CalleeRTTIMatch =
4339 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4340 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004341 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004342 EmitCheckTypeDescriptor(CalleeType)
4343 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004344 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004345 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004346
4347 Builder.CreateBr(Cont);
4348 EmitBlock(Cont);
4349 }
4350 }
4351
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004352 // If we are checking indirect calls and this call is indirect, check that the
4353 // function pointer is a member of the bit set for the function type.
4354 if (SanOpts.has(SanitizerKind::CFIICall) &&
4355 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4356 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004357 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004358
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004359 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004360 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004361
John McCallb92ab1a2016-10-26 23:46:34 +00004362 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4363 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004364 llvm::Value *TypeTest = Builder.CreateCall(
4365 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004366
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004367 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004368 llvm::Constant *StaticData[] = {
4369 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4370 EmitCheckSourceLocation(E->getLocStart()),
4371 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4372 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004373 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4374 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004375 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004376 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004377 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004378 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004379 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004380 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004381 }
4382
Daniel Dunbarc722b852008-08-30 03:02:31 +00004383 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004384 if (Chain)
4385 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4386 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004387
4388 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004389 // right-to-left, and that we evaluate arguments to certain other operators
4390 // left-to-right. Note that we allow this to override the order dictated by
4391 // the calling convention on the MS ABI, which means that parameter
4392 // destruction order is not necessarily reverse construction order.
4393 // FIXME: Revisit this based on C++ committee response to unimplementability.
4394 EvaluationOrder Order = EvaluationOrder::Default;
4395 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4396 if (OCE->isAssignmentOp())
4397 Order = EvaluationOrder::ForceRightToLeft;
4398 else {
4399 switch (OCE->getOperator()) {
4400 case OO_LessLess:
4401 case OO_GreaterGreater:
4402 case OO_AmpAmp:
4403 case OO_PipePipe:
4404 case OO_Comma:
4405 case OO_ArrowStar:
4406 Order = EvaluationOrder::ForceLeftToRight;
4407 break;
4408 default:
4409 break;
4410 }
4411 }
4412 }
Richard Smith762672a2016-09-28 19:09:10 +00004413
David Blaikief05779e2015-07-21 18:37:18 +00004414 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004415 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004416
Peter Collingbournef7706832014-12-12 23:41:25 +00004417 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4418 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004419
4420 // C99 6.5.2.2p6:
4421 // If the expression that denotes the called function has a type
4422 // that does not include a prototype, [the default argument
4423 // promotions are performed]. If the number of arguments does not
4424 // equal the number of parameters, the behavior is undefined. If
4425 // the function is defined with a type that includes a prototype,
4426 // and either the prototype ends with an ellipsis (, ...) or the
4427 // types of the arguments after promotion are not compatible with
4428 // the types of the parameters, the behavior is undefined. If the
4429 // function is defined with a type that does not include a
4430 // prototype, and the types of the arguments after promotion are
4431 // not compatible with those of the parameters after promotion,
4432 // the behavior is undefined [except in some trivial cases].
4433 // That is, in the general case, we should assume that a call
4434 // through an unprototyped function type works like a *non-variadic*
4435 // call. The way we make this work is to cast to the exact type
4436 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004437 //
4438 // Chain calls use this same code path to add the invisible chain parameter
4439 // to the function type.
4440 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004441 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004442 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004443
4444 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4445 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4446 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004447 }
4448
John McCallb92ab1a2016-10-26 23:46:34 +00004449 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004450}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004451
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004452LValue CodeGenFunction::
4453EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004454 Address BaseAddr = Address::invalid();
4455 if (E->getOpcode() == BO_PtrMemI) {
4456 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4457 } else {
4458 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4459 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004460
John McCallc134eb52010-08-31 21:07:20 +00004461 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4462
4463 const MemberPointerType *MPT
4464 = E->getRHS()->getType()->getAs<MemberPointerType>();
4465
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004466 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00004467 Address MemberAddr =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004468 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
John McCallc134eb52010-08-31 21:07:20 +00004469
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004470 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004471}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004472
John McCall47fb9502013-03-07 21:37:08 +00004473/// Given the address of a temporary variable, produce an r-value of
4474/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004475RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004476 QualType type,
4477 SourceLocation loc) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004478 LValue lvalue = MakeAddrLValue(addr, type,
4479 LValueBaseInfo(AlignmentSource::Decl, false));
John McCall47fb9502013-03-07 21:37:08 +00004480 switch (getEvaluationKind(type)) {
4481 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004482 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004483 case TEK_Aggregate:
4484 return lvalue.asAggregateRValue();
4485 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004486 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004487 }
4488 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004489}
4490
Duncan Sandse81111c2012-04-10 08:23:07 +00004491void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004492 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004493 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004494 return;
4495
Duncan Sands65229ed2012-04-16 16:29:47 +00004496 llvm::MDBuilder MDHelper(getLLVMContext());
4497 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004498
Duncan Sands6fc46192012-04-14 12:37:26 +00004499 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004500}
John McCallfe96e0b2011-11-06 09:01:30 +00004501
4502namespace {
4503 struct LValueOrRValue {
4504 LValue LV;
4505 RValue RV;
4506 };
4507}
4508
4509static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4510 const PseudoObjectExpr *E,
4511 bool forLValue,
4512 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004513 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004514
4515 // Find the result expression, if any.
4516 const Expr *resultExpr = E->getResultExpr();
4517 LValueOrRValue result;
4518
4519 for (PseudoObjectExpr::const_semantics_iterator
4520 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4521 const Expr *semantic = *i;
4522
4523 // If this semantic expression is an opaque value, bind it
4524 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004525 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004526
4527 // If this is the result expression, we may need to evaluate
4528 // directly into the slot.
4529 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4530 OVMA opaqueData;
4531 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004532 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004533 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004534 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
John McCall7f416cc2015-09-08 08:05:57 +00004535 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004536 BaseInfo);
John McCallfe96e0b2011-11-06 09:01:30 +00004537 opaqueData = OVMA::bind(CGF, ov, LV);
4538 result.RV = slot.asRValue();
4539
4540 // Otherwise, emit as normal.
4541 } else {
4542 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4543
4544 // If this is the result, also evaluate the result now.
4545 if (ov == resultExpr) {
4546 if (forLValue)
4547 result.LV = CGF.EmitLValue(ov);
4548 else
4549 result.RV = CGF.EmitAnyExpr(ov, slot);
4550 }
4551 }
4552
4553 opaques.push_back(opaqueData);
4554
4555 // Otherwise, if the expression is the result, evaluate it
4556 // and remember the result.
4557 } else if (semantic == resultExpr) {
4558 if (forLValue)
4559 result.LV = CGF.EmitLValue(semantic);
4560 else
4561 result.RV = CGF.EmitAnyExpr(semantic, slot);
4562
4563 // Otherwise, evaluate the expression in an ignored context.
4564 } else {
4565 CGF.EmitIgnoredExpr(semantic);
4566 }
4567 }
4568
4569 // Unbind all the opaques now.
4570 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4571 opaques[i].unbind(CGF);
4572
4573 return result;
4574}
4575
4576RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4577 AggValueSlot slot) {
4578 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4579}
4580
4581LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4582 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4583}