blob: c08735d1afa2ee907796571541e6e23b2f10ae93 [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) {
Craig Topper8a13c412014-05-21 05:09:00 +000074 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000075}
Chris Lattner8394d792007-06-05 20:53:16 +000076
John McCall7f416cc2015-09-08 08:05:57 +000077/// CreateDefaultAlignTempAlloca - This creates an alloca with the
78/// default alignment of the corresponding LLVM type, which is *not*
79/// guaranteed to be related in any way to the expected alignment of
80/// an AST type that might have been lowered to Ty.
81Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
82 const Twine &Name) {
83 CharUnits Align =
84 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
85 return CreateTempAlloca(Ty, Align, Name);
86}
87
88void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
89 assert(isa<llvm::AllocaInst>(Var.getPointer()));
90 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
91 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000092 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +000093 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +000094}
95
John McCall7f416cc2015-09-08 08:05:57 +000096Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000097 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000098 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +000099}
100
John McCall7f416cc2015-09-08 08:05:57 +0000101Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000102 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +0000103 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
104}
105
106Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
107 const Twine &Name) {
108 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000109}
110
Chris Lattner8394d792007-06-05 20:53:16 +0000111/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
112/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000113llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000114 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000115 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000116 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000117 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000118 }
John McCall7a9aac22010-08-23 01:21:21 +0000119
120 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000121 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000122 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000123 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000124
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000125 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
126 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000127}
128
John McCalla2342eb2010-12-05 02:00:02 +0000129/// EmitIgnoredExpr - Emit code to compute the specified expression,
130/// ignoring the result.
131void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
132 if (E->isRValue())
133 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
134
135 // Just emit it as an l-value and drop the result.
136 EmitLValue(E);
137}
138
John McCall7a626f62010-09-15 10:14:12 +0000139/// EmitAnyExpr - Emit code to compute the specified expression which
140/// can have any type. The result is returned as an RValue struct.
141/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000142/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000143RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
144 AggValueSlot aggSlot,
145 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000146 switch (getEvaluationKind(E->getType())) {
147 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000148 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000149 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000150 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000151 case TEK_Aggregate:
152 if (!ignoreResult && aggSlot.isIgnored())
153 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
154 EmitAggExpr(E, aggSlot);
155 return aggSlot.asRValue();
156 }
157 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000158}
159
Mike Stump4a3999f2009-09-09 13:00:44 +0000160/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
161/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000162RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
163 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000164
John McCall47fb9502013-03-07 21:37:08 +0000165 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000166 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
167 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000168}
169
John McCall21886962010-04-21 10:05:39 +0000170/// EmitAnyExprToMem - Evaluate an expression into a given memory
171/// location.
172void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000173 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000174 Qualifiers Quals,
175 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000176 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000177 switch (getEvaluationKind(E->getType())) {
178 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000179 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000180 /*isInit*/ false);
181 return;
182
183 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000184 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000185 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000186 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000187 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000188 return;
189 }
190
191 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000192 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000193 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000194 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000195 return;
John McCall21886962010-04-21 10:05:39 +0000196 }
John McCall47fb9502013-03-07 21:37:08 +0000197 }
198 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000199}
200
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000201static void
202pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000203 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000204 // Objective-C++ ARC:
205 // If we are binding a reference to a temporary that has ownership, we
206 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000207 //
208 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000209 if (auto Lifetime = M->getType().getObjCLifetime()) {
210 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000211 case Qualifiers::OCL_None:
212 case Qualifiers::OCL_ExplicitNone:
213 // Carry on to normal cleanup handling.
214 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000215
Richard Smith736a9472013-06-12 20:42:33 +0000216 case Qualifiers::OCL_Autoreleasing:
217 // Nothing to do; cleaned up by an autorelease pool.
218 return;
219
220 case Qualifiers::OCL_Strong:
221 case Qualifiers::OCL_Weak:
222 switch (StorageDuration Duration = M->getStorageDuration()) {
223 case SD_Static:
224 // Note: we intentionally do not register a cleanup to release
225 // the object on program termination.
226 return;
227
228 case SD_Thread:
229 // FIXME: We should probably register a cleanup in this case.
230 return;
231
232 case SD_Automatic:
233 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000234 CodeGenFunction::Destroyer *Destroy;
235 CleanupKind CleanupKind;
236 if (Lifetime == Qualifiers::OCL_Strong) {
237 const ValueDecl *VD = M->getExtendingDecl();
238 bool Precise =
239 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
240 CleanupKind = CGF.getARCCleanupKind();
241 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
242 : &CodeGenFunction::destroyARCStrongImprecise;
243 } else {
244 // __weak objects always get EH cleanups; otherwise, exceptions
245 // could cause really nasty crashes instead of mere leaks.
246 CleanupKind = NormalAndEHCleanup;
247 Destroy = &CodeGenFunction::destroyARCWeak;
248 }
249 if (Duration == SD_FullExpression)
250 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000251 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000252 CleanupKind & EHCleanup);
253 else
254 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000255 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000256 *Destroy, CleanupKind & EHCleanup);
257 return;
258
259 case SD_Dynamic:
260 llvm_unreachable("temporary cannot have dynamic storage duration");
261 }
262 llvm_unreachable("unknown storage duration");
263 }
264 }
265
Craig Topper8a13c412014-05-21 05:09:00 +0000266 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000267 if (const RecordType *RT =
268 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
269 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000270 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000271 if (!ClassDecl->hasTrivialDestructor())
272 ReferenceTemporaryDtor = ClassDecl->getDestructor();
273 }
274
275 if (!ReferenceTemporaryDtor)
276 return;
277
278 // Call the destructor for the temporary.
279 switch (M->getStorageDuration()) {
280 case SD_Static:
281 case SD_Thread: {
282 llvm::Constant *CleanupFn;
283 llvm::Constant *CleanupArg;
284 if (E->getType()->isArrayType()) {
285 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000286 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000287 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
288 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000289 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
290 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000291 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
292 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000293 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000294 }
295 CGF.CGM.getCXXABI().registerGlobalDtor(
296 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
297 break;
298 }
299
300 case SD_FullExpression:
301 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
302 CodeGenFunction::destroyCXXObject,
303 CGF.getLangOpts().Exceptions);
304 break;
305
306 case SD_Automatic:
307 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
308 ReferenceTemporary, E->getType(),
309 CodeGenFunction::destroyCXXObject,
310 CGF.getLangOpts().Exceptions);
311 break;
312
313 case SD_Dynamic:
314 llvm_unreachable("temporary cannot have dynamic storage duration");
315 }
316}
317
John McCall7f416cc2015-09-08 08:05:57 +0000318static Address
Richard Smith736a9472013-06-12 20:42:33 +0000319createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000320 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000321 switch (M->getStorageDuration()) {
322 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000323 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000324 // If we have a constant temporary array or record try to promote it into a
325 // constant global under the same rules a normal constant would've been
326 // promoted. This is easier on the optimizer and generally emits fewer
327 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000328 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000329 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000330 (Ty->isArrayType() || Ty->isRecordType()) &&
331 CGF.CGM.isTypeConstant(Ty, true))
332 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000333 auto *GV = new llvm::GlobalVariable(
334 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
335 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000336 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
337 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000338 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000339 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000340 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000341 return CGF.CreateMemTemp(Ty, "ref.tmp");
342 }
Richard Smith736a9472013-06-12 20:42:33 +0000343 case SD_Thread:
344 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000345 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000346
347 case SD_Dynamic:
348 llvm_unreachable("temporary can't have dynamic storage duration");
349 }
350 llvm_unreachable("unknown storage duration");
351}
352
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000353LValue CodeGenFunction::
354EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000355 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000356
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000357 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
358 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000359 auto ownership = M->getType().getObjCLifetime();
360 if (ownership != Qualifiers::OCL_None &&
361 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000362 Address Object = createReferenceTemporary(*this, M, E);
363 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
364 Object = Address(llvm::ConstantExpr::getBitCast(Var,
365 ConvertTypeForMem(E->getType())
366 ->getPointerTo(Object.getAddressSpace())),
367 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000368
369 // createReferenceTemporary will promote the temporary to a global with a
370 // constant initializer if it can. It can only do this to a value of
371 // ARC-manageable type if the value is global and therefore "immune" to
372 // ref-counting operations. Therefore we have no need to emit either a
373 // dynamic initialization or a cleanup and we can just return the address
374 // of the temporary.
375 if (Var->hasInitializer())
376 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
377
Richard Smitha509f2f2013-06-14 03:07:01 +0000378 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
379 }
John McCall7f416cc2015-09-08 08:05:57 +0000380 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
381 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000382
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000383 switch (getEvaluationKind(E->getType())) {
384 default: llvm_unreachable("expected scalar or aggregate expression");
385 case TEK_Scalar:
386 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
387 break;
388 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000389 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000390 E->getType().getQualifiers(),
391 AggValueSlot::IsDestructed,
392 AggValueSlot::DoesNotNeedGCBarriers,
393 AggValueSlot::IsNotAliased));
394 break;
395 }
396 }
Richard Smith736a9472013-06-12 20:42:33 +0000397
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000398 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000399 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000400 }
401
Richard Smithf3fabd22013-06-03 00:17:11 +0000402 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000403 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000404 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
405
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000406 for (const auto &Ignored : CommaLHSs)
407 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000408
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000409 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000410 if (opaque->getType()->isRecordType()) {
411 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000412 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000413 }
414 }
415
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000416 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000417 Address Object = createReferenceTemporary(*this, M, E);
418 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
419 Object = Address(llvm::ConstantExpr::getBitCast(
420 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
421 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000422 // If the temporary is a global and has a constant initializer or is a
423 // constant temporary that we promoted to a global, we may have already
424 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000425 if (!Var->hasInitializer()) {
426 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
427 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
428 }
429 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000430 switch (M->getStorageDuration()) {
431 case SD_Automatic:
432 case SD_FullExpression:
433 if (auto *Size = EmitLifetimeStart(
434 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
435 Object.getPointer())) {
436 if (M->getStorageDuration() == SD_Automatic)
437 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
438 Object, Size);
439 else
440 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
441 Size);
442 }
443 break;
444 default:
445 break;
446 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000447 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
448 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000449 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000450
Richard Smith736a9472013-06-12 20:42:33 +0000451 // Perform derived-to-base casts and/or field accesses, to get from the
452 // temporary object we created (and, potentially, for which we extended
453 // the lifetime) to the subobject we're binding the reference to.
454 for (unsigned I = Adjustments.size(); I != 0; --I) {
455 SubobjectAdjustment &Adjustment = Adjustments[I-1];
456 switch (Adjustment.Kind) {
457 case SubobjectAdjustment::DerivedToBaseAdjustment:
458 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000459 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
460 Adjustment.DerivedToBase.BasePath->path_begin(),
461 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000462 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000463 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000464
Richard Smith736a9472013-06-12 20:42:33 +0000465 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000466 LValue LV = MakeAddrLValue(Object, E->getType(),
467 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000468 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000469 assert(LV.isSimple() &&
470 "materialized temporary field is not a simple lvalue");
471 Object = LV.getAddress();
472 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000473 }
474
Richard Smith736a9472013-06-12 20:42:33 +0000475 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000476 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000477 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
478 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000479 break;
480 }
481 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000482 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000483
John McCall7f416cc2015-09-08 08:05:57 +0000484 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000485}
486
487RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000488CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
489 // Emit the expression as an lvalue.
490 LValue LV = EmitLValue(E);
491 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000492 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000493
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000494 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000495 // C++11 [dcl.ref]p5 (as amended by core issue 453):
496 // If a glvalue to which a reference is directly bound designates neither
497 // an existing object or function of an appropriate type nor a region of
498 // storage of suitable size and alignment to contain an object of the
499 // reference's type, the behavior is undefined.
500 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000501 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000502 }
John McCall8680f872010-07-21 06:29:51 +0000503
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000504 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000505}
506
507
Mike Stump4a3999f2009-09-09 13:00:44 +0000508/// getAccessedFieldNo - Given an encoded value and a result number, return the
509/// input field number being accessed.
510unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000511 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000512 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
513 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000514}
515
Richard Smith4d3110a2012-10-25 02:14:12 +0000516/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
517static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
518 llvm::Value *High) {
519 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
520 llvm::Value *K47 = Builder.getInt64(47);
521 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
522 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
523 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
524 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
525 return Builder.CreateMul(B1, KMul);
526}
527
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000528bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000529 return SanOpts.has(SanitizerKind::Null) |
530 SanOpts.has(SanitizerKind::Alignment) |
531 SanOpts.has(SanitizerKind::ObjectSize) |
532 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000533}
534
Richard Smithe30752c2012-10-09 19:52:38 +0000535void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000536 llvm::Value *Ptr, QualType Ty,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000537 CharUnits Alignment, bool SkipNullCheck) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000538 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000539 return;
540
Richard Smith2d8b2942012-11-01 07:22:08 +0000541 // Don't check pointers outside the default address space. The null check
542 // isn't correct, the object-size check isn't supported by LLVM, and we can't
543 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000544 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000545 return;
546
Alexey Samsonov24cad992014-07-17 18:46:27 +0000547 SanitizerScope SanScope(this);
548
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000549 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000550 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000551
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000552 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
553 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000554 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
555 !SkipNullCheck) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000556 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000557 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000558
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000559 if (AllowNullPointers) {
560 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000561 // Skip the remaining checks in that case.
562 Done = createBasicBlock("null");
563 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000564 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000565 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000566 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000567 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000568 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000569 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000570
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000571 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000572 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000573
Richard Smith69d0d262012-08-24 00:54:33 +0000574 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000575 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000576 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000577 // FIXME: Get object address space
578 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
579 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000580 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000581 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000582 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000583 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000584 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000585 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000586 }
Richard Smith69d0d262012-08-24 00:54:33 +0000587
Richard Smithb1b0ab42012-11-05 22:21:05 +0000588 uint64_t AlignVal = 0;
589
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000590 if (SanOpts.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000591 AlignVal = Alignment.getQuantity();
592 if (!Ty->isIncompleteType() && !AlignVal)
593 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
594
Richard Smith69d0d262012-08-24 00:54:33 +0000595 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000596 if (AlignVal) {
597 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000598 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000599 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
600 llvm::Value *Aligned =
601 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000602 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000603 }
Richard Smith69d0d262012-08-24 00:54:33 +0000604 }
605
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000606 if (Checks.size() > 0) {
Richard Smithe30752c2012-10-09 19:52:38 +0000607 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000608 EmitCheckSourceLocation(Loc),
Richard Smithe30752c2012-10-09 19:52:38 +0000609 EmitCheckTypeDescriptor(Ty),
610 llvm::ConstantInt::get(SizeTy, AlignVal),
611 llvm::ConstantInt::get(Int8Ty, TCK)
612 };
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000613 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000614 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000615
Richard Smithb1b0ab42012-11-05 22:21:05 +0000616 // If possible, check that the vptr indicates that there is a subobject of
617 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000618 //
619 // C++11 [basic.life]p5,6:
620 // [For storage which does not refer to an object within its lifetime]
621 // The program has undefined behavior if:
622 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000623 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000624 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000625 if (SanOpts.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000626 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000627 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
628 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000629 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000630 // Compute a hash of the mangled name of the type.
631 //
632 // FIXME: This is not guaranteed to be deterministic! Move to a
633 // fingerprinting mechanism once LLVM provides one. For the time
634 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000635 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000636 llvm::raw_svector_ostream Out(MangledName);
637 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
638 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000639
Alexey Samsonov84856012014-07-10 22:34:19 +0000640 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000641 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
642 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000643 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000644
Alexey Samsonov84856012014-07-10 22:34:19 +0000645 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
646 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
647 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000648 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000649 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
650 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000651
Alexey Samsonov84856012014-07-10 22:34:19 +0000652 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
653 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000654
Alexey Samsonov84856012014-07-10 22:34:19 +0000655 // Look the hash up in our cache.
656 const int CacheSize = 128;
657 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
658 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
659 "__ubsan_vptr_type_cache");
660 llvm::Value *Slot = Builder.CreateAnd(Hash,
661 llvm::ConstantInt::get(IntPtrTy,
662 CacheSize-1));
663 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
664 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000665 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
666 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000667
668 // If the hash isn't in the cache, call a runtime handler to perform the
669 // hard work of checking whether the vptr is for an object of the right
670 // type. This will either fill in the cache and return, or produce a
671 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000672 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000673 llvm::Constant *StaticData[] = {
674 EmitCheckSourceLocation(Loc),
675 EmitCheckTypeDescriptor(Ty),
676 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
677 llvm::ConstantInt::get(Int8Ty, TCK)
678 };
John McCall7f416cc2015-09-08 08:05:57 +0000679 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000680 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000681 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
682 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000683 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000684 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000685
686 if (Done) {
687 Builder.CreateBr(Done);
688 EmitBlock(Done);
689 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000690}
Chris Lattner4647a212007-08-31 22:49:20 +0000691
Richard Smith539e4a72013-02-23 02:53:19 +0000692/// Determine whether this expression refers to a flexible array member in a
693/// struct. We disable array bounds checks for such members.
694static bool isFlexibleArrayMemberExpr(const Expr *E) {
695 // For compatibility with existing code, we treat arrays of length 0 or
696 // 1 as flexible array members.
697 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000698 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000699 if (CAT->getSize().ugt(1))
700 return false;
701 } else if (!isa<IncompleteArrayType>(AT))
702 return false;
703
704 E = E->IgnoreParens();
705
706 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000707 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000708 // FIXME: If the base type of the member expr is not FD->getParent(),
709 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000710 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000711 RecordDecl::field_iterator FI(
712 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
713 return ++FI == FD->getParent()->field_end();
714 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000715 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
716 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000717 }
718
719 return false;
720}
721
722/// If Base is known to point to the start of an array, return the length of
723/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000724static llvm::Value *getArrayIndexingBound(
725 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000726 // For the vector indexing extension, the bound is the number of elements.
727 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
728 IndexedType = Base->getType();
729 return CGF.Builder.getInt32(VT->getNumElements());
730 }
731
732 Base = Base->IgnoreParens();
733
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000734 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000735 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
736 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
737 IndexedType = CE->getSubExpr()->getType();
738 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000739 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000740 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000741 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000742 return CGF.getVLASize(VAT).first;
743 }
744 }
745
Craig Topper8a13c412014-05-21 05:09:00 +0000746 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000747}
748
749void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
750 llvm::Value *Index, QualType IndexType,
751 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000752 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000753 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000754 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000755
Richard Smith539e4a72013-02-23 02:53:19 +0000756 QualType IndexedType;
757 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
758 if (!Bound)
759 return;
760
761 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
762 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
763 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
764
765 llvm::Constant *StaticData[] = {
766 EmitCheckSourceLocation(E->getExprLoc()),
767 EmitCheckTypeDescriptor(IndexedType),
768 EmitCheckTypeDescriptor(IndexType)
769 };
770 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
771 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000772 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
773 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000774}
775
Chris Lattner116ce8f2010-01-09 21:40:03 +0000776
Chris Lattner116ce8f2010-01-09 21:40:03 +0000777CodeGenFunction::ComplexPairTy CodeGenFunction::
778EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
779 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000780 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000781
Chris Lattner116ce8f2010-01-09 21:40:03 +0000782 llvm::Value *NextVal;
783 if (isa<llvm::IntegerType>(InVal.first->getType())) {
784 uint64_t AmountVal = isInc ? 1 : -1;
785 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000786
Chris Lattner116ce8f2010-01-09 21:40:03 +0000787 // Add the inc/dec to the real part.
788 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
789 } else {
790 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
791 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
792 if (!isInc)
793 FVal.changeSign();
794 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000795
Chris Lattner116ce8f2010-01-09 21:40:03 +0000796 // Add the inc/dec to the real part.
797 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
798 }
Craig Topper99e79272013-07-26 05:59:26 +0000799
Chris Lattner116ce8f2010-01-09 21:40:03 +0000800 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000801
Chris Lattner116ce8f2010-01-09 21:40:03 +0000802 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000803 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000804
Chris Lattner116ce8f2010-01-09 21:40:03 +0000805 // If this is a postinc, return the value read from memory, otherwise use the
806 // updated value.
807 return isPre ? IncVal : InVal;
808}
809
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000810void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
811 CodeGenFunction *CGF) {
812 // Bind VLAs in the cast type.
813 if (CGF && E->getType()->isVariablyModifiedType())
814 CGF->EmitVariablyModifiedType(E->getType());
815
816 if (CGDebugInfo *DI = getModuleDebugInfo())
817 DI->EmitExplicitCastType(E->getType());
818}
819
Chris Lattnera45c5af2007-06-02 19:47:04 +0000820//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000821// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000822//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000823
John McCall7f416cc2015-09-08 08:05:57 +0000824/// EmitPointerWithAlignment - Given an expression of pointer type, try to
825/// derive a more accurate bound on the alignment of the pointer.
826Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
827 AlignmentSource *Source) {
828 // We allow this with ObjC object pointers because of fragile ABIs.
829 assert(E->getType()->isPointerType() ||
830 E->getType()->isObjCObjectPointerType());
831 E = E->IgnoreParens();
832
833 // Casts:
834 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000835 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
836 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000837
838 switch (CE->getCastKind()) {
839 // Non-converting casts (but not C's implicit conversion from void*).
840 case CK_BitCast:
841 case CK_NoOp:
842 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
843 if (PtrTy->getPointeeType()->isVoidType())
844 break;
845
846 AlignmentSource InnerSource;
847 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
848 if (Source) *Source = InnerSource;
849
850 // If this is an explicit bitcast, and the source l-value is
851 // opaque, honor the alignment of the casted-to type.
852 if (isa<ExplicitCastExpr>(CE) &&
John McCall7f416cc2015-09-08 08:05:57 +0000853 InnerSource != AlignmentSource::Decl) {
854 Addr = Address(Addr.getPointer(),
855 getNaturalPointeeTypeAlignment(E->getType(), Source));
856 }
857
Peter Collingbourne574975e2016-01-14 02:49:48 +0000858 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
859 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000860 if (auto PT = E->getType()->getAs<PointerType>())
861 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
862 /*MayBeNull=*/true,
863 CodeGenFunction::CFITCK_UnrelatedCast,
864 CE->getLocStart());
865 }
866
John McCall7f416cc2015-09-08 08:05:57 +0000867 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
868 }
869 break;
870
871 // Array-to-pointer decay.
872 case CK_ArrayToPointerDecay:
873 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
874
875 // Derived-to-base conversions.
876 case CK_UncheckedDerivedToBase:
877 case CK_DerivedToBase: {
878 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
879 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
880 return GetAddressOfBaseClass(Addr, Derived,
881 CE->path_begin(), CE->path_end(),
882 ShouldNullCheckClassCastValue(CE),
883 CE->getExprLoc());
884 }
885
886 // TODO: Is there any reason to treat base-to-derived conversions
887 // specially?
888 default:
889 break;
890 }
891 }
892
893 // Unary &.
894 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
895 if (UO->getOpcode() == UO_AddrOf) {
896 LValue LV = EmitLValue(UO->getSubExpr());
897 if (Source) *Source = LV.getAlignmentSource();
898 return LV.getAddress();
899 }
900 }
901
902 // TODO: conditional operators, comma.
903
904 // Otherwise, use the alignment of the type.
905 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
906 return Address(EmitScalarExpr(E), Align);
907}
908
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000909RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000910 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000911 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000912
913 switch (getEvaluationKind(Ty)) {
914 case TEK_Complex: {
915 llvm::Type *EltTy =
916 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000917 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000918 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000919 }
Craig Topper99e79272013-07-26 05:59:26 +0000920
Chris Lattner65526f02010-08-23 05:26:13 +0000921 // If this is a use of an undefined aggregate type, the aggregate must have an
922 // identifiable address. Just because the contents of the value are undefined
923 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000924 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000925 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000926 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000927 }
John McCall47fb9502013-03-07 21:37:08 +0000928
929 case TEK_Scalar:
930 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
931 }
932 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000933}
934
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000935RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
936 const char *Name) {
937 ErrorUnsupported(E, Name);
938 return GetUndefRValue(E->getType());
939}
940
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000941LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
942 const char *Name) {
943 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000944 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000945 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
946 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000947}
948
Richard Smith4d1458e2012-09-08 02:08:36 +0000949LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000950 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000951 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000952 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
953 else
954 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000955 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000956 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000957 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000958 return LV;
959}
960
Chris Lattner8394d792007-06-05 20:53:16 +0000961/// EmitLValue - Emit code to compute a designator that specifies the location
962/// of the expression.
963///
Mike Stump4a3999f2009-09-09 13:00:44 +0000964/// This can return one of two things: a simple address or a bitfield reference.
965/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
966/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000967///
Mike Stump4a3999f2009-09-09 13:00:44 +0000968/// If this returns a bitfield reference, nothing about the pointee type of the
969/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000970///
Mike Stump4a3999f2009-09-09 13:00:44 +0000971/// If this returns a normal address, and if the lvalue's C type is fixed size,
972/// this method guarantees that the returned pointer type will point to an LLVM
973/// type of the same size of the lvalue's type. If the lvalue has a variable
974/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000975///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000976LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000977 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000978 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000979 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000980
John McCallc109a252011-11-07 03:59:57 +0000981 case Expr::ObjCPropertyRefExprClass:
982 llvm_unreachable("cannot emit a property reference directly");
983
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000984 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000985 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000986 case Expr::ObjCIsaExprClass:
987 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000988 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000989 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000990 case Expr::CompoundAssignOperatorClass: {
991 QualType Ty = E->getType();
992 if (const AtomicType *AT = Ty->getAs<AtomicType>())
993 Ty = AT->getValueType();
994 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000995 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
996 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000997 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000998 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000999 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001000 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001001 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001002 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001003 case Expr::VAArgExprClass:
1004 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001005 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001006 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001007 case Expr::ParenExprClass:
1008 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001009 case Expr::GenericSelectionExprClass:
1010 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001011 case Expr::PredefinedExprClass:
1012 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001013 case Expr::StringLiteralClass:
1014 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001015 case Expr::ObjCEncodeExprClass:
1016 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001017 case Expr::PseudoObjectExprClass:
1018 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001019 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001020 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001021 case Expr::CXXTemporaryObjectExprClass:
1022 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001023 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1024 case Expr::CXXBindTemporaryExprClass:
1025 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001026 case Expr::CXXUuidofExprClass:
1027 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001028 case Expr::LambdaExprClass:
1029 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001030
1031 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001032 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001033 enterFullExpression(cleanups);
1034 RunCleanupsScope Scope(*this);
1035 return EmitLValue(cleanups->getSubExpr());
1036 }
1037
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001038 case Expr::CXXDefaultArgExprClass:
1039 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001040 case Expr::CXXDefaultInitExprClass: {
1041 CXXDefaultInitExprScope Scope(*this);
1042 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1043 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001044 case Expr::CXXTypeidExprClass:
1045 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001046
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001047 case Expr::ObjCMessageExprClass:
1048 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001049 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001050 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001051 case Expr::StmtExprClass:
1052 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001053 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001054 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001055 case Expr::ArraySubscriptExprClass:
1056 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001057 case Expr::OMPArraySectionExprClass:
1058 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001059 case Expr::ExtVectorElementExprClass:
1060 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001061 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001062 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001063 case Expr::CompoundLiteralExprClass:
1064 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001065 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001066 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001067 case Expr::BinaryConditionalOperatorClass:
1068 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001069 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001070 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001071 case Expr::OpaqueValueExprClass:
1072 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001073 case Expr::SubstNonTypeTemplateParmExprClass:
1074 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001075 case Expr::ImplicitCastExprClass:
1076 case Expr::CStyleCastExprClass:
1077 case Expr::CXXFunctionalCastExprClass:
1078 case Expr::CXXStaticCastExprClass:
1079 case Expr::CXXDynamicCastExprClass:
1080 case Expr::CXXReinterpretCastExprClass:
1081 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001082 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001083 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001084
Douglas Gregorfe314812011-06-21 17:03:29 +00001085 case Expr::MaterializeTemporaryExprClass:
1086 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001087 }
1088}
1089
John McCall71335052012-03-10 03:05:10 +00001090/// Given an object of the given canonical type, can we safely copy a
1091/// value out of it based on its initializer?
1092static bool isConstantEmittableObjectType(QualType type) {
1093 assert(type.isCanonical());
1094 assert(!type->isReferenceType());
1095
1096 // Must be const-qualified but non-volatile.
1097 Qualifiers qs = type.getLocalQualifiers();
1098 if (!qs.hasConst() || qs.hasVolatile()) return false;
1099
1100 // Otherwise, all object types satisfy this except C++ classes with
1101 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001102 if (const auto *RT = dyn_cast<RecordType>(type))
1103 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001104 if (RD->hasMutableFields() || !RD->isTrivial())
1105 return false;
1106
1107 return true;
1108}
1109
1110/// Can we constant-emit a load of a reference to a variable of the
1111/// given type? This is different from predicates like
1112/// Decl::isUsableInConstantExpressions because we do want it to apply
1113/// in situations that don't necessarily satisfy the language's rules
1114/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1115/// to do this with const float variables even if those variables
1116/// aren't marked 'constexpr'.
1117enum ConstantEmissionKind {
1118 CEK_None,
1119 CEK_AsReferenceOnly,
1120 CEK_AsValueOrReference,
1121 CEK_AsValueOnly
1122};
1123static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1124 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001125 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001126 if (isConstantEmittableObjectType(ref->getPointeeType()))
1127 return CEK_AsValueOrReference;
1128 return CEK_AsReferenceOnly;
1129 }
1130 if (isConstantEmittableObjectType(type))
1131 return CEK_AsValueOnly;
1132 return CEK_None;
1133}
1134
1135/// Try to emit a reference to the given value without producing it as
1136/// an l-value. This is actually more than an optimization: we can't
1137/// produce an l-value for variables that we never actually captured
1138/// in a block or lambda, which means const int variables or constexpr
1139/// literals or similar.
1140CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001141CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1142 ValueDecl *value = refExpr->getDecl();
1143
John McCall71335052012-03-10 03:05:10 +00001144 // The value needs to be an enum constant or a constant variable.
1145 ConstantEmissionKind CEK;
1146 if (isa<ParmVarDecl>(value)) {
1147 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001148 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001149 CEK = checkVarTypeForConstantEmission(var->getType());
1150 } else if (isa<EnumConstantDecl>(value)) {
1151 CEK = CEK_AsValueOnly;
1152 } else {
1153 CEK = CEK_None;
1154 }
1155 if (CEK == CEK_None) return ConstantEmission();
1156
John McCall71335052012-03-10 03:05:10 +00001157 Expr::EvalResult result;
1158 bool resultIsReference;
1159 QualType resultType;
1160
1161 // It's best to evaluate all the way as an r-value if that's permitted.
1162 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001163 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001164 resultIsReference = false;
1165 resultType = refExpr->getType();
1166
1167 // Otherwise, try to evaluate as an l-value.
1168 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001169 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001170 resultIsReference = true;
1171 resultType = value->getType();
1172
1173 // Failure.
1174 } else {
1175 return ConstantEmission();
1176 }
1177
1178 // In any case, if the initializer has side-effects, abandon ship.
1179 if (result.HasSideEffects)
1180 return ConstantEmission();
1181
1182 // Emit as a constant.
1183 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1184
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001185 // Make sure we emit a debug reference to the global variable.
1186 // This should probably fire even for
1187 if (isa<VarDecl>(value)) {
1188 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001189 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001190 } else {
1191 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001192 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001193 }
John McCall71335052012-03-10 03:05:10 +00001194
1195 // If we emitted a reference constant, we need to dereference that.
1196 if (resultIsReference)
1197 return ConstantEmission::forReference(C);
1198
1199 return ConstantEmission::forValue(C);
1200}
1201
Nick Lewycky2d84e842013-10-02 02:29:49 +00001202llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1203 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001204 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001205 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1206 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001207 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1208 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001209}
1210
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001211static bool hasBooleanRepresentation(QualType Ty) {
1212 if (Ty->isBooleanType())
1213 return true;
1214
1215 if (const EnumType *ET = Ty->getAs<EnumType>())
1216 return ET->getDecl()->getIntegerType()->isBooleanType();
1217
Douglas Gregor298f43d2012-04-12 20:42:30 +00001218 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1219 return hasBooleanRepresentation(AT->getValueType());
1220
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001221 return false;
1222}
1223
Richard Smith1629da92012-12-13 07:11:50 +00001224static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1225 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001226 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001227 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001228 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1229 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001230 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001231 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001232
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001233 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001234 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1235 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001236 } else {
1237 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001238 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001239 unsigned Bitwidth = LTy->getScalarSizeInBits();
1240 unsigned NumNegativeBits = ED->getNumNegativeBits();
1241 unsigned NumPositiveBits = ED->getNumPositiveBits();
1242
1243 if (NumNegativeBits) {
1244 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1245 assert(NumBits <= Bitwidth);
1246 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1247 Min = -End;
1248 } else {
1249 assert(NumPositiveBits <= Bitwidth);
1250 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1251 Min = llvm::APInt(Bitwidth, 0);
1252 }
1253 }
Richard Smith1629da92012-12-13 07:11:50 +00001254 return true;
1255}
1256
1257llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1258 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001259 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1260 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001261 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001262
Duncan Sandsc720e782012-04-15 18:04:54 +00001263 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001264 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001265}
1266
John McCall7f416cc2015-09-08 08:05:57 +00001267llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1268 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001269 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001270 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001271 llvm::MDNode *TBAAInfo,
1272 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001273 uint64_t TBAAOffset,
1274 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001275 // For better performance, handle vector loads differently.
1276 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001277 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001278
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001279 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001280
John McCall7f416cc2015-09-08 08:05:57 +00001281 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001282 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001283
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001284 // Bitcast to vec4 type.
1285 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1286 4);
John McCall7f416cc2015-09-08 08:05:57 +00001287 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001288 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001289 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001290
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001291 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001292 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001293 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001294 return EmitFromMemory(V, Ty);
1295 }
1296 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001297
1298 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001299 LValue AtomicLValue =
John McCall7f416cc2015-09-08 08:05:57 +00001300 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001301 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1302 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001303 }
Craig Topper99e79272013-07-26 05:59:26 +00001304
John McCall7f416cc2015-09-08 08:05:57 +00001305 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001306 if (isNontemporal) {
1307 llvm::MDNode *Node = llvm::MDNode::get(
1308 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1309 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1310 }
Manman Renc451e572013-04-04 21:53:22 +00001311 if (TBAAInfo) {
1312 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1313 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001314 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001315 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1316 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001317 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001318
Vedant Kumar4593a462016-12-09 23:48:18 +00001319 bool IsBool = hasBooleanRepresentation(Ty) ||
1320 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1321 bool NeedsBoolCheck = SanOpts.has(SanitizerKind::Bool) && IsBool;
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001322 bool NeedsEnumCheck =
1323 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1324 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001325 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001326 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001327 if (getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool)) {
Richard Smith1629da92012-12-13 07:11:50 +00001328 --End;
1329 llvm::Value *Check;
1330 if (!Min)
1331 Check = Builder.CreateICmpULE(
1332 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1333 else {
1334 llvm::Value *Upper = Builder.CreateICmpSLE(
1335 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1336 llvm::Value *Lower = Builder.CreateICmpSGE(
1337 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1338 Check = Builder.CreateAnd(Upper, Lower);
1339 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001340 llvm::Constant *StaticArgs[] = {
1341 EmitCheckSourceLocation(Loc),
1342 EmitCheckTypeDescriptor(Ty)
1343 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001344 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001345 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1346 StaticArgs, EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001347 }
1348 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001349 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1350 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001351
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001352 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001353}
1354
John McCall3a7f6922010-10-27 20:58:56 +00001355llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1356 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001357 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001358 // This should really always be an i1, but sometimes it's already
1359 // an i8, and it's awkward to track those cases down.
1360 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001361 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1362 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1363 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001364 }
1365
1366 return Value;
1367}
1368
1369llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1370 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001371 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001372 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1373 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001374 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1375 }
1376
1377 return Value;
1378}
1379
John McCall7f416cc2015-09-08 08:05:57 +00001380void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1381 bool Volatile, QualType Ty,
1382 AlignmentSource AlignSource,
1383 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001384 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001385 uint64_t TBAAOffset,
1386 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001387
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001388 // Handle vectors differently to get better performance.
1389 if (Ty->isVectorType()) {
1390 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001391 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001392 // Handle vec3 special.
1393 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001394 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001395 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1396 Builder.getInt32(2),
1397 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001398 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1399 Value = Builder.CreateShuffleVector(Value,
1400 llvm::UndefValue::get(VecTy),
1401 MaskV, "extractVec");
1402 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1403 }
John McCall7f416cc2015-09-08 08:05:57 +00001404 if (Addr.getElementType() != SrcTy) {
1405 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001406 }
1407 }
Craig Topper99e79272013-07-26 05:59:26 +00001408
John McCall3a7f6922010-10-27 20:58:56 +00001409 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001410
David Majnemera38c9f12016-05-24 16:09:25 +00001411 LValue AtomicLValue =
1412 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001413 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001414 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1415 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001416 return;
1417 }
1418
Daniel Dunbar03816342010-08-21 02:24:36 +00001419 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001420 if (isNontemporal) {
1421 llvm::MDNode *Node =
1422 llvm::MDNode::get(Store->getContext(),
1423 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1424 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1425 }
Manman Renc451e572013-04-04 21:53:22 +00001426 if (TBAAInfo) {
1427 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1428 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001429 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001430 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1431 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001432 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001433}
1434
David Chisnallfa35df62012-01-16 17:27:18 +00001435void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001436 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001437 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001438 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001439 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001440 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001441}
1442
Mike Stump4a3999f2009-09-09 13:00:44 +00001443/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1444/// method emits the address of the lvalue, then loads the result as an rvalue,
1445/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001446RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001447 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001448 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001449 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001450 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1451 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001452 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001453 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001454 // In MRC mode, we do a load+autorelease.
1455 if (!getLangOpts().ObjCAutoRefCount) {
1456 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1457 }
1458
1459 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001460 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1461 Object = EmitObjCConsumeObject(LV.getType(), Object);
1462 return RValue::get(Object);
1463 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001464
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001465 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001466 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001467
John McCalla1dee5302010-08-22 10:59:02 +00001468 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001469 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001470 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001471
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001472 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001473 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001474 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001475 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001476 "vecext"));
1477 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001478
1479 // If this is a reference to a subset of the elements of a vector, either
1480 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001481 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001482 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001483
Renato Golin230c5eb2014-05-19 18:15:42 +00001484 // Global Register variables always invoke intrinsics
1485 if (LV.isGlobalReg())
1486 return EmitLoadOfGlobalRegLValue(LV);
1487
John McCallc109a252011-11-07 03:59:57 +00001488 assert(LV.isBitField() && "Unknown LValue type!");
1489 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001490}
1491
John McCall55e1fbc2011-06-25 02:11:03 +00001492RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001493 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001494
Daniel Dunbar3447a022010-04-13 23:34:15 +00001495 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001496 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001497
John McCall7f416cc2015-09-08 08:05:57 +00001498 Address Ptr = LV.getBitFieldAddress();
1499 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001500
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001501 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001502 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001503 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1504 if (HighBits)
1505 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1506 if (Info.Offset + HighBits)
1507 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1508 } else {
1509 if (Info.Offset)
1510 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001511 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001512 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1513 Info.Size),
1514 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001515 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001516 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001517
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001518 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001519}
1520
Nate Begemanb699c9b2009-01-18 06:42:49 +00001521// If this is a reference to a subset of the elements of a vector, create an
1522// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001523RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001524 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1525 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001526
Nate Begemanf322eab2008-05-09 06:41:27 +00001527 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001528
1529 // If the result of the expression is a non-vector type, we must be extracting
1530 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001531 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001532 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001533 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001534 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001535 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001536 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001537
1538 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001539 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001540
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001541 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001542 for (unsigned i = 0; i != NumResultElts; ++i)
1543 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001544
Chris Lattner91c08ad2011-02-15 00:14:06 +00001545 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1546 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001547 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001548 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001549}
1550
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001551/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001552Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1553 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001554 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1555 QualType EQT = ExprVT->getElementType();
1556 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001557
John McCall7f416cc2015-09-08 08:05:57 +00001558 Address CastToPointerElement =
1559 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1560 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001561
1562 const llvm::Constant *Elts = LV.getExtVectorElts();
1563 unsigned ix = getAccessedFieldNo(0, Elts);
1564
John McCall7f416cc2015-09-08 08:05:57 +00001565 Address VectorBasePtrPlusIx =
1566 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1567 getContext().getTypeSizeInChars(EQT),
1568 "vector.elt");
1569
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001570 return VectorBasePtrPlusIx;
1571}
1572
Renato Golin230c5eb2014-05-19 18:15:42 +00001573/// @brief Load of global gamed gegisters are always calls to intrinsics.
1574RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001575 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1576 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001577 llvm::MDNode *RegName = cast<llvm::MDNode>(
1578 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001579
1580 // We accept integer and pointer types only
1581 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1582 llvm::Type *Ty = OrigTy;
1583 if (OrigTy->isPointerTy())
1584 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1585 llvm::Type *Types[] = { Ty };
1586
Renato Golin230c5eb2014-05-19 18:15:42 +00001587 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001588 llvm::Value *Call = Builder.CreateCall(
1589 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001590 if (OrigTy->isPointerTy())
1591 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001592 return RValue::get(Call);
1593}
Chris Lattner40ff7012007-08-03 16:18:34 +00001594
Chris Lattner9369a562007-06-29 16:31:29 +00001595
Chris Lattner8394d792007-06-05 20:53:16 +00001596/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1597/// lvalue, where both are guaranteed to the have the same type, and that type
1598/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001599void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001600 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001601 if (!Dst.isSimple()) {
1602 if (Dst.isVectorElt()) {
1603 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001604 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1605 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001606 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001607 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001608 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1609 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001610 return;
1611 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001612
Nate Begemance4d7fc2008-04-18 23:10:10 +00001613 // If this is an update of extended vector elements, insert them as
1614 // appropriate.
1615 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001616 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001617
Renato Golin230c5eb2014-05-19 18:15:42 +00001618 if (Dst.isGlobalReg())
1619 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1620
John McCallc109a252011-11-07 03:59:57 +00001621 assert(Dst.isBitField() && "Unknown LValue type");
1622 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001623 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001624
John McCall31168b02011-06-15 23:02:42 +00001625 // There's special magic for assigning into an ARC-qualified l-value.
1626 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1627 switch (Lifetime) {
1628 case Qualifiers::OCL_None:
1629 llvm_unreachable("present but none");
1630
1631 case Qualifiers::OCL_ExplicitNone:
1632 // nothing special
1633 break;
1634
1635 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001636 if (isInit) {
1637 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1638 break;
1639 }
John McCall55e1fbc2011-06-25 02:11:03 +00001640 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001641 return;
1642
1643 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001644 if (isInit)
1645 // Initialize and then skip the primitive store.
1646 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1647 else
1648 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001649 return;
1650
1651 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001652 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1653 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001654 // fall into the normal path
1655 break;
1656 }
1657 }
1658
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001659 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001660 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001661 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001662 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001663 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001664 return;
1665 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001666
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001667 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001668 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001669 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001670 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001671 if (Dst.isObjCIvar()) {
1672 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001673 llvm::Type *ResultType = IntPtrTy;
1674 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1675 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001676 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001677 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001678 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1679 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001680 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001681 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001682 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001683 } else if (Dst.isGlobalObjCRef()) {
1684 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1685 Dst.isThreadLocalRef());
1686 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001687 else
1688 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001689 return;
1690 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001691
Chris Lattner6278e6a2007-08-11 00:04:45 +00001692 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001693 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001694}
1695
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001696void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001697 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001698 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001699 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001700 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001701
Daniel Dunbar67aba792010-04-15 03:47:33 +00001702 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001703 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001704
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001705 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001706 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001707 /*IsSigned=*/false);
1708 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001709
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001710 // See if there are other bits in the bitfield's storage we'll need to load
1711 // and mask together with source before storing.
1712 if (Info.StorageSize != Info.Size) {
1713 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001714 llvm::Value *Val =
1715 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001716
1717 // Mask the source value as needed.
1718 if (!hasBooleanRepresentation(Dst.getType()))
1719 SrcVal = Builder.CreateAnd(SrcVal,
1720 llvm::APInt::getLowBitsSet(Info.StorageSize,
1721 Info.Size),
1722 "bf.value");
1723 MaskedVal = SrcVal;
1724 if (Info.Offset)
1725 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1726
1727 // Mask out the original value.
1728 Val = Builder.CreateAnd(Val,
1729 ~llvm::APInt::getBitsSet(Info.StorageSize,
1730 Info.Offset,
1731 Info.Offset + Info.Size),
1732 "bf.clear");
1733
1734 // Or together the unchanged values and the source value.
1735 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1736 } else {
1737 assert(Info.Offset == 0);
1738 }
1739
1740 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001741 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001742
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001743 // Return the new value of the bit-field, if requested.
1744 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001745 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001746
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001747 // Sign extend the value if needed.
1748 if (Info.IsSigned) {
1749 assert(Info.Size <= Info.StorageSize);
1750 unsigned HighBits = Info.StorageSize - Info.Size;
1751 if (HighBits) {
1752 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1753 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1754 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001755 }
1756
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001757 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1758 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001759 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001760 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001761}
1762
Nate Begemance4d7fc2008-04-18 23:10:10 +00001763void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001764 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001765 // This access turns into a read/modify/write of the vector. Load the input
1766 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001767 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1768 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001769 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001770
Chris Lattner4647a212007-08-31 22:49:20 +00001771 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001772
John McCall55e1fbc2011-06-25 02:11:03 +00001773 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001774 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001775 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001776 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001777 // Use shuffle vector is the src and destination are the same number of
1778 // elements and restore the vector mask since it is on the side it will be
1779 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001780 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001781 for (unsigned i = 0; i != NumSrcElts; ++i)
1782 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001783
Chris Lattner91c08ad2011-02-15 00:14:06 +00001784 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001785 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001786 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001787 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001788 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001789 // Extended the source vector to the same length and then shuffle it
1790 // into the destination.
1791 // FIXME: since we're shuffling with undef, can we just use the indices
1792 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001793 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001794 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001795 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001796 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001797 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001798 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001799 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001800 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001801 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001802 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001803 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001804 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001805 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001806
Joey Goulycf4143b2013-11-21 17:09:05 +00001807 // When the vector size is odd and .odd or .hi is used, the last element
1808 // of the Elts constant array will be one past the size of the vector.
1809 // Ignore the last element here, if it is greater than the mask size.
1810 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1811 NumSrcElts--;
1812
Nate Begemanb699c9b2009-01-18 06:42:49 +00001813 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001814 for (unsigned i = 0; i != NumSrcElts; ++i)
1815 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001816 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001817 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001818 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001819 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001820 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001821 }
1822 } else {
1823 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001824 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001825 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001826 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001827 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001828
John McCall7f416cc2015-09-08 08:05:57 +00001829 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1830 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001831}
1832
Renato Golin230c5eb2014-05-19 18:15:42 +00001833/// @brief Store of global named registers are always calls to intrinsics.
1834void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001835 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1836 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001837 llvm::MDNode *RegName = cast<llvm::MDNode>(
1838 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001839 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001840
1841 // We accept integer and pointer types only
1842 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1843 llvm::Type *Ty = OrigTy;
1844 if (OrigTy->isPointerTy())
1845 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1846 llvm::Type *Types[] = { Ty };
1847
Renato Golin230c5eb2014-05-19 18:15:42 +00001848 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1849 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001850 if (OrigTy->isPointerTy())
1851 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001852 Builder.CreateCall(
1853 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001854}
1855
Eric Christopherc9e2a682014-05-20 17:10:39 +00001856// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001857// generating write-barries API. It is currently a global, ivar,
1858// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001859static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001860 LValue &LV,
1861 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001862 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001863 return;
Craig Topper99e79272013-07-26 05:59:26 +00001864
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001865 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001866 QualType ExpTy = E->getType();
1867 if (IsMemberAccess && ExpTy->isPointerType()) {
1868 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001869 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001870 // writer-barrier conservatively.
1871 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1872 if (ExpTy->isRecordType()) {
1873 LV.setObjCIvar(false);
1874 return;
1875 }
1876 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001877 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001878 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001879 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001880 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001881 return;
1882 }
Craig Topper99e79272013-07-26 05:59:26 +00001883
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001884 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1885 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001886 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001887 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001888 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001889 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001890 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001891 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001892 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001893 }
Craig Topper99e79272013-07-26 05:59:26 +00001894
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001895 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001896 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001897 return;
1898 }
Craig Topper99e79272013-07-26 05:59:26 +00001899
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001900 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001901 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001902 if (LV.isObjCIvar()) {
1903 // If cast is to a structure pointer, follow gcc's behavior and make it
1904 // a non-ivar write-barrier.
1905 QualType ExpTy = E->getType();
1906 if (ExpTy->isPointerType())
1907 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1908 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001909 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001910 }
1911 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001912 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001913
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001914 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001915 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1916 return;
1917 }
1918
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001919 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001920 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001921 return;
1922 }
Craig Topper99e79272013-07-26 05:59:26 +00001923
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001924 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001925 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001926 return;
1927 }
John McCall31168b02011-06-15 23:02:42 +00001928
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001929 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001930 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001931 return;
1932 }
1933
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001934 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001935 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001936 if (LV.isObjCIvar() && !LV.isObjCArray())
1937 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001938 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001939 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001940 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001941 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001942 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001943 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001944 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001945 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001946
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001947 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001948 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001949 // We don't know if member is an 'ivar', but this flag is looked at
1950 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001951 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001952 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001953 }
1954}
1955
Chris Lattner3f32d692011-07-12 06:52:18 +00001956static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001957EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001958 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001959 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001960 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001961 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001962}
1963
Alexey Bataev97720002014-11-11 04:05:39 +00001964static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001965 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1966 llvm::Type *RealVarTy, SourceLocation Loc) {
1967 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1968 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1969 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1970}
1971
1972Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1973 const ReferenceType *RefTy,
1974 AlignmentSource *Source) {
1975 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1976 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1977 Source, /*forPointee*/ true));
1978
1979}
1980
1981LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1982 const ReferenceType *RefTy) {
1983 AlignmentSource Source;
1984 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1985 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001986}
1987
Alexey Bataev31300ed2016-02-04 11:27:03 +00001988Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
1989 const PointerType *PtrTy,
1990 AlignmentSource *Source) {
1991 llvm::Value *Addr = Builder.CreateLoad(Ptr);
1992 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
1993 /*forPointeeType=*/true));
1994}
1995
1996LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
1997 const PointerType *PtrTy) {
1998 AlignmentSource Source;
1999 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
2000 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
2001}
2002
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002003static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2004 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002005 QualType T = E->getType();
2006
2007 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002008 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2009 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002010 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2011
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002012 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002013 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2014 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002015 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002016 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002017 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002018 // Emit reference to the private copy of the variable if it is an OpenMP
2019 // threadprivate variable.
2020 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002021 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002022 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002023 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2024 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002025 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002026 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002027 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002028 setObjCGCLValueClass(CGF.getContext(), E, LV);
2029 return LV;
2030}
2031
John McCallb92ab1a2016-10-26 23:46:34 +00002032static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2033 const FunctionDecl *FD) {
2034 if (FD->hasAttr<WeakRefAttr>()) {
2035 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2036 return aliasee.getPointer();
2037 }
2038
2039 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002040 if (!FD->hasPrototype()) {
2041 if (const FunctionProtoType *Proto =
2042 FD->getType()->getAs<FunctionProtoType>()) {
2043 // Ugly case: for a K&R-style definition, the type of the definition
2044 // isn't the same as the type of a use. Correct for this with a
2045 // bitcast.
2046 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002047 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2048 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2049 V = llvm::ConstantExpr::getBitCast(V,
2050 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002051 }
2052 }
John McCallb92ab1a2016-10-26 23:46:34 +00002053 return V;
2054}
2055
2056static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2057 const Expr *E, const FunctionDecl *FD) {
2058 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002059 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00002060 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002061}
2062
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002063static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2064 llvm::Value *ThisValue) {
2065 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2066 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2067 return CGF.EmitLValueForField(LV, FD);
2068}
2069
Renato Golin230c5eb2014-05-19 18:15:42 +00002070/// Named Registers are named metadata pointing to the register name
2071/// which will be read from/written to as an argument to the intrinsic
2072/// @llvm.read/write_register.
2073/// So far, only the name is being passed down, but other options such as
2074/// register type, allocation type or even optimization options could be
2075/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002076static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002077 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002078 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002079 assert(Asm->getLabel().size() < 64-Name.size() &&
2080 "Register name too big");
2081 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002082 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002083 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002084 if (M->getNumOperands() == 0) {
2085 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2086 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002087 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002088 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2089 }
John McCall7f416cc2015-09-08 08:05:57 +00002090
2091 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2092
2093 llvm::Value *Ptr =
2094 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2095 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002096}
2097
Chris Lattnerd7f58862007-06-02 05:24:33 +00002098LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002099 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002100 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002101
Renato Goline7b3d5d2014-05-27 16:46:27 +00002102 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2103 // Global Named registers access via intrinsics only
2104 if (VD->getStorageClass() == SC_Register &&
2105 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002106 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002107
Renato Goline7b3d5d2014-05-27 16:46:27 +00002108 // A DeclRefExpr for a reference initialized by a constant expression can
2109 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002110 const Expr *Init = VD->getAnyInitializer(VD);
2111 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2112 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002113 VD->checkInitIsICE() &&
2114 // Do not emit if it is private OpenMP variable.
2115 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2116 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002117 llvm::Constant *Val =
2118 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2119 assert(Val && "failed to emit reference constant expression");
2120 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002121
2122 // Should we be using the alignment of the constant pointer we emitted?
2123 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2124 /*pointee*/ true);
2125
2126 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002127 }
David Majnemer602cfe72015-01-01 09:49:44 +00002128
2129 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002130 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002131 if (auto *FD = LambdaCaptureFields.lookup(VD))
2132 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2133 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002134 auto I = LocalDeclMap.find(VD);
2135 if (I != LocalDeclMap.end()) {
2136 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2137 return EmitLoadOfReferenceLValue(I->second, RefTy);
2138 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002139 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002140 LValue CapLVal =
2141 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2142 CapturedStmtInfo->getContextValue());
2143 return MakeAddrLValue(
2144 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2145 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002146 }
John McCall7f416cc2015-09-08 08:05:57 +00002147
David Majnemer602cfe72015-01-01 09:49:44 +00002148 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002149 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2150 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002151 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002152 }
2153
Eli Friedman5720e342012-01-21 04:52:58 +00002154 // FIXME: We should be able to assert this for FunctionDecls as well!
2155 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2156 // those with a valid source location.
2157 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2158 !E->getLocation().isValid()) &&
2159 "Should not use decl without marking it used!");
2160
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002161 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002162 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002163 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2164 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002165 }
2166
Renato Goline7b3d5d2014-05-27 16:46:27 +00002167 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002168 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002169 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002170 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002171
John McCall7f416cc2015-09-08 08:05:57 +00002172 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002173
John McCall7f416cc2015-09-08 08:05:57 +00002174 // The variable should generally be present in the local decl map.
2175 auto iter = LocalDeclMap.find(VD);
2176 if (iter != LocalDeclMap.end()) {
2177 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002178
John McCall7f416cc2015-09-08 08:05:57 +00002179 // Otherwise, it might be static local we haven't emitted yet for
2180 // some reason; most likely, because it's in an outer function.
2181 } else if (VD->isStaticLocal()) {
2182 addr = Address(CGM.getOrCreateStaticVarDecl(
2183 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2184 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002185
John McCall7f416cc2015-09-08 08:05:57 +00002186 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002187 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002188 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2189 }
2190
2191
2192 // Check for OpenMP threadprivate variables.
2193 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2194 return EmitThreadPrivateVarDeclLValue(
2195 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2196 E->getExprLoc());
2197 }
2198
2199 // Drill into block byref variables.
2200 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2201 if (isBlockByref) {
2202 addr = emitBlockByrefAddress(addr, VD);
2203 }
2204
2205 // Drill into reference types.
2206 LValue LV;
2207 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2208 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2209 } else {
2210 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002211 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002212
John McCallcdda29c2013-03-13 03:10:54 +00002213 bool isLocalStorage = VD->hasLocalStorage();
2214
2215 bool NonGCable = isLocalStorage &&
2216 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002217 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002218 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002219 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002220 LV.setNonGC(true);
2221 }
John McCallcdda29c2013-03-13 03:10:54 +00002222
2223 bool isImpreciseLifetime =
2224 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2225 if (isImpreciseLifetime)
2226 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002227 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002228 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002229 }
John McCallf3a88602011-02-03 08:15:49 +00002230
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002231 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002232 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002233
Richard Smithda383632016-08-15 01:33:41 +00002234 // FIXME: While we're emitting a binding from an enclosing scope, all other
2235 // DeclRefExprs we see should be implicitly treated as if they also refer to
2236 // an enclosing scope.
2237 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2238 return EmitLValue(BD->getBinding());
2239
David Blaikie83d382b2011-09-23 05:06:16 +00002240 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002241}
Chris Lattnere47e4402007-06-01 18:02:12 +00002242
Chris Lattner8394d792007-06-05 20:53:16 +00002243LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2244 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002245 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002246 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002247
Chris Lattner0f398c42008-07-26 22:37:01 +00002248 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002249 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002250 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002251 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002252 QualType T = E->getSubExpr()->getType()->getPointeeType();
2253 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002254
John McCall7f416cc2015-09-08 08:05:57 +00002255 AlignmentSource AlignSource;
2256 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2257 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002258 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002259
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002260 // We should not generate __weak write barrier on indirect reference
2261 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2262 // But, we continue to generate __strong write barrier on indirect write
2263 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002264 if (getLangOpts().ObjC1 &&
2265 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002266 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002267 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002268 return LV;
2269 }
John McCalle3027922010-08-25 11:45:40 +00002270 case UO_Real:
2271 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002272 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002273 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002274
Richard Smith0b6b8e42012-02-18 20:53:32 +00002275 // __real is valid on scalars. This is a faster way of testing that.
2276 // __imag can only produce an rvalue on scalars.
2277 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002278 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002279 assert(E->getSubExpr()->getType()->isArithmeticType());
2280 return LV;
2281 }
2282
Alexey Bataev611b0a12016-11-07 18:15:02 +00002283 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002284
John McCall7f416cc2015-09-08 08:05:57 +00002285 Address Component =
2286 (E->getOpcode() == UO_Real
2287 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2288 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Alexey Bataev611b0a12016-11-07 18:15:02 +00002289 LValue ElemLV = MakeAddrLValue(Component, T, LV.getAlignmentSource());
2290 ElemLV.getQuals().addQualifiers(LV.getQuals());
2291 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002292 }
John McCalle3027922010-08-25 11:45:40 +00002293 case UO_PreInc:
2294 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002295 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002296 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002297
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002298 if (E->getType()->isAnyComplexType())
2299 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2300 else
2301 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2302 return LV;
2303 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002304 }
Chris Lattner8394d792007-06-05 20:53:16 +00002305}
2306
Chris Lattner4347e3692007-06-06 04:54:52 +00002307LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002308 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002309 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002310}
2311
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002312LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002313 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002314 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002315}
2316
Mike Stump4a3999f2009-09-09 13:00:44 +00002317LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002318 auto SL = E->getFunctionName();
2319 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2320 StringRef FnName = CurFn->getName();
2321 if (FnName.startswith("\01"))
2322 FnName = FnName.substr(1);
2323 StringRef NameItems[] = {
2324 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2325 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002326 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2327 std::string Name = SL->getString();
2328 if (!Name.empty()) {
2329 unsigned Discriminator =
2330 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2331 if (Discriminator)
2332 Name += "_" + Twine(Discriminator + 1).str();
2333 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2334 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2335 } else {
2336 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2337 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2338 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002339 }
Alexey Bataevec474782014-10-09 08:45:04 +00002340 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002341 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002342}
2343
Richard Smithe30752c2012-10-09 19:52:38 +00002344/// Emit a type description suitable for use by a runtime sanitizer library. The
2345/// format of a type descriptor is
2346///
2347/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002348/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002349/// \endcode
2350///
Richard Smith683398a2012-10-09 23:55:19 +00002351/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2352/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002353llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002354 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002355 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002356 return C;
2357
Richard Smithe30752c2012-10-09 19:52:38 +00002358 uint16_t TypeKind = -1;
2359 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002360
Richard Smithe30752c2012-10-09 19:52:38 +00002361 if (T->isIntegerType()) {
2362 TypeKind = 0;
2363 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002364 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002365 } else if (T->isFloatingType()) {
2366 TypeKind = 1;
2367 TypeInfo = getContext().getTypeSize(T);
2368 }
2369
2370 // Format the type name as if for a diagnostic, including quotes and
2371 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002372 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002373 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2374 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002375 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002376 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002377
2378 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002379 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2380 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002381 };
2382 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2383
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002384 auto *GV = new llvm::GlobalVariable(
2385 CGM.getModule(), Descriptor->getType(),
2386 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002387 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002388 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002389
2390 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002391 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002392
Richard Smithe30752c2012-10-09 19:52:38 +00002393 return GV;
2394}
2395
2396llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2397 llvm::Type *TargetTy = IntPtrTy;
2398
Richard Smith48366f72013-03-22 00:47:07 +00002399 // Floating-point types which fit into intptr_t are bitcast to integers
2400 // and then passed directly (after zero-extension, if necessary).
2401 if (V->getType()->isFloatingPointTy()) {
2402 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2403 if (Bits <= TargetTy->getIntegerBitWidth())
2404 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2405 Bits));
2406 }
2407
Richard Smithe30752c2012-10-09 19:52:38 +00002408 // Integers which fit in intptr_t are zero-extended and passed directly.
2409 if (V->getType()->isIntegerTy() &&
2410 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2411 return Builder.CreateZExt(V, TargetTy);
2412
2413 // Pointers are passed directly, everything else is passed by address.
2414 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002415 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002416 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002417 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002418 }
2419 return Builder.CreatePtrToInt(V, TargetTy);
2420}
2421
2422/// \brief Emit a representation of a SourceLocation for passing to a handler
2423/// in a sanitizer runtime library. The format for this data is:
2424/// \code
2425/// struct SourceLocation {
2426/// const char *Filename;
2427/// int32_t Line, Column;
2428/// };
2429/// \endcode
2430/// For an invalid SourceLocation, the Filename pointer is null.
2431llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002432 llvm::Constant *Filename;
2433 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002434
Alexey Samsonov6c124142014-07-18 17:50:06 +00002435 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2436 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002437 StringRef FilenameString = PLoc.getFilename();
2438
2439 int PathComponentsToStrip =
2440 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2441 if (PathComponentsToStrip < 0) {
2442 assert(PathComponentsToStrip != INT_MIN);
2443 int PathComponentsToKeep = -PathComponentsToStrip;
2444 auto I = llvm::sys::path::rbegin(FilenameString);
2445 auto E = llvm::sys::path::rend(FilenameString);
2446 while (I != E && --PathComponentsToKeep)
2447 ++I;
2448
2449 FilenameString = FilenameString.substr(I - E);
2450 } else if (PathComponentsToStrip > 0) {
2451 auto I = llvm::sys::path::begin(FilenameString);
2452 auto E = llvm::sys::path::end(FilenameString);
2453 while (I != E && PathComponentsToStrip--)
2454 ++I;
2455
2456 if (I != E)
2457 FilenameString =
2458 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2459 else
2460 FilenameString = llvm::sys::path::filename(FilenameString);
2461 }
2462
2463 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002464 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2465 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2466 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002467 Line = PLoc.getLine();
2468 Column = PLoc.getColumn();
2469 } else {
2470 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2471 Line = Column = 0;
2472 }
2473
2474 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2475 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002476
2477 return llvm::ConstantStruct::getAnon(Data);
2478}
2479
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002480namespace {
2481/// \brief Specify under what conditions this check can be recovered
2482enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002483 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002484 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002485 /// Check supports recovering, runtime has both fatal (noreturn) and
2486 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002487 Recoverable,
2488 /// Runtime conditionally aborts, always need to support recovery.
2489 AlwaysRecoverable
2490};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002491}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002492
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002493static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2494 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002495 switch (Kind) {
2496 case SanitizerKind::Vptr:
2497 return CheckRecoverableKind::AlwaysRecoverable;
2498 case SanitizerKind::Return:
2499 case SanitizerKind::Unreachable:
2500 return CheckRecoverableKind::Unrecoverable;
2501 default:
2502 return CheckRecoverableKind::Recoverable;
2503 }
2504}
2505
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002506namespace {
2507struct SanitizerHandlerInfo {
2508 char const *const Name;
2509 unsigned Version;
2510};
2511};
2512
2513const SanitizerHandlerInfo SanitizerHandlers[] = {
2514#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2515 LIST_SANITIZER_CHECKS
2516#undef SANITIZER_CHECK
2517};
2518
Alexey Samsonov88459522015-01-12 22:39:12 +00002519static void emitCheckHandlerCall(CodeGenFunction &CGF,
2520 llvm::FunctionType *FnType,
2521 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002522 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002523 CheckRecoverableKind RecoverKind, bool IsFatal,
2524 llvm::BasicBlock *ContBB) {
2525 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2526 bool NeedsAbortSuffix =
2527 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002528 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2529 const StringRef CheckName = CheckInfo.Name;
2530 std::string FnName =
2531 ("__ubsan_handle_" + CheckName +
2532 (CheckInfo.Version ? "_v" + std::to_string(CheckInfo.Version) : "") +
2533 (NeedsAbortSuffix ? "_abort" : ""))
2534 .str();
Alexey Samsonov88459522015-01-12 22:39:12 +00002535 bool MayReturn =
2536 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2537
2538 llvm::AttrBuilder B;
2539 if (!MayReturn) {
2540 B.addAttribute(llvm::Attribute::NoReturn)
2541 .addAttribute(llvm::Attribute::NoUnwind);
2542 }
2543 B.addAttribute(llvm::Attribute::UWTable);
2544
2545 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2546 FnType, FnName,
2547 llvm::AttributeSet::get(CGF.getLLVMContext(),
2548 llvm::AttributeSet::FunctionIndex, B));
2549 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2550 if (!MayReturn) {
2551 HandlerCall->setDoesNotReturn();
2552 CGF.Builder.CreateUnreachable();
2553 } else {
2554 CGF.Builder.CreateBr(ContBB);
2555 }
2556}
2557
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002558void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002559 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002560 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002561 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002562 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002563 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002564 assert(CheckHandler >= 0 &&
2565 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2566 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002567
2568 llvm::Value *FatalCond = nullptr;
2569 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002570 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002571 for (int i = 0, n = Checked.size(); i < n; ++i) {
2572 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002573 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002574 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002575 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2576 ? TrapCond
2577 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2578 ? RecoverableCond
2579 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002580 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2581 }
2582
Peter Collingbourne9881b782015-06-18 23:59:22 +00002583 if (TrapCond)
2584 EmitTrapCheck(TrapCond);
2585 if (!FatalCond && !RecoverableCond)
2586 return;
2587
Alexey Samsonov88459522015-01-12 22:39:12 +00002588 llvm::Value *JointCond;
2589 if (FatalCond && RecoverableCond)
2590 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2591 else
2592 JointCond = FatalCond ? FatalCond : RecoverableCond;
2593 assert(JointCond);
2594
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002595 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002596 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002597#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002598 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002599 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002600 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002601 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002602 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002603#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002604
Richard Smith4d1458e2012-09-08 02:08:36 +00002605 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002606 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2607 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002608 // Give hint that we very much don't expect to execute the handler
2609 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2610 llvm::MDBuilder MDHelper(getLLVMContext());
2611 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2612 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002613 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002614
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002615 // Handler functions take an i8* pointing to the (handler-specific) static
2616 // information block, followed by a sequence of intptr_t arguments
2617 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002618 SmallVector<llvm::Value *, 4> Args;
2619 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002620 Args.reserve(DynamicArgs.size() + 1);
2621 ArgTypes.reserve(DynamicArgs.size() + 1);
2622
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002623 // Emit handler arguments and create handler function type.
2624 if (!StaticArgs.empty()) {
2625 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2626 auto *InfoPtr =
2627 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2628 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002629 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002630 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2631 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2632 ArgTypes.push_back(Int8PtrTy);
2633 }
2634
Richard Smithe30752c2012-10-09 19:52:38 +00002635 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2636 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2637 ArgTypes.push_back(IntPtrTy);
2638 }
2639
2640 llvm::FunctionType *FnType =
2641 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002642
Alexey Samsonov88459522015-01-12 22:39:12 +00002643 if (!FatalCond || !RecoverableCond) {
2644 // Simple case: we need to generate a single handler call, either
2645 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002646 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002647 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002648 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002649 // Emit two handler calls: first one for set of unrecoverable checks,
2650 // another one for recoverable.
2651 llvm::BasicBlock *NonFatalHandlerBB =
2652 createBasicBlock("non_fatal." + CheckName);
2653 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2654 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2655 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002656 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002657 NonFatalHandlerBB);
2658 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002659 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002660 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002661 }
Richard Smithe30752c2012-10-09 19:52:38 +00002662
Richard Smith4d1458e2012-09-08 02:08:36 +00002663 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002664}
2665
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002666void CodeGenFunction::EmitCfiSlowPathCheck(
2667 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2668 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002669 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2670
2671 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2672 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2673
2674 llvm::MDBuilder MDHelper(getLLVMContext());
2675 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2676 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2677
2678 EmitBlock(CheckBB);
2679
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002680 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2681
2682 llvm::CallInst *CheckCall;
2683 if (WithDiag) {
2684 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2685 auto *InfoPtr =
2686 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2687 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002688 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002689 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2690
2691 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2692 "__cfi_slowpath_diag",
2693 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2694 false));
2695 CheckCall = Builder.CreateCall(
2696 SlowPathDiagFn,
2697 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2698 } else {
2699 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2700 "__cfi_slowpath",
2701 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2702 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2703 }
2704
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002705 CheckCall->setDoesNotThrow();
2706
2707 EmitBlock(Cont);
2708}
2709
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002710// This function is basically a switch over the CFI failure kind, which is
2711// extracted from CFICheckFailData (1st function argument). Each case is either
2712// llvm.trap or a call to one of the two runtime handlers, based on
2713// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2714// failure kind) traps, but this should really never happen. CFICheckFailData
2715// can be nullptr if the calling module has -fsanitize-trap behavior for this
2716// check kind; in this case __cfi_check_fail traps as well.
2717void CodeGenFunction::EmitCfiCheckFail() {
2718 SanitizerScope SanScope(this);
2719 FunctionArgList Args;
2720 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2721 getContext().VoidPtrTy);
2722 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2723 getContext().VoidPtrTy);
2724 Args.push_back(&ArgData);
2725 Args.push_back(&ArgAddr);
2726
John McCallc56a8b32016-03-11 04:30:31 +00002727 const CGFunctionInfo &FI =
2728 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002729
2730 llvm::Function *F = llvm::Function::Create(
2731 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2732 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2733 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2734
2735 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2736 SourceLocation());
2737
2738 llvm::Value *Data =
2739 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2740 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2741 llvm::Value *Addr =
2742 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2743 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2744
2745 // Data == nullptr means the calling module has trap behaviour for this check.
2746 llvm::Value *DataIsNotNullPtr =
2747 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2748 EmitTrapCheck(DataIsNotNullPtr);
2749
2750 llvm::StructType *SourceLocationTy =
2751 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2752 llvm::StructType *CfiCheckFailDataTy =
2753 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2754
2755 llvm::Value *V = Builder.CreateConstGEP2_32(
2756 CfiCheckFailDataTy,
2757 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2758 0);
2759 Address CheckKindAddr(V, getIntAlign());
2760 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2761
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002762 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2763 CGM.getLLVMContext(),
2764 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2765 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002766 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002767 {Addr, AllVtables}),
2768 IntPtrTy);
2769
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002770 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002771 {CFITCK_VCall, SanitizerKind::CFIVCall},
2772 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2773 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2774 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2775 {CFITCK_ICall, SanitizerKind::CFIICall}};
2776
2777 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2778 for (auto CheckKindMaskPair : CheckKinds) {
2779 int Kind = CheckKindMaskPair.first;
2780 SanitizerMask Mask = CheckKindMaskPair.second;
2781 llvm::Value *Cond =
2782 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002783 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002784 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002785 {Data, Addr, ValidVtable});
2786 else
2787 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002788 }
2789
2790 FinishFunction();
2791 // The only reference to this function will be created during LTO link.
2792 // Make sure it survives until then.
2793 CGM.addUsedGlobal(F);
2794}
2795
Chad Rosierae229d52013-01-29 23:31:22 +00002796void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002797 llvm::BasicBlock *Cont = createBasicBlock("cont");
2798
2799 // If we're optimizing, collapse all calls to trap down to just one per
2800 // function to save on code size.
2801 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2802 TrapBB = createBasicBlock("trap");
2803 Builder.CreateCondBr(Checked, Cont, TrapBB);
2804 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002805 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002806 TrapCall->setDoesNotReturn();
2807 TrapCall->setDoesNotThrow();
2808 Builder.CreateUnreachable();
2809 } else {
2810 Builder.CreateCondBr(Checked, Cont, TrapBB);
2811 }
2812
2813 EmitBlock(Cont);
2814}
2815
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002816llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002817 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002818
Amaury Sechet21f51b32016-09-09 04:42:49 +00002819 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2820 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2821 CGM.getCodeGenOpts().TrapFuncName);
2822 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex, A);
2823 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002824
2825 return TrapCall;
2826}
2827
John McCall7f416cc2015-09-08 08:05:57 +00002828Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2829 AlignmentSource *AlignSource) {
2830 assert(E->getType()->isArrayType() &&
2831 "Array to pointer decay must have array source type!");
2832
2833 // Expressions of array type can't be bitfields or vector elements.
2834 LValue LV = EmitLValue(E);
2835 Address Addr = LV.getAddress();
2836 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2837
2838 // If the array type was an incomplete type, we need to make sure
2839 // the decay ends up being the right type.
2840 llvm::Type *NewTy = ConvertType(E->getType());
2841 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2842
2843 // Note that VLA pointers are always decayed, so we don't need to do
2844 // anything here.
2845 if (!E->getType()->isVariableArrayType()) {
2846 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2847 "Expected pointer to array");
2848 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2849 }
2850
2851 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2852 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2853}
2854
Chris Lattner6c5abe82010-06-26 23:03:20 +00002855/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2856/// array to pointer, return the array subexpression.
2857static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2858 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002859 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002860 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002861 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002862
Chris Lattner6c5abe82010-06-26 23:03:20 +00002863 // If this is a decay from variable width array, bail out.
2864 const Expr *SubExpr = CE->getSubExpr();
2865 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002866 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002867
Chris Lattner6c5abe82010-06-26 23:03:20 +00002868 return SubExpr;
2869}
2870
John McCall7f416cc2015-09-08 08:05:57 +00002871static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2872 llvm::Value *ptr,
2873 ArrayRef<llvm::Value*> indices,
2874 bool inbounds,
2875 const llvm::Twine &name = "arrayidx") {
2876 if (inbounds) {
2877 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2878 } else {
2879 return CGF.Builder.CreateGEP(ptr, indices, name);
2880 }
2881}
2882
2883static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2884 llvm::Value *idx,
2885 CharUnits eltSize) {
2886 // If we have a constant index, we can use the exact offset of the
2887 // element we're accessing.
2888 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2889 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2890 return arrayAlign.alignmentAtOffset(offset);
2891
2892 // Otherwise, use the worst-case alignment for any element.
2893 } else {
2894 return arrayAlign.alignmentOfArrayElement(eltSize);
2895 }
2896}
2897
2898static QualType getFixedSizeElementType(const ASTContext &ctx,
2899 const VariableArrayType *vla) {
2900 QualType eltType;
2901 do {
2902 eltType = vla->getElementType();
2903 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2904 return eltType;
2905}
2906
2907static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2908 ArrayRef<llvm::Value*> indices,
2909 QualType eltType, bool inbounds,
2910 const llvm::Twine &name = "arrayidx") {
2911 // All the indices except that last must be zero.
2912#ifndef NDEBUG
2913 for (auto idx : indices.drop_back())
2914 assert(isa<llvm::ConstantInt>(idx) &&
2915 cast<llvm::ConstantInt>(idx)->isZero());
2916#endif
2917
2918 // Determine the element size of the statically-sized base. This is
2919 // the thing that the indices are expressed in terms of.
2920 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2921 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2922 }
2923
2924 // We can use that to compute the best alignment of the element.
2925 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2926 CharUnits eltAlign =
2927 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2928
2929 llvm::Value *eltPtr =
2930 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2931 return Address(eltPtr, eltAlign);
2932}
2933
Richard Smith539e4a72013-02-23 02:53:19 +00002934LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2935 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00002936 // The index must always be an integer, which is not an aggregate. Emit it
2937 // in lexical order (this complexity is, sadly, required by C++17).
2938 llvm::Value *IdxPre =
2939 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Richard Smith40885712016-09-27 00:53:24 +00002940 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00002941 auto *Idx = IdxPre;
2942 if (E->getLHS() != E->getIdx()) {
2943 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
2944 Idx = EmitScalarExpr(E->getIdx());
2945 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00002946
Richard Smith9e67b992016-09-26 23:49:47 +00002947 QualType IdxTy = E->getIdx()->getType();
2948 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
2949
2950 if (SanOpts.has(SanitizerKind::ArrayBounds))
2951 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2952
2953 // Extend or truncate the index type to 32 or 64-bits.
2954 if (Promote && Idx->getType() != IntPtrTy)
2955 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
2956
2957 return Idx;
2958 };
2959 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00002960
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002961 // If the base is a vector type, then we are forming a vector element lvalue
2962 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002963 if (E->getBase()->getType()->isVectorType() &&
2964 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002965 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002966 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00002967 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00002968 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002969 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002970 E->getBase()->getType(),
2971 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002972 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002973
John McCall7f416cc2015-09-08 08:05:57 +00002974 // All the other cases basically behave like simple offsetting.
2975
John McCall7f416cc2015-09-08 08:05:57 +00002976 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002977 if (isa<ExtVectorElementExpr>(E->getBase())) {
2978 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00002979 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00002980 Address Addr = EmitExtVectorElementLValue(LV);
2981
2982 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2983 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2984 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002985 }
John McCall7f416cc2015-09-08 08:05:57 +00002986
2987 AlignmentSource AlignSource;
2988 Address Addr = Address::invalid();
2989 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002990 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002991 // The base must be a pointer, which is not an aggregate. Emit
2992 // it. It needs to be emitted first in case it's what captures
2993 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002994 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00002995 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00002996
John McCall23c29fe2011-06-24 21:55:10 +00002997 // The element count here is the total number of non-VLA elements.
2998 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002999
John McCall77527a82011-06-25 01:32:37 +00003000 // Effectively, the multiply by the VLA size is part of the GEP.
3001 // GEP indexes are signed, and scaling an index isn't permitted to
3002 // signed-overflow, so we use the same semantics for our explicit
3003 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003004 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003005 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003006 } else {
3007 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003008 }
John McCall7f416cc2015-09-08 08:05:57 +00003009
3010 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3011 !getLangOpts().isSignedOverflowDefined());
3012
Chris Lattner6c5abe82010-06-26 23:03:20 +00003013 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3014 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003015
John McCall7f416cc2015-09-08 08:05:57 +00003016 // Emit the base pointer.
3017 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003018 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3019
3020 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3021 llvm::Value *InterfaceSizeVal =
3022 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3023
3024 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003025
3026 // We don't necessarily build correct LLVM struct types for ObjC
3027 // interfaces, so we can't rely on GEP to do this scaling
3028 // correctly, so we need to cast to i8*. FIXME: is this actually
3029 // true? A lot of other things in the fragile ABI would break...
3030 llvm::Type *OrigBaseTy = Addr.getType();
3031 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3032
3033 // Do the GEP.
3034 CharUnits EltAlign =
3035 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3036 llvm::Value *EltPtr =
3037 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3038 Addr = Address(EltPtr, EltAlign);
3039
3040 // Cast back.
3041 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003042 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3043 // If this is A[i] where A is an array, the frontend will have decayed the
3044 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3045 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3046 // "gep x, i" here. Emit one "gep A, 0, i".
3047 assert(Array->getType()->isArrayType() &&
3048 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003049 LValue ArrayLV;
3050 // For simple multidimensional array indexing, set the 'accessed' flag for
3051 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003052 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003053 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3054 else
3055 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003056 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003057
Daniel Dunbar82634272011-04-01 00:49:43 +00003058 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00003059 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3060 {CGM.getSize(CharUnits::Zero()), Idx},
3061 E->getType(),
3062 !getLangOpts().isSignedOverflowDefined());
3063 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003064 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003065 // The base must be a pointer; emit it with an estimate of its alignment.
3066 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003067 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003068 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3069 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003070 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003071
John McCall7f416cc2015-09-08 08:05:57 +00003072 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00003073
John McCall7f416cc2015-09-08 08:05:57 +00003074 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003075
Richard Smith9c6890a2012-11-01 22:30:59 +00003076 if (getLangOpts().ObjC1 &&
3077 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003078 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003079 setObjCGCLValueClass(getContext(), E, LV);
3080 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003081 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003082}
3083
Alexey Bataev31300ed2016-02-04 11:27:03 +00003084static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3085 AlignmentSource &AlignSource,
3086 QualType BaseTy, QualType ElTy,
3087 bool IsLowerBound) {
3088 LValue BaseLVal;
3089 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3090 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3091 if (BaseTy->isArrayType()) {
3092 Address Addr = BaseLVal.getAddress();
3093 AlignSource = BaseLVal.getAlignmentSource();
3094
3095 // If the array type was an incomplete type, we need to make sure
3096 // the decay ends up being the right type.
3097 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3098 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3099
3100 // Note that VLA pointers are always decayed, so we don't need to do
3101 // anything here.
3102 if (!BaseTy->isVariableArrayType()) {
3103 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3104 "Expected pointer to array");
3105 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3106 "arraydecay");
3107 }
3108
3109 return CGF.Builder.CreateElementBitCast(Addr,
3110 CGF.ConvertTypeForMem(ElTy));
3111 }
3112 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3113 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3114 }
3115 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3116}
3117
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003118LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3119 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003120 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003121 if (auto *ASE =
3122 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003123 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003124 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003125 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003126 QualType ResultExprTy;
3127 if (auto *AT = getContext().getAsArrayType(BaseTy))
3128 ResultExprTy = AT->getElementType();
3129 else
3130 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003131 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003132 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003133 // Requesting lower bound or upper bound, but without provided length and
3134 // without ':' symbol for the default length -> length = 1.
3135 // Idx = LowerBound ?: 0;
3136 if (auto *LowerBound = E->getLowerBound()) {
3137 Idx = Builder.CreateIntCast(
3138 EmitScalarExpr(LowerBound), IntPtrTy,
3139 LowerBound->getType()->hasSignedIntegerRepresentation());
3140 } else
3141 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3142 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003143 // Try to emit length or lower bound as constant. If this is possible, 1
3144 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3145 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003146 auto &C = CGM.getContext();
3147 auto *Length = E->getLength();
3148 llvm::APSInt ConstLength;
3149 if (Length) {
3150 // Idx = LowerBound + Length - 1;
3151 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3152 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3153 Length = nullptr;
3154 }
3155 auto *LowerBound = E->getLowerBound();
3156 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3157 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3158 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3159 LowerBound = nullptr;
3160 }
3161 if (!Length)
3162 --ConstLength;
3163 else if (!LowerBound)
3164 --ConstLowerBound;
3165
3166 if (Length || LowerBound) {
3167 auto *LowerBoundVal =
3168 LowerBound
3169 ? Builder.CreateIntCast(
3170 EmitScalarExpr(LowerBound), IntPtrTy,
3171 LowerBound->getType()->hasSignedIntegerRepresentation())
3172 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3173 auto *LengthVal =
3174 Length
3175 ? Builder.CreateIntCast(
3176 EmitScalarExpr(Length), IntPtrTy,
3177 Length->getType()->hasSignedIntegerRepresentation())
3178 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3179 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3180 /*HasNUW=*/false,
3181 !getLangOpts().isSignedOverflowDefined());
3182 if (Length && LowerBound) {
3183 Idx = Builder.CreateSub(
3184 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3185 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3186 }
3187 } else
3188 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3189 } else {
3190 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003191 QualType ArrayTy = BaseTy->isPointerType()
3192 ? E->getBase()->IgnoreParenImpCasts()->getType()
3193 : BaseTy;
3194 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003195 Length = VAT->getSizeExpr();
3196 if (Length->isIntegerConstantExpr(ConstLength, C))
3197 Length = nullptr;
3198 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003199 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003200 ConstLength = CAT->getSize();
3201 }
3202 if (Length) {
3203 auto *LengthVal = Builder.CreateIntCast(
3204 EmitScalarExpr(Length), IntPtrTy,
3205 Length->getType()->hasSignedIntegerRepresentation());
3206 Idx = Builder.CreateSub(
3207 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3208 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3209 } else {
3210 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3211 --ConstLength;
3212 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3213 }
3214 }
3215 }
3216 assert(Idx);
3217
Alexey Bataev31300ed2016-02-04 11:27:03 +00003218 Address EltPtr = Address::invalid();
3219 AlignmentSource AlignSource;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003220 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003221 // The base must be a pointer, which is not an aggregate. Emit
3222 // it. It needs to be emitted first in case it's what captures
3223 // the VLA bounds.
3224 Address Base =
3225 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3226 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003227 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003228 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003229
3230 // Effectively, the multiply by the VLA size is part of the GEP.
3231 // GEP indexes are signed, and scaling an index isn't permitted to
3232 // signed-overflow, so we use the same semantics for our explicit
3233 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003234 if (getLangOpts().isSignedOverflowDefined())
3235 Idx = Builder.CreateMul(Idx, NumElements);
3236 else
3237 Idx = Builder.CreateNSWMul(Idx, NumElements);
3238 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3239 !getLangOpts().isSignedOverflowDefined());
3240 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3241 // If this is A[i] where A is an array, the frontend will have decayed the
3242 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3243 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3244 // "gep x, i" here. Emit one "gep A, 0, i".
3245 assert(Array->getType()->isArrayType() &&
3246 "Array to pointer decay must have array source type!");
3247 LValue ArrayLV;
3248 // For simple multidimensional array indexing, set the 'accessed' flag for
3249 // better bounds-checking of the base expression.
3250 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3251 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3252 else
3253 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003254
Alexey Bataev31300ed2016-02-04 11:27:03 +00003255 // Propagate the alignment from the array itself to the result.
3256 EltPtr = emitArraySubscriptGEP(
3257 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3258 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3259 AlignSource = ArrayLV.getAlignmentSource();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003260 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003261 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3262 BaseTy, ResultExprTy, IsLowerBound);
3263 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3264 !getLangOpts().isSignedOverflowDefined());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003265 }
3266
Alexey Bataev31300ed2016-02-04 11:27:03 +00003267 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003268}
3269
Chris Lattner9e751ca2007-08-02 23:37:31 +00003270LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003271EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003272 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003273 LValue Base;
3274
3275 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003276 if (E->isArrow()) {
3277 // If it is a pointer to a vector, emit the address and form an lvalue with
3278 // it.
John McCall7f416cc2015-09-08 08:05:57 +00003279 AlignmentSource AlignSource;
3280 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003281 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00003282 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003283 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003284 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003285 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3286 // emit the base as an lvalue.
3287 assert(E->getBase()->getType()->isVectorType());
3288 Base = EmitLValue(E->getBase());
3289 } else {
3290 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003291 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003292 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003293 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003294
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003295 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003296 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003297 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003298 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3299 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003300 }
John McCall1553b192011-06-16 04:16:24 +00003301
3302 QualType type =
3303 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003304
Nate Begemand3862152008-05-13 21:03:02 +00003305 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003306 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003307 E->getEncodedElementAccess(Indices);
3308
3309 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003310 llvm::Constant *CV =
3311 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003312 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00003313 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00003314 }
3315 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3316
3317 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003318 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003319
Chris Lattner595ba3a2012-01-30 06:20:36 +00003320 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3321 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003322 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003323 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3324 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003325}
3326
Devang Patel30efa2e2007-10-23 20:28:39 +00003327LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003328 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003329
Chris Lattner4e4186b2007-12-02 18:52:07 +00003330 // 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 +00003331 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003332 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003333 AlignmentSource AlignSource;
3334 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003335 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003336 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3337 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003338 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003339 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003340
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003341 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003342 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003343 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003344 setObjCGCLValueClass(getContext(), E, LV);
3345 return LV;
3346 }
Craig Topper99e79272013-07-26 05:59:26 +00003347
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003348 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003349 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003350
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003351 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003352 return EmitFunctionDeclLValue(*this, E, FD);
3353
David Blaikie83d382b2011-09-23 05:06:16 +00003354 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003355}
Devang Patel30efa2e2007-10-23 20:28:39 +00003356
John McCalldec348f72013-05-03 07:33:41 +00003357/// Given that we are currently emitting a lambda, emit an l-value for
3358/// one of its members.
3359LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3360 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3361 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3362 QualType LambdaTagType =
3363 getContext().getTagDeclType(Field->getParent());
3364 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3365 return EmitLValueForField(LambdaLV, Field);
3366}
3367
John McCall7f416cc2015-09-08 08:05:57 +00003368/// Drill down to the storage of a field without walking into
3369/// reference types.
3370///
3371/// The resulting address doesn't necessarily have the right type.
3372static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3373 const FieldDecl *field) {
3374 const RecordDecl *rec = field->getParent();
3375
3376 unsigned idx =
3377 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3378
3379 CharUnits offset;
3380 // Adjust the alignment down to the given offset.
3381 // As a special case, if the LLVM field index is 0, we know that this
3382 // is zero.
3383 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3384 .getFieldOffset(field->getFieldIndex()) == 0) &&
3385 "LLVM field at index zero had non-zero offset?");
3386 if (idx != 0) {
3387 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3388 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3389 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3390 }
3391
3392 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3393}
3394
Eli Friedman7f1ff602012-04-16 03:54:45 +00003395LValue CodeGenFunction::EmitLValueForField(LValue base,
3396 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003397 AlignmentSource fieldAlignSource =
3398 getFieldAlignmentSource(base.getAlignmentSource());
3399
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003400 if (field->isBitField()) {
3401 const CGRecordLayout &RL =
3402 CGM.getTypes().getCGRecordLayout(field->getParent());
3403 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003404 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003405 unsigned Idx = RL.getLLVMFieldNo(field);
3406 if (Idx != 0)
3407 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003408 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3409 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003410 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003411 llvm::Type *FieldIntTy =
3412 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3413 if (Addr.getElementType() != FieldIntTy)
3414 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003415
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003416 QualType fieldType =
3417 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003418 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003419 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003420
John McCall53fcbd22011-02-26 08:07:02 +00003421 const RecordDecl *rec = field->getParent();
3422 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003423
John McCall53fcbd22011-02-26 08:07:02 +00003424 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3425
John McCall7f416cc2015-09-08 08:05:57 +00003426 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003427 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003428 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003429 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003430 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003431 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003432 // TODO: handle path-aware TBAA for union.
3433 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003434 } else {
3435 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003436 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003437
3438 // If this is a reference field, load the reference right now.
3439 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3440 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3441 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3442
Manman Renc451e572013-04-04 21:53:22 +00003443 // Loading the reference will disable path-aware TBAA.
3444 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003445 if (CGM.shouldUseTBAA()) {
3446 llvm::MDNode *tbaa;
3447 if (mayAlias)
3448 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3449 else
3450 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003451 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003452 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003453 }
3454
John McCall53fcbd22011-02-26 08:07:02 +00003455 mayAlias = false;
3456 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003457
3458 CharUnits alignment =
3459 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3460 addr = Address(load, alignment);
3461
3462 // Qualifiers on the struct don't apply to the referencee, and
3463 // we'll pick up CVR from the actual type later, so reset these
3464 // additional qualifiers now.
3465 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003466 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003467 }
Craig Topper99e79272013-07-26 05:59:26 +00003468
Chris Lattner13ee4f42011-07-10 05:34:54 +00003469 // Make sure that the address is pointing to the right type. This is critical
3470 // for both unions and structs. A union needs a bitcast, a struct element
3471 // will need a bitcast if the LLVM type laid out doesn't match the desired
3472 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003473 addr = Builder.CreateElementBitCast(addr,
3474 CGM.getTypes().ConvertTypeForMem(type),
3475 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003476
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003477 if (field->hasAttr<AnnotateAttr>())
3478 addr = EmitFieldAnnotations(field, addr);
3479
John McCall7f416cc2015-09-08 08:05:57 +00003480 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003481 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003482 if (TBAAPath) {
3483 const ASTRecordLayout &Layout =
3484 getContext().getASTRecordLayout(field->getParent());
3485 // Set the base type to be the base type of the base LValue and
3486 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003487 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3488 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003489 Layout.getFieldOffset(field->getFieldIndex()) /
3490 getContext().getCharWidth());
3491 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003492
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003493 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003494 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3495 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003496
3497 // Fields of may_alias structs act like 'char' for TBAA purposes.
3498 // FIXME: this should get propagated down through anonymous structs
3499 // and unions.
3500 if (mayAlias && LV.getTBAAInfo())
3501 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3502
Daniel Dunbarf166a522010-08-21 03:44:13 +00003503 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003504}
3505
Craig Topper99e79272013-07-26 05:59:26 +00003506LValue
3507CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003508 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003509 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003510
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003511 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003512 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003513
John McCall7f416cc2015-09-08 08:05:57 +00003514 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003515
John McCall7f416cc2015-09-08 08:05:57 +00003516 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003517 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003518 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003519
John McCall7f416cc2015-09-08 08:05:57 +00003520 // TODO: access-path TBAA?
3521 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3522 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003523}
3524
Chris Lattnerf53c0962010-09-06 00:11:41 +00003525LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003526 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003527 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3528 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003529 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003530 if (E->getType()->isVariablyModifiedType())
3531 // make sure to emit the VLA size.
3532 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003533
John McCall7f416cc2015-09-08 08:05:57 +00003534 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003535 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003536 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003537
Chad Rosier615ed1a2012-03-29 17:37:10 +00003538 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3539 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003540
3541 return Result;
3542}
3543
Richard Smithbb653bd2012-05-14 21:57:21 +00003544LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3545 if (!E->isGLValue())
3546 // Initializing an aggregate temporary in C++11: T{...}.
3547 return EmitAggExprToLValue(E);
3548
3549 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003550 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003551 return EmitLValue(E->getInit(0));
3552}
3553
Richard Smithf3076ff2014-06-20 18:43:47 +00003554/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3555/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3556/// LValue is returned and the current block has been terminated.
3557static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3558 const Expr *Operand) {
3559 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3560 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3561 return None;
3562 }
3563
3564 return CGF.EmitLValue(Operand);
3565}
3566
John McCallc07a0c72011-02-17 10:25:35 +00003567LValue CodeGenFunction::
3568EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3569 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003570 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003571 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003572 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003573 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003574 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003575
Eli Friedman59954892012-01-25 05:04:17 +00003576 OpaqueValueMapping binding(*this, expr);
3577
John McCallc07a0c72011-02-17 10:25:35 +00003578 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003579 bool CondExprBool;
3580 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003581 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003582 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003583
Justin Bogneref512b92014-01-06 22:27:43 +00003584 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003585 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003586 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003587 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003588 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003589 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003590 }
3591
John McCallc07a0c72011-02-17 10:25:35 +00003592 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3593 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3594 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003595
3596 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003597 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003598
John McCall0a6bf2e2011-01-26 19:21:13 +00003599 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003600 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003601 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003602 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003603 Optional<LValue> lhs =
3604 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003605 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003606
Richard Smithf3076ff2014-06-20 18:43:47 +00003607 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003608 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003609
John McCallc07a0c72011-02-17 10:25:35 +00003610 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003611 if (lhs)
3612 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003613
John McCall0a6bf2e2011-01-26 19:21:13 +00003614 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003615 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003616 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003617 Optional<LValue> rhs =
3618 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003619 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003620 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003621 return EmitUnsupportedLValue(expr, "conditional operator");
3622 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003623
John McCallc07a0c72011-02-17 10:25:35 +00003624 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003625
Richard Smithf3076ff2014-06-20 18:43:47 +00003626 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003627 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003628 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003629 phi->addIncoming(lhs->getPointer(), lhsBlock);
3630 phi->addIncoming(rhs->getPointer(), rhsBlock);
3631 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3632 AlignmentSource alignSource =
3633 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3634 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003635 } else {
3636 assert((lhs || rhs) &&
3637 "both operands of glvalue conditional are throw-expressions?");
3638 return lhs ? *lhs : *rhs;
3639 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003640}
3641
Richard Smithbb653bd2012-05-14 21:57:21 +00003642/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3643/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003644/// otherwise if a cast is needed by the code generator in an lvalue context,
3645/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003646/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003647/// are permitted with aggregate result, including noop aggregate casts, and
3648/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003649LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003650 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003651 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003652 case CK_BitCast:
3653 case CK_ArrayToPointerDecay:
3654 case CK_FunctionToPointerDecay:
3655 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003656 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003657 case CK_IntegralToPointer:
3658 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003659 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003660 case CK_VectorSplat:
3661 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003662 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003663 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003664 case CK_IntegralToFloating:
3665 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003666 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003667 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003668 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003669 case CK_FloatingComplexToReal:
3670 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003671 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003672 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003673 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003674 case CK_IntegralComplexToReal:
3675 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003676 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003677 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003678 case CK_DerivedToBaseMemberPointer:
3679 case CK_BaseToDerivedMemberPointer:
3680 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003681 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003682 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003683 case CK_ARCProduceObject:
3684 case CK_ARCConsumeObject:
3685 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003686 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003687 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003688 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003689 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003690 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3691
3692 case CK_Dependent:
3693 llvm_unreachable("dependent cast kind in IR gen!");
3694
3695 case CK_BuiltinFnToFnPtr:
3696 llvm_unreachable("builtin functions are handled elsewhere");
3697
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003698 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003699 case CK_NonAtomicToAtomic:
3700 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003701 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003702
Anders Carlsson8a01a752011-04-11 02:03:26 +00003703 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003704 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003705 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003706 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003707 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003708 }
3709
John McCalle3027922010-08-25 11:45:40 +00003710 case CK_ConstructorConversion:
3711 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003712 case CK_CPointerToObjCPointerCast:
3713 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003714 case CK_NoOp:
3715 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003716 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003717
John McCalle3027922010-08-25 11:45:40 +00003718 case CK_UncheckedDerivedToBase:
3719 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003720 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003721 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003722 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003723
Anders Carlssond95f9602009-09-12 16:16:49 +00003724 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003725 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003726
Anders Carlssond95f9602009-09-12 16:16:49 +00003727 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003728 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003729 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3730 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003731
John McCall7f416cc2015-09-08 08:05:57 +00003732 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003733 }
John McCalle3027922010-08-25 11:45:40 +00003734 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003735 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003736 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003737 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003738 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003739
Anders Carlsson8c793172009-11-23 17:57:54 +00003740 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003741
Anders Carlsson8c793172009-11-23 17:57:54 +00003742 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003743 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003744 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003745 E->path_begin(), E->path_end(),
3746 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003747
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003748 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3749 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003750 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003751 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003752 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003753
Peter Collingbourned2926c92015-03-14 02:42:25 +00003754 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003755 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3756 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003757 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003758
John McCall7f416cc2015-09-08 08:05:57 +00003759 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003760 }
John McCalle3027922010-08-25 11:45:40 +00003761 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003762 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003763 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003764
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003765 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003766 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003767 Address V = Builder.CreateBitCast(LV.getAddress(),
3768 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003769
3770 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003771 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3772 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003773 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003774
John McCall7f416cc2015-09-08 08:05:57 +00003775 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003776 }
John McCalle3027922010-08-25 11:45:40 +00003777 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003778 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003779 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3780 ConvertType(E->getType()));
3781 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003782 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003783 case CK_ZeroToOCLEvent:
3784 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003785 }
Craig Topper99e79272013-07-26 05:59:26 +00003786
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003787 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003788}
3789
John McCall1bf58462011-02-16 08:02:54 +00003790LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003791 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003792 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003793}
3794
Eli Friedman7f1ff602012-04-16 03:54:45 +00003795RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003796 const FieldDecl *FD,
3797 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003798 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003799 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003800 switch (getEvaluationKind(FT)) {
3801 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003802 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003803 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003804 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003805 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00003806 // This routine is used to load fields one-by-one to perform a copy, so
3807 // don't load reference fields.
3808 if (FD->getType()->isReferenceType())
3809 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00003810 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003811 }
3812 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003813}
Douglas Gregorfe314812011-06-21 17:03:29 +00003814
Chris Lattnere47e4402007-06-01 18:02:12 +00003815//===--------------------------------------------------------------------===//
3816// Expression Emission
3817//===--------------------------------------------------------------------===//
3818
Craig Topper99e79272013-07-26 05:59:26 +00003819RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003820 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003821 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003822 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003823 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003824
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003825 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003826 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003827
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003828 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003829 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3830
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003831 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00003832 if (const CXXMethodDecl *MD =
3833 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003834 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003835
John McCallb92ab1a2016-10-26 23:46:34 +00003836 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00003837
John McCallb92ab1a2016-10-26 23:46:34 +00003838 if (callee.isBuiltin()) {
3839 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3840 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003841 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003842
John McCallb92ab1a2016-10-26 23:46:34 +00003843 if (callee.isPseudoDestructor()) {
3844 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3845 }
3846
3847 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3848}
3849
3850/// Emit a CallExpr without considering whether it might be a subclass.
3851RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
3852 ReturnValueSlot ReturnValue) {
3853 CGCallee Callee = EmitCallee(E->getCallee());
3854 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
3855}
3856
3857static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
3858 if (auto builtinID = FD->getBuiltinID()) {
3859 return CGCallee::forBuiltin(builtinID, FD);
3860 }
3861
3862 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
3863 return CGCallee::forDirect(calleePtr, FD);
3864}
3865
3866CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
3867 E = E->IgnoreParens();
3868
3869 // Look through function-to-pointer decay.
3870 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
3871 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
3872 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
3873 return EmitCallee(ICE->getSubExpr());
3874 }
3875
3876 // Resolve direct calls.
3877 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
3878 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
3879 return EmitDirectCallee(*this, FD);
3880 }
3881 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
3882 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
3883 EmitIgnoredExpr(ME->getBase());
3884 return EmitDirectCallee(*this, FD);
3885 }
3886
3887 // Look through template substitutions.
3888 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
3889 return EmitCallee(NTTP->getReplacement());
3890
3891 // Treat pseudo-destructor calls differently.
3892 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
3893 return CGCallee::forPseudoDestructor(PDE);
3894 }
3895
3896 // Otherwise, we have an indirect reference.
3897 llvm::Value *calleePtr;
3898 QualType functionType;
3899 if (auto ptrType = E->getType()->getAs<PointerType>()) {
3900 calleePtr = EmitScalarExpr(E);
3901 functionType = ptrType->getPointeeType();
3902 } else {
3903 functionType = E->getType();
3904 calleePtr = EmitLValue(E).getPointer();
3905 }
3906 assert(functionType->isFunctionType());
3907 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
3908 E->getReferencedDeclOfCallee());
3909 CGCallee callee(calleeInfo, calleePtr);
3910 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00003911}
3912
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003913LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003914 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003915 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003916 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003917 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003918 return EmitLValue(E->getRHS());
3919 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003920
John McCalle3027922010-08-25 11:45:40 +00003921 if (E->getOpcode() == BO_PtrMemD ||
3922 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003923 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003924
John McCalla2342eb2010-12-05 02:00:02 +00003925 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003926
3927 // Note that in all of these cases, __block variables need the RHS
3928 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003929
3930 switch (getEvaluationKind(E->getType())) {
3931 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003932 switch (E->getLHS()->getType().getObjCLifetime()) {
3933 case Qualifiers::OCL_Strong:
3934 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3935
3936 case Qualifiers::OCL_Autoreleasing:
3937 return EmitARCStoreAutoreleasing(E).first;
3938
3939 // No reason to do any of these differently.
3940 case Qualifiers::OCL_None:
3941 case Qualifiers::OCL_ExplicitNone:
3942 case Qualifiers::OCL_Weak:
3943 break;
3944 }
3945
John McCalld0a30012010-12-06 06:10:02 +00003946 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003947 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003948 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003949 return LV;
3950 }
John McCall4f29b492010-11-16 23:07:28 +00003951
John McCall47fb9502013-03-07 21:37:08 +00003952 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003953 return EmitComplexAssignmentLValue(E);
3954
John McCall47fb9502013-03-07 21:37:08 +00003955 case TEK_Aggregate:
3956 return EmitAggExprToLValue(E);
3957 }
3958 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003959}
3960
Christopher Lambd91c3d42007-12-29 05:02:41 +00003961LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003962 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003963
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003964 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003965 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3966 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003967
David Majnemerced8bdf2015-02-25 17:36:15 +00003968 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003969 "Can't have a scalar return unless the return type is a "
3970 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003971
John McCall7f416cc2015-09-08 08:05:57 +00003972 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003973}
3974
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003975LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3976 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003977 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003978}
3979
Anders Carlsson3be22e22009-05-30 23:23:33 +00003980LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003981 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3982 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003983 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003984 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003985 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3986 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003987}
3988
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003989LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003990CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003991 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003992}
3993
John McCall7f416cc2015-09-08 08:05:57 +00003994Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3995 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3996 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003997}
3998
3999LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004000 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4001 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00004002}
4003
Mike Stumpc9b231c2009-11-15 08:09:41 +00004004LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004005CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004006 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004007 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004008 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004009 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4010 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4011 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004012}
4013
Eli Friedman5bc17122012-02-08 05:34:55 +00004014LValue
4015CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004016 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004017 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004018 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4019 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00004020}
4021
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004022LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004023 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004024
Anders Carlsson280e61f12010-06-21 20:59:55 +00004025 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004026 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4027 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004028
Alp Toker314cc812014-01-25 16:55:45 +00004029 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004030 "Can't have a scalar return unless the return type is a "
4031 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004032
John McCall7f416cc2015-09-08 08:05:57 +00004033 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004034}
4035
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004036LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004037 Address V =
4038 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4039 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004040}
4041
Daniel Dunbar722f4242009-04-22 05:08:15 +00004042llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004043 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004044 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004045}
4046
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004047LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4048 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004049 const ObjCIvarDecl *Ivar,
4050 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004051 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004052 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004053}
4054
4055LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004056 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004057 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004058 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004059 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004060 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004061 if (E->isArrow()) {
4062 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004063 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004064 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004065 } else {
4066 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004067 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004068 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004069 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004070 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004071
Craig Topper99e79272013-07-26 05:59:26 +00004072 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004073 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4074 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004075 setObjCGCLValueClass(getContext(), E, LV);
4076 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004077}
4078
Chris Lattnera4185c52009-04-25 19:35:26 +00004079LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004080 // Can only get l-value for message expression returning aggregate type
4081 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004082 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4083 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00004084}
4085
John McCallb92ab1a2016-10-26 23:46:34 +00004086RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004087 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004088 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004089 // Get the actual function type. The callee type will always be a pointer to
4090 // function type or a block pointer type.
4091 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004092 "Call must have function pointer type!");
4093
John McCallb92ab1a2016-10-26 23:46:34 +00004094 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004095
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004096 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004097 // We can only guarantee that a function is called from the correct
4098 // context/function based on the appropriate target attributes,
4099 // so only check in the case where we have both always_inline and target
4100 // since otherwise we could be making a conditional call after a check for
4101 // the proper cpu features (and it won't cause code generation issues due to
4102 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004103 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4104 TargetDecl->hasAttr<TargetAttr>())
4105 checkTargetFeatures(E, FD);
4106
John McCall6fd4c232009-10-23 08:22:42 +00004107 CalleeType = getContext().getCanonicalType(CalleeType);
4108
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004109 const auto *FnType =
4110 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004111
John McCallb92ab1a2016-10-26 23:46:34 +00004112 CGCallee Callee = OrigCallee;
4113
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004114 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004115 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4116 if (llvm::Constant *PrefixSig =
4117 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004118 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004119 llvm::Constant *FTRTTIConst =
4120 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4121 llvm::Type *PrefixStructTyElems[] = {
4122 PrefixSig->getType(),
4123 FTRTTIConst->getType()
4124 };
4125 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4126 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4127
John McCallb92ab1a2016-10-26 23:46:34 +00004128 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4129
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004130 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004131 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004132 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004133 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004134 llvm::Value *CalleeSig =
4135 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004136 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4137
4138 llvm::BasicBlock *Cont = createBasicBlock("cont");
4139 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4140 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4141
4142 EmitBlock(TypeCheck);
4143 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004144 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004145 llvm::Value *CalleeRTTI =
4146 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004147 llvm::Value *CalleeRTTIMatch =
4148 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4149 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004150 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004151 EmitCheckTypeDescriptor(CalleeType)
4152 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004153 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004154 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004155
4156 Builder.CreateBr(Cont);
4157 EmitBlock(Cont);
4158 }
4159 }
4160
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004161 // If we are checking indirect calls and this call is indirect, check that the
4162 // function pointer is a member of the bit set for the function type.
4163 if (SanOpts.has(SanitizerKind::CFIICall) &&
4164 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4165 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004166 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004167
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004168 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004169 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004170
John McCallb92ab1a2016-10-26 23:46:34 +00004171 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4172 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004173 llvm::Value *TypeTest = Builder.CreateCall(
4174 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004175
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004176 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004177 llvm::Constant *StaticData[] = {
4178 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4179 EmitCheckSourceLocation(E->getLocStart()),
4180 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4181 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004182 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4183 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004184 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004185 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004186 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004187 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004188 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004189 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004190 }
4191
Daniel Dunbarc722b852008-08-30 03:02:31 +00004192 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004193 if (Chain)
4194 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4195 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004196
4197 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004198 // right-to-left, and that we evaluate arguments to certain other operators
4199 // left-to-right. Note that we allow this to override the order dictated by
4200 // the calling convention on the MS ABI, which means that parameter
4201 // destruction order is not necessarily reverse construction order.
4202 // FIXME: Revisit this based on C++ committee response to unimplementability.
4203 EvaluationOrder Order = EvaluationOrder::Default;
4204 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4205 if (OCE->isAssignmentOp())
4206 Order = EvaluationOrder::ForceRightToLeft;
4207 else {
4208 switch (OCE->getOperator()) {
4209 case OO_LessLess:
4210 case OO_GreaterGreater:
4211 case OO_AmpAmp:
4212 case OO_PipePipe:
4213 case OO_Comma:
4214 case OO_ArrowStar:
4215 Order = EvaluationOrder::ForceLeftToRight;
4216 break;
4217 default:
4218 break;
4219 }
4220 }
4221 }
Richard Smith762672a2016-09-28 19:09:10 +00004222
David Blaikief05779e2015-07-21 18:37:18 +00004223 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004224 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004225
Peter Collingbournef7706832014-12-12 23:41:25 +00004226 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4227 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004228
4229 // C99 6.5.2.2p6:
4230 // If the expression that denotes the called function has a type
4231 // that does not include a prototype, [the default argument
4232 // promotions are performed]. If the number of arguments does not
4233 // equal the number of parameters, the behavior is undefined. If
4234 // the function is defined with a type that includes a prototype,
4235 // and either the prototype ends with an ellipsis (, ...) or the
4236 // types of the arguments after promotion are not compatible with
4237 // the types of the parameters, the behavior is undefined. If the
4238 // function is defined with a type that does not include a
4239 // prototype, and the types of the arguments after promotion are
4240 // not compatible with those of the parameters after promotion,
4241 // the behavior is undefined [except in some trivial cases].
4242 // That is, in the general case, we should assume that a call
4243 // through an unprototyped function type works like a *non-variadic*
4244 // call. The way we make this work is to cast to the exact type
4245 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004246 //
4247 // Chain calls use this same code path to add the invisible chain parameter
4248 // to the function type.
4249 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004250 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004251 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004252
4253 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4254 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4255 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004256 }
4257
John McCallb92ab1a2016-10-26 23:46:34 +00004258 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004259}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004260
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004261LValue CodeGenFunction::
4262EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004263 Address BaseAddr = Address::invalid();
4264 if (E->getOpcode() == BO_PtrMemI) {
4265 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4266 } else {
4267 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4268 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004269
John McCallc134eb52010-08-31 21:07:20 +00004270 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4271
4272 const MemberPointerType *MPT
4273 = E->getRHS()->getType()->getAs<MemberPointerType>();
4274
John McCall7f416cc2015-09-08 08:05:57 +00004275 AlignmentSource AlignSource;
4276 Address MemberAddr =
4277 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4278 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00004279
John McCall7f416cc2015-09-08 08:05:57 +00004280 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004281}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004282
John McCall47fb9502013-03-07 21:37:08 +00004283/// Given the address of a temporary variable, produce an r-value of
4284/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004285RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004286 QualType type,
4287 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00004288 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004289 switch (getEvaluationKind(type)) {
4290 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004291 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004292 case TEK_Aggregate:
4293 return lvalue.asAggregateRValue();
4294 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004295 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004296 }
4297 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004298}
4299
Duncan Sandse81111c2012-04-10 08:23:07 +00004300void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004301 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004302 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004303 return;
4304
Duncan Sands65229ed2012-04-16 16:29:47 +00004305 llvm::MDBuilder MDHelper(getLLVMContext());
4306 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004307
Duncan Sands6fc46192012-04-14 12:37:26 +00004308 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004309}
John McCallfe96e0b2011-11-06 09:01:30 +00004310
4311namespace {
4312 struct LValueOrRValue {
4313 LValue LV;
4314 RValue RV;
4315 };
4316}
4317
4318static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4319 const PseudoObjectExpr *E,
4320 bool forLValue,
4321 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004322 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004323
4324 // Find the result expression, if any.
4325 const Expr *resultExpr = E->getResultExpr();
4326 LValueOrRValue result;
4327
4328 for (PseudoObjectExpr::const_semantics_iterator
4329 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4330 const Expr *semantic = *i;
4331
4332 // If this semantic expression is an opaque value, bind it
4333 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004334 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004335
4336 // If this is the result expression, we may need to evaluate
4337 // directly into the slot.
4338 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4339 OVMA opaqueData;
4340 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004341 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004342 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4343
John McCall7f416cc2015-09-08 08:05:57 +00004344 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4345 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004346 opaqueData = OVMA::bind(CGF, ov, LV);
4347 result.RV = slot.asRValue();
4348
4349 // Otherwise, emit as normal.
4350 } else {
4351 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4352
4353 // If this is the result, also evaluate the result now.
4354 if (ov == resultExpr) {
4355 if (forLValue)
4356 result.LV = CGF.EmitLValue(ov);
4357 else
4358 result.RV = CGF.EmitAnyExpr(ov, slot);
4359 }
4360 }
4361
4362 opaques.push_back(opaqueData);
4363
4364 // Otherwise, if the expression is the result, evaluate it
4365 // and remember the result.
4366 } else if (semantic == resultExpr) {
4367 if (forLValue)
4368 result.LV = CGF.EmitLValue(semantic);
4369 else
4370 result.RV = CGF.EmitAnyExpr(semantic, slot);
4371
4372 // Otherwise, evaluate the expression in an ignored context.
4373 } else {
4374 CGF.EmitIgnoredExpr(semantic);
4375 }
4376 }
4377
4378 // Unbind all the opaques now.
4379 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4380 opaques[i].unbind(CGF);
4381
4382 return result;
4383}
4384
4385RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4386 AggValueSlot slot) {
4387 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4388}
4389
4390LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4391 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4392}