blob: 7e12f5e73586650b04e81f47962d2a84fa56b682 [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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000027#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000029#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000034#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000035#include "llvm/Support/MathExtras.h"
Filipe Cabecinhasab731f72016-05-12 16:51:36 +000036#include "llvm/Support/Path.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000037#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038
Chris Lattnere47e4402007-06-01 18:02:12 +000039using namespace clang;
40using namespace CodeGen;
41
Chris Lattnerd7f58862007-06-02 05:24:33 +000042//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000043// Miscellaneous Helper Methods
44//===--------------------------------------------------------------------===//
45
John McCallad7c5c12011-02-08 08:22:06 +000046llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
47 unsigned addressSpace =
48 cast<llvm::PointerType>(value->getType())->getAddressSpace();
49
Chris Lattner2192fe52011-07-18 04:24:23 +000050 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000051 if (addressSpace)
52 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
53
54 if (value->getType() == destType) return value;
55 return Builder.CreateBitCast(value, destType);
56}
57
Chris Lattnere9a64532007-06-22 21:44:33 +000058/// CreateTempAlloca - This creates a alloca and inserts it into the entry
59/// block.
John McCall7f416cc2015-09-08 08:05:57 +000060Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
61 const Twine &Name) {
62 auto Alloca = CreateTempAlloca(Ty, Name);
63 Alloca->setAlignment(Align.getQuantity());
64 return Address(Alloca, Align);
65}
66
67/// CreateTempAlloca - This creates a alloca and inserts it into the entry
68/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000069llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 const Twine &Name) {
Craig Topper8a13c412014-05-21 05:09:00 +000071 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000072}
Chris Lattner8394d792007-06-05 20:53:16 +000073
John McCall7f416cc2015-09-08 08:05:57 +000074/// CreateDefaultAlignTempAlloca - This creates an alloca with the
75/// default alignment of the corresponding LLVM type, which is *not*
76/// guaranteed to be related in any way to the expected alignment of
77/// an AST type that might have been lowered to Ty.
78Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
79 const Twine &Name) {
80 CharUnits Align =
81 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
82 return CreateTempAlloca(Ty, Align, Name);
83}
84
85void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
86 assert(isa<llvm::AllocaInst>(Var.getPointer()));
87 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
88 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000089 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +000090 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +000091}
92
John McCall7f416cc2015-09-08 08:05:57 +000093Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000094 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000095 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +000096}
97
John McCall7f416cc2015-09-08 08:05:57 +000098Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000099 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +0000100 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
101}
102
103Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
104 const Twine &Name) {
105 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000106}
107
Chris Lattner8394d792007-06-05 20:53:16 +0000108/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
109/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000110llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000111 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000112 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000113 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000114 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000115 }
John McCall7a9aac22010-08-23 01:21:21 +0000116
117 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000118 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000119 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000120 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000121
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000122 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
123 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000124}
125
John McCalla2342eb2010-12-05 02:00:02 +0000126/// EmitIgnoredExpr - Emit code to compute the specified expression,
127/// ignoring the result.
128void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
129 if (E->isRValue())
130 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
131
132 // Just emit it as an l-value and drop the result.
133 EmitLValue(E);
134}
135
John McCall7a626f62010-09-15 10:14:12 +0000136/// EmitAnyExpr - Emit code to compute the specified expression which
137/// can have any type. The result is returned as an RValue struct.
138/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000139/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000140RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
141 AggValueSlot aggSlot,
142 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000143 switch (getEvaluationKind(E->getType())) {
144 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000145 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000146 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000147 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000148 case TEK_Aggregate:
149 if (!ignoreResult && aggSlot.isIgnored())
150 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
151 EmitAggExpr(E, aggSlot);
152 return aggSlot.asRValue();
153 }
154 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000155}
156
Mike Stump4a3999f2009-09-09 13:00:44 +0000157/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
158/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000159RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
160 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000161
John McCall47fb9502013-03-07 21:37:08 +0000162 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000163 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
164 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000165}
166
John McCall21886962010-04-21 10:05:39 +0000167/// EmitAnyExprToMem - Evaluate an expression into a given memory
168/// location.
169void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000170 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000171 Qualifiers Quals,
172 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000173 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000174 switch (getEvaluationKind(E->getType())) {
175 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000176 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000177 /*isInit*/ false);
178 return;
179
180 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000181 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000182 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000183 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000184 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000185 return;
186 }
187
188 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000189 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000190 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000191 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000192 return;
John McCall21886962010-04-21 10:05:39 +0000193 }
John McCall47fb9502013-03-07 21:37:08 +0000194 }
195 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000196}
197
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000198static void
199pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000200 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000201 // Objective-C++ ARC:
202 // If we are binding a reference to a temporary that has ownership, we
203 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000204 //
205 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000206 if (auto Lifetime = M->getType().getObjCLifetime()) {
207 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000208 case Qualifiers::OCL_None:
209 case Qualifiers::OCL_ExplicitNone:
210 // Carry on to normal cleanup handling.
211 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000212
Richard Smith736a9472013-06-12 20:42:33 +0000213 case Qualifiers::OCL_Autoreleasing:
214 // Nothing to do; cleaned up by an autorelease pool.
215 return;
216
217 case Qualifiers::OCL_Strong:
218 case Qualifiers::OCL_Weak:
219 switch (StorageDuration Duration = M->getStorageDuration()) {
220 case SD_Static:
221 // Note: we intentionally do not register a cleanup to release
222 // the object on program termination.
223 return;
224
225 case SD_Thread:
226 // FIXME: We should probably register a cleanup in this case.
227 return;
228
229 case SD_Automatic:
230 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000231 CodeGenFunction::Destroyer *Destroy;
232 CleanupKind CleanupKind;
233 if (Lifetime == Qualifiers::OCL_Strong) {
234 const ValueDecl *VD = M->getExtendingDecl();
235 bool Precise =
236 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
237 CleanupKind = CGF.getARCCleanupKind();
238 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
239 : &CodeGenFunction::destroyARCStrongImprecise;
240 } else {
241 // __weak objects always get EH cleanups; otherwise, exceptions
242 // could cause really nasty crashes instead of mere leaks.
243 CleanupKind = NormalAndEHCleanup;
244 Destroy = &CodeGenFunction::destroyARCWeak;
245 }
246 if (Duration == SD_FullExpression)
247 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000248 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000249 CleanupKind & EHCleanup);
250 else
251 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000252 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000253 *Destroy, CleanupKind & EHCleanup);
254 return;
255
256 case SD_Dynamic:
257 llvm_unreachable("temporary cannot have dynamic storage duration");
258 }
259 llvm_unreachable("unknown storage duration");
260 }
261 }
262
Craig Topper8a13c412014-05-21 05:09:00 +0000263 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000264 if (const RecordType *RT =
265 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
266 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000267 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000268 if (!ClassDecl->hasTrivialDestructor())
269 ReferenceTemporaryDtor = ClassDecl->getDestructor();
270 }
271
272 if (!ReferenceTemporaryDtor)
273 return;
274
275 // Call the destructor for the temporary.
276 switch (M->getStorageDuration()) {
277 case SD_Static:
278 case SD_Thread: {
279 llvm::Constant *CleanupFn;
280 llvm::Constant *CleanupArg;
281 if (E->getType()->isArrayType()) {
282 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000283 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000284 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
285 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000286 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
287 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000288 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
289 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000290 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000291 }
292 CGF.CGM.getCXXABI().registerGlobalDtor(
293 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
294 break;
295 }
296
297 case SD_FullExpression:
298 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
299 CodeGenFunction::destroyCXXObject,
300 CGF.getLangOpts().Exceptions);
301 break;
302
303 case SD_Automatic:
304 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
305 ReferenceTemporary, E->getType(),
306 CodeGenFunction::destroyCXXObject,
307 CGF.getLangOpts().Exceptions);
308 break;
309
310 case SD_Dynamic:
311 llvm_unreachable("temporary cannot have dynamic storage duration");
312 }
313}
314
John McCall7f416cc2015-09-08 08:05:57 +0000315static Address
Richard Smith736a9472013-06-12 20:42:33 +0000316createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000317 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000318 switch (M->getStorageDuration()) {
319 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000320 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000321 // If we have a constant temporary array or record try to promote it into a
322 // constant global under the same rules a normal constant would've been
323 // promoted. This is easier on the optimizer and generally emits fewer
324 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000325 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000326 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000327 (Ty->isArrayType() || Ty->isRecordType()) &&
328 CGF.CGM.isTypeConstant(Ty, true))
329 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000330 auto *GV = new llvm::GlobalVariable(
331 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
332 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000333 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
334 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000335 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000336 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000337 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000338 return CGF.CreateMemTemp(Ty, "ref.tmp");
339 }
Richard Smith736a9472013-06-12 20:42:33 +0000340 case SD_Thread:
341 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000342 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000343
344 case SD_Dynamic:
345 llvm_unreachable("temporary can't have dynamic storage duration");
346 }
347 llvm_unreachable("unknown storage duration");
348}
349
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000350LValue CodeGenFunction::
351EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000352 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000353
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000354 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
355 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000356 auto ownership = M->getType().getObjCLifetime();
357 if (ownership != Qualifiers::OCL_None &&
358 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000359 Address Object = createReferenceTemporary(*this, M, E);
360 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
361 Object = Address(llvm::ConstantExpr::getBitCast(Var,
362 ConvertTypeForMem(E->getType())
363 ->getPointerTo(Object.getAddressSpace())),
364 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000365
366 // createReferenceTemporary will promote the temporary to a global with a
367 // constant initializer if it can. It can only do this to a value of
368 // ARC-manageable type if the value is global and therefore "immune" to
369 // ref-counting operations. Therefore we have no need to emit either a
370 // dynamic initialization or a cleanup and we can just return the address
371 // of the temporary.
372 if (Var->hasInitializer())
373 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
374
Richard Smitha509f2f2013-06-14 03:07:01 +0000375 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
376 }
John McCall7f416cc2015-09-08 08:05:57 +0000377 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
378 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000379
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000380 switch (getEvaluationKind(E->getType())) {
381 default: llvm_unreachable("expected scalar or aggregate expression");
382 case TEK_Scalar:
383 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
384 break;
385 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000386 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000387 E->getType().getQualifiers(),
388 AggValueSlot::IsDestructed,
389 AggValueSlot::DoesNotNeedGCBarriers,
390 AggValueSlot::IsNotAliased));
391 break;
392 }
393 }
Richard Smith736a9472013-06-12 20:42:33 +0000394
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000395 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000396 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000397 }
398
Richard Smithf3fabd22013-06-03 00:17:11 +0000399 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000400 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000401 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
402
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000403 for (const auto &Ignored : CommaLHSs)
404 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000405
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000406 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000407 if (opaque->getType()->isRecordType()) {
408 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000409 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000410 }
411 }
412
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000413 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000414 Address Object = createReferenceTemporary(*this, M, E);
415 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
416 Object = Address(llvm::ConstantExpr::getBitCast(
417 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
418 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000419 // If the temporary is a global and has a constant initializer or is a
420 // constant temporary that we promoted to a global, we may have already
421 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000422 if (!Var->hasInitializer()) {
423 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
424 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
425 }
426 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000427 switch (M->getStorageDuration()) {
428 case SD_Automatic:
429 case SD_FullExpression:
430 if (auto *Size = EmitLifetimeStart(
431 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
432 Object.getPointer())) {
433 if (M->getStorageDuration() == SD_Automatic)
434 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
435 Object, Size);
436 else
437 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
438 Size);
439 }
440 break;
441 default:
442 break;
443 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000444 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
445 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000446 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000447
Richard Smith736a9472013-06-12 20:42:33 +0000448 // Perform derived-to-base casts and/or field accesses, to get from the
449 // temporary object we created (and, potentially, for which we extended
450 // the lifetime) to the subobject we're binding the reference to.
451 for (unsigned I = Adjustments.size(); I != 0; --I) {
452 SubobjectAdjustment &Adjustment = Adjustments[I-1];
453 switch (Adjustment.Kind) {
454 case SubobjectAdjustment::DerivedToBaseAdjustment:
455 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000456 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
457 Adjustment.DerivedToBase.BasePath->path_begin(),
458 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000459 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000460 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000461
Richard Smith736a9472013-06-12 20:42:33 +0000462 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000463 LValue LV = MakeAddrLValue(Object, E->getType(),
464 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000465 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000466 assert(LV.isSimple() &&
467 "materialized temporary field is not a simple lvalue");
468 Object = LV.getAddress();
469 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000470 }
471
Richard Smith736a9472013-06-12 20:42:33 +0000472 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000473 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000474 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
475 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000476 break;
477 }
478 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000479 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000480
John McCall7f416cc2015-09-08 08:05:57 +0000481 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000482}
483
484RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000485CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
486 // Emit the expression as an lvalue.
487 LValue LV = EmitLValue(E);
488 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000489 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000490
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000491 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000492 // C++11 [dcl.ref]p5 (as amended by core issue 453):
493 // If a glvalue to which a reference is directly bound designates neither
494 // an existing object or function of an appropriate type nor a region of
495 // storage of suitable size and alignment to contain an object of the
496 // reference's type, the behavior is undefined.
497 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000498 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000499 }
John McCall8680f872010-07-21 06:29:51 +0000500
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000501 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000502}
503
504
Mike Stump4a3999f2009-09-09 13:00:44 +0000505/// getAccessedFieldNo - Given an encoded value and a result number, return the
506/// input field number being accessed.
507unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000508 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000509 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
510 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000511}
512
Richard Smith4d3110a2012-10-25 02:14:12 +0000513/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
514static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
515 llvm::Value *High) {
516 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
517 llvm::Value *K47 = Builder.getInt64(47);
518 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
519 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
520 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
521 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
522 return Builder.CreateMul(B1, KMul);
523}
524
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000525bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000526 return SanOpts.has(SanitizerKind::Null) |
527 SanOpts.has(SanitizerKind::Alignment) |
528 SanOpts.has(SanitizerKind::ObjectSize) |
529 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000530}
531
Richard Smithe30752c2012-10-09 19:52:38 +0000532void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000533 llvm::Value *Ptr, QualType Ty,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000534 CharUnits Alignment, bool SkipNullCheck) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000535 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000536 return;
537
Richard Smith2d8b2942012-11-01 07:22:08 +0000538 // Don't check pointers outside the default address space. The null check
539 // isn't correct, the object-size check isn't supported by LLVM, and we can't
540 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000541 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000542 return;
543
Alexey Samsonov24cad992014-07-17 18:46:27 +0000544 SanitizerScope SanScope(this);
545
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000546 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000547 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000548
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000549 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
550 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000551 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
552 !SkipNullCheck) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000553 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000554 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000555
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000556 if (AllowNullPointers) {
557 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000558 // Skip the remaining checks in that case.
559 Done = createBasicBlock("null");
560 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000561 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000562 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000563 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000564 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000565 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000566 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000567
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000568 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000569 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000570
Richard Smith69d0d262012-08-24 00:54:33 +0000571 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000572 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000573 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000574 // FIXME: Get object address space
575 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
576 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000577 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000578 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000579 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000580 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000581 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000582 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000583 }
Richard Smith69d0d262012-08-24 00:54:33 +0000584
Richard Smithb1b0ab42012-11-05 22:21:05 +0000585 uint64_t AlignVal = 0;
586
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000587 if (SanOpts.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000588 AlignVal = Alignment.getQuantity();
589 if (!Ty->isIncompleteType() && !AlignVal)
590 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
591
Richard Smith69d0d262012-08-24 00:54:33 +0000592 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000593 if (AlignVal) {
594 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000595 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000596 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
597 llvm::Value *Aligned =
598 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000599 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000600 }
Richard Smith69d0d262012-08-24 00:54:33 +0000601 }
602
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000603 if (Checks.size() > 0) {
Richard Smithe30752c2012-10-09 19:52:38 +0000604 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000605 EmitCheckSourceLocation(Loc),
Richard Smithe30752c2012-10-09 19:52:38 +0000606 EmitCheckTypeDescriptor(Ty),
607 llvm::ConstantInt::get(SizeTy, AlignVal),
608 llvm::ConstantInt::get(Int8Ty, TCK)
609 };
John McCall7f416cc2015-09-08 08:05:57 +0000610 EmitCheck(Checks, "type_mismatch", StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000611 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000612
Richard Smithb1b0ab42012-11-05 22:21:05 +0000613 // If possible, check that the vptr indicates that there is a subobject of
614 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000615 //
616 // C++11 [basic.life]p5,6:
617 // [For storage which does not refer to an object within its lifetime]
618 // The program has undefined behavior if:
619 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000620 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000621 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000622 if (SanOpts.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000623 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000624 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
625 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000626 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000627 // Compute a hash of the mangled name of the type.
628 //
629 // FIXME: This is not guaranteed to be deterministic! Move to a
630 // fingerprinting mechanism once LLVM provides one. For the time
631 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000632 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000633 llvm::raw_svector_ostream Out(MangledName);
634 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
635 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000636
Alexey Samsonov84856012014-07-10 22:34:19 +0000637 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000638 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
639 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000640 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000641
Alexey Samsonov84856012014-07-10 22:34:19 +0000642 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
643 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
644 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000645 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000646 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
647 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000648
Alexey Samsonov84856012014-07-10 22:34:19 +0000649 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
650 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000651
Alexey Samsonov84856012014-07-10 22:34:19 +0000652 // Look the hash up in our cache.
653 const int CacheSize = 128;
654 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
655 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
656 "__ubsan_vptr_type_cache");
657 llvm::Value *Slot = Builder.CreateAnd(Hash,
658 llvm::ConstantInt::get(IntPtrTy,
659 CacheSize-1));
660 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
661 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000662 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
663 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000664
665 // If the hash isn't in the cache, call a runtime handler to perform the
666 // hard work of checking whether the vptr is for an object of the right
667 // type. This will either fill in the cache and return, or produce a
668 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000669 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000670 llvm::Constant *StaticData[] = {
671 EmitCheckSourceLocation(Loc),
672 EmitCheckTypeDescriptor(Ty),
673 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
674 llvm::ConstantInt::get(Int8Ty, TCK)
675 };
John McCall7f416cc2015-09-08 08:05:57 +0000676 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000677 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
678 "dynamic_type_cache_miss", StaticData, DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000679 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000680 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000681
682 if (Done) {
683 Builder.CreateBr(Done);
684 EmitBlock(Done);
685 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000686}
Chris Lattner4647a212007-08-31 22:49:20 +0000687
Richard Smith539e4a72013-02-23 02:53:19 +0000688/// Determine whether this expression refers to a flexible array member in a
689/// struct. We disable array bounds checks for such members.
690static bool isFlexibleArrayMemberExpr(const Expr *E) {
691 // For compatibility with existing code, we treat arrays of length 0 or
692 // 1 as flexible array members.
693 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000694 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000695 if (CAT->getSize().ugt(1))
696 return false;
697 } else if (!isa<IncompleteArrayType>(AT))
698 return false;
699
700 E = E->IgnoreParens();
701
702 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000703 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000704 // FIXME: If the base type of the member expr is not FD->getParent(),
705 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000706 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000707 RecordDecl::field_iterator FI(
708 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
709 return ++FI == FD->getParent()->field_end();
710 }
711 }
712
713 return false;
714}
715
716/// If Base is known to point to the start of an array, return the length of
717/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000718static llvm::Value *getArrayIndexingBound(
719 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000720 // For the vector indexing extension, the bound is the number of elements.
721 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
722 IndexedType = Base->getType();
723 return CGF.Builder.getInt32(VT->getNumElements());
724 }
725
726 Base = Base->IgnoreParens();
727
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000728 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000729 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
730 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
731 IndexedType = CE->getSubExpr()->getType();
732 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000733 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000734 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000735 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000736 return CGF.getVLASize(VAT).first;
737 }
738 }
739
Craig Topper8a13c412014-05-21 05:09:00 +0000740 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000741}
742
743void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
744 llvm::Value *Index, QualType IndexType,
745 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000746 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000747 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000748 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000749
Richard Smith539e4a72013-02-23 02:53:19 +0000750 QualType IndexedType;
751 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
752 if (!Bound)
753 return;
754
755 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
756 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
757 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
758
759 llvm::Constant *StaticData[] = {
760 EmitCheckSourceLocation(E->getExprLoc()),
761 EmitCheckTypeDescriptor(IndexedType),
762 EmitCheckTypeDescriptor(IndexType)
763 };
764 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
765 : Builder.CreateICmpULE(IndexVal, BoundVal);
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000766 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
767 StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000768}
769
Chris Lattner116ce8f2010-01-09 21:40:03 +0000770
Chris Lattner116ce8f2010-01-09 21:40:03 +0000771CodeGenFunction::ComplexPairTy CodeGenFunction::
772EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
773 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000774 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000775
Chris Lattner116ce8f2010-01-09 21:40:03 +0000776 llvm::Value *NextVal;
777 if (isa<llvm::IntegerType>(InVal.first->getType())) {
778 uint64_t AmountVal = isInc ? 1 : -1;
779 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000780
Chris Lattner116ce8f2010-01-09 21:40:03 +0000781 // Add the inc/dec to the real part.
782 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
783 } else {
784 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
785 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
786 if (!isInc)
787 FVal.changeSign();
788 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000789
Chris Lattner116ce8f2010-01-09 21:40:03 +0000790 // Add the inc/dec to the real part.
791 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
792 }
Craig Topper99e79272013-07-26 05:59:26 +0000793
Chris Lattner116ce8f2010-01-09 21:40:03 +0000794 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000795
Chris Lattner116ce8f2010-01-09 21:40:03 +0000796 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000797 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000798
Chris Lattner116ce8f2010-01-09 21:40:03 +0000799 // If this is a postinc, return the value read from memory, otherwise use the
800 // updated value.
801 return isPre ? IncVal : InVal;
802}
803
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000804void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
805 CodeGenFunction *CGF) {
806 // Bind VLAs in the cast type.
807 if (CGF && E->getType()->isVariablyModifiedType())
808 CGF->EmitVariablyModifiedType(E->getType());
809
810 if (CGDebugInfo *DI = getModuleDebugInfo())
811 DI->EmitExplicitCastType(E->getType());
812}
813
Chris Lattnera45c5af2007-06-02 19:47:04 +0000814//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000815// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000816//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000817
John McCall7f416cc2015-09-08 08:05:57 +0000818/// EmitPointerWithAlignment - Given an expression of pointer type, try to
819/// derive a more accurate bound on the alignment of the pointer.
820Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
821 AlignmentSource *Source) {
822 // We allow this with ObjC object pointers because of fragile ABIs.
823 assert(E->getType()->isPointerType() ||
824 E->getType()->isObjCObjectPointerType());
825 E = E->IgnoreParens();
826
827 // Casts:
828 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000829 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
830 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000831
832 switch (CE->getCastKind()) {
833 // Non-converting casts (but not C's implicit conversion from void*).
834 case CK_BitCast:
835 case CK_NoOp:
836 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
837 if (PtrTy->getPointeeType()->isVoidType())
838 break;
839
840 AlignmentSource InnerSource;
841 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
842 if (Source) *Source = InnerSource;
843
844 // If this is an explicit bitcast, and the source l-value is
845 // opaque, honor the alignment of the casted-to type.
846 if (isa<ExplicitCastExpr>(CE) &&
John McCall7f416cc2015-09-08 08:05:57 +0000847 InnerSource != AlignmentSource::Decl) {
848 Addr = Address(Addr.getPointer(),
849 getNaturalPointeeTypeAlignment(E->getType(), Source));
850 }
851
Peter Collingbourne574975e2016-01-14 02:49:48 +0000852 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
853 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000854 if (auto PT = E->getType()->getAs<PointerType>())
855 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
856 /*MayBeNull=*/true,
857 CodeGenFunction::CFITCK_UnrelatedCast,
858 CE->getLocStart());
859 }
860
John McCall7f416cc2015-09-08 08:05:57 +0000861 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
862 }
863 break;
864
865 // Array-to-pointer decay.
866 case CK_ArrayToPointerDecay:
867 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
868
869 // Derived-to-base conversions.
870 case CK_UncheckedDerivedToBase:
871 case CK_DerivedToBase: {
872 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
873 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
874 return GetAddressOfBaseClass(Addr, Derived,
875 CE->path_begin(), CE->path_end(),
876 ShouldNullCheckClassCastValue(CE),
877 CE->getExprLoc());
878 }
879
880 // TODO: Is there any reason to treat base-to-derived conversions
881 // specially?
882 default:
883 break;
884 }
885 }
886
887 // Unary &.
888 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
889 if (UO->getOpcode() == UO_AddrOf) {
890 LValue LV = EmitLValue(UO->getSubExpr());
891 if (Source) *Source = LV.getAlignmentSource();
892 return LV.getAddress();
893 }
894 }
895
896 // TODO: conditional operators, comma.
897
898 // Otherwise, use the alignment of the type.
899 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
900 return Address(EmitScalarExpr(E), Align);
901}
902
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000903RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000904 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000905 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000906
907 switch (getEvaluationKind(Ty)) {
908 case TEK_Complex: {
909 llvm::Type *EltTy =
910 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000911 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000912 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000913 }
Craig Topper99e79272013-07-26 05:59:26 +0000914
Chris Lattner65526f02010-08-23 05:26:13 +0000915 // If this is a use of an undefined aggregate type, the aggregate must have an
916 // identifiable address. Just because the contents of the value are undefined
917 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000918 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000919 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000920 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000921 }
John McCall47fb9502013-03-07 21:37:08 +0000922
923 case TEK_Scalar:
924 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
925 }
926 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000927}
928
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000929RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
930 const char *Name) {
931 ErrorUnsupported(E, Name);
932 return GetUndefRValue(E->getType());
933}
934
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000935LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
936 const char *Name) {
937 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000938 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000939 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
940 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000941}
942
Richard Smith4d1458e2012-09-08 02:08:36 +0000943LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000944 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000945 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000946 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
947 else
948 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000949 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000950 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000951 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000952 return LV;
953}
954
Chris Lattner8394d792007-06-05 20:53:16 +0000955/// EmitLValue - Emit code to compute a designator that specifies the location
956/// of the expression.
957///
Mike Stump4a3999f2009-09-09 13:00:44 +0000958/// This can return one of two things: a simple address or a bitfield reference.
959/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
960/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000961///
Mike Stump4a3999f2009-09-09 13:00:44 +0000962/// If this returns a bitfield reference, nothing about the pointee type of the
963/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000964///
Mike Stump4a3999f2009-09-09 13:00:44 +0000965/// If this returns a normal address, and if the lvalue's C type is fixed size,
966/// this method guarantees that the returned pointer type will point to an LLVM
967/// type of the same size of the lvalue's type. If the lvalue has a variable
968/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000969///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000970LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000971 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000972 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000973 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000974
John McCallc109a252011-11-07 03:59:57 +0000975 case Expr::ObjCPropertyRefExprClass:
976 llvm_unreachable("cannot emit a property reference directly");
977
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000978 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000979 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000980 case Expr::ObjCIsaExprClass:
981 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000982 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000983 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000984 case Expr::CompoundAssignOperatorClass: {
985 QualType Ty = E->getType();
986 if (const AtomicType *AT = Ty->getAs<AtomicType>())
987 Ty = AT->getValueType();
988 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000989 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
990 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000991 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000992 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000993 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000994 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000995 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000996 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000997 case Expr::VAArgExprClass:
998 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000999 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001000 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001001 case Expr::ParenExprClass:
1002 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001003 case Expr::GenericSelectionExprClass:
1004 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001005 case Expr::PredefinedExprClass:
1006 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001007 case Expr::StringLiteralClass:
1008 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001009 case Expr::ObjCEncodeExprClass:
1010 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001011 case Expr::PseudoObjectExprClass:
1012 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001013 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001014 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001015 case Expr::CXXTemporaryObjectExprClass:
1016 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001017 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1018 case Expr::CXXBindTemporaryExprClass:
1019 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001020 case Expr::CXXUuidofExprClass:
1021 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001022 case Expr::LambdaExprClass:
1023 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001024
1025 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001026 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001027 enterFullExpression(cleanups);
1028 RunCleanupsScope Scope(*this);
1029 return EmitLValue(cleanups->getSubExpr());
1030 }
1031
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001032 case Expr::CXXDefaultArgExprClass:
1033 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001034 case Expr::CXXDefaultInitExprClass: {
1035 CXXDefaultInitExprScope Scope(*this);
1036 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1037 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001038 case Expr::CXXTypeidExprClass:
1039 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001040
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001041 case Expr::ObjCMessageExprClass:
1042 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001043 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001044 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001045 case Expr::StmtExprClass:
1046 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001047 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001048 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001049 case Expr::ArraySubscriptExprClass:
1050 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001051 case Expr::OMPArraySectionExprClass:
1052 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001053 case Expr::ExtVectorElementExprClass:
1054 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001055 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001056 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001057 case Expr::CompoundLiteralExprClass:
1058 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001059 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001060 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001061 case Expr::BinaryConditionalOperatorClass:
1062 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001063 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001064 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001065 case Expr::OpaqueValueExprClass:
1066 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001067 case Expr::SubstNonTypeTemplateParmExprClass:
1068 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001069 case Expr::ImplicitCastExprClass:
1070 case Expr::CStyleCastExprClass:
1071 case Expr::CXXFunctionalCastExprClass:
1072 case Expr::CXXStaticCastExprClass:
1073 case Expr::CXXDynamicCastExprClass:
1074 case Expr::CXXReinterpretCastExprClass:
1075 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001076 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001077 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001078
Douglas Gregorfe314812011-06-21 17:03:29 +00001079 case Expr::MaterializeTemporaryExprClass:
1080 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001081 }
1082}
1083
John McCall71335052012-03-10 03:05:10 +00001084/// Given an object of the given canonical type, can we safely copy a
1085/// value out of it based on its initializer?
1086static bool isConstantEmittableObjectType(QualType type) {
1087 assert(type.isCanonical());
1088 assert(!type->isReferenceType());
1089
1090 // Must be const-qualified but non-volatile.
1091 Qualifiers qs = type.getLocalQualifiers();
1092 if (!qs.hasConst() || qs.hasVolatile()) return false;
1093
1094 // Otherwise, all object types satisfy this except C++ classes with
1095 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001096 if (const auto *RT = dyn_cast<RecordType>(type))
1097 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001098 if (RD->hasMutableFields() || !RD->isTrivial())
1099 return false;
1100
1101 return true;
1102}
1103
1104/// Can we constant-emit a load of a reference to a variable of the
1105/// given type? This is different from predicates like
1106/// Decl::isUsableInConstantExpressions because we do want it to apply
1107/// in situations that don't necessarily satisfy the language's rules
1108/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1109/// to do this with const float variables even if those variables
1110/// aren't marked 'constexpr'.
1111enum ConstantEmissionKind {
1112 CEK_None,
1113 CEK_AsReferenceOnly,
1114 CEK_AsValueOrReference,
1115 CEK_AsValueOnly
1116};
1117static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1118 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001119 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001120 if (isConstantEmittableObjectType(ref->getPointeeType()))
1121 return CEK_AsValueOrReference;
1122 return CEK_AsReferenceOnly;
1123 }
1124 if (isConstantEmittableObjectType(type))
1125 return CEK_AsValueOnly;
1126 return CEK_None;
1127}
1128
1129/// Try to emit a reference to the given value without producing it as
1130/// an l-value. This is actually more than an optimization: we can't
1131/// produce an l-value for variables that we never actually captured
1132/// in a block or lambda, which means const int variables or constexpr
1133/// literals or similar.
1134CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001135CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1136 ValueDecl *value = refExpr->getDecl();
1137
John McCall71335052012-03-10 03:05:10 +00001138 // The value needs to be an enum constant or a constant variable.
1139 ConstantEmissionKind CEK;
1140 if (isa<ParmVarDecl>(value)) {
1141 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001142 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001143 CEK = checkVarTypeForConstantEmission(var->getType());
1144 } else if (isa<EnumConstantDecl>(value)) {
1145 CEK = CEK_AsValueOnly;
1146 } else {
1147 CEK = CEK_None;
1148 }
1149 if (CEK == CEK_None) return ConstantEmission();
1150
John McCall71335052012-03-10 03:05:10 +00001151 Expr::EvalResult result;
1152 bool resultIsReference;
1153 QualType resultType;
1154
1155 // It's best to evaluate all the way as an r-value if that's permitted.
1156 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001157 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001158 resultIsReference = false;
1159 resultType = refExpr->getType();
1160
1161 // Otherwise, try to evaluate as an l-value.
1162 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001163 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001164 resultIsReference = true;
1165 resultType = value->getType();
1166
1167 // Failure.
1168 } else {
1169 return ConstantEmission();
1170 }
1171
1172 // In any case, if the initializer has side-effects, abandon ship.
1173 if (result.HasSideEffects)
1174 return ConstantEmission();
1175
1176 // Emit as a constant.
1177 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1178
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001179 // Make sure we emit a debug reference to the global variable.
1180 // This should probably fire even for
1181 if (isa<VarDecl>(value)) {
1182 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001183 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001184 } else {
1185 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001186 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001187 }
John McCall71335052012-03-10 03:05:10 +00001188
1189 // If we emitted a reference constant, we need to dereference that.
1190 if (resultIsReference)
1191 return ConstantEmission::forReference(C);
1192
1193 return ConstantEmission::forValue(C);
1194}
1195
Nick Lewycky2d84e842013-10-02 02:29:49 +00001196llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1197 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001198 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001199 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1200 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001201 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1202 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001203}
1204
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001205static bool hasBooleanRepresentation(QualType Ty) {
1206 if (Ty->isBooleanType())
1207 return true;
1208
1209 if (const EnumType *ET = Ty->getAs<EnumType>())
1210 return ET->getDecl()->getIntegerType()->isBooleanType();
1211
Douglas Gregor298f43d2012-04-12 20:42:30 +00001212 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1213 return hasBooleanRepresentation(AT->getValueType());
1214
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001215 return false;
1216}
1217
Richard Smith1629da92012-12-13 07:11:50 +00001218static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1219 llvm::APInt &Min, llvm::APInt &End,
1220 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001221 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001222 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1223 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001224 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001225 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001226 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001227
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001228 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001229 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1230 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001231 } else {
1232 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001233 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001234 unsigned Bitwidth = LTy->getScalarSizeInBits();
1235 unsigned NumNegativeBits = ED->getNumNegativeBits();
1236 unsigned NumPositiveBits = ED->getNumPositiveBits();
1237
1238 if (NumNegativeBits) {
1239 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1240 assert(NumBits <= Bitwidth);
1241 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1242 Min = -End;
1243 } else {
1244 assert(NumPositiveBits <= Bitwidth);
1245 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1246 Min = llvm::APInt(Bitwidth, 0);
1247 }
1248 }
Richard Smith1629da92012-12-13 07:11:50 +00001249 return true;
1250}
1251
1252llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1253 llvm::APInt Min, End;
1254 if (!getRangeForType(*this, Ty, Min, End,
1255 CGM.getCodeGenOpts().StrictEnums))
Craig Topper8a13c412014-05-21 05:09:00 +00001256 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001257
Duncan Sandsc720e782012-04-15 18:04:54 +00001258 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001259 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001260}
1261
John McCall7f416cc2015-09-08 08:05:57 +00001262llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1263 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001264 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001265 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001266 llvm::MDNode *TBAAInfo,
1267 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001268 uint64_t TBAAOffset,
1269 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001270 // For better performance, handle vector loads differently.
1271 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001272 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001273
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001274 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001275
John McCall7f416cc2015-09-08 08:05:57 +00001276 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001277 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001278
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001279 // Bitcast to vec4 type.
1280 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1281 4);
John McCall7f416cc2015-09-08 08:05:57 +00001282 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001283 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001284 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001285
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001286 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001287 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001288 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001289 return EmitFromMemory(V, Ty);
1290 }
1291 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001292
1293 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001294 LValue AtomicLValue =
John McCall7f416cc2015-09-08 08:05:57 +00001295 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001296 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1297 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001298 }
Craig Topper99e79272013-07-26 05:59:26 +00001299
John McCall7f416cc2015-09-08 08:05:57 +00001300 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001301 if (isNontemporal) {
1302 llvm::MDNode *Node = llvm::MDNode::get(
1303 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1304 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1305 }
Manman Renc451e572013-04-04 21:53:22 +00001306 if (TBAAInfo) {
1307 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1308 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001309 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001310 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1311 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001312 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001313
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001314 bool NeedsBoolCheck =
1315 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1316 bool NeedsEnumCheck =
1317 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1318 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001319 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001320 llvm::APInt Min, End;
1321 if (getRangeForType(*this, Ty, Min, End, true)) {
1322 --End;
1323 llvm::Value *Check;
1324 if (!Min)
1325 Check = Builder.CreateICmpULE(
1326 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1327 else {
1328 llvm::Value *Upper = Builder.CreateICmpSLE(
1329 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1330 llvm::Value *Lower = Builder.CreateICmpSGE(
1331 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1332 Check = Builder.CreateAnd(Upper, Lower);
1333 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001334 llvm::Constant *StaticArgs[] = {
1335 EmitCheckSourceLocation(Loc),
1336 EmitCheckTypeDescriptor(Ty)
1337 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001338 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001339 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1340 EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001341 }
1342 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001343 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1344 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001345
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001346 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001347}
1348
John McCall3a7f6922010-10-27 20:58:56 +00001349llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1350 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001351 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001352 // This should really always be an i1, but sometimes it's already
1353 // an i8, and it's awkward to track those cases down.
1354 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001355 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1356 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1357 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001358 }
1359
1360 return Value;
1361}
1362
1363llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1364 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001365 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001366 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1367 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001368 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1369 }
1370
1371 return Value;
1372}
1373
John McCall7f416cc2015-09-08 08:05:57 +00001374void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1375 bool Volatile, QualType Ty,
1376 AlignmentSource AlignSource,
1377 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001378 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001379 uint64_t TBAAOffset,
1380 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001381
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001382 // Handle vectors differently to get better performance.
1383 if (Ty->isVectorType()) {
1384 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001385 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001386 // Handle vec3 special.
1387 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001388 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001389 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1390 Builder.getInt32(2),
1391 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001392 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1393 Value = Builder.CreateShuffleVector(Value,
1394 llvm::UndefValue::get(VecTy),
1395 MaskV, "extractVec");
1396 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1397 }
John McCall7f416cc2015-09-08 08:05:57 +00001398 if (Addr.getElementType() != SrcTy) {
1399 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001400 }
1401 }
Craig Topper99e79272013-07-26 05:59:26 +00001402
John McCall3a7f6922010-10-27 20:58:56 +00001403 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001404
David Majnemera38c9f12016-05-24 16:09:25 +00001405 LValue AtomicLValue =
1406 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001407 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001408 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1409 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001410 return;
1411 }
1412
Daniel Dunbar03816342010-08-21 02:24:36 +00001413 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001414 if (isNontemporal) {
1415 llvm::MDNode *Node =
1416 llvm::MDNode::get(Store->getContext(),
1417 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1418 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1419 }
Manman Renc451e572013-04-04 21:53:22 +00001420 if (TBAAInfo) {
1421 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1422 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001423 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001424 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1425 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001426 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001427}
1428
David Chisnallfa35df62012-01-16 17:27:18 +00001429void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001430 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001431 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001432 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001433 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001434 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001435}
1436
Mike Stump4a3999f2009-09-09 13:00:44 +00001437/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1438/// method emits the address of the lvalue, then loads the result as an rvalue,
1439/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001440RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001441 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001442 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001443 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001444 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1445 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001446 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001447 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001448 // In MRC mode, we do a load+autorelease.
1449 if (!getLangOpts().ObjCAutoRefCount) {
1450 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1451 }
1452
1453 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001454 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1455 Object = EmitObjCConsumeObject(LV.getType(), Object);
1456 return RValue::get(Object);
1457 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001458
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001459 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001460 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001461
John McCalla1dee5302010-08-22 10:59:02 +00001462 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001463 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001464 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001465
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001466 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001467 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001468 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001469 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001470 "vecext"));
1471 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001472
1473 // If this is a reference to a subset of the elements of a vector, either
1474 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001475 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001476 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001477
Renato Golin230c5eb2014-05-19 18:15:42 +00001478 // Global Register variables always invoke intrinsics
1479 if (LV.isGlobalReg())
1480 return EmitLoadOfGlobalRegLValue(LV);
1481
John McCallc109a252011-11-07 03:59:57 +00001482 assert(LV.isBitField() && "Unknown LValue type!");
1483 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001484}
1485
John McCall55e1fbc2011-06-25 02:11:03 +00001486RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001487 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001488
Daniel Dunbar3447a022010-04-13 23:34:15 +00001489 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001490 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001491
John McCall7f416cc2015-09-08 08:05:57 +00001492 Address Ptr = LV.getBitFieldAddress();
1493 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001494
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001495 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001496 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001497 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1498 if (HighBits)
1499 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1500 if (Info.Offset + HighBits)
1501 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1502 } else {
1503 if (Info.Offset)
1504 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001505 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001506 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1507 Info.Size),
1508 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001509 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001510 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001511
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001512 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001513}
1514
Nate Begemanb699c9b2009-01-18 06:42:49 +00001515// If this is a reference to a subset of the elements of a vector, create an
1516// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001517RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001518 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1519 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001520
Nate Begemanf322eab2008-05-09 06:41:27 +00001521 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001522
1523 // If the result of the expression is a non-vector type, we must be extracting
1524 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001525 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001526 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001527 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001528 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001529 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001530 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001531
1532 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001533 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001534
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001535 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001536 for (unsigned i = 0; i != NumResultElts; ++i)
1537 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001538
Chris Lattner91c08ad2011-02-15 00:14:06 +00001539 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1540 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001541 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001542 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001543}
1544
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001545/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001546Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1547 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001548 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1549 QualType EQT = ExprVT->getElementType();
1550 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001551
John McCall7f416cc2015-09-08 08:05:57 +00001552 Address CastToPointerElement =
1553 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1554 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001555
1556 const llvm::Constant *Elts = LV.getExtVectorElts();
1557 unsigned ix = getAccessedFieldNo(0, Elts);
1558
John McCall7f416cc2015-09-08 08:05:57 +00001559 Address VectorBasePtrPlusIx =
1560 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1561 getContext().getTypeSizeInChars(EQT),
1562 "vector.elt");
1563
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001564 return VectorBasePtrPlusIx;
1565}
1566
Renato Golin230c5eb2014-05-19 18:15:42 +00001567/// @brief Load of global gamed gegisters are always calls to intrinsics.
1568RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001569 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1570 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001571 llvm::MDNode *RegName = cast<llvm::MDNode>(
1572 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001573
1574 // We accept integer and pointer types only
1575 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1576 llvm::Type *Ty = OrigTy;
1577 if (OrigTy->isPointerTy())
1578 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1579 llvm::Type *Types[] = { Ty };
1580
Renato Golin230c5eb2014-05-19 18:15:42 +00001581 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001582 llvm::Value *Call = Builder.CreateCall(
1583 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001584 if (OrigTy->isPointerTy())
1585 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001586 return RValue::get(Call);
1587}
Chris Lattner40ff7012007-08-03 16:18:34 +00001588
Chris Lattner9369a562007-06-29 16:31:29 +00001589
Chris Lattner8394d792007-06-05 20:53:16 +00001590/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1591/// lvalue, where both are guaranteed to the have the same type, and that type
1592/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001593void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001594 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001595 if (!Dst.isSimple()) {
1596 if (Dst.isVectorElt()) {
1597 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001598 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1599 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001600 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001601 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001602 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1603 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001604 return;
1605 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001606
Nate Begemance4d7fc2008-04-18 23:10:10 +00001607 // If this is an update of extended vector elements, insert them as
1608 // appropriate.
1609 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001610 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001611
Renato Golin230c5eb2014-05-19 18:15:42 +00001612 if (Dst.isGlobalReg())
1613 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1614
John McCallc109a252011-11-07 03:59:57 +00001615 assert(Dst.isBitField() && "Unknown LValue type");
1616 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001617 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001618
John McCall31168b02011-06-15 23:02:42 +00001619 // There's special magic for assigning into an ARC-qualified l-value.
1620 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1621 switch (Lifetime) {
1622 case Qualifiers::OCL_None:
1623 llvm_unreachable("present but none");
1624
1625 case Qualifiers::OCL_ExplicitNone:
1626 // nothing special
1627 break;
1628
1629 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001630 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001631 return;
1632
1633 case Qualifiers::OCL_Weak:
1634 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1635 return;
1636
1637 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001638 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1639 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001640 // fall into the normal path
1641 break;
1642 }
1643 }
1644
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001645 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001646 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001647 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001648 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001649 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001650 return;
1651 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001652
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001653 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001654 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001655 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001656 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001657 if (Dst.isObjCIvar()) {
1658 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001659 llvm::Type *ResultType = IntPtrTy;
1660 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1661 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001662 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001663 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001664 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1665 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001666 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001667 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001668 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001669 } else if (Dst.isGlobalObjCRef()) {
1670 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1671 Dst.isThreadLocalRef());
1672 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001673 else
1674 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001675 return;
1676 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001677
Chris Lattner6278e6a2007-08-11 00:04:45 +00001678 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001679 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001680}
1681
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001682void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001683 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001684 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001685 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001686 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001687
Daniel Dunbar67aba792010-04-15 03:47:33 +00001688 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001689 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001690
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001691 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001692 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001693 /*IsSigned=*/false);
1694 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001695
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001696 // See if there are other bits in the bitfield's storage we'll need to load
1697 // and mask together with source before storing.
1698 if (Info.StorageSize != Info.Size) {
1699 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001700 llvm::Value *Val =
1701 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001702
1703 // Mask the source value as needed.
1704 if (!hasBooleanRepresentation(Dst.getType()))
1705 SrcVal = Builder.CreateAnd(SrcVal,
1706 llvm::APInt::getLowBitsSet(Info.StorageSize,
1707 Info.Size),
1708 "bf.value");
1709 MaskedVal = SrcVal;
1710 if (Info.Offset)
1711 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1712
1713 // Mask out the original value.
1714 Val = Builder.CreateAnd(Val,
1715 ~llvm::APInt::getBitsSet(Info.StorageSize,
1716 Info.Offset,
1717 Info.Offset + Info.Size),
1718 "bf.clear");
1719
1720 // Or together the unchanged values and the source value.
1721 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1722 } else {
1723 assert(Info.Offset == 0);
1724 }
1725
1726 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001727 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001728
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001729 // Return the new value of the bit-field, if requested.
1730 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001731 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001732
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001733 // Sign extend the value if needed.
1734 if (Info.IsSigned) {
1735 assert(Info.Size <= Info.StorageSize);
1736 unsigned HighBits = Info.StorageSize - Info.Size;
1737 if (HighBits) {
1738 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1739 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1740 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001741 }
1742
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001743 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1744 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001745 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001746 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001747}
1748
Nate Begemance4d7fc2008-04-18 23:10:10 +00001749void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001750 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001751 // This access turns into a read/modify/write of the vector. Load the input
1752 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001753 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1754 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001755 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001756
Chris Lattner4647a212007-08-31 22:49:20 +00001757 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001758
John McCall55e1fbc2011-06-25 02:11:03 +00001759 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001760 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001761 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001762 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001763 // Use shuffle vector is the src and destination are the same number of
1764 // elements and restore the vector mask since it is on the side it will be
1765 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001766 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001767 for (unsigned i = 0; i != NumSrcElts; ++i)
1768 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001769
Chris Lattner91c08ad2011-02-15 00:14:06 +00001770 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001771 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001772 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001773 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001774 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001775 // Extended the source vector to the same length and then shuffle it
1776 // into the destination.
1777 // FIXME: since we're shuffling with undef, can we just use the indices
1778 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001779 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001780 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001781 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001782 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001783 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001784 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001785 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001786 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001787 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001788 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001789 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001790 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001791 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001792
Joey Goulycf4143b2013-11-21 17:09:05 +00001793 // When the vector size is odd and .odd or .hi is used, the last element
1794 // of the Elts constant array will be one past the size of the vector.
1795 // Ignore the last element here, if it is greater than the mask size.
1796 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1797 NumSrcElts--;
1798
Nate Begemanb699c9b2009-01-18 06:42:49 +00001799 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001800 for (unsigned i = 0; i != NumSrcElts; ++i)
1801 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001802 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001803 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001804 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001805 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001806 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001807 }
1808 } else {
1809 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001810 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001811 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001812 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001813 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001814
John McCall7f416cc2015-09-08 08:05:57 +00001815 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1816 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001817}
1818
Renato Golin230c5eb2014-05-19 18:15:42 +00001819/// @brief Store of global named registers are always calls to intrinsics.
1820void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001821 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1822 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001823 llvm::MDNode *RegName = cast<llvm::MDNode>(
1824 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001825 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001826
1827 // We accept integer and pointer types only
1828 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1829 llvm::Type *Ty = OrigTy;
1830 if (OrigTy->isPointerTy())
1831 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1832 llvm::Type *Types[] = { Ty };
1833
Renato Golin230c5eb2014-05-19 18:15:42 +00001834 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1835 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001836 if (OrigTy->isPointerTy())
1837 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001838 Builder.CreateCall(
1839 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001840}
1841
Eric Christopherc9e2a682014-05-20 17:10:39 +00001842// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001843// generating write-barries API. It is currently a global, ivar,
1844// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001845static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001846 LValue &LV,
1847 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001848 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001849 return;
Craig Topper99e79272013-07-26 05:59:26 +00001850
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001851 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001852 QualType ExpTy = E->getType();
1853 if (IsMemberAccess && ExpTy->isPointerType()) {
1854 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001855 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001856 // writer-barrier conservatively.
1857 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1858 if (ExpTy->isRecordType()) {
1859 LV.setObjCIvar(false);
1860 return;
1861 }
1862 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001863 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001864 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001865 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001866 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001867 return;
1868 }
Craig Topper99e79272013-07-26 05:59:26 +00001869
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001870 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1871 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001872 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001873 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001874 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001875 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001876 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001877 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001878 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001879 }
Craig Topper99e79272013-07-26 05:59:26 +00001880
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001881 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001882 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001883 return;
1884 }
Craig Topper99e79272013-07-26 05:59:26 +00001885
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001886 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001887 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001888 if (LV.isObjCIvar()) {
1889 // If cast is to a structure pointer, follow gcc's behavior and make it
1890 // a non-ivar write-barrier.
1891 QualType ExpTy = E->getType();
1892 if (ExpTy->isPointerType())
1893 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1894 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001895 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001896 }
1897 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001898 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001899
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001900 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001901 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1902 return;
1903 }
1904
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001905 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001906 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001907 return;
1908 }
Craig Topper99e79272013-07-26 05:59:26 +00001909
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001910 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001911 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001912 return;
1913 }
John McCall31168b02011-06-15 23:02:42 +00001914
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001915 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001916 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001917 return;
1918 }
1919
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001920 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001921 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001922 if (LV.isObjCIvar() && !LV.isObjCArray())
1923 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001924 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001925 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001926 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001927 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001928 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001929 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001930 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001931 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001932
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001933 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001934 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001935 // We don't know if member is an 'ivar', but this flag is looked at
1936 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001937 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001938 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001939 }
1940}
1941
Chris Lattner3f32d692011-07-12 06:52:18 +00001942static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001943EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001944 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001945 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001946 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001947 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001948}
1949
Alexey Bataev97720002014-11-11 04:05:39 +00001950static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001951 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1952 llvm::Type *RealVarTy, SourceLocation Loc) {
1953 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1954 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1955 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1956}
1957
1958Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1959 const ReferenceType *RefTy,
1960 AlignmentSource *Source) {
1961 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1962 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1963 Source, /*forPointee*/ true));
1964
1965}
1966
1967LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1968 const ReferenceType *RefTy) {
1969 AlignmentSource Source;
1970 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1971 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001972}
1973
Alexey Bataev31300ed2016-02-04 11:27:03 +00001974Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
1975 const PointerType *PtrTy,
1976 AlignmentSource *Source) {
1977 llvm::Value *Addr = Builder.CreateLoad(Ptr);
1978 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
1979 /*forPointeeType=*/true));
1980}
1981
1982LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
1983 const PointerType *PtrTy) {
1984 AlignmentSource Source;
1985 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
1986 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
1987}
1988
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001989static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1990 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001991 QualType T = E->getType();
1992
1993 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00001994 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1995 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00001996 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1997
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001998 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001999 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2000 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002001 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002002 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002003 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002004 // Emit reference to the private copy of the variable if it is an OpenMP
2005 // threadprivate variable.
2006 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002007 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002008 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002009 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2010 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002011 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002012 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002013 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002014 setObjCGCLValueClass(CGF.getContext(), E, LV);
2015 return LV;
2016}
2017
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002018static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00002019 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00002020 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002021 if (!FD->hasPrototype()) {
2022 if (const FunctionProtoType *Proto =
2023 FD->getType()->getAs<FunctionProtoType>()) {
2024 // Ugly case: for a K&R-style definition, the type of the definition
2025 // isn't the same as the type of a use. Correct for this with a
2026 // bitcast.
2027 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00002028 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002029 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002030 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002031 }
2032 }
Eli Friedmana0544d62011-12-03 04:14:32 +00002033 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00002034 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002035}
2036
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002037static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2038 llvm::Value *ThisValue) {
2039 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2040 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2041 return CGF.EmitLValueForField(LV, FD);
2042}
2043
Renato Golin230c5eb2014-05-19 18:15:42 +00002044/// Named Registers are named metadata pointing to the register name
2045/// which will be read from/written to as an argument to the intrinsic
2046/// @llvm.read/write_register.
2047/// So far, only the name is being passed down, but other options such as
2048/// register type, allocation type or even optimization options could be
2049/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002050static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002051 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002052 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002053 assert(Asm->getLabel().size() < 64-Name.size() &&
2054 "Register name too big");
2055 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002056 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002057 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002058 if (M->getNumOperands() == 0) {
2059 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2060 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002061 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002062 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2063 }
John McCall7f416cc2015-09-08 08:05:57 +00002064
2065 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2066
2067 llvm::Value *Ptr =
2068 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2069 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002070}
2071
Chris Lattnerd7f58862007-06-02 05:24:33 +00002072LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002073 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002074 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002075
Renato Goline7b3d5d2014-05-27 16:46:27 +00002076 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2077 // Global Named registers access via intrinsics only
2078 if (VD->getStorageClass() == SC_Register &&
2079 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002080 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002081
Renato Goline7b3d5d2014-05-27 16:46:27 +00002082 // A DeclRefExpr for a reference initialized by a constant expression can
2083 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002084 const Expr *Init = VD->getAnyInitializer(VD);
2085 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2086 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002087 VD->checkInitIsICE() &&
2088 // Do not emit if it is private OpenMP variable.
2089 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2090 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002091 llvm::Constant *Val =
2092 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2093 assert(Val && "failed to emit reference constant expression");
2094 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002095
2096 // Should we be using the alignment of the constant pointer we emitted?
2097 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2098 /*pointee*/ true);
2099
2100 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002101 }
David Majnemer602cfe72015-01-01 09:49:44 +00002102
2103 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002104 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002105 if (auto *FD = LambdaCaptureFields.lookup(VD))
2106 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2107 else if (CapturedStmtInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002108 auto it = LocalDeclMap.find(VD);
2109 if (it != LocalDeclMap.end()) {
2110 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2111 return EmitLoadOfReferenceLValue(it->second, RefTy);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002112 }
John McCall7f416cc2015-09-08 08:05:57 +00002113 return MakeAddrLValue(it->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002114 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002115 LValue CapLVal =
2116 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2117 CapturedStmtInfo->getContextValue());
2118 return MakeAddrLValue(
2119 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2120 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002121 }
John McCall7f416cc2015-09-08 08:05:57 +00002122
David Majnemer602cfe72015-01-01 09:49:44 +00002123 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002124 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2125 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002126 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002127 }
2128
Eli Friedman5720e342012-01-21 04:52:58 +00002129 // FIXME: We should be able to assert this for FunctionDecls as well!
2130 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2131 // those with a valid source location.
2132 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2133 !E->getLocation().isValid()) &&
2134 "Should not use decl without marking it used!");
2135
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002136 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002137 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002138 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2139 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002140 }
2141
Renato Goline7b3d5d2014-05-27 16:46:27 +00002142 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002143 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002144 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002145 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002146
John McCall7f416cc2015-09-08 08:05:57 +00002147 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002148
John McCall7f416cc2015-09-08 08:05:57 +00002149 // The variable should generally be present in the local decl map.
2150 auto iter = LocalDeclMap.find(VD);
2151 if (iter != LocalDeclMap.end()) {
2152 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002153
John McCall7f416cc2015-09-08 08:05:57 +00002154 // Otherwise, it might be static local we haven't emitted yet for
2155 // some reason; most likely, because it's in an outer function.
2156 } else if (VD->isStaticLocal()) {
2157 addr = Address(CGM.getOrCreateStaticVarDecl(
2158 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2159 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002160
John McCall7f416cc2015-09-08 08:05:57 +00002161 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002162 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002163 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2164 }
2165
2166
2167 // Check for OpenMP threadprivate variables.
2168 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2169 return EmitThreadPrivateVarDeclLValue(
2170 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2171 E->getExprLoc());
2172 }
2173
2174 // Drill into block byref variables.
2175 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2176 if (isBlockByref) {
2177 addr = emitBlockByrefAddress(addr, VD);
2178 }
2179
2180 // Drill into reference types.
2181 LValue LV;
2182 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2183 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2184 } else {
2185 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002186 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002187
John McCallcdda29c2013-03-13 03:10:54 +00002188 bool isLocalStorage = VD->hasLocalStorage();
2189
2190 bool NonGCable = isLocalStorage &&
2191 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002192 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002193 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002194 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002195 LV.setNonGC(true);
2196 }
John McCallcdda29c2013-03-13 03:10:54 +00002197
2198 bool isImpreciseLifetime =
2199 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2200 if (isImpreciseLifetime)
2201 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002202 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002203 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002204 }
John McCallf3a88602011-02-03 08:15:49 +00002205
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002206 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002207 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002208
Richard Smithda383632016-08-15 01:33:41 +00002209 // FIXME: While we're emitting a binding from an enclosing scope, all other
2210 // DeclRefExprs we see should be implicitly treated as if they also refer to
2211 // an enclosing scope.
2212 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2213 return EmitLValue(BD->getBinding());
2214
David Blaikie83d382b2011-09-23 05:06:16 +00002215 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002216}
Chris Lattnere47e4402007-06-01 18:02:12 +00002217
Chris Lattner8394d792007-06-05 20:53:16 +00002218LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2219 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002220 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002221 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002222
Chris Lattner0f398c42008-07-26 22:37:01 +00002223 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002224 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002225 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002226 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002227 QualType T = E->getSubExpr()->getType()->getPointeeType();
2228 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002229
John McCall7f416cc2015-09-08 08:05:57 +00002230 AlignmentSource AlignSource;
2231 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2232 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002233 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002234
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002235 // We should not generate __weak write barrier on indirect reference
2236 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2237 // But, we continue to generate __strong write barrier on indirect write
2238 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002239 if (getLangOpts().ObjC1 &&
2240 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002241 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002242 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002243 return LV;
2244 }
John McCalle3027922010-08-25 11:45:40 +00002245 case UO_Real:
2246 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002247 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002248 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002249
Richard Smith0b6b8e42012-02-18 20:53:32 +00002250 // __real is valid on scalars. This is a faster way of testing that.
2251 // __imag can only produce an rvalue on scalars.
2252 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002253 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002254 assert(E->getSubExpr()->getType()->isArithmeticType());
2255 return LV;
2256 }
2257
2258 assert(E->getSubExpr()->getType()->isAnyComplexType());
2259
John McCall7f416cc2015-09-08 08:05:57 +00002260 Address Component =
2261 (E->getOpcode() == UO_Real
2262 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2263 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2264 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
Chris Lattner595db862007-10-30 22:53:42 +00002265 }
John McCalle3027922010-08-25 11:45:40 +00002266 case UO_PreInc:
2267 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002268 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002269 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002270
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002271 if (E->getType()->isAnyComplexType())
2272 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2273 else
2274 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2275 return LV;
2276 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002277 }
Chris Lattner8394d792007-06-05 20:53:16 +00002278}
2279
Chris Lattner4347e3692007-06-06 04:54:52 +00002280LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002281 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002282 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002283}
2284
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002285LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002286 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002287 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002288}
2289
Mike Stump4a3999f2009-09-09 13:00:44 +00002290LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002291 auto SL = E->getFunctionName();
2292 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2293 StringRef FnName = CurFn->getName();
2294 if (FnName.startswith("\01"))
2295 FnName = FnName.substr(1);
2296 StringRef NameItems[] = {
2297 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2298 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002299 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
John McCall7f416cc2015-09-08 08:05:57 +00002300 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2301 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002302 }
Alexey Bataevec474782014-10-09 08:45:04 +00002303 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002304 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002305}
2306
Richard Smithe30752c2012-10-09 19:52:38 +00002307/// Emit a type description suitable for use by a runtime sanitizer library. The
2308/// format of a type descriptor is
2309///
2310/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002311/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002312/// \endcode
2313///
Richard Smith683398a2012-10-09 23:55:19 +00002314/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2315/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002316llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002317 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002318 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002319 return C;
2320
Richard Smithe30752c2012-10-09 19:52:38 +00002321 uint16_t TypeKind = -1;
2322 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002323
Richard Smithe30752c2012-10-09 19:52:38 +00002324 if (T->isIntegerType()) {
2325 TypeKind = 0;
2326 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002327 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002328 } else if (T->isFloatingType()) {
2329 TypeKind = 1;
2330 TypeInfo = getContext().getTypeSize(T);
2331 }
2332
2333 // Format the type name as if for a diagnostic, including quotes and
2334 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002335 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002336 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2337 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002338 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002339 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002340
2341 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002342 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2343 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002344 };
2345 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2346
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002347 auto *GV = new llvm::GlobalVariable(
2348 CGM.getModule(), Descriptor->getType(),
2349 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002350 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002351 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002352
2353 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002354 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002355
Richard Smithe30752c2012-10-09 19:52:38 +00002356 return GV;
2357}
2358
2359llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2360 llvm::Type *TargetTy = IntPtrTy;
2361
Richard Smith48366f72013-03-22 00:47:07 +00002362 // Floating-point types which fit into intptr_t are bitcast to integers
2363 // and then passed directly (after zero-extension, if necessary).
2364 if (V->getType()->isFloatingPointTy()) {
2365 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2366 if (Bits <= TargetTy->getIntegerBitWidth())
2367 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2368 Bits));
2369 }
2370
Richard Smithe30752c2012-10-09 19:52:38 +00002371 // Integers which fit in intptr_t are zero-extended and passed directly.
2372 if (V->getType()->isIntegerTy() &&
2373 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2374 return Builder.CreateZExt(V, TargetTy);
2375
2376 // Pointers are passed directly, everything else is passed by address.
2377 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002378 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002379 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002380 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002381 }
2382 return Builder.CreatePtrToInt(V, TargetTy);
2383}
2384
2385/// \brief Emit a representation of a SourceLocation for passing to a handler
2386/// in a sanitizer runtime library. The format for this data is:
2387/// \code
2388/// struct SourceLocation {
2389/// const char *Filename;
2390/// int32_t Line, Column;
2391/// };
2392/// \endcode
2393/// For an invalid SourceLocation, the Filename pointer is null.
2394llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002395 llvm::Constant *Filename;
2396 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002397
Alexey Samsonov6c124142014-07-18 17:50:06 +00002398 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2399 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002400 StringRef FilenameString = PLoc.getFilename();
2401
2402 int PathComponentsToStrip =
2403 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2404 if (PathComponentsToStrip < 0) {
2405 assert(PathComponentsToStrip != INT_MIN);
2406 int PathComponentsToKeep = -PathComponentsToStrip;
2407 auto I = llvm::sys::path::rbegin(FilenameString);
2408 auto E = llvm::sys::path::rend(FilenameString);
2409 while (I != E && --PathComponentsToKeep)
2410 ++I;
2411
2412 FilenameString = FilenameString.substr(I - E);
2413 } else if (PathComponentsToStrip > 0) {
2414 auto I = llvm::sys::path::begin(FilenameString);
2415 auto E = llvm::sys::path::end(FilenameString);
2416 while (I != E && PathComponentsToStrip--)
2417 ++I;
2418
2419 if (I != E)
2420 FilenameString =
2421 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2422 else
2423 FilenameString = llvm::sys::path::filename(FilenameString);
2424 }
2425
2426 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002427 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2428 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2429 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002430 Line = PLoc.getLine();
2431 Column = PLoc.getColumn();
2432 } else {
2433 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2434 Line = Column = 0;
2435 }
2436
2437 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2438 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002439
2440 return llvm::ConstantStruct::getAnon(Data);
2441}
2442
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002443namespace {
2444/// \brief Specify under what conditions this check can be recovered
2445enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002446 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002447 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002448 /// Check supports recovering, runtime has both fatal (noreturn) and
2449 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002450 Recoverable,
2451 /// Runtime conditionally aborts, always need to support recovery.
2452 AlwaysRecoverable
2453};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002454}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002455
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002456static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2457 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002458 switch (Kind) {
2459 case SanitizerKind::Vptr:
2460 return CheckRecoverableKind::AlwaysRecoverable;
2461 case SanitizerKind::Return:
2462 case SanitizerKind::Unreachable:
2463 return CheckRecoverableKind::Unrecoverable;
2464 default:
2465 return CheckRecoverableKind::Recoverable;
2466 }
2467}
2468
Alexey Samsonov88459522015-01-12 22:39:12 +00002469static void emitCheckHandlerCall(CodeGenFunction &CGF,
2470 llvm::FunctionType *FnType,
2471 ArrayRef<llvm::Value *> FnArgs,
2472 StringRef CheckName,
2473 CheckRecoverableKind RecoverKind, bool IsFatal,
2474 llvm::BasicBlock *ContBB) {
2475 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2476 bool NeedsAbortSuffix =
2477 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2478 std::string FnName = ("__ubsan_handle_" + CheckName +
2479 (NeedsAbortSuffix ? "_abort" : "")).str();
2480 bool MayReturn =
2481 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2482
2483 llvm::AttrBuilder B;
2484 if (!MayReturn) {
2485 B.addAttribute(llvm::Attribute::NoReturn)
2486 .addAttribute(llvm::Attribute::NoUnwind);
2487 }
2488 B.addAttribute(llvm::Attribute::UWTable);
2489
2490 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2491 FnType, FnName,
2492 llvm::AttributeSet::get(CGF.getLLVMContext(),
2493 llvm::AttributeSet::FunctionIndex, B));
2494 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2495 if (!MayReturn) {
2496 HandlerCall->setDoesNotReturn();
2497 CGF.Builder.CreateUnreachable();
2498 } else {
2499 CGF.Builder.CreateBr(ContBB);
2500 }
2501}
2502
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002503void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002504 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002505 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2506 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002507 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002508 assert(Checked.size() > 0);
Alexey Samsonov88459522015-01-12 22:39:12 +00002509
2510 llvm::Value *FatalCond = nullptr;
2511 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002512 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002513 for (int i = 0, n = Checked.size(); i < n; ++i) {
2514 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002515 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002516 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002517 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2518 ? TrapCond
2519 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2520 ? RecoverableCond
2521 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002522 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2523 }
2524
Peter Collingbourne9881b782015-06-18 23:59:22 +00002525 if (TrapCond)
2526 EmitTrapCheck(TrapCond);
2527 if (!FatalCond && !RecoverableCond)
2528 return;
2529
Alexey Samsonov88459522015-01-12 22:39:12 +00002530 llvm::Value *JointCond;
2531 if (FatalCond && RecoverableCond)
2532 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2533 else
2534 JointCond = FatalCond ? FatalCond : RecoverableCond;
2535 assert(JointCond);
2536
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002537 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002538 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002539#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002540 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002541 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002542 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002543 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002544 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002545#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002546
Richard Smith4d1458e2012-09-08 02:08:36 +00002547 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002548 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2549 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002550 // Give hint that we very much don't expect to execute the handler
2551 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2552 llvm::MDBuilder MDHelper(getLLVMContext());
2553 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2554 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002555 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002556
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002557 // Handler functions take an i8* pointing to the (handler-specific) static
2558 // information block, followed by a sequence of intptr_t arguments
2559 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002560 SmallVector<llvm::Value *, 4> Args;
2561 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002562 Args.reserve(DynamicArgs.size() + 1);
2563 ArgTypes.reserve(DynamicArgs.size() + 1);
2564
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002565 // Emit handler arguments and create handler function type.
2566 if (!StaticArgs.empty()) {
2567 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2568 auto *InfoPtr =
2569 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2570 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002571 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002572 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2573 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2574 ArgTypes.push_back(Int8PtrTy);
2575 }
2576
Richard Smithe30752c2012-10-09 19:52:38 +00002577 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2578 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2579 ArgTypes.push_back(IntPtrTy);
2580 }
2581
2582 llvm::FunctionType *FnType =
2583 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002584
Alexey Samsonov88459522015-01-12 22:39:12 +00002585 if (!FatalCond || !RecoverableCond) {
2586 // Simple case: we need to generate a single handler call, either
2587 // fatal, or non-fatal.
2588 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2589 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002590 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002591 // Emit two handler calls: first one for set of unrecoverable checks,
2592 // another one for recoverable.
2593 llvm::BasicBlock *NonFatalHandlerBB =
2594 createBasicBlock("non_fatal." + CheckName);
2595 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2596 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2597 EmitBlock(FatalHandlerBB);
2598 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2599 NonFatalHandlerBB);
2600 EmitBlock(NonFatalHandlerBB);
2601 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2602 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002603 }
Richard Smithe30752c2012-10-09 19:52:38 +00002604
Richard Smith4d1458e2012-09-08 02:08:36 +00002605 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002606}
2607
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002608void CodeGenFunction::EmitCfiSlowPathCheck(
2609 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2610 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002611 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2612
2613 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2614 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2615
2616 llvm::MDBuilder MDHelper(getLLVMContext());
2617 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2618 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2619
2620 EmitBlock(CheckBB);
2621
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002622 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2623
2624 llvm::CallInst *CheckCall;
2625 if (WithDiag) {
2626 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2627 auto *InfoPtr =
2628 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2629 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002630 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002631 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2632
2633 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2634 "__cfi_slowpath_diag",
2635 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2636 false));
2637 CheckCall = Builder.CreateCall(
2638 SlowPathDiagFn,
2639 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2640 } else {
2641 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2642 "__cfi_slowpath",
2643 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2644 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2645 }
2646
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002647 CheckCall->setDoesNotThrow();
2648
2649 EmitBlock(Cont);
2650}
2651
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002652// This function is basically a switch over the CFI failure kind, which is
2653// extracted from CFICheckFailData (1st function argument). Each case is either
2654// llvm.trap or a call to one of the two runtime handlers, based on
2655// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2656// failure kind) traps, but this should really never happen. CFICheckFailData
2657// can be nullptr if the calling module has -fsanitize-trap behavior for this
2658// check kind; in this case __cfi_check_fail traps as well.
2659void CodeGenFunction::EmitCfiCheckFail() {
2660 SanitizerScope SanScope(this);
2661 FunctionArgList Args;
2662 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2663 getContext().VoidPtrTy);
2664 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2665 getContext().VoidPtrTy);
2666 Args.push_back(&ArgData);
2667 Args.push_back(&ArgAddr);
2668
John McCallc56a8b32016-03-11 04:30:31 +00002669 const CGFunctionInfo &FI =
2670 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002671
2672 llvm::Function *F = llvm::Function::Create(
2673 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2674 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2675 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2676
2677 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2678 SourceLocation());
2679
2680 llvm::Value *Data =
2681 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2682 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2683 llvm::Value *Addr =
2684 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2685 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2686
2687 // Data == nullptr means the calling module has trap behaviour for this check.
2688 llvm::Value *DataIsNotNullPtr =
2689 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2690 EmitTrapCheck(DataIsNotNullPtr);
2691
2692 llvm::StructType *SourceLocationTy =
2693 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2694 llvm::StructType *CfiCheckFailDataTy =
2695 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2696
2697 llvm::Value *V = Builder.CreateConstGEP2_32(
2698 CfiCheckFailDataTy,
2699 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2700 0);
2701 Address CheckKindAddr(V, getIntAlign());
2702 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2703
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002704 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2705 CGM.getLLVMContext(),
2706 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2707 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002708 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002709 {Addr, AllVtables}),
2710 IntPtrTy);
2711
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002712 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002713 {CFITCK_VCall, SanitizerKind::CFIVCall},
2714 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2715 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2716 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2717 {CFITCK_ICall, SanitizerKind::CFIICall}};
2718
2719 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2720 for (auto CheckKindMaskPair : CheckKinds) {
2721 int Kind = CheckKindMaskPair.first;
2722 SanitizerMask Mask = CheckKindMaskPair.second;
2723 llvm::Value *Cond =
2724 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002725 if (CGM.getLangOpts().Sanitize.has(Mask))
2726 EmitCheck(std::make_pair(Cond, Mask), "cfi_check_fail", {},
2727 {Data, Addr, ValidVtable});
2728 else
2729 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002730 }
2731
2732 FinishFunction();
2733 // The only reference to this function will be created during LTO link.
2734 // Make sure it survives until then.
2735 CGM.addUsedGlobal(F);
2736}
2737
Chad Rosierae229d52013-01-29 23:31:22 +00002738void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002739 llvm::BasicBlock *Cont = createBasicBlock("cont");
2740
2741 // If we're optimizing, collapse all calls to trap down to just one per
2742 // function to save on code size.
2743 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2744 TrapBB = createBasicBlock("trap");
2745 Builder.CreateCondBr(Checked, Cont, TrapBB);
2746 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002747 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002748 TrapCall->setDoesNotReturn();
2749 TrapCall->setDoesNotThrow();
2750 Builder.CreateUnreachable();
2751 } else {
2752 Builder.CreateCondBr(Checked, Cont, TrapBB);
2753 }
2754
2755 EmitBlock(Cont);
2756}
2757
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002758llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002759 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002760
Amaury Sechet21f51b32016-09-09 04:42:49 +00002761 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2762 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2763 CGM.getCodeGenOpts().TrapFuncName);
2764 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex, A);
2765 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002766
2767 return TrapCall;
2768}
2769
John McCall7f416cc2015-09-08 08:05:57 +00002770Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2771 AlignmentSource *AlignSource) {
2772 assert(E->getType()->isArrayType() &&
2773 "Array to pointer decay must have array source type!");
2774
2775 // Expressions of array type can't be bitfields or vector elements.
2776 LValue LV = EmitLValue(E);
2777 Address Addr = LV.getAddress();
2778 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2779
2780 // If the array type was an incomplete type, we need to make sure
2781 // the decay ends up being the right type.
2782 llvm::Type *NewTy = ConvertType(E->getType());
2783 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2784
2785 // Note that VLA pointers are always decayed, so we don't need to do
2786 // anything here.
2787 if (!E->getType()->isVariableArrayType()) {
2788 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2789 "Expected pointer to array");
2790 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2791 }
2792
2793 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2794 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2795}
2796
Chris Lattner6c5abe82010-06-26 23:03:20 +00002797/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2798/// array to pointer, return the array subexpression.
2799static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2800 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002801 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002802 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002803 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002804
Chris Lattner6c5abe82010-06-26 23:03:20 +00002805 // If this is a decay from variable width array, bail out.
2806 const Expr *SubExpr = CE->getSubExpr();
2807 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002808 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002809
Chris Lattner6c5abe82010-06-26 23:03:20 +00002810 return SubExpr;
2811}
2812
John McCall7f416cc2015-09-08 08:05:57 +00002813static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2814 llvm::Value *ptr,
2815 ArrayRef<llvm::Value*> indices,
2816 bool inbounds,
2817 const llvm::Twine &name = "arrayidx") {
2818 if (inbounds) {
2819 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2820 } else {
2821 return CGF.Builder.CreateGEP(ptr, indices, name);
2822 }
2823}
2824
2825static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2826 llvm::Value *idx,
2827 CharUnits eltSize) {
2828 // If we have a constant index, we can use the exact offset of the
2829 // element we're accessing.
2830 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2831 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2832 return arrayAlign.alignmentAtOffset(offset);
2833
2834 // Otherwise, use the worst-case alignment for any element.
2835 } else {
2836 return arrayAlign.alignmentOfArrayElement(eltSize);
2837 }
2838}
2839
2840static QualType getFixedSizeElementType(const ASTContext &ctx,
2841 const VariableArrayType *vla) {
2842 QualType eltType;
2843 do {
2844 eltType = vla->getElementType();
2845 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2846 return eltType;
2847}
2848
2849static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2850 ArrayRef<llvm::Value*> indices,
2851 QualType eltType, bool inbounds,
2852 const llvm::Twine &name = "arrayidx") {
2853 // All the indices except that last must be zero.
2854#ifndef NDEBUG
2855 for (auto idx : indices.drop_back())
2856 assert(isa<llvm::ConstantInt>(idx) &&
2857 cast<llvm::ConstantInt>(idx)->isZero());
2858#endif
2859
2860 // Determine the element size of the statically-sized base. This is
2861 // the thing that the indices are expressed in terms of.
2862 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2863 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2864 }
2865
2866 // We can use that to compute the best alignment of the element.
2867 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2868 CharUnits eltAlign =
2869 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2870
2871 llvm::Value *eltPtr =
2872 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2873 return Address(eltPtr, eltAlign);
2874}
2875
Richard Smith539e4a72013-02-23 02:53:19 +00002876LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2877 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00002878 // The index must always be an integer, which is not an aggregate. Emit it
2879 // in lexical order (this complexity is, sadly, required by C++17).
2880 llvm::Value *IdxPre =
2881 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Richard Smith40885712016-09-27 00:53:24 +00002882 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00002883 auto *Idx = IdxPre;
2884 if (E->getLHS() != E->getIdx()) {
2885 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
2886 Idx = EmitScalarExpr(E->getIdx());
2887 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00002888
Richard Smith9e67b992016-09-26 23:49:47 +00002889 QualType IdxTy = E->getIdx()->getType();
2890 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
2891
2892 if (SanOpts.has(SanitizerKind::ArrayBounds))
2893 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2894
2895 // Extend or truncate the index type to 32 or 64-bits.
2896 if (Promote && Idx->getType() != IntPtrTy)
2897 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
2898
2899 return Idx;
2900 };
2901 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00002902
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002903 // If the base is a vector type, then we are forming a vector element lvalue
2904 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002905 if (E->getBase()->getType()->isVectorType() &&
2906 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002907 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002908 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00002909 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00002910 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002911 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002912 E->getBase()->getType(),
2913 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002914 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002915
John McCall7f416cc2015-09-08 08:05:57 +00002916 // All the other cases basically behave like simple offsetting.
2917
John McCall7f416cc2015-09-08 08:05:57 +00002918 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002919 if (isa<ExtVectorElementExpr>(E->getBase())) {
2920 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00002921 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00002922 Address Addr = EmitExtVectorElementLValue(LV);
2923
2924 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2925 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2926 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002927 }
John McCall7f416cc2015-09-08 08:05:57 +00002928
2929 AlignmentSource AlignSource;
2930 Address Addr = Address::invalid();
2931 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002932 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002933 // The base must be a pointer, which is not an aggregate. Emit
2934 // it. It needs to be emitted first in case it's what captures
2935 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002936 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00002937 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00002938
John McCall23c29fe2011-06-24 21:55:10 +00002939 // The element count here is the total number of non-VLA elements.
2940 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002941
John McCall77527a82011-06-25 01:32:37 +00002942 // Effectively, the multiply by the VLA size is part of the GEP.
2943 // GEP indexes are signed, and scaling an index isn't permitted to
2944 // signed-overflow, so we use the same semantics for our explicit
2945 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002946 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002947 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002948 } else {
2949 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002950 }
John McCall7f416cc2015-09-08 08:05:57 +00002951
2952 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2953 !getLangOpts().isSignedOverflowDefined());
2954
Chris Lattner6c5abe82010-06-26 23:03:20 +00002955 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2956 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002957
John McCall7f416cc2015-09-08 08:05:57 +00002958 // Emit the base pointer.
2959 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00002960 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
2961
2962 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2963 llvm::Value *InterfaceSizeVal =
2964 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
2965
2966 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00002967
2968 // We don't necessarily build correct LLVM struct types for ObjC
2969 // interfaces, so we can't rely on GEP to do this scaling
2970 // correctly, so we need to cast to i8*. FIXME: is this actually
2971 // true? A lot of other things in the fragile ABI would break...
2972 llvm::Type *OrigBaseTy = Addr.getType();
2973 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2974
2975 // Do the GEP.
2976 CharUnits EltAlign =
2977 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2978 llvm::Value *EltPtr =
2979 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2980 Addr = Address(EltPtr, EltAlign);
2981
2982 // Cast back.
2983 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00002984 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2985 // If this is A[i] where A is an array, the frontend will have decayed the
2986 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2987 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2988 // "gep x, i" here. Emit one "gep A, 0, i".
2989 assert(Array->getType()->isArrayType() &&
2990 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002991 LValue ArrayLV;
2992 // For simple multidimensional array indexing, set the 'accessed' flag for
2993 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002994 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002995 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2996 else
2997 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00002998 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00002999
Daniel Dunbar82634272011-04-01 00:49:43 +00003000 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00003001 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3002 {CGM.getSize(CharUnits::Zero()), Idx},
3003 E->getType(),
3004 !getLangOpts().isSignedOverflowDefined());
3005 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003006 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003007 // The base must be a pointer; emit it with an estimate of its alignment.
3008 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003009 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003010 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3011 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003012 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003013
John McCall7f416cc2015-09-08 08:05:57 +00003014 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00003015
John McCall7f416cc2015-09-08 08:05:57 +00003016 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003017
Richard Smith9c6890a2012-11-01 22:30:59 +00003018 if (getLangOpts().ObjC1 &&
3019 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003020 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003021 setObjCGCLValueClass(getContext(), E, LV);
3022 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003023 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003024}
3025
Alexey Bataev31300ed2016-02-04 11:27:03 +00003026static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3027 AlignmentSource &AlignSource,
3028 QualType BaseTy, QualType ElTy,
3029 bool IsLowerBound) {
3030 LValue BaseLVal;
3031 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3032 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3033 if (BaseTy->isArrayType()) {
3034 Address Addr = BaseLVal.getAddress();
3035 AlignSource = BaseLVal.getAlignmentSource();
3036
3037 // If the array type was an incomplete type, we need to make sure
3038 // the decay ends up being the right type.
3039 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3040 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3041
3042 // Note that VLA pointers are always decayed, so we don't need to do
3043 // anything here.
3044 if (!BaseTy->isVariableArrayType()) {
3045 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3046 "Expected pointer to array");
3047 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3048 "arraydecay");
3049 }
3050
3051 return CGF.Builder.CreateElementBitCast(Addr,
3052 CGF.ConvertTypeForMem(ElTy));
3053 }
3054 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3055 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3056 }
3057 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3058}
3059
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003060LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3061 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003062 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003063 if (auto *ASE =
3064 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003065 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003066 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003067 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003068 QualType ResultExprTy;
3069 if (auto *AT = getContext().getAsArrayType(BaseTy))
3070 ResultExprTy = AT->getElementType();
3071 else
3072 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003073 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003074 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003075 // Requesting lower bound or upper bound, but without provided length and
3076 // without ':' symbol for the default length -> length = 1.
3077 // Idx = LowerBound ?: 0;
3078 if (auto *LowerBound = E->getLowerBound()) {
3079 Idx = Builder.CreateIntCast(
3080 EmitScalarExpr(LowerBound), IntPtrTy,
3081 LowerBound->getType()->hasSignedIntegerRepresentation());
3082 } else
3083 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3084 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003085 // Try to emit length or lower bound as constant. If this is possible, 1
3086 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3087 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003088 auto &C = CGM.getContext();
3089 auto *Length = E->getLength();
3090 llvm::APSInt ConstLength;
3091 if (Length) {
3092 // Idx = LowerBound + Length - 1;
3093 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3094 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3095 Length = nullptr;
3096 }
3097 auto *LowerBound = E->getLowerBound();
3098 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3099 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3100 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3101 LowerBound = nullptr;
3102 }
3103 if (!Length)
3104 --ConstLength;
3105 else if (!LowerBound)
3106 --ConstLowerBound;
3107
3108 if (Length || LowerBound) {
3109 auto *LowerBoundVal =
3110 LowerBound
3111 ? Builder.CreateIntCast(
3112 EmitScalarExpr(LowerBound), IntPtrTy,
3113 LowerBound->getType()->hasSignedIntegerRepresentation())
3114 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3115 auto *LengthVal =
3116 Length
3117 ? Builder.CreateIntCast(
3118 EmitScalarExpr(Length), IntPtrTy,
3119 Length->getType()->hasSignedIntegerRepresentation())
3120 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3121 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3122 /*HasNUW=*/false,
3123 !getLangOpts().isSignedOverflowDefined());
3124 if (Length && LowerBound) {
3125 Idx = Builder.CreateSub(
3126 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3127 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3128 }
3129 } else
3130 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3131 } else {
3132 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003133 QualType ArrayTy = BaseTy->isPointerType()
3134 ? E->getBase()->IgnoreParenImpCasts()->getType()
3135 : BaseTy;
3136 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003137 Length = VAT->getSizeExpr();
3138 if (Length->isIntegerConstantExpr(ConstLength, C))
3139 Length = nullptr;
3140 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003141 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003142 ConstLength = CAT->getSize();
3143 }
3144 if (Length) {
3145 auto *LengthVal = Builder.CreateIntCast(
3146 EmitScalarExpr(Length), IntPtrTy,
3147 Length->getType()->hasSignedIntegerRepresentation());
3148 Idx = Builder.CreateSub(
3149 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3150 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3151 } else {
3152 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3153 --ConstLength;
3154 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3155 }
3156 }
3157 }
3158 assert(Idx);
3159
Alexey Bataev31300ed2016-02-04 11:27:03 +00003160 Address EltPtr = Address::invalid();
3161 AlignmentSource AlignSource;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003162 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003163 // The base must be a pointer, which is not an aggregate. Emit
3164 // it. It needs to be emitted first in case it's what captures
3165 // the VLA bounds.
3166 Address Base =
3167 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3168 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003169 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003170 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003171
3172 // Effectively, the multiply by the VLA size is part of the GEP.
3173 // GEP indexes are signed, and scaling an index isn't permitted to
3174 // signed-overflow, so we use the same semantics for our explicit
3175 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003176 if (getLangOpts().isSignedOverflowDefined())
3177 Idx = Builder.CreateMul(Idx, NumElements);
3178 else
3179 Idx = Builder.CreateNSWMul(Idx, NumElements);
3180 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3181 !getLangOpts().isSignedOverflowDefined());
3182 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3183 // If this is A[i] where A is an array, the frontend will have decayed the
3184 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3185 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3186 // "gep x, i" here. Emit one "gep A, 0, i".
3187 assert(Array->getType()->isArrayType() &&
3188 "Array to pointer decay must have array source type!");
3189 LValue ArrayLV;
3190 // For simple multidimensional array indexing, set the 'accessed' flag for
3191 // better bounds-checking of the base expression.
3192 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3193 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3194 else
3195 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003196
Alexey Bataev31300ed2016-02-04 11:27:03 +00003197 // Propagate the alignment from the array itself to the result.
3198 EltPtr = emitArraySubscriptGEP(
3199 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3200 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3201 AlignSource = ArrayLV.getAlignmentSource();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003202 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003203 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3204 BaseTy, ResultExprTy, IsLowerBound);
3205 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3206 !getLangOpts().isSignedOverflowDefined());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003207 }
3208
Alexey Bataev31300ed2016-02-04 11:27:03 +00003209 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003210}
3211
Chris Lattner9e751ca2007-08-02 23:37:31 +00003212LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003213EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003214 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003215 LValue Base;
3216
3217 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003218 if (E->isArrow()) {
3219 // If it is a pointer to a vector, emit the address and form an lvalue with
3220 // it.
John McCall7f416cc2015-09-08 08:05:57 +00003221 AlignmentSource AlignSource;
3222 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003223 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00003224 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003225 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003226 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003227 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3228 // emit the base as an lvalue.
3229 assert(E->getBase()->getType()->isVectorType());
3230 Base = EmitLValue(E->getBase());
3231 } else {
3232 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003233 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003234 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003235 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003236
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003237 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003238 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003239 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003240 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3241 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003242 }
John McCall1553b192011-06-16 04:16:24 +00003243
3244 QualType type =
3245 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003246
Nate Begemand3862152008-05-13 21:03:02 +00003247 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003248 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003249 E->getEncodedElementAccess(Indices);
3250
3251 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003252 llvm::Constant *CV =
3253 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003254 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00003255 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00003256 }
3257 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3258
3259 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003260 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003261
Chris Lattner595ba3a2012-01-30 06:20:36 +00003262 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3263 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003264 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003265 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3266 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003267}
3268
Devang Patel30efa2e2007-10-23 20:28:39 +00003269LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003270 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003271
Chris Lattner4e4186b2007-12-02 18:52:07 +00003272 // 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 +00003273 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003274 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003275 AlignmentSource AlignSource;
3276 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003277 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003278 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3279 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003280 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003281 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003282
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003283 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003284 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003285 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003286 setObjCGCLValueClass(getContext(), E, LV);
3287 return LV;
3288 }
Craig Topper99e79272013-07-26 05:59:26 +00003289
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003290 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003291 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003292
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003293 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003294 return EmitFunctionDeclLValue(*this, E, FD);
3295
David Blaikie83d382b2011-09-23 05:06:16 +00003296 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003297}
Devang Patel30efa2e2007-10-23 20:28:39 +00003298
John McCalldec348f72013-05-03 07:33:41 +00003299/// Given that we are currently emitting a lambda, emit an l-value for
3300/// one of its members.
3301LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3302 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3303 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3304 QualType LambdaTagType =
3305 getContext().getTagDeclType(Field->getParent());
3306 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3307 return EmitLValueForField(LambdaLV, Field);
3308}
3309
John McCall7f416cc2015-09-08 08:05:57 +00003310/// Drill down to the storage of a field without walking into
3311/// reference types.
3312///
3313/// The resulting address doesn't necessarily have the right type.
3314static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3315 const FieldDecl *field) {
3316 const RecordDecl *rec = field->getParent();
3317
3318 unsigned idx =
3319 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3320
3321 CharUnits offset;
3322 // Adjust the alignment down to the given offset.
3323 // As a special case, if the LLVM field index is 0, we know that this
3324 // is zero.
3325 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3326 .getFieldOffset(field->getFieldIndex()) == 0) &&
3327 "LLVM field at index zero had non-zero offset?");
3328 if (idx != 0) {
3329 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3330 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3331 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3332 }
3333
3334 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3335}
3336
Eli Friedman7f1ff602012-04-16 03:54:45 +00003337LValue CodeGenFunction::EmitLValueForField(LValue base,
3338 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003339 AlignmentSource fieldAlignSource =
3340 getFieldAlignmentSource(base.getAlignmentSource());
3341
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003342 if (field->isBitField()) {
3343 const CGRecordLayout &RL =
3344 CGM.getTypes().getCGRecordLayout(field->getParent());
3345 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003346 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003347 unsigned Idx = RL.getLLVMFieldNo(field);
3348 if (Idx != 0)
3349 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003350 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3351 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003352 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003353 llvm::Type *FieldIntTy =
3354 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3355 if (Addr.getElementType() != FieldIntTy)
3356 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003357
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003358 QualType fieldType =
3359 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003360 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003361 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003362
John McCall53fcbd22011-02-26 08:07:02 +00003363 const RecordDecl *rec = field->getParent();
3364 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003365
John McCall53fcbd22011-02-26 08:07:02 +00003366 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3367
John McCall7f416cc2015-09-08 08:05:57 +00003368 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003369 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003370 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003371 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003372 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003373 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003374 // TODO: handle path-aware TBAA for union.
3375 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003376 } else {
3377 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003378 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003379
3380 // If this is a reference field, load the reference right now.
3381 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3382 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3383 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3384
Manman Renc451e572013-04-04 21:53:22 +00003385 // Loading the reference will disable path-aware TBAA.
3386 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003387 if (CGM.shouldUseTBAA()) {
3388 llvm::MDNode *tbaa;
3389 if (mayAlias)
3390 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3391 else
3392 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003393 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003394 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003395 }
3396
John McCall53fcbd22011-02-26 08:07:02 +00003397 mayAlias = false;
3398 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003399
3400 CharUnits alignment =
3401 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3402 addr = Address(load, alignment);
3403
3404 // Qualifiers on the struct don't apply to the referencee, and
3405 // we'll pick up CVR from the actual type later, so reset these
3406 // additional qualifiers now.
3407 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003408 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003409 }
Craig Topper99e79272013-07-26 05:59:26 +00003410
Chris Lattner13ee4f42011-07-10 05:34:54 +00003411 // Make sure that the address is pointing to the right type. This is critical
3412 // for both unions and structs. A union needs a bitcast, a struct element
3413 // will need a bitcast if the LLVM type laid out doesn't match the desired
3414 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003415 addr = Builder.CreateElementBitCast(addr,
3416 CGM.getTypes().ConvertTypeForMem(type),
3417 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003418
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003419 if (field->hasAttr<AnnotateAttr>())
3420 addr = EmitFieldAnnotations(field, addr);
3421
John McCall7f416cc2015-09-08 08:05:57 +00003422 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003423 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003424 if (TBAAPath) {
3425 const ASTRecordLayout &Layout =
3426 getContext().getASTRecordLayout(field->getParent());
3427 // Set the base type to be the base type of the base LValue and
3428 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003429 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3430 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003431 Layout.getFieldOffset(field->getFieldIndex()) /
3432 getContext().getCharWidth());
3433 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003434
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003435 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003436 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3437 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003438
3439 // Fields of may_alias structs act like 'char' for TBAA purposes.
3440 // FIXME: this should get propagated down through anonymous structs
3441 // and unions.
3442 if (mayAlias && LV.getTBAAInfo())
3443 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3444
Daniel Dunbarf166a522010-08-21 03:44:13 +00003445 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003446}
3447
Craig Topper99e79272013-07-26 05:59:26 +00003448LValue
3449CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003450 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003451 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003452
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003453 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003454 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003455
John McCall7f416cc2015-09-08 08:05:57 +00003456 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003457
John McCall7f416cc2015-09-08 08:05:57 +00003458 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003459 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003460 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003461
John McCall7f416cc2015-09-08 08:05:57 +00003462 // TODO: access-path TBAA?
3463 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3464 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003465}
3466
Chris Lattnerf53c0962010-09-06 00:11:41 +00003467LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003468 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003469 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3470 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003471 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003472 if (E->getType()->isVariablyModifiedType())
3473 // make sure to emit the VLA size.
3474 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003475
John McCall7f416cc2015-09-08 08:05:57 +00003476 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003477 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003478 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003479
Chad Rosier615ed1a2012-03-29 17:37:10 +00003480 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3481 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003482
3483 return Result;
3484}
3485
Richard Smithbb653bd2012-05-14 21:57:21 +00003486LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3487 if (!E->isGLValue())
3488 // Initializing an aggregate temporary in C++11: T{...}.
3489 return EmitAggExprToLValue(E);
3490
3491 // An lvalue initializer list must be initializing a reference.
3492 assert(E->getNumInits() == 1 && "reference init with multiple values");
3493 return EmitLValue(E->getInit(0));
3494}
3495
Richard Smithf3076ff2014-06-20 18:43:47 +00003496/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3497/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3498/// LValue is returned and the current block has been terminated.
3499static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3500 const Expr *Operand) {
3501 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3502 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3503 return None;
3504 }
3505
3506 return CGF.EmitLValue(Operand);
3507}
3508
John McCallc07a0c72011-02-17 10:25:35 +00003509LValue CodeGenFunction::
3510EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3511 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003512 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003513 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003514 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003515 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003516 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003517
Eli Friedman59954892012-01-25 05:04:17 +00003518 OpaqueValueMapping binding(*this, expr);
3519
John McCallc07a0c72011-02-17 10:25:35 +00003520 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003521 bool CondExprBool;
3522 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003523 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003524 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003525
Justin Bogneref512b92014-01-06 22:27:43 +00003526 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003527 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003528 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003529 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003530 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003531 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003532 }
3533
John McCallc07a0c72011-02-17 10:25:35 +00003534 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3535 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3536 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003537
3538 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003539 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003540
John McCall0a6bf2e2011-01-26 19:21:13 +00003541 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003542 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003543 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003544 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003545 Optional<LValue> lhs =
3546 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003547 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003548
Richard Smithf3076ff2014-06-20 18:43:47 +00003549 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003550 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003551
John McCallc07a0c72011-02-17 10:25:35 +00003552 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003553 if (lhs)
3554 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003555
John McCall0a6bf2e2011-01-26 19:21:13 +00003556 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003557 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003558 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003559 Optional<LValue> rhs =
3560 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003561 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003562 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003563 return EmitUnsupportedLValue(expr, "conditional operator");
3564 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003565
John McCallc07a0c72011-02-17 10:25:35 +00003566 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003567
Richard Smithf3076ff2014-06-20 18:43:47 +00003568 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003569 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003570 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003571 phi->addIncoming(lhs->getPointer(), lhsBlock);
3572 phi->addIncoming(rhs->getPointer(), rhsBlock);
3573 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3574 AlignmentSource alignSource =
3575 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3576 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003577 } else {
3578 assert((lhs || rhs) &&
3579 "both operands of glvalue conditional are throw-expressions?");
3580 return lhs ? *lhs : *rhs;
3581 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003582}
3583
Richard Smithbb653bd2012-05-14 21:57:21 +00003584/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3585/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003586/// otherwise if a cast is needed by the code generator in an lvalue context,
3587/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003588/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003589/// are permitted with aggregate result, including noop aggregate casts, and
3590/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003591LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003592 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003593 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003594 case CK_BitCast:
3595 case CK_ArrayToPointerDecay:
3596 case CK_FunctionToPointerDecay:
3597 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003598 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003599 case CK_IntegralToPointer:
3600 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003601 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003602 case CK_VectorSplat:
3603 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003604 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003605 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003606 case CK_IntegralToFloating:
3607 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003608 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003609 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003610 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003611 case CK_FloatingComplexToReal:
3612 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003613 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003614 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003615 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003616 case CK_IntegralComplexToReal:
3617 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003618 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003619 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003620 case CK_DerivedToBaseMemberPointer:
3621 case CK_BaseToDerivedMemberPointer:
3622 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003623 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003624 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003625 case CK_ARCProduceObject:
3626 case CK_ARCConsumeObject:
3627 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003628 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003629 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003630 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003631 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003632 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3633
3634 case CK_Dependent:
3635 llvm_unreachable("dependent cast kind in IR gen!");
3636
3637 case CK_BuiltinFnToFnPtr:
3638 llvm_unreachable("builtin functions are handled elsewhere");
3639
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003640 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003641 case CK_NonAtomicToAtomic:
3642 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003643 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003644
Anders Carlsson8a01a752011-04-11 02:03:26 +00003645 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003646 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003647 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003648 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003649 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003650 }
3651
John McCalle3027922010-08-25 11:45:40 +00003652 case CK_ConstructorConversion:
3653 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003654 case CK_CPointerToObjCPointerCast:
3655 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003656 case CK_NoOp:
3657 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003658 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003659
John McCalle3027922010-08-25 11:45:40 +00003660 case CK_UncheckedDerivedToBase:
3661 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003662 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003663 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003664 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003665
Anders Carlssond95f9602009-09-12 16:16:49 +00003666 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003667 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003668
Anders Carlssond95f9602009-09-12 16:16:49 +00003669 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003670 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003671 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3672 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003673
John McCall7f416cc2015-09-08 08:05:57 +00003674 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003675 }
John McCalle3027922010-08-25 11:45:40 +00003676 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003677 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003678 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003679 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003680 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003681
Anders Carlsson8c793172009-11-23 17:57:54 +00003682 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003683
Anders Carlsson8c793172009-11-23 17:57:54 +00003684 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003685 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003686 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003687 E->path_begin(), E->path_end(),
3688 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003689
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003690 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3691 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003692 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003693 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003694 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003695
Peter Collingbourned2926c92015-03-14 02:42:25 +00003696 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003697 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3698 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003699 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003700
John McCall7f416cc2015-09-08 08:05:57 +00003701 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003702 }
John McCalle3027922010-08-25 11:45:40 +00003703 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003704 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003705 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003706
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003707 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003708 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003709 Address V = Builder.CreateBitCast(LV.getAddress(),
3710 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003711
3712 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003713 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3714 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003715 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003716
John McCall7f416cc2015-09-08 08:05:57 +00003717 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003718 }
John McCalle3027922010-08-25 11:45:40 +00003719 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003720 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003721 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3722 ConvertType(E->getType()));
3723 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003724 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003725 case CK_ZeroToOCLEvent:
3726 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003727 }
Craig Topper99e79272013-07-26 05:59:26 +00003728
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003729 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003730}
3731
John McCall1bf58462011-02-16 08:02:54 +00003732LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003733 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003734 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003735}
3736
Eli Friedman7f1ff602012-04-16 03:54:45 +00003737RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003738 const FieldDecl *FD,
3739 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003740 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003741 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003742 switch (getEvaluationKind(FT)) {
3743 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003744 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003745 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003746 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003747 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00003748 // This routine is used to load fields one-by-one to perform a copy, so
3749 // don't load reference fields.
3750 if (FD->getType()->isReferenceType())
3751 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00003752 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003753 }
3754 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003755}
Douglas Gregorfe314812011-06-21 17:03:29 +00003756
Chris Lattnere47e4402007-06-01 18:02:12 +00003757//===--------------------------------------------------------------------===//
3758// Expression Emission
3759//===--------------------------------------------------------------------===//
3760
Craig Topper99e79272013-07-26 05:59:26 +00003761RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003762 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003763 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003764 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003765 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003766
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003767 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003768 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003769
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003770 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003771 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3772
Douglas Gregore0e96302011-09-06 21:41:04 +00003773 const Decl *TargetDecl = E->getCalleeDecl();
3774 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3775 if (unsigned builtinID = FD->getBuiltinID())
Peter Collingbournef7706832014-12-12 23:41:25 +00003776 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003777 }
3778
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003779 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00003780 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003781 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003782
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003783 if (const auto *PseudoDtor =
3784 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00003785 QualType DestroyedType = PseudoDtor->getDestroyedType();
John McCall460ce582015-10-22 18:38:17 +00003786 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003787 // Automatic Reference Counting:
3788 // If the pseudo-expression names a retainable object with weak or
3789 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00003790 Expr *BaseExpr = PseudoDtor->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003791 Address BaseValue = Address::invalid();
John McCall31168b02011-06-15 23:02:42 +00003792 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00003793
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003794 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
John McCall31168b02011-06-15 23:02:42 +00003795 if (PseudoDtor->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003796 BaseValue = EmitPointerWithAlignment(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003797 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3798 BaseQuals = PTy->getPointeeType().getQualifiers();
3799 } else {
3800 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003801 BaseValue = BaseLV.getAddress();
3802 QualType BaseTy = BaseExpr->getType();
3803 BaseQuals = BaseTy.getQualifiers();
3804 }
Craig Topper99e79272013-07-26 05:59:26 +00003805
John McCall460ce582015-10-22 18:38:17 +00003806 switch (DestroyedType.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00003807 case Qualifiers::OCL_None:
3808 case Qualifiers::OCL_ExplicitNone:
3809 case Qualifiers::OCL_Autoreleasing:
3810 break;
Craig Topper99e79272013-07-26 05:59:26 +00003811
John McCall31168b02011-06-15 23:02:42 +00003812 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00003813 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003814 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00003815 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00003816 break;
3817
3818 case Qualifiers::OCL_Weak:
3819 EmitARCDestroyWeak(BaseValue);
3820 break;
3821 }
3822 } else {
3823 // C++ [expr.pseudo]p1:
3824 // The result shall only be used as the operand for the function call
3825 // operator (), and the result of such a call has type void. The only
3826 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00003827 // arrow.
John McCall31168b02011-06-15 23:02:42 +00003828 EmitScalarExpr(E->getCallee());
3829 }
Craig Topper99e79272013-07-26 05:59:26 +00003830
Craig Topper8a13c412014-05-21 05:09:00 +00003831 return RValue::get(nullptr);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003832 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003833
Chris Lattner2da04b32007-08-24 05:35:26 +00003834 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003835 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3836 TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00003837}
3838
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003839LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003840 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003841 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003842 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003843 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003844 return EmitLValue(E->getRHS());
3845 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003846
John McCalle3027922010-08-25 11:45:40 +00003847 if (E->getOpcode() == BO_PtrMemD ||
3848 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003849 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003850
John McCalla2342eb2010-12-05 02:00:02 +00003851 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003852
3853 // Note that in all of these cases, __block variables need the RHS
3854 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003855
3856 switch (getEvaluationKind(E->getType())) {
3857 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003858 switch (E->getLHS()->getType().getObjCLifetime()) {
3859 case Qualifiers::OCL_Strong:
3860 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3861
3862 case Qualifiers::OCL_Autoreleasing:
3863 return EmitARCStoreAutoreleasing(E).first;
3864
3865 // No reason to do any of these differently.
3866 case Qualifiers::OCL_None:
3867 case Qualifiers::OCL_ExplicitNone:
3868 case Qualifiers::OCL_Weak:
3869 break;
3870 }
3871
John McCalld0a30012010-12-06 06:10:02 +00003872 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003873 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003874 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003875 return LV;
3876 }
John McCall4f29b492010-11-16 23:07:28 +00003877
John McCall47fb9502013-03-07 21:37:08 +00003878 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003879 return EmitComplexAssignmentLValue(E);
3880
John McCall47fb9502013-03-07 21:37:08 +00003881 case TEK_Aggregate:
3882 return EmitAggExprToLValue(E);
3883 }
3884 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003885}
3886
Christopher Lambd91c3d42007-12-29 05:02:41 +00003887LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003888 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003889
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003890 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003891 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3892 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003893
David Majnemerced8bdf2015-02-25 17:36:15 +00003894 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003895 "Can't have a scalar return unless the return type is a "
3896 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003897
John McCall7f416cc2015-09-08 08:05:57 +00003898 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003899}
3900
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003901LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3902 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003903 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003904}
3905
Anders Carlsson3be22e22009-05-30 23:23:33 +00003906LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003907 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3908 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003909 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003910 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003911 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3912 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003913}
3914
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003915LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003916CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003917 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003918}
3919
John McCall7f416cc2015-09-08 08:05:57 +00003920Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3921 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3922 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003923}
3924
3925LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003926 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3927 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00003928}
3929
Mike Stumpc9b231c2009-11-15 08:09:41 +00003930LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003931CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003932 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003933 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003934 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003935 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3936 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3937 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003938}
3939
Eli Friedman5bc17122012-02-08 05:34:55 +00003940LValue
3941CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003942 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003943 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003944 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3945 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00003946}
3947
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003948LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003949 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003950
Anders Carlsson280e61f12010-06-21 20:59:55 +00003951 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003952 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3953 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003954
Alp Toker314cc812014-01-25 16:55:45 +00003955 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003956 "Can't have a scalar return unless the return type is a "
3957 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003958
John McCall7f416cc2015-09-08 08:05:57 +00003959 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003960}
3961
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003962LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003963 Address V =
3964 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3965 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003966}
3967
Daniel Dunbar722f4242009-04-22 05:08:15 +00003968llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003969 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003970 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003971}
3972
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003973LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3974 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003975 const ObjCIvarDecl *Ivar,
3976 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003977 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003978 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003979}
3980
3981LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003982 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00003983 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003984 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003985 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003986 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003987 if (E->isArrow()) {
3988 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003989 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003990 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003991 } else {
3992 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00003993 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003994 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003995 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003996 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003997
Craig Topper99e79272013-07-26 05:59:26 +00003998 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003999 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4000 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004001 setObjCGCLValueClass(getContext(), E, LV);
4002 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004003}
4004
Chris Lattnera4185c52009-04-25 19:35:26 +00004005LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004006 // Can only get l-value for message expression returning aggregate type
4007 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004008 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4009 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00004010}
4011
Anders Carlsson0435ed52009-12-24 19:08:58 +00004012RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004013 const CallExpr *E, ReturnValueSlot ReturnValue,
Samuel Antao798f11c2015-11-23 22:04:44 +00004014 CGCalleeInfo CalleeInfo, llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004015 // Get the actual function type. The callee type will always be a pointer to
4016 // function type or a block pointer type.
4017 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004018 "Call must have function pointer type!");
4019
Samuel Antao798f11c2015-11-23 22:04:44 +00004020 // Preserve the non-canonical function type because things like exception
4021 // specifications disappear in the canonical type. That information is useful
4022 // to drive the generation of more accurate code for this call later on.
4023 const FunctionProtoType *NonCanonicalFTP = CalleeType->getAs<PointerType>()
4024 ->getPointeeType()
4025 ->getAs<FunctionProtoType>();
4026
4027 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
4028
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004029 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004030 // We can only guarantee that a function is called from the correct
4031 // context/function based on the appropriate target attributes,
4032 // so only check in the case where we have both always_inline and target
4033 // since otherwise we could be making a conditional call after a check for
4034 // the proper cpu features (and it won't cause code generation issues due to
4035 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004036 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4037 TargetDecl->hasAttr<TargetAttr>())
4038 checkTargetFeatures(E, FD);
4039
John McCall6fd4c232009-10-23 08:22:42 +00004040 CalleeType = getContext().getCanonicalType(CalleeType);
4041
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004042 const auto *FnType =
4043 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004044
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004045 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004046 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4047 if (llvm::Constant *PrefixSig =
4048 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004049 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004050 llvm::Constant *FTRTTIConst =
4051 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4052 llvm::Type *PrefixStructTyElems[] = {
4053 PrefixSig->getType(),
4054 FTRTTIConst->getType()
4055 };
4056 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4057 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4058
4059 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4060 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
4061 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004062 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004063 llvm::Value *CalleeSig =
4064 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004065 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4066
4067 llvm::BasicBlock *Cont = createBasicBlock("cont");
4068 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4069 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4070
4071 EmitBlock(TypeCheck);
4072 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004073 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004074 llvm::Value *CalleeRTTI =
4075 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004076 llvm::Value *CalleeRTTIMatch =
4077 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4078 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004079 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004080 EmitCheckTypeDescriptor(CalleeType)
4081 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004082 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4083 "function_type_mismatch", StaticData, Callee);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004084
4085 Builder.CreateBr(Cont);
4086 EmitBlock(Cont);
4087 }
4088 }
4089
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004090 // If we are checking indirect calls and this call is indirect, check that the
4091 // function pointer is a member of the bit set for the function type.
4092 if (SanOpts.has(SanitizerKind::CFIICall) &&
4093 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4094 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004095 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004096
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004097 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004098 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004099
4100 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004101 llvm::Value *TypeTest = Builder.CreateCall(
4102 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004103
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004104 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004105 llvm::Constant *StaticData[] = {
4106 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4107 EmitCheckSourceLocation(E->getLocStart()),
4108 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4109 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004110 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4111 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004112 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004113 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004114 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004115 "cfi_check_fail", StaticData,
4116 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004117 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004118 }
4119
Daniel Dunbarc722b852008-08-30 03:02:31 +00004120 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004121 if (Chain)
4122 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4123 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004124
4125 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004126 // right-to-left, and that we evaluate arguments to certain other operators
4127 // left-to-right. Note that we allow this to override the order dictated by
4128 // the calling convention on the MS ABI, which means that parameter
4129 // destruction order is not necessarily reverse construction order.
4130 // FIXME: Revisit this based on C++ committee response to unimplementability.
4131 EvaluationOrder Order = EvaluationOrder::Default;
4132 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4133 if (OCE->isAssignmentOp())
4134 Order = EvaluationOrder::ForceRightToLeft;
4135 else {
4136 switch (OCE->getOperator()) {
4137 case OO_LessLess:
4138 case OO_GreaterGreater:
4139 case OO_AmpAmp:
4140 case OO_PipePipe:
4141 case OO_Comma:
4142 case OO_ArrowStar:
4143 Order = EvaluationOrder::ForceLeftToRight;
4144 break;
4145 default:
4146 break;
4147 }
4148 }
4149 }
Richard Smith762672a2016-09-28 19:09:10 +00004150
David Blaikief05779e2015-07-21 18:37:18 +00004151 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004152 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004153
Peter Collingbournef7706832014-12-12 23:41:25 +00004154 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4155 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004156
4157 // C99 6.5.2.2p6:
4158 // If the expression that denotes the called function has a type
4159 // that does not include a prototype, [the default argument
4160 // promotions are performed]. If the number of arguments does not
4161 // equal the number of parameters, the behavior is undefined. If
4162 // the function is defined with a type that includes a prototype,
4163 // and either the prototype ends with an ellipsis (, ...) or the
4164 // types of the arguments after promotion are not compatible with
4165 // the types of the parameters, the behavior is undefined. If the
4166 // function is defined with a type that does not include a
4167 // prototype, and the types of the arguments after promotion are
4168 // not compatible with those of the parameters after promotion,
4169 // the behavior is undefined [except in some trivial cases].
4170 // That is, in the general case, we should assume that a call
4171 // through an unprototyped function type works like a *non-variadic*
4172 // call. The way we make this work is to cast to the exact type
4173 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004174 //
4175 // Chain calls use this same code path to add the invisible chain parameter
4176 // to the function type.
4177 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004178 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004179 CalleeTy = CalleeTy->getPointerTo();
4180 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
4181 }
4182
Samuel Antao798f11c2015-11-23 22:04:44 +00004183 return EmitCall(FnInfo, Callee, ReturnValue, Args,
4184 CGCalleeInfo(NonCanonicalFTP, TargetDecl));
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004185}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004186
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004187LValue CodeGenFunction::
4188EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004189 Address BaseAddr = Address::invalid();
4190 if (E->getOpcode() == BO_PtrMemI) {
4191 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4192 } else {
4193 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4194 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004195
John McCallc134eb52010-08-31 21:07:20 +00004196 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4197
4198 const MemberPointerType *MPT
4199 = E->getRHS()->getType()->getAs<MemberPointerType>();
4200
John McCall7f416cc2015-09-08 08:05:57 +00004201 AlignmentSource AlignSource;
4202 Address MemberAddr =
4203 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4204 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00004205
John McCall7f416cc2015-09-08 08:05:57 +00004206 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004207}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004208
John McCall47fb9502013-03-07 21:37:08 +00004209/// Given the address of a temporary variable, produce an r-value of
4210/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004211RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004212 QualType type,
4213 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00004214 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004215 switch (getEvaluationKind(type)) {
4216 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004217 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004218 case TEK_Aggregate:
4219 return lvalue.asAggregateRValue();
4220 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004221 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004222 }
4223 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004224}
4225
Duncan Sandse81111c2012-04-10 08:23:07 +00004226void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004227 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004228 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004229 return;
4230
Duncan Sands65229ed2012-04-16 16:29:47 +00004231 llvm::MDBuilder MDHelper(getLLVMContext());
4232 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004233
Duncan Sands6fc46192012-04-14 12:37:26 +00004234 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004235}
John McCallfe96e0b2011-11-06 09:01:30 +00004236
4237namespace {
4238 struct LValueOrRValue {
4239 LValue LV;
4240 RValue RV;
4241 };
4242}
4243
4244static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4245 const PseudoObjectExpr *E,
4246 bool forLValue,
4247 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004248 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004249
4250 // Find the result expression, if any.
4251 const Expr *resultExpr = E->getResultExpr();
4252 LValueOrRValue result;
4253
4254 for (PseudoObjectExpr::const_semantics_iterator
4255 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4256 const Expr *semantic = *i;
4257
4258 // If this semantic expression is an opaque value, bind it
4259 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004260 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004261
4262 // If this is the result expression, we may need to evaluate
4263 // directly into the slot.
4264 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4265 OVMA opaqueData;
4266 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004267 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004268 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4269
John McCall7f416cc2015-09-08 08:05:57 +00004270 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4271 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004272 opaqueData = OVMA::bind(CGF, ov, LV);
4273 result.RV = slot.asRValue();
4274
4275 // Otherwise, emit as normal.
4276 } else {
4277 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4278
4279 // If this is the result, also evaluate the result now.
4280 if (ov == resultExpr) {
4281 if (forLValue)
4282 result.LV = CGF.EmitLValue(ov);
4283 else
4284 result.RV = CGF.EmitAnyExpr(ov, slot);
4285 }
4286 }
4287
4288 opaques.push_back(opaqueData);
4289
4290 // Otherwise, if the expression is the result, evaluate it
4291 // and remember the result.
4292 } else if (semantic == resultExpr) {
4293 if (forLValue)
4294 result.LV = CGF.EmitLValue(semantic);
4295 else
4296 result.RV = CGF.EmitAnyExpr(semantic, slot);
4297
4298 // Otherwise, evaluate the expression in an ignored context.
4299 } else {
4300 CGF.EmitIgnoredExpr(semantic);
4301 }
4302 }
4303
4304 // Unbind all the opaques now.
4305 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4306 opaques[i].unbind(CGF);
4307
4308 return result;
4309}
4310
4311RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4312 AggValueSlot slot) {
4313 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4314}
4315
4316LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4317 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4318}