blob: cef6292c0e4d9355517cbbc7c89e07f46069bf26 [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())
377 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
378
Richard Smitha509f2f2013-06-14 03:07:01 +0000379 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
380 }
John McCall7f416cc2015-09-08 08:05:57 +0000381 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
382 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000383
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000384 switch (getEvaluationKind(E->getType())) {
385 default: llvm_unreachable("expected scalar or aggregate expression");
386 case TEK_Scalar:
387 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
388 break;
389 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000390 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000391 E->getType().getQualifiers(),
392 AggValueSlot::IsDestructed,
393 AggValueSlot::DoesNotNeedGCBarriers,
394 AggValueSlot::IsNotAliased));
395 break;
396 }
397 }
Richard Smith736a9472013-06-12 20:42:33 +0000398
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000399 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000400 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000401 }
402
Richard Smithf3fabd22013-06-03 00:17:11 +0000403 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000404 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000405 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
406
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000407 for (const auto &Ignored : CommaLHSs)
408 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000409
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000410 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000411 if (opaque->getType()->isRecordType()) {
412 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000413 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000414 }
415 }
416
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000417 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000418 Address Object = createReferenceTemporary(*this, M, E);
419 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
420 Object = Address(llvm::ConstantExpr::getBitCast(
421 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
422 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000423 // If the temporary is a global and has a constant initializer or is a
424 // constant temporary that we promoted to a global, we may have already
425 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000426 if (!Var->hasInitializer()) {
427 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
428 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
429 }
430 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000431 switch (M->getStorageDuration()) {
432 case SD_Automatic:
433 case SD_FullExpression:
434 if (auto *Size = EmitLifetimeStart(
435 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
436 Object.getPointer())) {
437 if (M->getStorageDuration() == SD_Automatic)
438 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
439 Object, Size);
440 else
441 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
442 Size);
443 }
444 break;
445 default:
446 break;
447 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000448 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
449 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000450 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000451
Richard Smith736a9472013-06-12 20:42:33 +0000452 // Perform derived-to-base casts and/or field accesses, to get from the
453 // temporary object we created (and, potentially, for which we extended
454 // the lifetime) to the subobject we're binding the reference to.
455 for (unsigned I = Adjustments.size(); I != 0; --I) {
456 SubobjectAdjustment &Adjustment = Adjustments[I-1];
457 switch (Adjustment.Kind) {
458 case SubobjectAdjustment::DerivedToBaseAdjustment:
459 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000460 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
461 Adjustment.DerivedToBase.BasePath->path_begin(),
462 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000463 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000464 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000465
Richard Smith736a9472013-06-12 20:42:33 +0000466 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000467 LValue LV = MakeAddrLValue(Object, E->getType(),
468 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000469 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000470 assert(LV.isSimple() &&
471 "materialized temporary field is not a simple lvalue");
472 Object = LV.getAddress();
473 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000474 }
475
Richard Smith736a9472013-06-12 20:42:33 +0000476 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000477 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000478 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
479 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000480 break;
481 }
482 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000483 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000484
John McCall7f416cc2015-09-08 08:05:57 +0000485 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000486}
487
488RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000489CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
490 // Emit the expression as an lvalue.
491 LValue LV = EmitLValue(E);
492 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000493 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000494
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000495 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000496 // C++11 [dcl.ref]p5 (as amended by core issue 453):
497 // If a glvalue to which a reference is directly bound designates neither
498 // an existing object or function of an appropriate type nor a region of
499 // storage of suitable size and alignment to contain an object of the
500 // reference's type, the behavior is undefined.
501 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000502 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000503 }
John McCall8680f872010-07-21 06:29:51 +0000504
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000505 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000506}
507
508
Mike Stump4a3999f2009-09-09 13:00:44 +0000509/// getAccessedFieldNo - Given an encoded value and a result number, return the
510/// input field number being accessed.
511unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000512 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000513 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
514 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000515}
516
Richard Smith4d3110a2012-10-25 02:14:12 +0000517/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
518static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
519 llvm::Value *High) {
520 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
521 llvm::Value *K47 = Builder.getInt64(47);
522 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
523 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
524 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
525 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
526 return Builder.CreateMul(B1, KMul);
527}
528
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000529bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000530 return SanOpts.has(SanitizerKind::Null) |
531 SanOpts.has(SanitizerKind::Alignment) |
532 SanOpts.has(SanitizerKind::ObjectSize) |
533 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000534}
535
Richard Smithe30752c2012-10-09 19:52:38 +0000536void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000537 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000538 CharUnits Alignment,
539 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000540 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000541 return;
542
Richard Smith2d8b2942012-11-01 07:22:08 +0000543 // Don't check pointers outside the default address space. The null check
544 // isn't correct, the object-size check isn't supported by LLVM, and we can't
545 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000546 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000547 return;
548
Alexey Samsonov24cad992014-07-17 18:46:27 +0000549 SanitizerScope SanScope(this);
550
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000551 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000552 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000553
Vedant Kumare859ebb2017-04-26 02:17:21 +0000554 // Quickly determine whether we have a pointer to an alloca. It's possible
555 // to skip null checks, and some alignment checks, for these pointers. This
556 // can reduce compile-time significantly.
557 auto PtrToAlloca =
558 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
559
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000560 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
561 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000562 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumare859ebb2017-04-26 02:17:21 +0000563 !SkippedChecks.has(SanitizerKind::Null) && !PtrToAlloca) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000564 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000565 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000566
Vedant Kumardbbdda42017-04-17 22:26:10 +0000567 // The IR builder can constant-fold the null check if the pointer points to
568 // a constant.
569 bool PtrIsNonNull =
570 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext());
571
572 // Skip the null check if the pointer is known to be non-null.
573 if (!PtrIsNonNull) {
574 if (AllowNullPointers) {
575 // When performing pointer casts, it's OK if the value is null.
576 // Skip the remaining checks in that case.
577 Done = createBasicBlock("null");
578 llvm::BasicBlock *Rest = createBasicBlock("not.null");
579 Builder.CreateCondBr(IsNonNull, Rest, Done);
580 EmitBlock(Rest);
581 } else {
582 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
583 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000584 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000585 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000586
Vedant Kumar18348ea2017-02-17 23:22:55 +0000587 if (SanOpts.has(SanitizerKind::ObjectSize) &&
588 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
589 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000590 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000591
Richard Smith69d0d262012-08-24 00:54:33 +0000592 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000593 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000594 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000595 // FIXME: Get object address space
596 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
597 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000598 llvm::Value *Min = Builder.getFalse();
George Burgess IVa63f9152017-03-21 20:09:35 +0000599 llvm::Value *NullIsUnknown = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000600 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
George Burgess IVa63f9152017-03-21 20:09:35 +0000601 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
602 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
603 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000604 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000605 }
Richard Smith69d0d262012-08-24 00:54:33 +0000606
Richard Smithb1b0ab42012-11-05 22:21:05 +0000607 uint64_t AlignVal = 0;
608
Vedant Kumar18348ea2017-02-17 23:22:55 +0000609 if (SanOpts.has(SanitizerKind::Alignment) &&
610 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000611 AlignVal = Alignment.getQuantity();
612 if (!Ty->isIncompleteType() && !AlignVal)
613 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
614
Richard Smith69d0d262012-08-24 00:54:33 +0000615 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000616 if (AlignVal > 1 &&
617 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000618 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000619 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000620 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
621 llvm::Value *Aligned =
622 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000623 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000624 }
Richard Smith69d0d262012-08-24 00:54:33 +0000625 }
626
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000627 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000628 // Make sure we're not losing information. Alignment needs to be a power of
629 // 2
630 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000631 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000632 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
633 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
634 llvm::ConstantInt::get(Int8Ty, TCK)};
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000635 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000636 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000637
Richard Smithb1b0ab42012-11-05 22:21:05 +0000638 // If possible, check that the vptr indicates that there is a subobject of
639 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000640 //
641 // C++11 [basic.life]p5,6:
642 // [For storage which does not refer to an object within its lifetime]
643 // The program has undefined behavior if:
644 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000645 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000646 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000647 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumar18348ea2017-02-17 23:22:55 +0000648 !SkippedChecks.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000649 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000650 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
651 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000652 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000653 // Compute a hash of the mangled name of the type.
654 //
655 // FIXME: This is not guaranteed to be deterministic! Move to a
656 // fingerprinting mechanism once LLVM provides one. For the time
657 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000658 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000659 llvm::raw_svector_ostream Out(MangledName);
660 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
661 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000662
Alexey Samsonov84856012014-07-10 22:34:19 +0000663 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000664 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
665 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000666 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000667
Alexey Samsonov84856012014-07-10 22:34:19 +0000668 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
669 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
670 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000671 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000672 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
673 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000674
Alexey Samsonov84856012014-07-10 22:34:19 +0000675 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
676 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000677
Alexey Samsonov84856012014-07-10 22:34:19 +0000678 // Look the hash up in our cache.
679 const int CacheSize = 128;
680 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
681 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
682 "__ubsan_vptr_type_cache");
683 llvm::Value *Slot = Builder.CreateAnd(Hash,
684 llvm::ConstantInt::get(IntPtrTy,
685 CacheSize-1));
686 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
687 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000688 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
689 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000690
691 // If the hash isn't in the cache, call a runtime handler to perform the
692 // hard work of checking whether the vptr is for an object of the right
693 // type. This will either fill in the cache and return, or produce a
694 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000695 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000696 llvm::Constant *StaticData[] = {
697 EmitCheckSourceLocation(Loc),
698 EmitCheckTypeDescriptor(Ty),
699 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
700 llvm::ConstantInt::get(Int8Ty, TCK)
701 };
John McCall7f416cc2015-09-08 08:05:57 +0000702 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000703 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000704 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
705 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000706 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000707 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000708
709 if (Done) {
710 Builder.CreateBr(Done);
711 EmitBlock(Done);
712 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000713}
Chris Lattner4647a212007-08-31 22:49:20 +0000714
Richard Smith539e4a72013-02-23 02:53:19 +0000715/// Determine whether this expression refers to a flexible array member in a
716/// struct. We disable array bounds checks for such members.
717static bool isFlexibleArrayMemberExpr(const Expr *E) {
718 // For compatibility with existing code, we treat arrays of length 0 or
719 // 1 as flexible array members.
720 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000721 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000722 if (CAT->getSize().ugt(1))
723 return false;
724 } else if (!isa<IncompleteArrayType>(AT))
725 return false;
726
727 E = E->IgnoreParens();
728
729 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000730 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000731 // FIXME: If the base type of the member expr is not FD->getParent(),
732 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000733 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000734 RecordDecl::field_iterator FI(
735 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
736 return ++FI == FD->getParent()->field_end();
737 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000738 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
739 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000740 }
741
742 return false;
743}
744
745/// If Base is known to point to the start of an array, return the length of
746/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000747static llvm::Value *getArrayIndexingBound(
748 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000749 // For the vector indexing extension, the bound is the number of elements.
750 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
751 IndexedType = Base->getType();
752 return CGF.Builder.getInt32(VT->getNumElements());
753 }
754
755 Base = Base->IgnoreParens();
756
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000757 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000758 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
759 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
760 IndexedType = CE->getSubExpr()->getType();
761 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000762 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000763 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000764 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000765 return CGF.getVLASize(VAT).first;
766 }
767 }
768
Craig Topper8a13c412014-05-21 05:09:00 +0000769 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000770}
771
772void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
773 llvm::Value *Index, QualType IndexType,
774 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000775 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000776 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000777 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000778
Richard Smith539e4a72013-02-23 02:53:19 +0000779 QualType IndexedType;
780 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
781 if (!Bound)
782 return;
783
784 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
785 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
786 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
787
788 llvm::Constant *StaticData[] = {
789 EmitCheckSourceLocation(E->getExprLoc()),
790 EmitCheckTypeDescriptor(IndexedType),
791 EmitCheckTypeDescriptor(IndexType)
792 };
793 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
794 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000795 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
796 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000797}
798
Chris Lattner116ce8f2010-01-09 21:40:03 +0000799
Chris Lattner116ce8f2010-01-09 21:40:03 +0000800CodeGenFunction::ComplexPairTy CodeGenFunction::
801EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
802 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000803 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000804
Chris Lattner116ce8f2010-01-09 21:40:03 +0000805 llvm::Value *NextVal;
806 if (isa<llvm::IntegerType>(InVal.first->getType())) {
807 uint64_t AmountVal = isInc ? 1 : -1;
808 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000809
Chris Lattner116ce8f2010-01-09 21:40:03 +0000810 // Add the inc/dec to the real part.
811 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
812 } else {
813 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
814 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
815 if (!isInc)
816 FVal.changeSign();
817 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000818
Chris Lattner116ce8f2010-01-09 21:40:03 +0000819 // Add the inc/dec to the real part.
820 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
821 }
Craig Topper99e79272013-07-26 05:59:26 +0000822
Chris Lattner116ce8f2010-01-09 21:40:03 +0000823 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000824
Chris Lattner116ce8f2010-01-09 21:40:03 +0000825 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000826 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000827
Chris Lattner116ce8f2010-01-09 21:40:03 +0000828 // If this is a postinc, return the value read from memory, otherwise use the
829 // updated value.
830 return isPre ? IncVal : InVal;
831}
832
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000833void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
834 CodeGenFunction *CGF) {
835 // Bind VLAs in the cast type.
836 if (CGF && E->getType()->isVariablyModifiedType())
837 CGF->EmitVariablyModifiedType(E->getType());
838
839 if (CGDebugInfo *DI = getModuleDebugInfo())
840 DI->EmitExplicitCastType(E->getType());
841}
842
Chris Lattnera45c5af2007-06-02 19:47:04 +0000843//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000844// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000845//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000846
John McCall7f416cc2015-09-08 08:05:57 +0000847/// EmitPointerWithAlignment - Given an expression of pointer type, try to
848/// derive a more accurate bound on the alignment of the pointer.
849Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
850 AlignmentSource *Source) {
851 // We allow this with ObjC object pointers because of fragile ABIs.
852 assert(E->getType()->isPointerType() ||
853 E->getType()->isObjCObjectPointerType());
854 E = E->IgnoreParens();
855
856 // Casts:
857 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000858 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
859 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000860
861 switch (CE->getCastKind()) {
862 // Non-converting casts (but not C's implicit conversion from void*).
863 case CK_BitCast:
864 case CK_NoOp:
865 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
866 if (PtrTy->getPointeeType()->isVoidType())
867 break;
868
869 AlignmentSource InnerSource;
870 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
871 if (Source) *Source = InnerSource;
872
873 // If this is an explicit bitcast, and the source l-value is
874 // opaque, honor the alignment of the casted-to type.
875 if (isa<ExplicitCastExpr>(CE) &&
John McCall7f416cc2015-09-08 08:05:57 +0000876 InnerSource != AlignmentSource::Decl) {
877 Addr = Address(Addr.getPointer(),
878 getNaturalPointeeTypeAlignment(E->getType(), Source));
879 }
880
Peter Collingbourne574975e2016-01-14 02:49:48 +0000881 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
882 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000883 if (auto PT = E->getType()->getAs<PointerType>())
884 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
885 /*MayBeNull=*/true,
886 CodeGenFunction::CFITCK_UnrelatedCast,
887 CE->getLocStart());
888 }
889
John McCall7f416cc2015-09-08 08:05:57 +0000890 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
891 }
892 break;
893
894 // Array-to-pointer decay.
895 case CK_ArrayToPointerDecay:
896 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
897
898 // Derived-to-base conversions.
899 case CK_UncheckedDerivedToBase:
900 case CK_DerivedToBase: {
901 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
902 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
903 return GetAddressOfBaseClass(Addr, Derived,
904 CE->path_begin(), CE->path_end(),
905 ShouldNullCheckClassCastValue(CE),
906 CE->getExprLoc());
907 }
908
909 // TODO: Is there any reason to treat base-to-derived conversions
910 // specially?
911 default:
912 break;
913 }
914 }
915
916 // Unary &.
917 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
918 if (UO->getOpcode() == UO_AddrOf) {
919 LValue LV = EmitLValue(UO->getSubExpr());
920 if (Source) *Source = LV.getAlignmentSource();
921 return LV.getAddress();
922 }
923 }
924
925 // TODO: conditional operators, comma.
926
927 // Otherwise, use the alignment of the type.
928 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
929 return Address(EmitScalarExpr(E), Align);
930}
931
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000932RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000933 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000934 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000935
936 switch (getEvaluationKind(Ty)) {
937 case TEK_Complex: {
938 llvm::Type *EltTy =
939 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000940 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000941 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000942 }
Craig Topper99e79272013-07-26 05:59:26 +0000943
Chris Lattner65526f02010-08-23 05:26:13 +0000944 // If this is a use of an undefined aggregate type, the aggregate must have an
945 // identifiable address. Just because the contents of the value are undefined
946 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000947 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000948 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000949 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000950 }
John McCall47fb9502013-03-07 21:37:08 +0000951
952 case TEK_Scalar:
953 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
954 }
955 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000956}
957
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000958RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
959 const char *Name) {
960 ErrorUnsupported(E, Name);
961 return GetUndefRValue(E->getType());
962}
963
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000964LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
965 const char *Name) {
966 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000967 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000968 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
969 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000970}
971
Vedant Kumarffd7c882017-04-14 22:03:34 +0000972bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000973 const Expr *Base = Obj;
974 while (!isa<CXXThisExpr>(Base)) {
975 // The result of a dynamic_cast can be null.
976 if (isa<CXXDynamicCastExpr>(Base))
977 return false;
978
979 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
980 Base = CE->getSubExpr();
981 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
982 Base = PE->getSubExpr();
983 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
984 if (UO->getOpcode() == UO_Extension)
985 Base = UO->getSubExpr();
986 else
987 return false;
988 } else {
989 return false;
990 }
991 }
992 return true;
993}
994
Richard Smith4d1458e2012-09-08 02:08:36 +0000995LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000996 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000997 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000998 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
999 else
1000 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001001 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1002 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001003 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1004 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1005 if (IsBaseCXXThis)
1006 SkippedChecks.set(SanitizerKind::Alignment, true);
1007 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001008 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001009 }
John McCall7f416cc2015-09-08 08:05:57 +00001010 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001011 E->getType(), LV.getAlignment(), SkippedChecks);
1012 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001013 return LV;
1014}
1015
Chris Lattner8394d792007-06-05 20:53:16 +00001016/// EmitLValue - Emit code to compute a designator that specifies the location
1017/// of the expression.
1018///
Mike Stump4a3999f2009-09-09 13:00:44 +00001019/// This can return one of two things: a simple address or a bitfield reference.
1020/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1021/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001022///
Mike Stump4a3999f2009-09-09 13:00:44 +00001023/// If this returns a bitfield reference, nothing about the pointee type of the
1024/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001025///
Mike Stump4a3999f2009-09-09 13:00:44 +00001026/// If this returns a normal address, and if the lvalue's C type is fixed size,
1027/// this method guarantees that the returned pointer type will point to an LLVM
1028/// type of the same size of the lvalue's type. If the lvalue has a variable
1029/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001030///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001031LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001032 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001033 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001034 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001035
John McCallc109a252011-11-07 03:59:57 +00001036 case Expr::ObjCPropertyRefExprClass:
1037 llvm_unreachable("cannot emit a property reference directly");
1038
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001039 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001040 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001041 case Expr::ObjCIsaExprClass:
1042 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001043 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001044 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001045 case Expr::CompoundAssignOperatorClass: {
1046 QualType Ty = E->getType();
1047 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1048 Ty = AT->getValueType();
1049 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001050 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1051 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001052 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001053 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001054 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001055 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001056 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001057 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001058 case Expr::VAArgExprClass:
1059 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001060 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001061 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001062 case Expr::ParenExprClass:
1063 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001064 case Expr::GenericSelectionExprClass:
1065 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001066 case Expr::PredefinedExprClass:
1067 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001068 case Expr::StringLiteralClass:
1069 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001070 case Expr::ObjCEncodeExprClass:
1071 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001072 case Expr::PseudoObjectExprClass:
1073 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001074 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001075 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001076 case Expr::CXXTemporaryObjectExprClass:
1077 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001078 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1079 case Expr::CXXBindTemporaryExprClass:
1080 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001081 case Expr::CXXUuidofExprClass:
1082 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001083 case Expr::LambdaExprClass:
1084 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001085
1086 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001087 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001088 enterFullExpression(cleanups);
1089 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001090 LValue LV = EmitLValue(cleanups->getSubExpr());
1091 if (LV.isSimple()) {
1092 // Defend against branches out of gnu statement expressions surrounded by
1093 // cleanups.
1094 llvm::Value *V = LV.getPointer();
1095 Scope.ForceCleanup({&V});
1096 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1097 getContext(), LV.getAlignmentSource(),
1098 LV.getTBAAInfo());
1099 }
1100 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1101 // bitfield lvalue or some other non-simple lvalue?
1102 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001103 }
1104
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001105 case Expr::CXXDefaultArgExprClass:
1106 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001107 case Expr::CXXDefaultInitExprClass: {
1108 CXXDefaultInitExprScope Scope(*this);
1109 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1110 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001111 case Expr::CXXTypeidExprClass:
1112 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001113
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001114 case Expr::ObjCMessageExprClass:
1115 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001116 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001117 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001118 case Expr::StmtExprClass:
1119 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001120 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001121 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001122 case Expr::ArraySubscriptExprClass:
1123 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001124 case Expr::OMPArraySectionExprClass:
1125 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001126 case Expr::ExtVectorElementExprClass:
1127 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001128 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001129 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001130 case Expr::CompoundLiteralExprClass:
1131 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001132 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001133 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001134 case Expr::BinaryConditionalOperatorClass:
1135 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001136 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001137 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001138 case Expr::OpaqueValueExprClass:
1139 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001140 case Expr::SubstNonTypeTemplateParmExprClass:
1141 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001142 case Expr::ImplicitCastExprClass:
1143 case Expr::CStyleCastExprClass:
1144 case Expr::CXXFunctionalCastExprClass:
1145 case Expr::CXXStaticCastExprClass:
1146 case Expr::CXXDynamicCastExprClass:
1147 case Expr::CXXReinterpretCastExprClass:
1148 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001149 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001150 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001151
Douglas Gregorfe314812011-06-21 17:03:29 +00001152 case Expr::MaterializeTemporaryExprClass:
1153 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001154 }
1155}
1156
John McCall71335052012-03-10 03:05:10 +00001157/// Given an object of the given canonical type, can we safely copy a
1158/// value out of it based on its initializer?
1159static bool isConstantEmittableObjectType(QualType type) {
1160 assert(type.isCanonical());
1161 assert(!type->isReferenceType());
1162
1163 // Must be const-qualified but non-volatile.
1164 Qualifiers qs = type.getLocalQualifiers();
1165 if (!qs.hasConst() || qs.hasVolatile()) return false;
1166
1167 // Otherwise, all object types satisfy this except C++ classes with
1168 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001169 if (const auto *RT = dyn_cast<RecordType>(type))
1170 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001171 if (RD->hasMutableFields() || !RD->isTrivial())
1172 return false;
1173
1174 return true;
1175}
1176
1177/// Can we constant-emit a load of a reference to a variable of the
1178/// given type? This is different from predicates like
1179/// Decl::isUsableInConstantExpressions because we do want it to apply
1180/// in situations that don't necessarily satisfy the language's rules
1181/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1182/// to do this with const float variables even if those variables
1183/// aren't marked 'constexpr'.
1184enum ConstantEmissionKind {
1185 CEK_None,
1186 CEK_AsReferenceOnly,
1187 CEK_AsValueOrReference,
1188 CEK_AsValueOnly
1189};
1190static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1191 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001192 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001193 if (isConstantEmittableObjectType(ref->getPointeeType()))
1194 return CEK_AsValueOrReference;
1195 return CEK_AsReferenceOnly;
1196 }
1197 if (isConstantEmittableObjectType(type))
1198 return CEK_AsValueOnly;
1199 return CEK_None;
1200}
1201
1202/// Try to emit a reference to the given value without producing it as
1203/// an l-value. This is actually more than an optimization: we can't
1204/// produce an l-value for variables that we never actually captured
1205/// in a block or lambda, which means const int variables or constexpr
1206/// literals or similar.
1207CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001208CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1209 ValueDecl *value = refExpr->getDecl();
1210
John McCall71335052012-03-10 03:05:10 +00001211 // The value needs to be an enum constant or a constant variable.
1212 ConstantEmissionKind CEK;
1213 if (isa<ParmVarDecl>(value)) {
1214 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001215 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001216 CEK = checkVarTypeForConstantEmission(var->getType());
1217 } else if (isa<EnumConstantDecl>(value)) {
1218 CEK = CEK_AsValueOnly;
1219 } else {
1220 CEK = CEK_None;
1221 }
1222 if (CEK == CEK_None) return ConstantEmission();
1223
John McCall71335052012-03-10 03:05:10 +00001224 Expr::EvalResult result;
1225 bool resultIsReference;
1226 QualType resultType;
1227
1228 // It's best to evaluate all the way as an r-value if that's permitted.
1229 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001230 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001231 resultIsReference = false;
1232 resultType = refExpr->getType();
1233
1234 // Otherwise, try to evaluate as an l-value.
1235 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001236 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001237 resultIsReference = true;
1238 resultType = value->getType();
1239
1240 // Failure.
1241 } else {
1242 return ConstantEmission();
1243 }
1244
1245 // In any case, if the initializer has side-effects, abandon ship.
1246 if (result.HasSideEffects)
1247 return ConstantEmission();
1248
1249 // Emit as a constant.
1250 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1251
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001252 // Make sure we emit a debug reference to the global variable.
1253 // This should probably fire even for
1254 if (isa<VarDecl>(value)) {
1255 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001256 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001257 } else {
1258 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001259 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001260 }
John McCall71335052012-03-10 03:05:10 +00001261
1262 // If we emitted a reference constant, we need to dereference that.
1263 if (resultIsReference)
1264 return ConstantEmission::forReference(C);
1265
1266 return ConstantEmission::forValue(C);
1267}
1268
Nick Lewycky2d84e842013-10-02 02:29:49 +00001269llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1270 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001271 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001272 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1273 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001274 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1275 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001276}
1277
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001278static bool hasBooleanRepresentation(QualType Ty) {
1279 if (Ty->isBooleanType())
1280 return true;
1281
1282 if (const EnumType *ET = Ty->getAs<EnumType>())
1283 return ET->getDecl()->getIntegerType()->isBooleanType();
1284
Douglas Gregor298f43d2012-04-12 20:42:30 +00001285 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1286 return hasBooleanRepresentation(AT->getValueType());
1287
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001288 return false;
1289}
1290
Richard Smith1629da92012-12-13 07:11:50 +00001291static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1292 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001293 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001294 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001295 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1296 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001297 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001298 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001299
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001300 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001301 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1302 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001303 } else {
1304 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001305 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001306 unsigned Bitwidth = LTy->getScalarSizeInBits();
1307 unsigned NumNegativeBits = ED->getNumNegativeBits();
1308 unsigned NumPositiveBits = ED->getNumPositiveBits();
1309
1310 if (NumNegativeBits) {
1311 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1312 assert(NumBits <= Bitwidth);
1313 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1314 Min = -End;
1315 } else {
1316 assert(NumPositiveBits <= Bitwidth);
1317 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1318 Min = llvm::APInt(Bitwidth, 0);
1319 }
1320 }
Richard Smith1629da92012-12-13 07:11:50 +00001321 return true;
1322}
1323
1324llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1325 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001326 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1327 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001328 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001329
Duncan Sandsc720e782012-04-15 18:04:54 +00001330 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001331 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001332}
1333
Vedant Kumar5a972652017-02-27 19:46:19 +00001334bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1335 SourceLocation Loc) {
1336 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1337 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1338 if (!HasBoolCheck && !HasEnumCheck)
1339 return false;
1340
1341 bool IsBool = hasBooleanRepresentation(Ty) ||
1342 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1343 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1344 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1345 if (!NeedsBoolCheck && !NeedsEnumCheck)
1346 return false;
1347
Vedant Kumar129edab2017-03-09 16:06:27 +00001348 // Single-bit booleans don't need to be checked. Special-case this to avoid
1349 // a bit width mismatch when handling bitfield values. This is handled by
1350 // EmitFromMemory for the non-bitfield case.
1351 if (IsBool &&
1352 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1353 return false;
1354
Vedant Kumar5a972652017-02-27 19:46:19 +00001355 llvm::APInt Min, End;
1356 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1357 return true;
1358
1359 SanitizerScope SanScope(this);
1360 llvm::Value *Check;
1361 --End;
1362 if (!Min) {
1363 Check = Builder.CreateICmpULE(
1364 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1365 } else {
1366 llvm::Value *Upper = Builder.CreateICmpSLE(
1367 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1368 llvm::Value *Lower = Builder.CreateICmpSGE(
1369 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1370 Check = Builder.CreateAnd(Upper, Lower);
1371 }
1372 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1373 EmitCheckTypeDescriptor(Ty)};
1374 SanitizerMask Kind =
1375 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1376 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1377 StaticArgs, EmitCheckValue(Value));
1378 return true;
1379}
1380
John McCall7f416cc2015-09-08 08:05:57 +00001381llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1382 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001383 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001384 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001385 llvm::MDNode *TBAAInfo,
1386 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001387 uint64_t TBAAOffset,
1388 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001389 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1390 // For better performance, handle vector loads differently.
1391 if (Ty->isVectorType()) {
1392 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001393
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001394 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001395
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001396 // Handle vectors of size 3 like size 4 for better performance.
1397 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001398
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001399 // Bitcast to vec4 type.
1400 llvm::VectorType *vec4Ty =
1401 llvm::VectorType::get(VTy->getElementType(), 4);
1402 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1403 // Now load value.
1404 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001405
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001406 // Shuffle vector to get vec3.
1407 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1408 {0, 1, 2}, "extractVec");
1409 return EmitFromMemory(V, Ty);
1410 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001411 }
1412 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001413
1414 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001415 LValue AtomicLValue =
John McCall7f416cc2015-09-08 08:05:57 +00001416 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001417 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1418 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001419 }
Craig Topper99e79272013-07-26 05:59:26 +00001420
John McCall7f416cc2015-09-08 08:05:57 +00001421 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001422 if (isNontemporal) {
1423 llvm::MDNode *Node = llvm::MDNode::get(
1424 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1425 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1426 }
Manman Renc451e572013-04-04 21:53:22 +00001427 if (TBAAInfo) {
1428 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1429 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001430 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001431 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1432 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001433 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001434
Vedant Kumar5a972652017-02-27 19:46:19 +00001435 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1436 // In order to prevent the optimizer from throwing away the check, don't
1437 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001438 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001439 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1440 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001441
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001442 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001443}
1444
John McCall3a7f6922010-10-27 20:58:56 +00001445llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1446 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001447 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001448 // This should really always be an i1, but sometimes it's already
1449 // an i8, and it's awkward to track those cases down.
1450 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001451 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1452 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1453 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001454 }
1455
1456 return Value;
1457}
1458
1459llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1460 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001461 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001462 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1463 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001464 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1465 }
1466
1467 return Value;
1468}
1469
John McCall7f416cc2015-09-08 08:05:57 +00001470void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1471 bool Volatile, QualType Ty,
1472 AlignmentSource AlignSource,
1473 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001474 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001475 uint64_t TBAAOffset,
1476 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001477
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001478 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1479 // Handle vectors differently to get better performance.
1480 if (Ty->isVectorType()) {
1481 llvm::Type *SrcTy = Value->getType();
1482 auto *VecTy = cast<llvm::VectorType>(SrcTy);
1483 // Handle vec3 special.
1484 if (VecTy->getNumElements() == 3) {
1485 // Our source is a vec3, do a shuffle vector to make it a vec4.
1486 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1487 Builder.getInt32(2),
1488 llvm::UndefValue::get(Builder.getInt32Ty())};
1489 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1490 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1491 MaskV, "extractVec");
1492 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1493 }
1494 if (Addr.getElementType() != SrcTy) {
1495 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1496 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001497 }
1498 }
Craig Topper99e79272013-07-26 05:59:26 +00001499
John McCall3a7f6922010-10-27 20:58:56 +00001500 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001501
David Majnemera38c9f12016-05-24 16:09:25 +00001502 LValue AtomicLValue =
1503 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001504 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001505 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1506 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001507 return;
1508 }
1509
Daniel Dunbar03816342010-08-21 02:24:36 +00001510 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001511 if (isNontemporal) {
1512 llvm::MDNode *Node =
1513 llvm::MDNode::get(Store->getContext(),
1514 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1515 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1516 }
Manman Renc451e572013-04-04 21:53:22 +00001517 if (TBAAInfo) {
1518 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1519 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001520 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001521 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1522 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001523 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001524}
1525
David Chisnallfa35df62012-01-16 17:27:18 +00001526void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001527 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001528 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001529 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001530 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001531 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001532}
1533
Mike Stump4a3999f2009-09-09 13:00:44 +00001534/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1535/// method emits the address of the lvalue, then loads the result as an rvalue,
1536/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001537RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001538 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001539 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001540 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001541 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1542 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001543 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001544 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001545 // In MRC mode, we do a load+autorelease.
1546 if (!getLangOpts().ObjCAutoRefCount) {
1547 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1548 }
1549
1550 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001551 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1552 Object = EmitObjCConsumeObject(LV.getType(), Object);
1553 return RValue::get(Object);
1554 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001555
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001556 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001557 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001558
John McCalla1dee5302010-08-22 10:59:02 +00001559 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001560 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001561 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001562
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001563 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001564 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001565 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001566 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001567 "vecext"));
1568 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001569
1570 // If this is a reference to a subset of the elements of a vector, either
1571 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001572 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001573 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001574
Renato Golin230c5eb2014-05-19 18:15:42 +00001575 // Global Register variables always invoke intrinsics
1576 if (LV.isGlobalReg())
1577 return EmitLoadOfGlobalRegLValue(LV);
1578
John McCallc109a252011-11-07 03:59:57 +00001579 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001580 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001581}
1582
Vedant Kumar129edab2017-03-09 16:06:27 +00001583RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1584 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001585 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001586
Daniel Dunbar3447a022010-04-13 23:34:15 +00001587 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001588 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001589
John McCall7f416cc2015-09-08 08:05:57 +00001590 Address Ptr = LV.getBitFieldAddress();
1591 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001592
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001593 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001594 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001595 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1596 if (HighBits)
1597 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1598 if (Info.Offset + HighBits)
1599 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1600 } else {
1601 if (Info.Offset)
1602 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001603 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001604 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1605 Info.Size),
1606 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001607 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001608 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001609 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001610 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001611}
1612
Nate Begemanb699c9b2009-01-18 06:42:49 +00001613// If this is a reference to a subset of the elements of a vector, create an
1614// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001615RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001616 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1617 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001618
Nate Begemanf322eab2008-05-09 06:41:27 +00001619 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001620
1621 // If the result of the expression is a non-vector type, we must be extracting
1622 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001623 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001624 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001625 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001626 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001627 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001628 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001629
1630 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001631 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001632
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001633 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001634 for (unsigned i = 0; i != NumResultElts; ++i)
1635 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001636
Chris Lattner91c08ad2011-02-15 00:14:06 +00001637 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1638 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001639 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001640 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001641}
1642
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001643/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001644Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1645 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001646 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1647 QualType EQT = ExprVT->getElementType();
1648 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001649
John McCall7f416cc2015-09-08 08:05:57 +00001650 Address CastToPointerElement =
1651 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1652 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001653
1654 const llvm::Constant *Elts = LV.getExtVectorElts();
1655 unsigned ix = getAccessedFieldNo(0, Elts);
1656
John McCall7f416cc2015-09-08 08:05:57 +00001657 Address VectorBasePtrPlusIx =
1658 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1659 getContext().getTypeSizeInChars(EQT),
1660 "vector.elt");
1661
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001662 return VectorBasePtrPlusIx;
1663}
1664
Renato Golin230c5eb2014-05-19 18:15:42 +00001665/// @brief Load of global gamed gegisters are always calls to intrinsics.
1666RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001667 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1668 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001669 llvm::MDNode *RegName = cast<llvm::MDNode>(
1670 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001671
1672 // We accept integer and pointer types only
1673 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1674 llvm::Type *Ty = OrigTy;
1675 if (OrigTy->isPointerTy())
1676 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1677 llvm::Type *Types[] = { Ty };
1678
Renato Golin230c5eb2014-05-19 18:15:42 +00001679 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001680 llvm::Value *Call = Builder.CreateCall(
1681 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001682 if (OrigTy->isPointerTy())
1683 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001684 return RValue::get(Call);
1685}
Chris Lattner40ff7012007-08-03 16:18:34 +00001686
Chris Lattner9369a562007-06-29 16:31:29 +00001687
Chris Lattner8394d792007-06-05 20:53:16 +00001688/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1689/// lvalue, where both are guaranteed to the have the same type, and that type
1690/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001691void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001692 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001693 if (!Dst.isSimple()) {
1694 if (Dst.isVectorElt()) {
1695 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001696 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1697 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001698 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001699 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001700 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1701 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001702 return;
1703 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001704
Nate Begemance4d7fc2008-04-18 23:10:10 +00001705 // If this is an update of extended vector elements, insert them as
1706 // appropriate.
1707 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001708 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001709
Renato Golin230c5eb2014-05-19 18:15:42 +00001710 if (Dst.isGlobalReg())
1711 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1712
John McCallc109a252011-11-07 03:59:57 +00001713 assert(Dst.isBitField() && "Unknown LValue type");
1714 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001715 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001716
John McCall31168b02011-06-15 23:02:42 +00001717 // There's special magic for assigning into an ARC-qualified l-value.
1718 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1719 switch (Lifetime) {
1720 case Qualifiers::OCL_None:
1721 llvm_unreachable("present but none");
1722
1723 case Qualifiers::OCL_ExplicitNone:
1724 // nothing special
1725 break;
1726
1727 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001728 if (isInit) {
1729 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1730 break;
1731 }
John McCall55e1fbc2011-06-25 02:11:03 +00001732 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001733 return;
1734
1735 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001736 if (isInit)
1737 // Initialize and then skip the primitive store.
1738 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1739 else
1740 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001741 return;
1742
1743 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001744 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1745 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001746 // fall into the normal path
1747 break;
1748 }
1749 }
1750
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001751 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001752 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001753 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001754 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001755 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001756 return;
1757 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001758
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001759 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001760 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001761 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001762 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001763 if (Dst.isObjCIvar()) {
1764 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001765 llvm::Type *ResultType = IntPtrTy;
1766 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1767 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001768 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001769 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001770 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1771 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001772 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001773 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001774 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001775 } else if (Dst.isGlobalObjCRef()) {
1776 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1777 Dst.isThreadLocalRef());
1778 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001779 else
1780 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001781 return;
1782 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001783
Chris Lattner6278e6a2007-08-11 00:04:45 +00001784 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001785 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001786}
1787
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001788void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001789 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001790 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001791 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001792 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001793
Daniel Dunbar67aba792010-04-15 03:47:33 +00001794 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001795 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001796
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001797 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001798 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001799 /*IsSigned=*/false);
1800 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001801
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001802 // See if there are other bits in the bitfield's storage we'll need to load
1803 // and mask together with source before storing.
1804 if (Info.StorageSize != Info.Size) {
1805 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001806 llvm::Value *Val =
1807 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001808
1809 // Mask the source value as needed.
1810 if (!hasBooleanRepresentation(Dst.getType()))
1811 SrcVal = Builder.CreateAnd(SrcVal,
1812 llvm::APInt::getLowBitsSet(Info.StorageSize,
1813 Info.Size),
1814 "bf.value");
1815 MaskedVal = SrcVal;
1816 if (Info.Offset)
1817 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1818
1819 // Mask out the original value.
1820 Val = Builder.CreateAnd(Val,
1821 ~llvm::APInt::getBitsSet(Info.StorageSize,
1822 Info.Offset,
1823 Info.Offset + Info.Size),
1824 "bf.clear");
1825
1826 // Or together the unchanged values and the source value.
1827 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1828 } else {
1829 assert(Info.Offset == 0);
1830 }
1831
1832 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001833 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001834
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001835 // Return the new value of the bit-field, if requested.
1836 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001837 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001838
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001839 // Sign extend the value if needed.
1840 if (Info.IsSigned) {
1841 assert(Info.Size <= Info.StorageSize);
1842 unsigned HighBits = Info.StorageSize - Info.Size;
1843 if (HighBits) {
1844 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1845 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1846 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001847 }
1848
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001849 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1850 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001851 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001852 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001853}
1854
Nate Begemance4d7fc2008-04-18 23:10:10 +00001855void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001856 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001857 // This access turns into a read/modify/write of the vector. Load the input
1858 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001859 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1860 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001861 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001862
Chris Lattner4647a212007-08-31 22:49:20 +00001863 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001864
John McCall55e1fbc2011-06-25 02:11:03 +00001865 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001866 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001867 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001868 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001869 // Use shuffle vector is the src and destination are the same number of
1870 // elements and restore the vector mask since it is on the side it will be
1871 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001872 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001873 for (unsigned i = 0; i != NumSrcElts; ++i)
1874 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001875
Chris Lattner91c08ad2011-02-15 00:14:06 +00001876 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001877 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001878 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001879 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001880 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001881 // Extended the source vector to the same length and then shuffle it
1882 // into the destination.
1883 // FIXME: since we're shuffling with undef, can we just use the indices
1884 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001885 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001886 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001887 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001888 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001889 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001890 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001891 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001892 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001893 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001894 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001895 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001896 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001897 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001898
Joey Goulycf4143b2013-11-21 17:09:05 +00001899 // When the vector size is odd and .odd or .hi is used, the last element
1900 // of the Elts constant array will be one past the size of the vector.
1901 // Ignore the last element here, if it is greater than the mask size.
1902 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1903 NumSrcElts--;
1904
Nate Begemanb699c9b2009-01-18 06:42:49 +00001905 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001906 for (unsigned i = 0; i != NumSrcElts; ++i)
1907 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001908 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001909 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001910 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001911 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001912 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001913 }
1914 } else {
1915 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001916 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001917 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001918 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001919 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001920
John McCall7f416cc2015-09-08 08:05:57 +00001921 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1922 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001923}
1924
Renato Golin230c5eb2014-05-19 18:15:42 +00001925/// @brief Store of global named registers are always calls to intrinsics.
1926void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001927 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1928 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001929 llvm::MDNode *RegName = cast<llvm::MDNode>(
1930 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001931 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001932
1933 // We accept integer and pointer types only
1934 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1935 llvm::Type *Ty = OrigTy;
1936 if (OrigTy->isPointerTy())
1937 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1938 llvm::Type *Types[] = { Ty };
1939
Renato Golin230c5eb2014-05-19 18:15:42 +00001940 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1941 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001942 if (OrigTy->isPointerTy())
1943 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001944 Builder.CreateCall(
1945 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001946}
1947
Eric Christopherc9e2a682014-05-20 17:10:39 +00001948// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001949// generating write-barries API. It is currently a global, ivar,
1950// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001951static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001952 LValue &LV,
1953 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001954 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001955 return;
Craig Topper99e79272013-07-26 05:59:26 +00001956
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001957 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001958 QualType ExpTy = E->getType();
1959 if (IsMemberAccess && ExpTy->isPointerType()) {
1960 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001961 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001962 // writer-barrier conservatively.
1963 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1964 if (ExpTy->isRecordType()) {
1965 LV.setObjCIvar(false);
1966 return;
1967 }
1968 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001969 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001970 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001971 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001972 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001973 return;
1974 }
Craig Topper99e79272013-07-26 05:59:26 +00001975
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001976 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1977 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001978 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001979 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001980 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001981 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001982 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001983 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001984 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001985 }
Craig Topper99e79272013-07-26 05:59:26 +00001986
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001987 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001988 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001989 return;
1990 }
Craig Topper99e79272013-07-26 05:59:26 +00001991
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001992 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001993 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001994 if (LV.isObjCIvar()) {
1995 // If cast is to a structure pointer, follow gcc's behavior and make it
1996 // a non-ivar write-barrier.
1997 QualType ExpTy = E->getType();
1998 if (ExpTy->isPointerType())
1999 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2000 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002001 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002002 }
2003 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002004 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002005
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002006 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002007 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2008 return;
2009 }
2010
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002011 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002012 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002013 return;
2014 }
Craig Topper99e79272013-07-26 05:59:26 +00002015
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002016 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002017 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002018 return;
2019 }
John McCall31168b02011-06-15 23:02:42 +00002020
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002021 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002022 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002023 return;
2024 }
2025
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002026 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002027 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002028 if (LV.isObjCIvar() && !LV.isObjCArray())
2029 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002030 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002031 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002032 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002033 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002034 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002035 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002036 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002037 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002038
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002039 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002040 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002041 // We don't know if member is an 'ivar', but this flag is looked at
2042 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002043 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002044 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002045 }
2046}
2047
Chris Lattner3f32d692011-07-12 06:52:18 +00002048static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002049EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002050 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002051 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002052 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002053 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002054}
2055
Alexey Bataev97720002014-11-11 04:05:39 +00002056static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002057 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2058 llvm::Type *RealVarTy, SourceLocation Loc) {
2059 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2060 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2061 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2062}
2063
2064Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2065 const ReferenceType *RefTy,
2066 AlignmentSource *Source) {
2067 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2068 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
2069 Source, /*forPointee*/ true));
2070
2071}
2072
2073LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2074 const ReferenceType *RefTy) {
2075 AlignmentSource Source;
2076 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
2077 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00002078}
2079
Alexey Bataev31300ed2016-02-04 11:27:03 +00002080Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2081 const PointerType *PtrTy,
2082 AlignmentSource *Source) {
2083 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2084 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
2085 /*forPointeeType=*/true));
2086}
2087
2088LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2089 const PointerType *PtrTy) {
2090 AlignmentSource Source;
2091 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
2092 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
2093}
2094
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002095static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2096 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002097 QualType T = E->getType();
2098
2099 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002100 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2101 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002102 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2103
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002104 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002105 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2106 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002107 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002108 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002109 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002110 // Emit reference to the private copy of the variable if it is an OpenMP
2111 // threadprivate variable.
2112 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002113 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002114 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002115 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2116 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002117 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002118 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002119 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002120 setObjCGCLValueClass(CGF.getContext(), E, LV);
2121 return LV;
2122}
2123
John McCallb92ab1a2016-10-26 23:46:34 +00002124static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2125 const FunctionDecl *FD) {
2126 if (FD->hasAttr<WeakRefAttr>()) {
2127 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2128 return aliasee.getPointer();
2129 }
2130
2131 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002132 if (!FD->hasPrototype()) {
2133 if (const FunctionProtoType *Proto =
2134 FD->getType()->getAs<FunctionProtoType>()) {
2135 // Ugly case: for a K&R-style definition, the type of the definition
2136 // isn't the same as the type of a use. Correct for this with a
2137 // bitcast.
2138 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002139 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2140 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2141 V = llvm::ConstantExpr::getBitCast(V,
2142 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002143 }
2144 }
John McCallb92ab1a2016-10-26 23:46:34 +00002145 return V;
2146}
2147
2148static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2149 const Expr *E, const FunctionDecl *FD) {
2150 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002151 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00002152 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002153}
2154
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002155static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2156 llvm::Value *ThisValue) {
2157 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2158 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2159 return CGF.EmitLValueForField(LV, FD);
2160}
2161
Renato Golin230c5eb2014-05-19 18:15:42 +00002162/// Named Registers are named metadata pointing to the register name
2163/// which will be read from/written to as an argument to the intrinsic
2164/// @llvm.read/write_register.
2165/// So far, only the name is being passed down, but other options such as
2166/// register type, allocation type or even optimization options could be
2167/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002168static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002169 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002170 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002171 assert(Asm->getLabel().size() < 64-Name.size() &&
2172 "Register name too big");
2173 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002174 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002175 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002176 if (M->getNumOperands() == 0) {
2177 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2178 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002179 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002180 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2181 }
John McCall7f416cc2015-09-08 08:05:57 +00002182
2183 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2184
2185 llvm::Value *Ptr =
2186 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2187 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002188}
2189
Chris Lattnerd7f58862007-06-02 05:24:33 +00002190LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002191 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002192 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002193
Renato Goline7b3d5d2014-05-27 16:46:27 +00002194 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2195 // Global Named registers access via intrinsics only
2196 if (VD->getStorageClass() == SC_Register &&
2197 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002198 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002199
Renato Goline7b3d5d2014-05-27 16:46:27 +00002200 // A DeclRefExpr for a reference initialized by a constant expression can
2201 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002202 const Expr *Init = VD->getAnyInitializer(VD);
2203 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2204 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002205 VD->checkInitIsICE() &&
2206 // Do not emit if it is private OpenMP variable.
2207 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2208 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002209 llvm::Constant *Val =
2210 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2211 assert(Val && "failed to emit reference constant expression");
2212 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002213
2214 // Should we be using the alignment of the constant pointer we emitted?
2215 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2216 /*pointee*/ true);
2217
2218 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002219 }
David Majnemer602cfe72015-01-01 09:49:44 +00002220
2221 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002222 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002223 if (auto *FD = LambdaCaptureFields.lookup(VD))
2224 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2225 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002226 auto I = LocalDeclMap.find(VD);
2227 if (I != LocalDeclMap.end()) {
2228 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2229 return EmitLoadOfReferenceLValue(I->second, RefTy);
2230 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002231 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002232 LValue CapLVal =
2233 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2234 CapturedStmtInfo->getContextValue());
2235 return MakeAddrLValue(
2236 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2237 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002238 }
John McCall7f416cc2015-09-08 08:05:57 +00002239
David Majnemer602cfe72015-01-01 09:49:44 +00002240 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002241 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2242 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002243 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002244 }
2245
Eli Friedman5720e342012-01-21 04:52:58 +00002246 // FIXME: We should be able to assert this for FunctionDecls as well!
2247 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2248 // those with a valid source location.
2249 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2250 !E->getLocation().isValid()) &&
2251 "Should not use decl without marking it used!");
2252
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002253 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002254 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002255 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2256 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002257 }
2258
Renato Goline7b3d5d2014-05-27 16:46:27 +00002259 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002260 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002261 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002262 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002263
John McCall7f416cc2015-09-08 08:05:57 +00002264 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002265
John McCall7f416cc2015-09-08 08:05:57 +00002266 // The variable should generally be present in the local decl map.
2267 auto iter = LocalDeclMap.find(VD);
2268 if (iter != LocalDeclMap.end()) {
2269 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002270
John McCall7f416cc2015-09-08 08:05:57 +00002271 // Otherwise, it might be static local we haven't emitted yet for
2272 // some reason; most likely, because it's in an outer function.
2273 } else if (VD->isStaticLocal()) {
2274 addr = Address(CGM.getOrCreateStaticVarDecl(
2275 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2276 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002277
John McCall7f416cc2015-09-08 08:05:57 +00002278 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002279 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002280 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2281 }
2282
2283
2284 // Check for OpenMP threadprivate variables.
2285 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2286 return EmitThreadPrivateVarDeclLValue(
2287 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2288 E->getExprLoc());
2289 }
2290
2291 // Drill into block byref variables.
2292 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2293 if (isBlockByref) {
2294 addr = emitBlockByrefAddress(addr, VD);
2295 }
2296
2297 // Drill into reference types.
2298 LValue LV;
2299 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2300 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2301 } else {
2302 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002303 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002304
John McCallcdda29c2013-03-13 03:10:54 +00002305 bool isLocalStorage = VD->hasLocalStorage();
2306
2307 bool NonGCable = isLocalStorage &&
2308 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002309 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002310 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002311 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002312 LV.setNonGC(true);
2313 }
John McCallcdda29c2013-03-13 03:10:54 +00002314
2315 bool isImpreciseLifetime =
2316 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2317 if (isImpreciseLifetime)
2318 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002319 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002320 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002321 }
John McCallf3a88602011-02-03 08:15:49 +00002322
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002323 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002324 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002325
Richard Smithda383632016-08-15 01:33:41 +00002326 // FIXME: While we're emitting a binding from an enclosing scope, all other
2327 // DeclRefExprs we see should be implicitly treated as if they also refer to
2328 // an enclosing scope.
2329 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2330 return EmitLValue(BD->getBinding());
2331
David Blaikie83d382b2011-09-23 05:06:16 +00002332 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002333}
Chris Lattnere47e4402007-06-01 18:02:12 +00002334
Chris Lattner8394d792007-06-05 20:53:16 +00002335LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2336 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002337 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002338 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002339
Chris Lattner0f398c42008-07-26 22:37:01 +00002340 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002341 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002342 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002343 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002344 QualType T = E->getSubExpr()->getType()->getPointeeType();
2345 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002346
John McCall7f416cc2015-09-08 08:05:57 +00002347 AlignmentSource AlignSource;
2348 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2349 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002350 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002351
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002352 // We should not generate __weak write barrier on indirect reference
2353 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2354 // But, we continue to generate __strong write barrier on indirect write
2355 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002356 if (getLangOpts().ObjC1 &&
2357 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002358 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002359 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002360 return LV;
2361 }
John McCalle3027922010-08-25 11:45:40 +00002362 case UO_Real:
2363 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002364 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002365 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002366
Richard Smith0b6b8e42012-02-18 20:53:32 +00002367 // __real is valid on scalars. This is a faster way of testing that.
2368 // __imag can only produce an rvalue on scalars.
2369 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002370 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002371 assert(E->getSubExpr()->getType()->isArithmeticType());
2372 return LV;
2373 }
2374
Alexey Bataev611b0a12016-11-07 18:15:02 +00002375 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002376
John McCall7f416cc2015-09-08 08:05:57 +00002377 Address Component =
2378 (E->getOpcode() == UO_Real
2379 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2380 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Alexey Bataev611b0a12016-11-07 18:15:02 +00002381 LValue ElemLV = MakeAddrLValue(Component, T, LV.getAlignmentSource());
2382 ElemLV.getQuals().addQualifiers(LV.getQuals());
2383 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002384 }
John McCalle3027922010-08-25 11:45:40 +00002385 case UO_PreInc:
2386 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002387 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002388 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002389
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002390 if (E->getType()->isAnyComplexType())
2391 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2392 else
2393 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2394 return LV;
2395 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002396 }
Chris Lattner8394d792007-06-05 20:53:16 +00002397}
2398
Chris Lattner4347e3692007-06-06 04:54:52 +00002399LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002400 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002401 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002402}
2403
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002404LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002405 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002406 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002407}
2408
Mike Stump4a3999f2009-09-09 13:00:44 +00002409LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002410 auto SL = E->getFunctionName();
2411 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2412 StringRef FnName = CurFn->getName();
2413 if (FnName.startswith("\01"))
2414 FnName = FnName.substr(1);
2415 StringRef NameItems[] = {
2416 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2417 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002418 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2419 std::string Name = SL->getString();
2420 if (!Name.empty()) {
2421 unsigned Discriminator =
2422 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2423 if (Discriminator)
2424 Name += "_" + Twine(Discriminator + 1).str();
2425 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2426 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2427 } else {
2428 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2429 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2430 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002431 }
Alexey Bataevec474782014-10-09 08:45:04 +00002432 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002433 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002434}
2435
Richard Smithe30752c2012-10-09 19:52:38 +00002436/// Emit a type description suitable for use by a runtime sanitizer library. The
2437/// format of a type descriptor is
2438///
2439/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002440/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002441/// \endcode
2442///
Richard Smith683398a2012-10-09 23:55:19 +00002443/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2444/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002445llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002446 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002447 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002448 return C;
2449
Richard Smithe30752c2012-10-09 19:52:38 +00002450 uint16_t TypeKind = -1;
2451 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002452
Richard Smithe30752c2012-10-09 19:52:38 +00002453 if (T->isIntegerType()) {
2454 TypeKind = 0;
2455 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002456 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002457 } else if (T->isFloatingType()) {
2458 TypeKind = 1;
2459 TypeInfo = getContext().getTypeSize(T);
2460 }
2461
2462 // Format the type name as if for a diagnostic, including quotes and
2463 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002464 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002465 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2466 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002467 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002468 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002469
2470 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002471 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2472 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002473 };
2474 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2475
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002476 auto *GV = new llvm::GlobalVariable(
2477 CGM.getModule(), Descriptor->getType(),
2478 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002479 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002480 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002481
2482 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002483 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002484
Richard Smithe30752c2012-10-09 19:52:38 +00002485 return GV;
2486}
2487
2488llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2489 llvm::Type *TargetTy = IntPtrTy;
2490
Richard Smith48366f72013-03-22 00:47:07 +00002491 // Floating-point types which fit into intptr_t are bitcast to integers
2492 // and then passed directly (after zero-extension, if necessary).
2493 if (V->getType()->isFloatingPointTy()) {
2494 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2495 if (Bits <= TargetTy->getIntegerBitWidth())
2496 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2497 Bits));
2498 }
2499
Richard Smithe30752c2012-10-09 19:52:38 +00002500 // Integers which fit in intptr_t are zero-extended and passed directly.
2501 if (V->getType()->isIntegerTy() &&
2502 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2503 return Builder.CreateZExt(V, TargetTy);
2504
2505 // Pointers are passed directly, everything else is passed by address.
2506 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002507 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002508 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002509 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002510 }
2511 return Builder.CreatePtrToInt(V, TargetTy);
2512}
2513
2514/// \brief Emit a representation of a SourceLocation for passing to a handler
2515/// in a sanitizer runtime library. The format for this data is:
2516/// \code
2517/// struct SourceLocation {
2518/// const char *Filename;
2519/// int32_t Line, Column;
2520/// };
2521/// \endcode
2522/// For an invalid SourceLocation, the Filename pointer is null.
2523llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002524 llvm::Constant *Filename;
2525 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002526
Alexey Samsonov6c124142014-07-18 17:50:06 +00002527 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2528 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002529 StringRef FilenameString = PLoc.getFilename();
2530
2531 int PathComponentsToStrip =
2532 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2533 if (PathComponentsToStrip < 0) {
2534 assert(PathComponentsToStrip != INT_MIN);
2535 int PathComponentsToKeep = -PathComponentsToStrip;
2536 auto I = llvm::sys::path::rbegin(FilenameString);
2537 auto E = llvm::sys::path::rend(FilenameString);
2538 while (I != E && --PathComponentsToKeep)
2539 ++I;
2540
2541 FilenameString = FilenameString.substr(I - E);
2542 } else if (PathComponentsToStrip > 0) {
2543 auto I = llvm::sys::path::begin(FilenameString);
2544 auto E = llvm::sys::path::end(FilenameString);
2545 while (I != E && PathComponentsToStrip--)
2546 ++I;
2547
2548 if (I != E)
2549 FilenameString =
2550 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2551 else
2552 FilenameString = llvm::sys::path::filename(FilenameString);
2553 }
2554
2555 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002556 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2557 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2558 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002559 Line = PLoc.getLine();
2560 Column = PLoc.getColumn();
2561 } else {
2562 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2563 Line = Column = 0;
2564 }
2565
2566 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2567 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002568
2569 return llvm::ConstantStruct::getAnon(Data);
2570}
2571
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002572namespace {
2573/// \brief Specify under what conditions this check can be recovered
2574enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002575 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002576 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002577 /// Check supports recovering, runtime has both fatal (noreturn) and
2578 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002579 Recoverable,
2580 /// Runtime conditionally aborts, always need to support recovery.
2581 AlwaysRecoverable
2582};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002583}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002584
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002585static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2586 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002587 switch (Kind) {
2588 case SanitizerKind::Vptr:
2589 return CheckRecoverableKind::AlwaysRecoverable;
2590 case SanitizerKind::Return:
2591 case SanitizerKind::Unreachable:
2592 return CheckRecoverableKind::Unrecoverable;
2593 default:
2594 return CheckRecoverableKind::Recoverable;
2595 }
2596}
2597
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002598namespace {
2599struct SanitizerHandlerInfo {
2600 char const *const Name;
2601 unsigned Version;
2602};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002603}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002604
2605const SanitizerHandlerInfo SanitizerHandlers[] = {
2606#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2607 LIST_SANITIZER_CHECKS
2608#undef SANITIZER_CHECK
2609};
2610
Alexey Samsonov88459522015-01-12 22:39:12 +00002611static void emitCheckHandlerCall(CodeGenFunction &CGF,
2612 llvm::FunctionType *FnType,
2613 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002614 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002615 CheckRecoverableKind RecoverKind, bool IsFatal,
2616 llvm::BasicBlock *ContBB) {
2617 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2618 bool NeedsAbortSuffix =
2619 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002620 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2621 const StringRef CheckName = CheckInfo.Name;
2622 std::string FnName =
2623 ("__ubsan_handle_" + CheckName +
Vedant Kumar4881bdf2016-12-12 18:47:33 +00002624 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002625 (NeedsAbortSuffix ? "_abort" : ""))
2626 .str();
Alexey Samsonov88459522015-01-12 22:39:12 +00002627 bool MayReturn =
2628 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2629
2630 llvm::AttrBuilder B;
2631 if (!MayReturn) {
2632 B.addAttribute(llvm::Attribute::NoReturn)
2633 .addAttribute(llvm::Attribute::NoUnwind);
2634 }
2635 B.addAttribute(llvm::Attribute::UWTable);
2636
2637 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2638 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002639 llvm::AttributeList::get(CGF.getLLVMContext(),
2640 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002641 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002642 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2643 if (!MayReturn) {
2644 HandlerCall->setDoesNotReturn();
2645 CGF.Builder.CreateUnreachable();
2646 } else {
2647 CGF.Builder.CreateBr(ContBB);
2648 }
2649}
2650
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002651void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002652 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002653 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002654 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002655 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002656 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002657 assert(CheckHandler >= 0 &&
2658 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2659 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002660
2661 llvm::Value *FatalCond = nullptr;
2662 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002663 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002664 for (int i = 0, n = Checked.size(); i < n; ++i) {
2665 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002666 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002667 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002668 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2669 ? TrapCond
2670 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2671 ? RecoverableCond
2672 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002673 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2674 }
2675
Peter Collingbourne9881b782015-06-18 23:59:22 +00002676 if (TrapCond)
2677 EmitTrapCheck(TrapCond);
2678 if (!FatalCond && !RecoverableCond)
2679 return;
2680
Alexey Samsonov88459522015-01-12 22:39:12 +00002681 llvm::Value *JointCond;
2682 if (FatalCond && RecoverableCond)
2683 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2684 else
2685 JointCond = FatalCond ? FatalCond : RecoverableCond;
2686 assert(JointCond);
2687
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002688 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002689 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002690#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002691 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002692 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002693 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002694 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002695 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002696#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002697
Richard Smith4d1458e2012-09-08 02:08:36 +00002698 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002699 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2700 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002701 // Give hint that we very much don't expect to execute the handler
2702 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2703 llvm::MDBuilder MDHelper(getLLVMContext());
2704 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2705 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002706 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002707
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002708 // Handler functions take an i8* pointing to the (handler-specific) static
2709 // information block, followed by a sequence of intptr_t arguments
2710 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002711 SmallVector<llvm::Value *, 4> Args;
2712 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002713 Args.reserve(DynamicArgs.size() + 1);
2714 ArgTypes.reserve(DynamicArgs.size() + 1);
2715
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002716 // Emit handler arguments and create handler function type.
2717 if (!StaticArgs.empty()) {
2718 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2719 auto *InfoPtr =
2720 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2721 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002722 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002723 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2724 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2725 ArgTypes.push_back(Int8PtrTy);
2726 }
2727
Richard Smithe30752c2012-10-09 19:52:38 +00002728 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2729 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2730 ArgTypes.push_back(IntPtrTy);
2731 }
2732
2733 llvm::FunctionType *FnType =
2734 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002735
Alexey Samsonov88459522015-01-12 22:39:12 +00002736 if (!FatalCond || !RecoverableCond) {
2737 // Simple case: we need to generate a single handler call, either
2738 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002739 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002740 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002741 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002742 // Emit two handler calls: first one for set of unrecoverable checks,
2743 // another one for recoverable.
2744 llvm::BasicBlock *NonFatalHandlerBB =
2745 createBasicBlock("non_fatal." + CheckName);
2746 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2747 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2748 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002749 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002750 NonFatalHandlerBB);
2751 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002752 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002753 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002754 }
Richard Smithe30752c2012-10-09 19:52:38 +00002755
Richard Smith4d1458e2012-09-08 02:08:36 +00002756 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002757}
2758
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002759void CodeGenFunction::EmitCfiSlowPathCheck(
2760 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2761 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002762 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2763
2764 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2765 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2766
2767 llvm::MDBuilder MDHelper(getLLVMContext());
2768 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2769 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2770
2771 EmitBlock(CheckBB);
2772
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002773 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2774
2775 llvm::CallInst *CheckCall;
2776 if (WithDiag) {
2777 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2778 auto *InfoPtr =
2779 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2780 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002781 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002782 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2783
2784 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2785 "__cfi_slowpath_diag",
2786 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2787 false));
2788 CheckCall = Builder.CreateCall(
2789 SlowPathDiagFn,
2790 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2791 } else {
2792 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2793 "__cfi_slowpath",
2794 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2795 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2796 }
2797
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002798 CheckCall->setDoesNotThrow();
2799
2800 EmitBlock(Cont);
2801}
2802
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00002803// Emit a stub for __cfi_check function so that the linker knows about this
2804// symbol in LTO mode.
2805void CodeGenFunction::EmitCfiCheckStub() {
2806 llvm::Module *M = &CGM.getModule();
2807 auto &Ctx = M->getContext();
2808 llvm::Function *F = llvm::Function::Create(
2809 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2810 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2811 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2812 // FIXME: consider emitting an intrinsic call like
2813 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2814 // which can be lowered in CrossDSOCFI pass to the actual contents of
2815 // __cfi_check. This would allow inlining of __cfi_check calls.
2816 llvm::CallInst::Create(
2817 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2818 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2819}
2820
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002821// This function is basically a switch over the CFI failure kind, which is
2822// extracted from CFICheckFailData (1st function argument). Each case is either
2823// llvm.trap or a call to one of the two runtime handlers, based on
2824// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2825// failure kind) traps, but this should really never happen. CFICheckFailData
2826// can be nullptr if the calling module has -fsanitize-trap behavior for this
2827// check kind; in this case __cfi_check_fail traps as well.
2828void CodeGenFunction::EmitCfiCheckFail() {
2829 SanitizerScope SanScope(this);
2830 FunctionArgList Args;
2831 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2832 getContext().VoidPtrTy);
2833 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2834 getContext().VoidPtrTy);
2835 Args.push_back(&ArgData);
2836 Args.push_back(&ArgAddr);
2837
John McCallc56a8b32016-03-11 04:30:31 +00002838 const CGFunctionInfo &FI =
2839 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002840
2841 llvm::Function *F = llvm::Function::Create(
2842 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2843 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2844 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2845
2846 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2847 SourceLocation());
2848
2849 llvm::Value *Data =
2850 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2851 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2852 llvm::Value *Addr =
2853 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2854 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2855
2856 // Data == nullptr means the calling module has trap behaviour for this check.
2857 llvm::Value *DataIsNotNullPtr =
2858 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2859 EmitTrapCheck(DataIsNotNullPtr);
2860
2861 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002862 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002863 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002864 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002865
2866 llvm::Value *V = Builder.CreateConstGEP2_32(
2867 CfiCheckFailDataTy,
2868 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2869 0);
2870 Address CheckKindAddr(V, getIntAlign());
2871 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2872
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002873 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2874 CGM.getLLVMContext(),
2875 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2876 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002877 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002878 {Addr, AllVtables}),
2879 IntPtrTy);
2880
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002881 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002882 {CFITCK_VCall, SanitizerKind::CFIVCall},
2883 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2884 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2885 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2886 {CFITCK_ICall, SanitizerKind::CFIICall}};
2887
2888 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2889 for (auto CheckKindMaskPair : CheckKinds) {
2890 int Kind = CheckKindMaskPair.first;
2891 SanitizerMask Mask = CheckKindMaskPair.second;
2892 llvm::Value *Cond =
2893 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002894 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002895 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002896 {Data, Addr, ValidVtable});
2897 else
2898 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002899 }
2900
2901 FinishFunction();
2902 // The only reference to this function will be created during LTO link.
2903 // Make sure it survives until then.
2904 CGM.addUsedGlobal(F);
2905}
2906
Chad Rosierae229d52013-01-29 23:31:22 +00002907void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002908 llvm::BasicBlock *Cont = createBasicBlock("cont");
2909
2910 // If we're optimizing, collapse all calls to trap down to just one per
2911 // function to save on code size.
2912 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2913 TrapBB = createBasicBlock("trap");
2914 Builder.CreateCondBr(Checked, Cont, TrapBB);
2915 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002916 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002917 TrapCall->setDoesNotReturn();
2918 TrapCall->setDoesNotThrow();
2919 Builder.CreateUnreachable();
2920 } else {
2921 Builder.CreateCondBr(Checked, Cont, TrapBB);
2922 }
2923
2924 EmitBlock(Cont);
2925}
2926
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002927llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002928 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002929
Amaury Sechet21f51b32016-09-09 04:42:49 +00002930 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2931 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2932 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00002933 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00002934 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002935
2936 return TrapCall;
2937}
2938
John McCall7f416cc2015-09-08 08:05:57 +00002939Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2940 AlignmentSource *AlignSource) {
2941 assert(E->getType()->isArrayType() &&
2942 "Array to pointer decay must have array source type!");
2943
2944 // Expressions of array type can't be bitfields or vector elements.
2945 LValue LV = EmitLValue(E);
2946 Address Addr = LV.getAddress();
2947 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2948
2949 // If the array type was an incomplete type, we need to make sure
2950 // the decay ends up being the right type.
2951 llvm::Type *NewTy = ConvertType(E->getType());
2952 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2953
2954 // Note that VLA pointers are always decayed, so we don't need to do
2955 // anything here.
2956 if (!E->getType()->isVariableArrayType()) {
2957 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2958 "Expected pointer to array");
2959 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2960 }
2961
2962 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2963 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2964}
2965
Chris Lattner6c5abe82010-06-26 23:03:20 +00002966/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2967/// array to pointer, return the array subexpression.
2968static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2969 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002970 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002971 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002972 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002973
Chris Lattner6c5abe82010-06-26 23:03:20 +00002974 // If this is a decay from variable width array, bail out.
2975 const Expr *SubExpr = CE->getSubExpr();
2976 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002977 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002978
Chris Lattner6c5abe82010-06-26 23:03:20 +00002979 return SubExpr;
2980}
2981
John McCall7f416cc2015-09-08 08:05:57 +00002982static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2983 llvm::Value *ptr,
2984 ArrayRef<llvm::Value*> indices,
2985 bool inbounds,
2986 const llvm::Twine &name = "arrayidx") {
2987 if (inbounds) {
2988 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2989 } else {
2990 return CGF.Builder.CreateGEP(ptr, indices, name);
2991 }
2992}
2993
2994static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2995 llvm::Value *idx,
2996 CharUnits eltSize) {
2997 // If we have a constant index, we can use the exact offset of the
2998 // element we're accessing.
2999 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3000 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3001 return arrayAlign.alignmentAtOffset(offset);
3002
3003 // Otherwise, use the worst-case alignment for any element.
3004 } else {
3005 return arrayAlign.alignmentOfArrayElement(eltSize);
3006 }
3007}
3008
3009static QualType getFixedSizeElementType(const ASTContext &ctx,
3010 const VariableArrayType *vla) {
3011 QualType eltType;
3012 do {
3013 eltType = vla->getElementType();
3014 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3015 return eltType;
3016}
3017
3018static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3019 ArrayRef<llvm::Value*> indices,
3020 QualType eltType, bool inbounds,
3021 const llvm::Twine &name = "arrayidx") {
3022 // All the indices except that last must be zero.
3023#ifndef NDEBUG
3024 for (auto idx : indices.drop_back())
3025 assert(isa<llvm::ConstantInt>(idx) &&
3026 cast<llvm::ConstantInt>(idx)->isZero());
3027#endif
3028
3029 // Determine the element size of the statically-sized base. This is
3030 // the thing that the indices are expressed in terms of.
3031 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3032 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3033 }
3034
3035 // We can use that to compute the best alignment of the element.
3036 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3037 CharUnits eltAlign =
3038 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3039
3040 llvm::Value *eltPtr =
3041 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
3042 return Address(eltPtr, eltAlign);
3043}
3044
Richard Smith539e4a72013-02-23 02:53:19 +00003045LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3046 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003047 // The index must always be an integer, which is not an aggregate. Emit it
3048 // in lexical order (this complexity is, sadly, required by C++17).
3049 llvm::Value *IdxPre =
3050 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Richard Smith40885712016-09-27 00:53:24 +00003051 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003052 auto *Idx = IdxPre;
3053 if (E->getLHS() != E->getIdx()) {
3054 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3055 Idx = EmitScalarExpr(E->getIdx());
3056 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003057
Richard Smith9e67b992016-09-26 23:49:47 +00003058 QualType IdxTy = E->getIdx()->getType();
3059 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3060
3061 if (SanOpts.has(SanitizerKind::ArrayBounds))
3062 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3063
3064 // Extend or truncate the index type to 32 or 64-bits.
3065 if (Promote && Idx->getType() != IntPtrTy)
3066 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3067
3068 return Idx;
3069 };
3070 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003071
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003072 // If the base is a vector type, then we are forming a vector element lvalue
3073 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003074 if (E->getBase()->getType()->isVectorType() &&
3075 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003076 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003077 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003078 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003079 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00003080 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00003081 E->getBase()->getType(),
3082 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003083 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003084
John McCall7f416cc2015-09-08 08:05:57 +00003085 // All the other cases basically behave like simple offsetting.
3086
John McCall7f416cc2015-09-08 08:05:57 +00003087 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003088 if (isa<ExtVectorElementExpr>(E->getBase())) {
3089 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003090 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003091 Address Addr = EmitExtVectorElementLValue(LV);
3092
3093 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3094 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
3095 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003096 }
John McCall7f416cc2015-09-08 08:05:57 +00003097
3098 AlignmentSource AlignSource;
3099 Address Addr = Address::invalid();
3100 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003101 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003102 // The base must be a pointer, which is not an aggregate. Emit
3103 // it. It needs to be emitted first in case it's what captures
3104 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00003105 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003106 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003107
John McCall23c29fe2011-06-24 21:55:10 +00003108 // The element count here is the total number of non-VLA elements.
3109 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003110
John McCall77527a82011-06-25 01:32:37 +00003111 // Effectively, the multiply by the VLA size is part of the GEP.
3112 // GEP indexes are signed, and scaling an index isn't permitted to
3113 // signed-overflow, so we use the same semantics for our explicit
3114 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003115 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003116 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003117 } else {
3118 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003119 }
John McCall7f416cc2015-09-08 08:05:57 +00003120
3121 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3122 !getLangOpts().isSignedOverflowDefined());
3123
Chris Lattner6c5abe82010-06-26 23:03:20 +00003124 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3125 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003126
John McCall7f416cc2015-09-08 08:05:57 +00003127 // Emit the base pointer.
3128 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003129 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3130
3131 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3132 llvm::Value *InterfaceSizeVal =
3133 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3134
3135 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003136
3137 // We don't necessarily build correct LLVM struct types for ObjC
3138 // interfaces, so we can't rely on GEP to do this scaling
3139 // correctly, so we need to cast to i8*. FIXME: is this actually
3140 // true? A lot of other things in the fragile ABI would break...
3141 llvm::Type *OrigBaseTy = Addr.getType();
3142 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3143
3144 // Do the GEP.
3145 CharUnits EltAlign =
3146 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3147 llvm::Value *EltPtr =
3148 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3149 Addr = Address(EltPtr, EltAlign);
3150
3151 // Cast back.
3152 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003153 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3154 // If this is A[i] where A is an array, the frontend will have decayed the
3155 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3156 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3157 // "gep x, i" here. Emit one "gep A, 0, i".
3158 assert(Array->getType()->isArrayType() &&
3159 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003160 LValue ArrayLV;
3161 // For simple multidimensional array indexing, set the 'accessed' flag for
3162 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003163 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003164 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3165 else
3166 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003167 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003168
Daniel Dunbar82634272011-04-01 00:49:43 +00003169 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00003170 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3171 {CGM.getSize(CharUnits::Zero()), Idx},
3172 E->getType(),
3173 !getLangOpts().isSignedOverflowDefined());
3174 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003175 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003176 // The base must be a pointer; emit it with an estimate of its alignment.
3177 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003178 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003179 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3180 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003181 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003182
John McCall7f416cc2015-09-08 08:05:57 +00003183 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00003184
John McCall7f416cc2015-09-08 08:05:57 +00003185 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003186
Richard Smith9c6890a2012-11-01 22:30:59 +00003187 if (getLangOpts().ObjC1 &&
3188 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003189 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003190 setObjCGCLValueClass(getContext(), E, LV);
3191 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003192 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003193}
3194
Alexey Bataev31300ed2016-02-04 11:27:03 +00003195static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3196 AlignmentSource &AlignSource,
3197 QualType BaseTy, QualType ElTy,
3198 bool IsLowerBound) {
3199 LValue BaseLVal;
3200 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3201 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3202 if (BaseTy->isArrayType()) {
3203 Address Addr = BaseLVal.getAddress();
3204 AlignSource = BaseLVal.getAlignmentSource();
3205
3206 // If the array type was an incomplete type, we need to make sure
3207 // the decay ends up being the right type.
3208 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3209 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3210
3211 // Note that VLA pointers are always decayed, so we don't need to do
3212 // anything here.
3213 if (!BaseTy->isVariableArrayType()) {
3214 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3215 "Expected pointer to array");
3216 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3217 "arraydecay");
3218 }
3219
3220 return CGF.Builder.CreateElementBitCast(Addr,
3221 CGF.ConvertTypeForMem(ElTy));
3222 }
3223 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3224 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3225 }
3226 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3227}
3228
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003229LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3230 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003231 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003232 if (auto *ASE =
3233 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003234 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003235 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003236 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003237 QualType ResultExprTy;
3238 if (auto *AT = getContext().getAsArrayType(BaseTy))
3239 ResultExprTy = AT->getElementType();
3240 else
3241 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003242 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003243 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003244 // Requesting lower bound or upper bound, but without provided length and
3245 // without ':' symbol for the default length -> length = 1.
3246 // Idx = LowerBound ?: 0;
3247 if (auto *LowerBound = E->getLowerBound()) {
3248 Idx = Builder.CreateIntCast(
3249 EmitScalarExpr(LowerBound), IntPtrTy,
3250 LowerBound->getType()->hasSignedIntegerRepresentation());
3251 } else
3252 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3253 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003254 // Try to emit length or lower bound as constant. If this is possible, 1
3255 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3256 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003257 auto &C = CGM.getContext();
3258 auto *Length = E->getLength();
3259 llvm::APSInt ConstLength;
3260 if (Length) {
3261 // Idx = LowerBound + Length - 1;
3262 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3263 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3264 Length = nullptr;
3265 }
3266 auto *LowerBound = E->getLowerBound();
3267 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3268 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3269 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3270 LowerBound = nullptr;
3271 }
3272 if (!Length)
3273 --ConstLength;
3274 else if (!LowerBound)
3275 --ConstLowerBound;
3276
3277 if (Length || LowerBound) {
3278 auto *LowerBoundVal =
3279 LowerBound
3280 ? Builder.CreateIntCast(
3281 EmitScalarExpr(LowerBound), IntPtrTy,
3282 LowerBound->getType()->hasSignedIntegerRepresentation())
3283 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3284 auto *LengthVal =
3285 Length
3286 ? Builder.CreateIntCast(
3287 EmitScalarExpr(Length), IntPtrTy,
3288 Length->getType()->hasSignedIntegerRepresentation())
3289 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3290 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3291 /*HasNUW=*/false,
3292 !getLangOpts().isSignedOverflowDefined());
3293 if (Length && LowerBound) {
3294 Idx = Builder.CreateSub(
3295 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3296 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3297 }
3298 } else
3299 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3300 } else {
3301 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003302 QualType ArrayTy = BaseTy->isPointerType()
3303 ? E->getBase()->IgnoreParenImpCasts()->getType()
3304 : BaseTy;
3305 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003306 Length = VAT->getSizeExpr();
3307 if (Length->isIntegerConstantExpr(ConstLength, C))
3308 Length = nullptr;
3309 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003310 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003311 ConstLength = CAT->getSize();
3312 }
3313 if (Length) {
3314 auto *LengthVal = Builder.CreateIntCast(
3315 EmitScalarExpr(Length), IntPtrTy,
3316 Length->getType()->hasSignedIntegerRepresentation());
3317 Idx = Builder.CreateSub(
3318 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3319 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3320 } else {
3321 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3322 --ConstLength;
3323 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3324 }
3325 }
3326 }
3327 assert(Idx);
3328
Alexey Bataev31300ed2016-02-04 11:27:03 +00003329 Address EltPtr = Address::invalid();
3330 AlignmentSource AlignSource;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003331 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003332 // The base must be a pointer, which is not an aggregate. Emit
3333 // it. It needs to be emitted first in case it's what captures
3334 // the VLA bounds.
3335 Address Base =
3336 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3337 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003338 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003339 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003340
3341 // Effectively, the multiply by the VLA size is part of the GEP.
3342 // GEP indexes are signed, and scaling an index isn't permitted to
3343 // signed-overflow, so we use the same semantics for our explicit
3344 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003345 if (getLangOpts().isSignedOverflowDefined())
3346 Idx = Builder.CreateMul(Idx, NumElements);
3347 else
3348 Idx = Builder.CreateNSWMul(Idx, NumElements);
3349 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3350 !getLangOpts().isSignedOverflowDefined());
3351 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3352 // If this is A[i] where A is an array, the frontend will have decayed the
3353 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3354 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3355 // "gep x, i" here. Emit one "gep A, 0, i".
3356 assert(Array->getType()->isArrayType() &&
3357 "Array to pointer decay must have array source type!");
3358 LValue ArrayLV;
3359 // For simple multidimensional array indexing, set the 'accessed' flag for
3360 // better bounds-checking of the base expression.
3361 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3362 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3363 else
3364 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003365
Alexey Bataev31300ed2016-02-04 11:27:03 +00003366 // Propagate the alignment from the array itself to the result.
3367 EltPtr = emitArraySubscriptGEP(
3368 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3369 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3370 AlignSource = ArrayLV.getAlignmentSource();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003371 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003372 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3373 BaseTy, ResultExprTy, IsLowerBound);
3374 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3375 !getLangOpts().isSignedOverflowDefined());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003376 }
3377
Alexey Bataev31300ed2016-02-04 11:27:03 +00003378 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003379}
3380
Chris Lattner9e751ca2007-08-02 23:37:31 +00003381LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003382EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003383 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003384 LValue Base;
3385
3386 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003387 if (E->isArrow()) {
3388 // If it is a pointer to a vector, emit the address and form an lvalue with
3389 // it.
John McCall7f416cc2015-09-08 08:05:57 +00003390 AlignmentSource AlignSource;
3391 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003392 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00003393 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003394 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003395 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003396 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3397 // emit the base as an lvalue.
3398 assert(E->getBase()->getType()->isVectorType());
3399 Base = EmitLValue(E->getBase());
3400 } else {
3401 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003402 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003403 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003404 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003405
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003406 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003407 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003408 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003409 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3410 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003411 }
John McCall1553b192011-06-16 04:16:24 +00003412
3413 QualType type =
3414 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003415
Nate Begemand3862152008-05-13 21:03:02 +00003416 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003417 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003418 E->getEncodedElementAccess(Indices);
3419
3420 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003421 llvm::Constant *CV =
3422 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003423 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00003424 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00003425 }
3426 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3427
3428 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003429 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003430
Chris Lattner595ba3a2012-01-30 06:20:36 +00003431 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3432 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003433 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003434 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3435 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003436}
3437
Devang Patel30efa2e2007-10-23 20:28:39 +00003438LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003439 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003440
Chris Lattner4e4186b2007-12-02 18:52:07 +00003441 // 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 +00003442 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003443 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003444 AlignmentSource AlignSource;
3445 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003446 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003447 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003448 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3449 if (IsBaseCXXThis)
3450 SkippedChecks.set(SanitizerKind::Alignment, true);
3451 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003452 SkippedChecks.set(SanitizerKind::Null, true);
3453 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3454 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
John McCall7f416cc2015-09-08 08:05:57 +00003455 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003456 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003457 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003458
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003459 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003460 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003461 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003462 setObjCGCLValueClass(getContext(), E, LV);
3463 return LV;
3464 }
Craig Topper99e79272013-07-26 05:59:26 +00003465
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003466 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003467 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003468
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003469 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003470 return EmitFunctionDeclLValue(*this, E, FD);
3471
David Blaikie83d382b2011-09-23 05:06:16 +00003472 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003473}
Devang Patel30efa2e2007-10-23 20:28:39 +00003474
John McCalldec348f72013-05-03 07:33:41 +00003475/// Given that we are currently emitting a lambda, emit an l-value for
3476/// one of its members.
3477LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3478 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3479 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3480 QualType LambdaTagType =
3481 getContext().getTagDeclType(Field->getParent());
3482 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3483 return EmitLValueForField(LambdaLV, Field);
3484}
3485
John McCall7f416cc2015-09-08 08:05:57 +00003486/// Drill down to the storage of a field without walking into
3487/// reference types.
3488///
3489/// The resulting address doesn't necessarily have the right type.
3490static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3491 const FieldDecl *field) {
3492 const RecordDecl *rec = field->getParent();
3493
3494 unsigned idx =
3495 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3496
3497 CharUnits offset;
3498 // Adjust the alignment down to the given offset.
3499 // As a special case, if the LLVM field index is 0, we know that this
3500 // is zero.
3501 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3502 .getFieldOffset(field->getFieldIndex()) == 0) &&
3503 "LLVM field at index zero had non-zero offset?");
3504 if (idx != 0) {
3505 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3506 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3507 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3508 }
3509
3510 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3511}
3512
Eli Friedman7f1ff602012-04-16 03:54:45 +00003513LValue CodeGenFunction::EmitLValueForField(LValue base,
3514 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003515 AlignmentSource fieldAlignSource =
3516 getFieldAlignmentSource(base.getAlignmentSource());
3517
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003518 if (field->isBitField()) {
3519 const CGRecordLayout &RL =
3520 CGM.getTypes().getCGRecordLayout(field->getParent());
3521 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003522 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003523 unsigned Idx = RL.getLLVMFieldNo(field);
3524 if (Idx != 0)
3525 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003526 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3527 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003528 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003529 llvm::Type *FieldIntTy =
3530 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3531 if (Addr.getElementType() != FieldIntTy)
3532 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003533
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003534 QualType fieldType =
3535 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003536 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003537 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003538
John McCall53fcbd22011-02-26 08:07:02 +00003539 const RecordDecl *rec = field->getParent();
3540 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003541
John McCall53fcbd22011-02-26 08:07:02 +00003542 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3543
John McCall7f416cc2015-09-08 08:05:57 +00003544 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003545 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003546 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003547 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003548 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003549 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003550 // TODO: handle path-aware TBAA for union.
3551 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003552 } else {
3553 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003554 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003555
3556 // If this is a reference field, load the reference right now.
3557 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3558 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3559 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3560
Manman Renc451e572013-04-04 21:53:22 +00003561 // Loading the reference will disable path-aware TBAA.
3562 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003563 if (CGM.shouldUseTBAA()) {
3564 llvm::MDNode *tbaa;
3565 if (mayAlias)
3566 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3567 else
3568 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003569 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003570 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003571 }
3572
John McCall53fcbd22011-02-26 08:07:02 +00003573 mayAlias = false;
3574 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003575
3576 CharUnits alignment =
3577 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3578 addr = Address(load, alignment);
3579
3580 // Qualifiers on the struct don't apply to the referencee, and
3581 // we'll pick up CVR from the actual type later, so reset these
3582 // additional qualifiers now.
3583 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003584 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003585 }
Craig Topper99e79272013-07-26 05:59:26 +00003586
Chris Lattner13ee4f42011-07-10 05:34:54 +00003587 // Make sure that the address is pointing to the right type. This is critical
3588 // for both unions and structs. A union needs a bitcast, a struct element
3589 // will need a bitcast if the LLVM type laid out doesn't match the desired
3590 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003591 addr = Builder.CreateElementBitCast(addr,
3592 CGM.getTypes().ConvertTypeForMem(type),
3593 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003594
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003595 if (field->hasAttr<AnnotateAttr>())
3596 addr = EmitFieldAnnotations(field, addr);
3597
John McCall7f416cc2015-09-08 08:05:57 +00003598 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003599 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003600 if (TBAAPath) {
3601 const ASTRecordLayout &Layout =
3602 getContext().getASTRecordLayout(field->getParent());
3603 // Set the base type to be the base type of the base LValue and
3604 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003605 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3606 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003607 Layout.getFieldOffset(field->getFieldIndex()) /
3608 getContext().getCharWidth());
3609 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003610
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003611 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003612 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3613 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003614
3615 // Fields of may_alias structs act like 'char' for TBAA purposes.
3616 // FIXME: this should get propagated down through anonymous structs
3617 // and unions.
3618 if (mayAlias && LV.getTBAAInfo())
3619 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3620
Daniel Dunbarf166a522010-08-21 03:44:13 +00003621 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003622}
3623
Craig Topper99e79272013-07-26 05:59:26 +00003624LValue
3625CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003626 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003627 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003628
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003629 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003630 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003631
John McCall7f416cc2015-09-08 08:05:57 +00003632 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003633
John McCall7f416cc2015-09-08 08:05:57 +00003634 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003635 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003636 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003637
John McCall7f416cc2015-09-08 08:05:57 +00003638 // TODO: access-path TBAA?
3639 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3640 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003641}
3642
Chris Lattnerf53c0962010-09-06 00:11:41 +00003643LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003644 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003645 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3646 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003647 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003648 if (E->getType()->isVariablyModifiedType())
3649 // make sure to emit the VLA size.
3650 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003651
John McCall7f416cc2015-09-08 08:05:57 +00003652 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003653 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003654 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003655
Chad Rosier615ed1a2012-03-29 17:37:10 +00003656 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3657 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003658
3659 return Result;
3660}
3661
Richard Smithbb653bd2012-05-14 21:57:21 +00003662LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3663 if (!E->isGLValue())
3664 // Initializing an aggregate temporary in C++11: T{...}.
3665 return EmitAggExprToLValue(E);
3666
3667 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003668 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003669 return EmitLValue(E->getInit(0));
3670}
3671
Richard Smithf3076ff2014-06-20 18:43:47 +00003672/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3673/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3674/// LValue is returned and the current block has been terminated.
3675static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3676 const Expr *Operand) {
3677 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3678 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3679 return None;
3680 }
3681
3682 return CGF.EmitLValue(Operand);
3683}
3684
John McCallc07a0c72011-02-17 10:25:35 +00003685LValue CodeGenFunction::
3686EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3687 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003688 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003689 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003690 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003691 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003692 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003693
Eli Friedman59954892012-01-25 05:04:17 +00003694 OpaqueValueMapping binding(*this, expr);
3695
John McCallc07a0c72011-02-17 10:25:35 +00003696 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003697 bool CondExprBool;
3698 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003699 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003700 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003701
Justin Bogneref512b92014-01-06 22:27:43 +00003702 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003703 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003704 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003705 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003706 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003707 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003708 }
3709
John McCallc07a0c72011-02-17 10:25:35 +00003710 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3711 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3712 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003713
3714 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003715 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003716
John McCall0a6bf2e2011-01-26 19:21:13 +00003717 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003718 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003719 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003720 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003721 Optional<LValue> lhs =
3722 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003723 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003724
Richard Smithf3076ff2014-06-20 18:43:47 +00003725 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003726 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003727
John McCallc07a0c72011-02-17 10:25:35 +00003728 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003729 if (lhs)
3730 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003731
John McCall0a6bf2e2011-01-26 19:21:13 +00003732 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003733 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003734 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003735 Optional<LValue> rhs =
3736 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003737 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003738 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003739 return EmitUnsupportedLValue(expr, "conditional operator");
3740 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003741
John McCallc07a0c72011-02-17 10:25:35 +00003742 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003743
Richard Smithf3076ff2014-06-20 18:43:47 +00003744 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003745 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003746 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003747 phi->addIncoming(lhs->getPointer(), lhsBlock);
3748 phi->addIncoming(rhs->getPointer(), rhsBlock);
3749 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3750 AlignmentSource alignSource =
3751 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3752 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003753 } else {
3754 assert((lhs || rhs) &&
3755 "both operands of glvalue conditional are throw-expressions?");
3756 return lhs ? *lhs : *rhs;
3757 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003758}
3759
Richard Smithbb653bd2012-05-14 21:57:21 +00003760/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3761/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003762/// otherwise if a cast is needed by the code generator in an lvalue context,
3763/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003764/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003765/// are permitted with aggregate result, including noop aggregate casts, and
3766/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003767LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003768 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003769 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003770 case CK_BitCast:
3771 case CK_ArrayToPointerDecay:
3772 case CK_FunctionToPointerDecay:
3773 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003774 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003775 case CK_IntegralToPointer:
3776 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003777 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003778 case CK_VectorSplat:
3779 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003780 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003781 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003782 case CK_IntegralToFloating:
3783 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003784 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003785 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003786 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003787 case CK_FloatingComplexToReal:
3788 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003789 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003790 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003791 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003792 case CK_IntegralComplexToReal:
3793 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003794 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003795 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003796 case CK_DerivedToBaseMemberPointer:
3797 case CK_BaseToDerivedMemberPointer:
3798 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003799 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003800 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003801 case CK_ARCProduceObject:
3802 case CK_ARCConsumeObject:
3803 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003804 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003805 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003806 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003807 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003808 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3809
3810 case CK_Dependent:
3811 llvm_unreachable("dependent cast kind in IR gen!");
3812
3813 case CK_BuiltinFnToFnPtr:
3814 llvm_unreachable("builtin functions are handled elsewhere");
3815
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003816 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003817 case CK_NonAtomicToAtomic:
3818 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003819 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003820
Anders Carlsson8a01a752011-04-11 02:03:26 +00003821 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003822 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003823 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003824 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003825 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003826 }
3827
John McCalle3027922010-08-25 11:45:40 +00003828 case CK_ConstructorConversion:
3829 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003830 case CK_CPointerToObjCPointerCast:
3831 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003832 case CK_NoOp:
3833 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003834 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003835
John McCalle3027922010-08-25 11:45:40 +00003836 case CK_UncheckedDerivedToBase:
3837 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003838 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003839 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003840 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003841
Anders Carlssond95f9602009-09-12 16:16:49 +00003842 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003843 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003844
Anders Carlssond95f9602009-09-12 16:16:49 +00003845 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003846 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003847 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3848 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003849
John McCall7f416cc2015-09-08 08:05:57 +00003850 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003851 }
John McCalle3027922010-08-25 11:45:40 +00003852 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003853 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003854 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003855 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003856 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003857
Anders Carlsson8c793172009-11-23 17:57:54 +00003858 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003859
Anders Carlsson8c793172009-11-23 17:57:54 +00003860 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003861 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003862 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003863 E->path_begin(), E->path_end(),
3864 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003865
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003866 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3867 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003868 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003869 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003870 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003871
Peter Collingbourned2926c92015-03-14 02:42:25 +00003872 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003873 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3874 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003875 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003876
John McCall7f416cc2015-09-08 08:05:57 +00003877 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003878 }
John McCalle3027922010-08-25 11:45:40 +00003879 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003880 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003881 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003882
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003883 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003884 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003885 Address V = Builder.CreateBitCast(LV.getAddress(),
3886 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003887
3888 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003889 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3890 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003891 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003892
John McCall7f416cc2015-09-08 08:05:57 +00003893 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003894 }
John McCalle3027922010-08-25 11:45:40 +00003895 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003896 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003897 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3898 ConvertType(E->getType()));
3899 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003900 }
Egor Churaev89831422016-12-23 14:55:49 +00003901 case CK_ZeroToOCLQueue:
3902 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003903 case CK_ZeroToOCLEvent:
3904 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003905 }
Craig Topper99e79272013-07-26 05:59:26 +00003906
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003907 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003908}
3909
John McCall1bf58462011-02-16 08:02:54 +00003910LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003911 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003912 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003913}
3914
Eli Friedman7f1ff602012-04-16 03:54:45 +00003915RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003916 const FieldDecl *FD,
3917 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003918 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003919 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003920 switch (getEvaluationKind(FT)) {
3921 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003922 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003923 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003924 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003925 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00003926 // This routine is used to load fields one-by-one to perform a copy, so
3927 // don't load reference fields.
3928 if (FD->getType()->isReferenceType())
3929 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00003930 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003931 }
3932 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003933}
Douglas Gregorfe314812011-06-21 17:03:29 +00003934
Chris Lattnere47e4402007-06-01 18:02:12 +00003935//===--------------------------------------------------------------------===//
3936// Expression Emission
3937//===--------------------------------------------------------------------===//
3938
Craig Topper99e79272013-07-26 05:59:26 +00003939RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003940 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003941 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003942 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003943 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003944
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003945 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003946 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003947
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003948 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003949 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3950
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003951 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00003952 if (const CXXMethodDecl *MD =
3953 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003954 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003955
John McCallb92ab1a2016-10-26 23:46:34 +00003956 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00003957
John McCallb92ab1a2016-10-26 23:46:34 +00003958 if (callee.isBuiltin()) {
3959 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3960 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003961 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003962
John McCallb92ab1a2016-10-26 23:46:34 +00003963 if (callee.isPseudoDestructor()) {
3964 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3965 }
3966
3967 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3968}
3969
3970/// Emit a CallExpr without considering whether it might be a subclass.
3971RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
3972 ReturnValueSlot ReturnValue) {
3973 CGCallee Callee = EmitCallee(E->getCallee());
3974 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
3975}
3976
3977static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
3978 if (auto builtinID = FD->getBuiltinID()) {
3979 return CGCallee::forBuiltin(builtinID, FD);
3980 }
3981
3982 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
3983 return CGCallee::forDirect(calleePtr, FD);
3984}
3985
3986CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
3987 E = E->IgnoreParens();
3988
3989 // Look through function-to-pointer decay.
3990 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
3991 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
3992 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
3993 return EmitCallee(ICE->getSubExpr());
3994 }
3995
3996 // Resolve direct calls.
3997 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
3998 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
3999 return EmitDirectCallee(*this, FD);
4000 }
4001 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4002 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4003 EmitIgnoredExpr(ME->getBase());
4004 return EmitDirectCallee(*this, FD);
4005 }
4006
4007 // Look through template substitutions.
4008 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4009 return EmitCallee(NTTP->getReplacement());
4010
4011 // Treat pseudo-destructor calls differently.
4012 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4013 return CGCallee::forPseudoDestructor(PDE);
4014 }
4015
4016 // Otherwise, we have an indirect reference.
4017 llvm::Value *calleePtr;
4018 QualType functionType;
4019 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4020 calleePtr = EmitScalarExpr(E);
4021 functionType = ptrType->getPointeeType();
4022 } else {
4023 functionType = E->getType();
4024 calleePtr = EmitLValue(E).getPointer();
4025 }
4026 assert(functionType->isFunctionType());
4027 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4028 E->getReferencedDeclOfCallee());
4029 CGCallee callee(calleeInfo, calleePtr);
4030 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004031}
4032
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004033LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004034 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004035 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004036 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004037 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004038 return EmitLValue(E->getRHS());
4039 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004040
John McCalle3027922010-08-25 11:45:40 +00004041 if (E->getOpcode() == BO_PtrMemD ||
4042 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004043 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004044
John McCalla2342eb2010-12-05 02:00:02 +00004045 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004046
4047 // Note that in all of these cases, __block variables need the RHS
4048 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004049
4050 switch (getEvaluationKind(E->getType())) {
4051 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004052 switch (E->getLHS()->getType().getObjCLifetime()) {
4053 case Qualifiers::OCL_Strong:
4054 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4055
4056 case Qualifiers::OCL_Autoreleasing:
4057 return EmitARCStoreAutoreleasing(E).first;
4058
4059 // No reason to do any of these differently.
4060 case Qualifiers::OCL_None:
4061 case Qualifiers::OCL_ExplicitNone:
4062 case Qualifiers::OCL_Weak:
4063 break;
4064 }
4065
John McCalld0a30012010-12-06 06:10:02 +00004066 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004067 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004068 if (RV.isScalar())
4069 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004070 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004071 return LV;
4072 }
John McCall4f29b492010-11-16 23:07:28 +00004073
John McCall47fb9502013-03-07 21:37:08 +00004074 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004075 return EmitComplexAssignmentLValue(E);
4076
John McCall47fb9502013-03-07 21:37:08 +00004077 case TEK_Aggregate:
4078 return EmitAggExprToLValue(E);
4079 }
4080 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004081}
4082
Christopher Lambd91c3d42007-12-29 05:02:41 +00004083LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004084 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004085
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004086 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004087 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4088 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004089
David Majnemerced8bdf2015-02-25 17:36:15 +00004090 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004091 "Can't have a scalar return unless the return type is a "
4092 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004093
John McCall7f416cc2015-09-08 08:05:57 +00004094 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004095}
4096
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004097LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4098 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004099 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004100}
4101
Anders Carlsson3be22e22009-05-30 23:23:33 +00004102LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004103 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4104 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004105 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004106 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004107 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4108 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00004109}
4110
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004111LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004112CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004113 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004114}
4115
John McCall7f416cc2015-09-08 08:05:57 +00004116Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4117 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4118 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004119}
4120
4121LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004122 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4123 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00004124}
4125
Mike Stumpc9b231c2009-11-15 08:09:41 +00004126LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004127CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004128 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004129 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004130 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004131 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4132 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4133 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004134}
4135
Eli Friedman5bc17122012-02-08 05:34:55 +00004136LValue
4137CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004138 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004139 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004140 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4141 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00004142}
4143
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004144LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004145 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004146
Anders Carlsson280e61f12010-06-21 20:59:55 +00004147 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004148 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4149 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004150
Alp Toker314cc812014-01-25 16:55:45 +00004151 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004152 "Can't have a scalar return unless the return type is a "
4153 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004154
John McCall7f416cc2015-09-08 08:05:57 +00004155 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004156}
4157
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004158LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004159 Address V =
4160 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4161 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004162}
4163
Daniel Dunbar722f4242009-04-22 05:08:15 +00004164llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004165 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004166 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004167}
4168
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004169LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4170 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004171 const ObjCIvarDecl *Ivar,
4172 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004173 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004174 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004175}
4176
4177LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004178 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004179 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004180 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004181 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004182 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004183 if (E->isArrow()) {
4184 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004185 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004186 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004187 } else {
4188 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004189 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004190 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004191 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004192 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004193
Craig Topper99e79272013-07-26 05:59:26 +00004194 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004195 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4196 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004197 setObjCGCLValueClass(getContext(), E, LV);
4198 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004199}
4200
Chris Lattnera4185c52009-04-25 19:35:26 +00004201LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004202 // Can only get l-value for message expression returning aggregate type
4203 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004204 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4205 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00004206}
4207
John McCallb92ab1a2016-10-26 23:46:34 +00004208RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004209 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004210 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004211 // Get the actual function type. The callee type will always be a pointer to
4212 // function type or a block pointer type.
4213 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004214 "Call must have function pointer type!");
4215
John McCallb92ab1a2016-10-26 23:46:34 +00004216 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004217
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004218 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004219 // We can only guarantee that a function is called from the correct
4220 // context/function based on the appropriate target attributes,
4221 // so only check in the case where we have both always_inline and target
4222 // since otherwise we could be making a conditional call after a check for
4223 // the proper cpu features (and it won't cause code generation issues due to
4224 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004225 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4226 TargetDecl->hasAttr<TargetAttr>())
4227 checkTargetFeatures(E, FD);
4228
John McCall6fd4c232009-10-23 08:22:42 +00004229 CalleeType = getContext().getCanonicalType(CalleeType);
4230
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004231 const auto *FnType =
4232 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004233
John McCallb92ab1a2016-10-26 23:46:34 +00004234 CGCallee Callee = OrigCallee;
4235
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004236 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004237 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4238 if (llvm::Constant *PrefixSig =
4239 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004240 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004241 llvm::Constant *FTRTTIConst =
4242 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4243 llvm::Type *PrefixStructTyElems[] = {
4244 PrefixSig->getType(),
4245 FTRTTIConst->getType()
4246 };
4247 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4248 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4249
John McCallb92ab1a2016-10-26 23:46:34 +00004250 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4251
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004252 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004253 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004254 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004255 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004256 llvm::Value *CalleeSig =
4257 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004258 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4259
4260 llvm::BasicBlock *Cont = createBasicBlock("cont");
4261 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4262 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4263
4264 EmitBlock(TypeCheck);
4265 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004266 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004267 llvm::Value *CalleeRTTI =
4268 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004269 llvm::Value *CalleeRTTIMatch =
4270 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4271 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004272 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004273 EmitCheckTypeDescriptor(CalleeType)
4274 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004275 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004276 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004277
4278 Builder.CreateBr(Cont);
4279 EmitBlock(Cont);
4280 }
4281 }
4282
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004283 // If we are checking indirect calls and this call is indirect, check that the
4284 // function pointer is a member of the bit set for the function type.
4285 if (SanOpts.has(SanitizerKind::CFIICall) &&
4286 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4287 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004288 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004289
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004290 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004291 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004292
John McCallb92ab1a2016-10-26 23:46:34 +00004293 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4294 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004295 llvm::Value *TypeTest = Builder.CreateCall(
4296 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004297
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004298 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004299 llvm::Constant *StaticData[] = {
4300 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4301 EmitCheckSourceLocation(E->getLocStart()),
4302 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4303 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004304 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4305 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004306 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004307 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004308 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004309 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004310 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004311 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004312 }
4313
Daniel Dunbarc722b852008-08-30 03:02:31 +00004314 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004315 if (Chain)
4316 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4317 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004318
4319 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004320 // right-to-left, and that we evaluate arguments to certain other operators
4321 // left-to-right. Note that we allow this to override the order dictated by
4322 // the calling convention on the MS ABI, which means that parameter
4323 // destruction order is not necessarily reverse construction order.
4324 // FIXME: Revisit this based on C++ committee response to unimplementability.
4325 EvaluationOrder Order = EvaluationOrder::Default;
4326 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4327 if (OCE->isAssignmentOp())
4328 Order = EvaluationOrder::ForceRightToLeft;
4329 else {
4330 switch (OCE->getOperator()) {
4331 case OO_LessLess:
4332 case OO_GreaterGreater:
4333 case OO_AmpAmp:
4334 case OO_PipePipe:
4335 case OO_Comma:
4336 case OO_ArrowStar:
4337 Order = EvaluationOrder::ForceLeftToRight;
4338 break;
4339 default:
4340 break;
4341 }
4342 }
4343 }
Richard Smith762672a2016-09-28 19:09:10 +00004344
David Blaikief05779e2015-07-21 18:37:18 +00004345 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004346 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004347
Peter Collingbournef7706832014-12-12 23:41:25 +00004348 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4349 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004350
4351 // C99 6.5.2.2p6:
4352 // If the expression that denotes the called function has a type
4353 // that does not include a prototype, [the default argument
4354 // promotions are performed]. If the number of arguments does not
4355 // equal the number of parameters, the behavior is undefined. If
4356 // the function is defined with a type that includes a prototype,
4357 // and either the prototype ends with an ellipsis (, ...) or the
4358 // types of the arguments after promotion are not compatible with
4359 // the types of the parameters, the behavior is undefined. If the
4360 // function is defined with a type that does not include a
4361 // prototype, and the types of the arguments after promotion are
4362 // not compatible with those of the parameters after promotion,
4363 // the behavior is undefined [except in some trivial cases].
4364 // That is, in the general case, we should assume that a call
4365 // through an unprototyped function type works like a *non-variadic*
4366 // call. The way we make this work is to cast to the exact type
4367 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004368 //
4369 // Chain calls use this same code path to add the invisible chain parameter
4370 // to the function type.
4371 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004372 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004373 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004374
4375 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4376 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4377 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004378 }
4379
John McCallb92ab1a2016-10-26 23:46:34 +00004380 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004381}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004382
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004383LValue CodeGenFunction::
4384EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004385 Address BaseAddr = Address::invalid();
4386 if (E->getOpcode() == BO_PtrMemI) {
4387 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4388 } else {
4389 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4390 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004391
John McCallc134eb52010-08-31 21:07:20 +00004392 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4393
4394 const MemberPointerType *MPT
4395 = E->getRHS()->getType()->getAs<MemberPointerType>();
4396
John McCall7f416cc2015-09-08 08:05:57 +00004397 AlignmentSource AlignSource;
4398 Address MemberAddr =
4399 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4400 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00004401
John McCall7f416cc2015-09-08 08:05:57 +00004402 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004403}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004404
John McCall47fb9502013-03-07 21:37:08 +00004405/// Given the address of a temporary variable, produce an r-value of
4406/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004407RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004408 QualType type,
4409 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00004410 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004411 switch (getEvaluationKind(type)) {
4412 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004413 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004414 case TEK_Aggregate:
4415 return lvalue.asAggregateRValue();
4416 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004417 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004418 }
4419 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004420}
4421
Duncan Sandse81111c2012-04-10 08:23:07 +00004422void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004423 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004424 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004425 return;
4426
Duncan Sands65229ed2012-04-16 16:29:47 +00004427 llvm::MDBuilder MDHelper(getLLVMContext());
4428 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004429
Duncan Sands6fc46192012-04-14 12:37:26 +00004430 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004431}
John McCallfe96e0b2011-11-06 09:01:30 +00004432
4433namespace {
4434 struct LValueOrRValue {
4435 LValue LV;
4436 RValue RV;
4437 };
4438}
4439
4440static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4441 const PseudoObjectExpr *E,
4442 bool forLValue,
4443 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004444 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004445
4446 // Find the result expression, if any.
4447 const Expr *resultExpr = E->getResultExpr();
4448 LValueOrRValue result;
4449
4450 for (PseudoObjectExpr::const_semantics_iterator
4451 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4452 const Expr *semantic = *i;
4453
4454 // If this semantic expression is an opaque value, bind it
4455 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004456 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004457
4458 // If this is the result expression, we may need to evaluate
4459 // directly into the slot.
4460 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4461 OVMA opaqueData;
4462 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004463 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004464 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4465
John McCall7f416cc2015-09-08 08:05:57 +00004466 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4467 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004468 opaqueData = OVMA::bind(CGF, ov, LV);
4469 result.RV = slot.asRValue();
4470
4471 // Otherwise, emit as normal.
4472 } else {
4473 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4474
4475 // If this is the result, also evaluate the result now.
4476 if (ov == resultExpr) {
4477 if (forLValue)
4478 result.LV = CGF.EmitLValue(ov);
4479 else
4480 result.RV = CGF.EmitAnyExpr(ov, slot);
4481 }
4482 }
4483
4484 opaques.push_back(opaqueData);
4485
4486 // Otherwise, if the expression is the result, evaluate it
4487 // and remember the result.
4488 } else if (semantic == resultExpr) {
4489 if (forLValue)
4490 result.LV = CGF.EmitLValue(semantic);
4491 else
4492 result.RV = CGF.EmitAnyExpr(semantic, slot);
4493
4494 // Otherwise, evaluate the expression in an ignored context.
4495 } else {
4496 CGF.EmitIgnoredExpr(semantic);
4497 }
4498 }
4499
4500 // Unbind all the opaques now.
4501 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4502 opaques[i].unbind(CGF);
4503
4504 return result;
4505}
4506
4507RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4508 AggValueSlot slot) {
4509 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4510}
4511
4512LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4513 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4514}