blob: 40870f890666b0cfe210d039a8c98a923b5d397b [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
14#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGCall.h"
Devang Pateld3a6b0f2011-03-04 18:54:42 +000017#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CGRecordLayout.h"
20#include "CodeGenModule.h"
John McCallcbc038a2011-09-21 08:08:30 +000021#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth85098242010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/ADT/Hashing.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000030#include "llvm/Support/ConvertUTF.h"
31
Chris Lattnere47e4402007-06-01 18:02:12 +000032using namespace clang;
33using namespace CodeGen;
34
Chris Lattnerd7f58862007-06-02 05:24:33 +000035//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000036// Miscellaneous Helper Methods
37//===--------------------------------------------------------------------===//
38
John McCallad7c5c12011-02-08 08:22:06 +000039llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
40 unsigned addressSpace =
41 cast<llvm::PointerType>(value->getType())->getAddressSpace();
42
Chris Lattner2192fe52011-07-18 04:24:23 +000043 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000044 if (addressSpace)
45 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
46
47 if (value->getType() == destType) return value;
48 return Builder.CreateBitCast(value, destType);
49}
50
Chris Lattnere9a64532007-06-22 21:44:33 +000051/// CreateTempAlloca - This creates a alloca and inserts it into the entry
52/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000053llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000054 const Twine &Name) {
Chris Lattner47640222009-03-22 00:24:14 +000055 if (!Builder.isNamePreserving())
Daniel Dunbarb5aacc22009-10-19 01:21:05 +000056 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
Devang Pateldac79de2009-10-12 22:29:02 +000057 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000058}
Chris Lattner8394d792007-06-05 20:53:16 +000059
John McCall2e6567a2010-04-22 01:10:34 +000060void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
61 llvm::Value *Init) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +000062 auto *Store = new llvm::StoreInst(Init, Var);
John McCall2e6567a2010-04-22 01:10:34 +000063 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
64 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
65}
66
Chris Lattnerc401de92010-07-05 20:21:00 +000067llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000069 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
70 // FIXME: Should we prefer the preferred type alignment here?
71 CharUnits Align = getContext().getTypeAlignInChars(Ty);
72 Alloc->setAlignment(Align.getQuantity());
73 return Alloc;
74}
75
Chris Lattnerc401de92010-07-05 20:21:00 +000076llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000078 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
79 // FIXME: Should we prefer the preferred type alignment here?
80 CharUnits Align = getContext().getTypeAlignInChars(Ty);
81 Alloc->setAlignment(Align.getQuantity());
82 return Alloc;
83}
84
Chris Lattner8394d792007-06-05 20:53:16 +000085/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
86/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000087llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +000088 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +000089 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +000090 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +000091 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +000092 }
John McCall7a9aac22010-08-23 01:21:21 +000093
94 QualType BoolTy = getContext().BoolTy;
Chris Lattnerf3bc75a2008-04-04 16:54:41 +000095 if (!E->getType()->isAnyComplexType())
Chris Lattner268fcce2007-08-26 16:46:58 +000096 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Chris Lattner8394d792007-06-05 20:53:16 +000097
Chris Lattner268fcce2007-08-26 16:46:58 +000098 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Chris Lattnerf0106d22007-06-02 19:33:17 +000099}
100
John McCalla2342eb2010-12-05 02:00:02 +0000101/// EmitIgnoredExpr - Emit code to compute the specified expression,
102/// ignoring the result.
103void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
104 if (E->isRValue())
105 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
106
107 // Just emit it as an l-value and drop the result.
108 EmitLValue(E);
109}
110
John McCall7a626f62010-09-15 10:14:12 +0000111/// EmitAnyExpr - Emit code to compute the specified expression which
112/// can have any type. The result is returned as an RValue struct.
113/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000114/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000115RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
116 AggValueSlot aggSlot,
117 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000118 switch (getEvaluationKind(E->getType())) {
119 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000120 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000121 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000122 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000123 case TEK_Aggregate:
124 if (!ignoreResult && aggSlot.isIgnored())
125 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
126 EmitAggExpr(E, aggSlot);
127 return aggSlot.asRValue();
128 }
129 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000130}
131
Mike Stump4a3999f2009-09-09 13:00:44 +0000132/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
133/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000134RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
135 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000136
John McCall47fb9502013-03-07 21:37:08 +0000137 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000138 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
139 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000140}
141
John McCall21886962010-04-21 10:05:39 +0000142/// EmitAnyExprToMem - Evaluate an expression into a given memory
143/// location.
144void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
145 llvm::Value *Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000146 Qualifiers Quals,
147 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000148 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000149 switch (getEvaluationKind(E->getType())) {
150 case TEK_Complex:
151 EmitComplexExprIntoLValue(E,
152 MakeNaturalAlignAddrLValue(Location, E->getType()),
153 /*isInit*/ false);
154 return;
155
156 case TEK_Aggregate: {
Eli Friedman38cd36d2011-12-03 02:13:40 +0000157 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000158 EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000159 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000160 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000161 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000162 return;
163 }
164
165 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000166 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000167 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000168 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000169 return;
John McCall21886962010-04-21 10:05:39 +0000170 }
John McCall47fb9502013-03-07 21:37:08 +0000171 }
172 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000173}
174
Richard Smith736a9472013-06-12 20:42:33 +0000175static void
176pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
177 const Expr *E, llvm::Value *ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000178 // Objective-C++ ARC:
179 // If we are binding a reference to a temporary that has ownership, we
180 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000181 //
182 // FIXME: This should be looking at E, not M.
183 if (CGF.getLangOpts().ObjCAutoRefCount &&
184 M->getType()->isObjCLifetimeType()) {
185 QualType ObjCARCReferenceLifetimeType = M->getType();
186 switch (Qualifiers::ObjCLifetime Lifetime =
187 ObjCARCReferenceLifetimeType.getObjCLifetime()) {
188 case Qualifiers::OCL_None:
189 case Qualifiers::OCL_ExplicitNone:
190 // Carry on to normal cleanup handling.
191 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000192
Richard Smith736a9472013-06-12 20:42:33 +0000193 case Qualifiers::OCL_Autoreleasing:
194 // Nothing to do; cleaned up by an autorelease pool.
195 return;
196
197 case Qualifiers::OCL_Strong:
198 case Qualifiers::OCL_Weak:
199 switch (StorageDuration Duration = M->getStorageDuration()) {
200 case SD_Static:
201 // Note: we intentionally do not register a cleanup to release
202 // the object on program termination.
203 return;
204
205 case SD_Thread:
206 // FIXME: We should probably register a cleanup in this case.
207 return;
208
209 case SD_Automatic:
210 case SD_FullExpression:
211 assert(!ObjCARCReferenceLifetimeType->isArrayType());
212 CodeGenFunction::Destroyer *Destroy;
213 CleanupKind CleanupKind;
214 if (Lifetime == Qualifiers::OCL_Strong) {
215 const ValueDecl *VD = M->getExtendingDecl();
216 bool Precise =
217 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
218 CleanupKind = CGF.getARCCleanupKind();
219 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
220 : &CodeGenFunction::destroyARCStrongImprecise;
221 } else {
222 // __weak objects always get EH cleanups; otherwise, exceptions
223 // could cause really nasty crashes instead of mere leaks.
224 CleanupKind = NormalAndEHCleanup;
225 Destroy = &CodeGenFunction::destroyARCWeak;
226 }
227 if (Duration == SD_FullExpression)
228 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
229 ObjCARCReferenceLifetimeType, *Destroy,
230 CleanupKind & EHCleanup);
231 else
232 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
233 ObjCARCReferenceLifetimeType,
234 *Destroy, CleanupKind & EHCleanup);
235 return;
236
237 case SD_Dynamic:
238 llvm_unreachable("temporary cannot have dynamic storage duration");
239 }
240 llvm_unreachable("unknown storage duration");
241 }
242 }
243
Richard Smith736a9472013-06-12 20:42:33 +0000244 CXXDestructorDecl *ReferenceTemporaryDtor = 0;
245 if (const RecordType *RT =
246 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
247 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000248 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000249 if (!ClassDecl->hasTrivialDestructor())
250 ReferenceTemporaryDtor = ClassDecl->getDestructor();
251 }
252
253 if (!ReferenceTemporaryDtor)
254 return;
255
256 // Call the destructor for the temporary.
257 switch (M->getStorageDuration()) {
258 case SD_Static:
259 case SD_Thread: {
260 llvm::Constant *CleanupFn;
261 llvm::Constant *CleanupArg;
262 if (E->getType()->isArrayType()) {
263 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
264 cast<llvm::Constant>(ReferenceTemporary), E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000265 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
266 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000267 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
268 } else {
269 CleanupFn =
270 CGF.CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
271 CleanupArg = cast<llvm::Constant>(ReferenceTemporary);
272 }
273 CGF.CGM.getCXXABI().registerGlobalDtor(
274 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
275 break;
276 }
277
278 case SD_FullExpression:
279 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
280 CodeGenFunction::destroyCXXObject,
281 CGF.getLangOpts().Exceptions);
282 break;
283
284 case SD_Automatic:
285 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
286 ReferenceTemporary, E->getType(),
287 CodeGenFunction::destroyCXXObject,
288 CGF.getLangOpts().Exceptions);
289 break;
290
291 case SD_Dynamic:
292 llvm_unreachable("temporary cannot have dynamic storage duration");
293 }
294}
295
296static llvm::Value *
297createReferenceTemporary(CodeGenFunction &CGF,
298 const MaterializeTemporaryExpr *M, const Expr *Inner) {
299 switch (M->getStorageDuration()) {
300 case SD_FullExpression:
301 case SD_Automatic:
302 return CGF.CreateMemTemp(Inner->getType(), "ref.tmp");
303
304 case SD_Thread:
305 case SD_Static:
306 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
307
308 case SD_Dynamic:
309 llvm_unreachable("temporary can't have dynamic storage duration");
310 }
311 llvm_unreachable("unknown storage duration");
312}
313
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000314LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
315 const MaterializeTemporaryExpr *M) {
316 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000317
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000318 if (getLangOpts().ObjCAutoRefCount &&
Richard Smith736a9472013-06-12 20:42:33 +0000319 M->getType()->isObjCLifetimeType() &&
320 M->getType().getObjCLifetime() != Qualifiers::OCL_None &&
321 M->getType().getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
322 // FIXME: Fold this into the general case below.
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000323 llvm::Value *Object = createReferenceTemporary(*this, M, E);
324 LValue RefTempDst = MakeAddrLValue(Object, M->getType());
Douglas Gregor58df5092011-06-22 16:12:01 +0000325
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000326 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
Richard Smitha509f2f2013-06-14 03:07:01 +0000327 // We should not have emitted the initializer for this temporary as a
328 // constant.
329 assert(!Var->hasInitializer());
330 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
331 }
332
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000333 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
Richard Smith736a9472013-06-12 20:42:33 +0000334
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000335 pushTemporaryCleanup(*this, M, E, Object);
336 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000337 }
338
Richard Smithf3fabd22013-06-03 00:17:11 +0000339 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000340 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000341 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
342
343 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000344 EmitIgnoredExpr(CommaLHSs[I]);
Richard Smithf3fabd22013-06-03 00:17:11 +0000345
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000346 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000347 if (opaque->getType()->isRecordType()) {
348 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000349 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000350 }
351 }
352
Richard Smith736a9472013-06-12 20:42:33 +0000353 // Create and initialize the reference temporary.
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000354 llvm::Value *Object = createReferenceTemporary(*this, M, E);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000355 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
Richard Smitha509f2f2013-06-14 03:07:01 +0000356 // If the temporary is a global and has a constant initializer, we may
357 // have already initialized it.
358 if (!Var->hasInitializer()) {
359 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
360 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
361 }
362 } else {
363 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
364 }
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000365 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000366
Richard Smith736a9472013-06-12 20:42:33 +0000367 // Perform derived-to-base casts and/or field accesses, to get from the
368 // temporary object we created (and, potentially, for which we extended
369 // the lifetime) to the subobject we're binding the reference to.
370 for (unsigned I = Adjustments.size(); I != 0; --I) {
371 SubobjectAdjustment &Adjustment = Adjustments[I-1];
372 switch (Adjustment.Kind) {
373 case SubobjectAdjustment::DerivedToBaseAdjustment:
374 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000375 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
376 Adjustment.DerivedToBase.BasePath->path_begin(),
377 Adjustment.DerivedToBase.BasePath->path_end(),
378 /*NullCheckValue=*/ false);
Richard Smith736a9472013-06-12 20:42:33 +0000379 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000380
Richard Smith736a9472013-06-12 20:42:33 +0000381 case SubobjectAdjustment::FieldAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000382 LValue LV = MakeAddrLValue(Object, E->getType());
383 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000384 assert(LV.isSimple() &&
385 "materialized temporary field is not a simple lvalue");
386 Object = LV.getAddress();
387 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000388 }
389
Richard Smith736a9472013-06-12 20:42:33 +0000390 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000391 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
392 Object = CGM.getCXXABI().EmitMemberDataPointerAddress(
David Majnemer2b0d66d2014-02-20 23:22:07 +0000393 *this, E, Object, Ptr, Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000394 break;
395 }
396 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000397 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000398
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000399 return MakeAddrLValue(Object, M->getType());
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000400}
401
402RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000403CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
404 // Emit the expression as an lvalue.
405 LValue LV = EmitLValue(E);
406 assert(LV.isSimple());
407 llvm::Value *Value = LV.getAddress();
Richard Smith736a9472013-06-12 20:42:33 +0000408
Richard Smithb1b0ab42012-11-05 22:21:05 +0000409 if (SanitizePerformTypeCheck && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000410 // C++11 [dcl.ref]p5 (as amended by core issue 453):
411 // If a glvalue to which a reference is directly bound designates neither
412 // an existing object or function of an appropriate type nor a region of
413 // storage of suitable size and alignment to contain an object of the
414 // reference's type, the behavior is undefined.
415 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000416 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000417 }
John McCall8680f872010-07-21 06:29:51 +0000418
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000419 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000420}
421
422
Mike Stump4a3999f2009-09-09 13:00:44 +0000423/// getAccessedFieldNo - Given an encoded value and a result number, return the
424/// input field number being accessed.
425unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000426 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000427 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
428 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000429}
430
Richard Smith4d3110a2012-10-25 02:14:12 +0000431/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
432static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
433 llvm::Value *High) {
434 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
435 llvm::Value *K47 = Builder.getInt64(47);
436 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
437 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
438 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
439 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
440 return Builder.CreateMul(B1, KMul);
441}
442
Richard Smithe30752c2012-10-09 19:52:38 +0000443void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
444 llvm::Value *Address,
Richard Smith4d1458e2012-09-08 02:08:36 +0000445 QualType Ty, CharUnits Alignment) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000446 if (!SanitizePerformTypeCheck)
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000447 return;
448
Richard Smith2d8b2942012-11-01 07:22:08 +0000449 // Don't check pointers outside the default address space. The null check
450 // isn't correct, the object-size check isn't supported by LLVM, and we can't
451 // communicate the addresses to the runtime handler for the vptr check.
452 if (Address->getType()->getPointerAddressSpace())
453 return;
454
Richard Smith69d0d262012-08-24 00:54:33 +0000455 llvm::Value *Cond = 0;
Richard Smith2c5868c2013-02-13 21:18:23 +0000456 llvm::BasicBlock *Done = 0;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000457
Will Dietzf54319c2013-01-18 11:30:38 +0000458 if (SanOpts->Null) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000459 // The glvalue must not be an empty glvalue.
460 Cond = Builder.CreateICmpNE(
461 Address, llvm::Constant::getNullValue(Address->getType()));
Richard Smith2c5868c2013-02-13 21:18:23 +0000462
463 if (TCK == TCK_DowncastPointer) {
464 // When performing a pointer downcast, it's OK if the value is null.
465 // Skip the remaining checks in that case.
466 Done = createBasicBlock("null");
467 llvm::BasicBlock *Rest = createBasicBlock("not.null");
468 Builder.CreateCondBr(Cond, Rest, Done);
469 EmitBlock(Rest);
470 Cond = 0;
471 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000472 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000473
Will Dietzf54319c2013-01-18 11:30:38 +0000474 if (SanOpts->ObjectSize && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000475 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000476
Richard Smith69d0d262012-08-24 00:54:33 +0000477 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000478 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000479 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000480 // FIXME: Get object address space
481 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
482 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000483 llvm::Value *Min = Builder.getFalse();
Richard Smith2d8b2942012-11-01 07:22:08 +0000484 llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000485 llvm::Value *LargeEnough =
Richard Smith2d8b2942012-11-01 07:22:08 +0000486 Builder.CreateICmpUGE(Builder.CreateCall2(F, CastAddr, Min),
Richard Smith69d0d262012-08-24 00:54:33 +0000487 llvm::ConstantInt::get(IntPtrTy, Size));
488 Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough;
Richard Smithe30752c2012-10-09 19:52:38 +0000489 }
Richard Smith69d0d262012-08-24 00:54:33 +0000490
Richard Smithb1b0ab42012-11-05 22:21:05 +0000491 uint64_t AlignVal = 0;
492
Will Dietzf54319c2013-01-18 11:30:38 +0000493 if (SanOpts->Alignment) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000494 AlignVal = Alignment.getQuantity();
495 if (!Ty->isIncompleteType() && !AlignVal)
496 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
497
Richard Smith69d0d262012-08-24 00:54:33 +0000498 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000499 if (AlignVal) {
500 llvm::Value *Align =
501 Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
502 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
503 llvm::Value *Aligned =
504 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
505 Cond = Cond ? Builder.CreateAnd(Cond, Aligned) : Aligned;
506 }
Richard Smith69d0d262012-08-24 00:54:33 +0000507 }
508
Richard Smithe30752c2012-10-09 19:52:38 +0000509 if (Cond) {
510 llvm::Constant *StaticData[] = {
511 EmitCheckSourceLocation(Loc),
512 EmitCheckTypeDescriptor(Ty),
513 llvm::ConstantInt::get(SizeTy, AlignVal),
514 llvm::ConstantInt::get(Int8Ty, TCK)
515 };
Will Dietz88e02332012-12-02 19:50:33 +0000516 EmitCheck(Cond, "type_mismatch", StaticData, Address, CRK_Recoverable);
Richard Smithe30752c2012-10-09 19:52:38 +0000517 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000518
Richard Smithb1b0ab42012-11-05 22:21:05 +0000519 // If possible, check that the vptr indicates that there is a subobject of
520 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000521 //
522 // C++11 [basic.life]p5,6:
523 // [For storage which does not refer to an object within its lifetime]
524 // The program has undefined behavior if:
525 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000526 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000527 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Will Dietzf54319c2013-01-18 11:30:38 +0000528 if (SanOpts->Vptr &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000529 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
530 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000531 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000532 // Compute a hash of the mangled name of the type.
533 //
534 // FIXME: This is not guaranteed to be deterministic! Move to a
535 // fingerprinting mechanism once LLVM provides one. For the time
536 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000537 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000538 llvm::raw_svector_ostream Out(MangledName);
539 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
540 Out);
541 llvm::hash_code TypeHash = hash_value(Out.str());
542
543 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
544 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
545 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
546 llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
547 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
548 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
549
550 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
551 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
552
553 // Look the hash up in our cache.
554 const int CacheSize = 128;
555 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
556 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
557 "__ubsan_vptr_type_cache");
558 llvm::Value *Slot = Builder.CreateAnd(Hash,
559 llvm::ConstantInt::get(IntPtrTy,
560 CacheSize-1));
561 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
562 llvm::Value *CacheVal =
563 Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
564
565 // If the hash isn't in the cache, call a runtime handler to perform the
566 // hard work of checking whether the vptr is for an object of the right
567 // type. This will either fill in the cache and return, or produce a
568 // diagnostic.
569 llvm::Constant *StaticData[] = {
570 EmitCheckSourceLocation(Loc),
571 EmitCheckTypeDescriptor(Ty),
572 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
573 llvm::ConstantInt::get(Int8Ty, TCK)
574 };
575 llvm::Value *DynamicData[] = { Address, Hash };
576 EmitCheck(Builder.CreateICmpEQ(CacheVal, Hash),
Will Dietz88e02332012-12-02 19:50:33 +0000577 "dynamic_type_cache_miss", StaticData, DynamicData,
578 CRK_AlwaysRecoverable);
Richard Smith4d3110a2012-10-25 02:14:12 +0000579 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000580
581 if (Done) {
582 Builder.CreateBr(Done);
583 EmitBlock(Done);
584 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000585}
Chris Lattner4647a212007-08-31 22:49:20 +0000586
Richard Smith539e4a72013-02-23 02:53:19 +0000587/// Determine whether this expression refers to a flexible array member in a
588/// struct. We disable array bounds checks for such members.
589static bool isFlexibleArrayMemberExpr(const Expr *E) {
590 // For compatibility with existing code, we treat arrays of length 0 or
591 // 1 as flexible array members.
592 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000593 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000594 if (CAT->getSize().ugt(1))
595 return false;
596 } else if (!isa<IncompleteArrayType>(AT))
597 return false;
598
599 E = E->IgnoreParens();
600
601 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000602 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000603 // FIXME: If the base type of the member expr is not FD->getParent(),
604 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000605 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000606 RecordDecl::field_iterator FI(
607 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
608 return ++FI == FD->getParent()->field_end();
609 }
610 }
611
612 return false;
613}
614
615/// If Base is known to point to the start of an array, return the length of
616/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000617static llvm::Value *getArrayIndexingBound(
618 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000619 // For the vector indexing extension, the bound is the number of elements.
620 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
621 IndexedType = Base->getType();
622 return CGF.Builder.getInt32(VT->getNumElements());
623 }
624
625 Base = Base->IgnoreParens();
626
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000627 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000628 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
629 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
630 IndexedType = CE->getSubExpr()->getType();
631 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000632 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000633 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000634 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000635 return CGF.getVLASize(VAT).first;
636 }
637 }
638
639 return 0;
640}
641
642void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
643 llvm::Value *Index, QualType IndexType,
644 bool Accessed) {
Richard Smith6b53e222013-10-22 22:51:04 +0000645 assert(SanOpts->ArrayBounds &&
646 "should not be called unless adding bounds checks");
Richard Smith2847b222013-02-24 01:56:24 +0000647
Richard Smith539e4a72013-02-23 02:53:19 +0000648 QualType IndexedType;
649 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
650 if (!Bound)
651 return;
652
653 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
654 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
655 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
656
657 llvm::Constant *StaticData[] = {
658 EmitCheckSourceLocation(E->getExprLoc()),
659 EmitCheckTypeDescriptor(IndexedType),
660 EmitCheckTypeDescriptor(IndexType)
661 };
662 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
663 : Builder.CreateICmpULE(IndexVal, BoundVal);
664 EmitCheck(Check, "out_of_bounds", StaticData, Index, CRK_Recoverable);
665}
666
Chris Lattner116ce8f2010-01-09 21:40:03 +0000667
Chris Lattner116ce8f2010-01-09 21:40:03 +0000668CodeGenFunction::ComplexPairTy CodeGenFunction::
669EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
670 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000671 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000672
Chris Lattner116ce8f2010-01-09 21:40:03 +0000673 llvm::Value *NextVal;
674 if (isa<llvm::IntegerType>(InVal.first->getType())) {
675 uint64_t AmountVal = isInc ? 1 : -1;
676 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000677
Chris Lattner116ce8f2010-01-09 21:40:03 +0000678 // Add the inc/dec to the real part.
679 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
680 } else {
681 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
682 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
683 if (!isInc)
684 FVal.changeSign();
685 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000686
Chris Lattner116ce8f2010-01-09 21:40:03 +0000687 // Add the inc/dec to the real part.
688 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
689 }
Craig Topper99e79272013-07-26 05:59:26 +0000690
Chris Lattner116ce8f2010-01-09 21:40:03 +0000691 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000692
Chris Lattner116ce8f2010-01-09 21:40:03 +0000693 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000694 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000695
Chris Lattner116ce8f2010-01-09 21:40:03 +0000696 // If this is a postinc, return the value read from memory, otherwise use the
697 // updated value.
698 return isPre ? IncVal : InVal;
699}
700
701
Chris Lattnera45c5af2007-06-02 19:47:04 +0000702//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000703// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000704//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000705
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000706RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000707 if (Ty->isVoidType())
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000708 return RValue::get(0);
John McCall47fb9502013-03-07 21:37:08 +0000709
710 switch (getEvaluationKind(Ty)) {
711 case TEK_Complex: {
712 llvm::Type *EltTy =
713 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000714 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000715 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000716 }
Craig Topper99e79272013-07-26 05:59:26 +0000717
Chris Lattner65526f02010-08-23 05:26:13 +0000718 // If this is a use of an undefined aggregate type, the aggregate must have an
719 // identifiable address. Just because the contents of the value are undefined
720 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000721 case TEK_Aggregate: {
Chris Lattner65526f02010-08-23 05:26:13 +0000722 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
723 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000724 }
John McCall47fb9502013-03-07 21:37:08 +0000725
726 case TEK_Scalar:
727 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
728 }
729 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000730}
731
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000732RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
733 const char *Name) {
734 ErrorUnsupported(E, Name);
735 return GetUndefRValue(E->getType());
736}
737
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000738LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
739 const char *Name) {
740 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000741 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000742 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000743}
744
Richard Smith4d1458e2012-09-08 02:08:36 +0000745LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000746 LValue LV;
Richard Smith6b53e222013-10-22 22:51:04 +0000747 if (SanOpts->ArrayBounds && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000748 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
749 else
750 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000751 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
Richard Smithe30752c2012-10-09 19:52:38 +0000752 EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
753 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000754 return LV;
755}
756
Chris Lattner8394d792007-06-05 20:53:16 +0000757/// EmitLValue - Emit code to compute a designator that specifies the location
758/// of the expression.
759///
Mike Stump4a3999f2009-09-09 13:00:44 +0000760/// This can return one of two things: a simple address or a bitfield reference.
761/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
762/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000763///
Mike Stump4a3999f2009-09-09 13:00:44 +0000764/// If this returns a bitfield reference, nothing about the pointee type of the
765/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000766///
Mike Stump4a3999f2009-09-09 13:00:44 +0000767/// If this returns a normal address, and if the lvalue's C type is fixed size,
768/// this method guarantees that the returned pointer type will point to an LLVM
769/// type of the same size of the lvalue's type. If the lvalue has a variable
770/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000771///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000772LValue CodeGenFunction::EmitLValue(const Expr *E) {
773 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000774 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000775
John McCallc109a252011-11-07 03:59:57 +0000776 case Expr::ObjCPropertyRefExprClass:
777 llvm_unreachable("cannot emit a property reference directly");
778
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000779 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000780 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000781 case Expr::ObjCIsaExprClass:
782 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000783 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000784 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
Douglas Gregor914af212010-04-23 04:16:32 +0000785 case Expr::CompoundAssignOperatorClass:
John McCalla2342eb2010-12-05 02:00:02 +0000786 if (!E->getType()->isAnyComplexType())
787 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
788 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000789 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000790 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000791 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000792 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000793 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000794 case Expr::VAArgExprClass:
795 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000796 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000797 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000798 case Expr::ParenExprClass:
799 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000800 case Expr::GenericSelectionExprClass:
801 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000802 case Expr::PredefinedExprClass:
803 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000804 case Expr::StringLiteralClass:
805 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000806 case Expr::ObjCEncodeExprClass:
807 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000808 case Expr::PseudoObjectExprClass:
809 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000810 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000811 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000812 case Expr::CXXTemporaryObjectExprClass:
813 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000814 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
815 case Expr::CXXBindTemporaryExprClass:
816 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000817 case Expr::CXXUuidofExprClass:
818 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000819 case Expr::LambdaExprClass:
820 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000821
822 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000823 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +0000824 enterFullExpression(cleanups);
825 RunCleanupsScope Scope(*this);
826 return EmitLValue(cleanups->getSubExpr());
827 }
828
Anders Carlsson52ce3bb2009-11-14 01:51:50 +0000829 case Expr::CXXDefaultArgExprClass:
830 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +0000831 case Expr::CXXDefaultInitExprClass: {
832 CXXDefaultInitExprScope Scope(*this);
833 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
834 }
Mike Stumpc9b231c2009-11-15 08:09:41 +0000835 case Expr::CXXTypeidExprClass:
836 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000837
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000838 case Expr::ObjCMessageExprClass:
839 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000840 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +0000841 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +0000842 case Expr::StmtExprClass:
843 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000844 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +0000845 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000846 case Expr::ArraySubscriptExprClass:
847 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +0000848 case Expr::ExtVectorElementExprClass:
849 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000850 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +0000851 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +0000852 case Expr::CompoundLiteralExprClass:
853 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +0000854 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +0000855 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +0000856 case Expr::BinaryConditionalOperatorClass:
857 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +0000858 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +0000859 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +0000860 case Expr::OpaqueValueExprClass:
861 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +0000862 case Expr::SubstNonTypeTemplateParmExprClass:
863 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +0000864 case Expr::ImplicitCastExprClass:
865 case Expr::CStyleCastExprClass:
866 case Expr::CXXFunctionalCastExprClass:
867 case Expr::CXXStaticCastExprClass:
868 case Expr::CXXDynamicCastExprClass:
869 case Expr::CXXReinterpretCastExprClass:
870 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +0000871 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +0000872 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000873
Douglas Gregorfe314812011-06-21 17:03:29 +0000874 case Expr::MaterializeTemporaryExprClass:
875 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000876 }
877}
878
John McCall71335052012-03-10 03:05:10 +0000879/// Given an object of the given canonical type, can we safely copy a
880/// value out of it based on its initializer?
881static bool isConstantEmittableObjectType(QualType type) {
882 assert(type.isCanonical());
883 assert(!type->isReferenceType());
884
885 // Must be const-qualified but non-volatile.
886 Qualifiers qs = type.getLocalQualifiers();
887 if (!qs.hasConst() || qs.hasVolatile()) return false;
888
889 // Otherwise, all object types satisfy this except C++ classes with
890 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000891 if (const auto *RT = dyn_cast<RecordType>(type))
892 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +0000893 if (RD->hasMutableFields() || !RD->isTrivial())
894 return false;
895
896 return true;
897}
898
899/// Can we constant-emit a load of a reference to a variable of the
900/// given type? This is different from predicates like
901/// Decl::isUsableInConstantExpressions because we do want it to apply
902/// in situations that don't necessarily satisfy the language's rules
903/// for this (e.g. C++'s ODR-use rules). For example, we want to able
904/// to do this with const float variables even if those variables
905/// aren't marked 'constexpr'.
906enum ConstantEmissionKind {
907 CEK_None,
908 CEK_AsReferenceOnly,
909 CEK_AsValueOrReference,
910 CEK_AsValueOnly
911};
912static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
913 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000914 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +0000915 if (isConstantEmittableObjectType(ref->getPointeeType()))
916 return CEK_AsValueOrReference;
917 return CEK_AsReferenceOnly;
918 }
919 if (isConstantEmittableObjectType(type))
920 return CEK_AsValueOnly;
921 return CEK_None;
922}
923
924/// Try to emit a reference to the given value without producing it as
925/// an l-value. This is actually more than an optimization: we can't
926/// produce an l-value for variables that we never actually captured
927/// in a block or lambda, which means const int variables or constexpr
928/// literals or similar.
929CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +0000930CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
931 ValueDecl *value = refExpr->getDecl();
932
John McCall71335052012-03-10 03:05:10 +0000933 // The value needs to be an enum constant or a constant variable.
934 ConstantEmissionKind CEK;
935 if (isa<ParmVarDecl>(value)) {
936 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000937 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +0000938 CEK = checkVarTypeForConstantEmission(var->getType());
939 } else if (isa<EnumConstantDecl>(value)) {
940 CEK = CEK_AsValueOnly;
941 } else {
942 CEK = CEK_None;
943 }
944 if (CEK == CEK_None) return ConstantEmission();
945
John McCall71335052012-03-10 03:05:10 +0000946 Expr::EvalResult result;
947 bool resultIsReference;
948 QualType resultType;
949
950 // It's best to evaluate all the way as an r-value if that's permitted.
951 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +0000952 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000953 resultIsReference = false;
954 resultType = refExpr->getType();
955
956 // Otherwise, try to evaluate as an l-value.
957 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +0000958 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000959 resultIsReference = true;
960 resultType = value->getType();
961
962 // Failure.
963 } else {
964 return ConstantEmission();
965 }
966
967 // In any case, if the initializer has side-effects, abandon ship.
968 if (result.HasSideEffects)
969 return ConstantEmission();
970
971 // Emit as a constant.
972 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
973
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +0000974 // Make sure we emit a debug reference to the global variable.
975 // This should probably fire even for
976 if (isa<VarDecl>(value)) {
977 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
978 EmitDeclRefExprDbgValue(refExpr, C);
979 } else {
980 assert(isa<EnumConstantDecl>(value));
981 EmitDeclRefExprDbgValue(refExpr, C);
982 }
John McCall71335052012-03-10 03:05:10 +0000983
984 // If we emitted a reference constant, we need to dereference that.
985 if (resultIsReference)
986 return ConstantEmission::forReference(C);
987
988 return ConstantEmission::forValue(C);
989}
990
Nick Lewycky2d84e842013-10-02 02:29:49 +0000991llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
992 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +0000993 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +0000994 lvalue.getAlignment().getQuantity(),
Nick Lewycky2d84e842013-10-02 02:29:49 +0000995 lvalue.getType(), Loc, lvalue.getTBAAInfo(),
Manman Renc451e572013-04-04 21:53:22 +0000996 lvalue.getTBAABaseType(), lvalue.getTBAAOffset());
John McCall1553b192011-06-16 04:16:24 +0000997}
998
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000999static bool hasBooleanRepresentation(QualType Ty) {
1000 if (Ty->isBooleanType())
1001 return true;
1002
1003 if (const EnumType *ET = Ty->getAs<EnumType>())
1004 return ET->getDecl()->getIntegerType()->isBooleanType();
1005
Douglas Gregor298f43d2012-04-12 20:42:30 +00001006 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1007 return hasBooleanRepresentation(AT->getValueType());
1008
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001009 return false;
1010}
1011
Richard Smith1629da92012-12-13 07:11:50 +00001012static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1013 llvm::APInt &Min, llvm::APInt &End,
1014 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001015 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001016 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1017 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001018 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001019 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001020 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001021
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001022 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001023 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1024 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001025 } else {
1026 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001027 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001028 unsigned Bitwidth = LTy->getScalarSizeInBits();
1029 unsigned NumNegativeBits = ED->getNumNegativeBits();
1030 unsigned NumPositiveBits = ED->getNumPositiveBits();
1031
1032 if (NumNegativeBits) {
1033 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1034 assert(NumBits <= Bitwidth);
1035 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1036 Min = -End;
1037 } else {
1038 assert(NumPositiveBits <= Bitwidth);
1039 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1040 Min = llvm::APInt(Bitwidth, 0);
1041 }
1042 }
Richard Smith1629da92012-12-13 07:11:50 +00001043 return true;
1044}
1045
1046llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1047 llvm::APInt Min, End;
1048 if (!getRangeForType(*this, Ty, Min, End,
1049 CGM.getCodeGenOpts().StrictEnums))
1050 return 0;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001051
Duncan Sandsc720e782012-04-15 18:04:54 +00001052 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001053 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001054}
1055
Daniel Dunbar1d425462009-02-10 00:57:50 +00001056llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001057 unsigned Alignment, QualType Ty,
1058 SourceLocation Loc,
1059 llvm::MDNode *TBAAInfo,
1060 QualType TBAABaseType,
1061 uint64_t TBAAOffset) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001062 // For better performance, handle vector loads differently.
1063 if (Ty->isVectorType()) {
1064 llvm::Value *V;
1065 const llvm::Type *EltTy =
1066 cast<llvm::PointerType>(Addr->getType())->getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001067
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001068 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001069
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001070 // Handle vectors of size 3, like size 4 for better performance.
1071 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001072
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001073 // Bitcast to vec4 type.
1074 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1075 4);
1076 llvm::PointerType *ptVec4Ty =
1077 llvm::PointerType::get(vec4Ty,
1078 (cast<llvm::PointerType>(
1079 Addr->getType()))->getAddressSpace());
1080 llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
1081 "castToVec4");
1082 // Now load value.
1083 llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001084
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001085 // Shuffle vector to get vec3.
Richard Smithf0480fc2012-12-13 05:41:48 +00001086 llvm::Constant *Mask[] = {
1087 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
1088 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
1089 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
1090 };
1091
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001092 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1093 V = Builder.CreateShuffleVector(LoadVal,
1094 llvm::UndefValue::get(vec4Ty),
1095 MaskV, "extractVec");
1096 return EmitFromMemory(V, Ty);
1097 }
1098 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001099
1100 // Atomic operations have to be done on integral types.
1101 if (Ty->isAtomicType()) {
1102 LValue lvalue = LValue::MakeAddr(Addr, Ty,
1103 CharUnits::fromQuantity(Alignment),
1104 getContext(), TBAAInfo);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001105 return EmitAtomicLoad(lvalue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001106 }
Craig Topper99e79272013-07-26 05:59:26 +00001107
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001108 llvm::LoadInst *Load = Builder.CreateLoad(Addr);
Daniel Dunbarc76493a2009-11-29 21:23:36 +00001109 if (Volatile)
1110 Load->setVolatile(true);
Daniel Dunbar03816342010-08-21 02:24:36 +00001111 if (Alignment)
1112 Load->setAlignment(Alignment);
Manman Renc451e572013-04-04 21:53:22 +00001113 if (TBAAInfo) {
1114 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1115 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001116 if (TBAAPath)
1117 CGM.DecorateInstruction(Load, TBAAPath, false/*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001118 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001119
Will Dietzf54319c2013-01-18 11:30:38 +00001120 if ((SanOpts->Bool && hasBooleanRepresentation(Ty)) ||
1121 (SanOpts->Enum && Ty->getAs<EnumType>())) {
Richard Smith1629da92012-12-13 07:11:50 +00001122 llvm::APInt Min, End;
1123 if (getRangeForType(*this, Ty, Min, End, true)) {
1124 --End;
1125 llvm::Value *Check;
1126 if (!Min)
1127 Check = Builder.CreateICmpULE(
1128 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1129 else {
1130 llvm::Value *Upper = Builder.CreateICmpSLE(
1131 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1132 llvm::Value *Lower = Builder.CreateICmpSGE(
1133 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1134 Check = Builder.CreateAnd(Upper, Lower);
1135 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001136 llvm::Constant *StaticArgs[] = {
1137 EmitCheckSourceLocation(Loc),
1138 EmitCheckTypeDescriptor(Ty)
1139 };
1140 EmitCheck(Check, "load_invalid_value", StaticArgs, EmitCheckValue(Load),
1141 CRK_Recoverable);
Richard Smith1629da92012-12-13 07:11:50 +00001142 }
1143 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001144 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1145 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001146
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001147 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001148}
1149
John McCall3a7f6922010-10-27 20:58:56 +00001150llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1151 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001152 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001153 // This should really always be an i1, but sometimes it's already
1154 // an i8, and it's awkward to track those cases down.
1155 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001156 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1157 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1158 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001159 }
1160
1161 return Value;
1162}
1163
1164llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1165 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001166 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001167 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1168 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001169 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1170 }
1171
1172 return Value;
1173}
1174
Daniel Dunbar1d425462009-02-10 00:57:50 +00001175void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
Daniel Dunbar03816342010-08-21 02:24:36 +00001176 bool Volatile, unsigned Alignment,
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001177 QualType Ty, llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001178 bool isInit, QualType TBAABaseType,
1179 uint64_t TBAAOffset) {
Craig Topper99e79272013-07-26 05:59:26 +00001180
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001181 // Handle vectors differently to get better performance.
1182 if (Ty->isVectorType()) {
1183 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001184 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001185 // Handle vec3 special.
1186 if (VecTy->getNumElements() == 3) {
1187 llvm::LLVMContext &VMContext = getLLVMContext();
Craig Topper99e79272013-07-26 05:59:26 +00001188
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001189 // Our source is a vec3, do a shuffle vector to make it a vec4.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001190 SmallVector<llvm::Constant*, 4> Mask;
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001191 Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001192 0));
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001193 Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001194 1));
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001195 Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001196 2));
1197 Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
Craig Topper99e79272013-07-26 05:59:26 +00001198
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001199 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1200 Value = Builder.CreateShuffleVector(Value,
1201 llvm::UndefValue::get(VecTy),
1202 MaskV, "extractVec");
1203 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1204 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001205 auto *DstPtr = cast<llvm::PointerType>(Addr->getType());
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001206 if (DstPtr->getElementType() != SrcTy) {
1207 llvm::Type *MemTy =
1208 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
1209 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
1210 }
1211 }
Craig Topper99e79272013-07-26 05:59:26 +00001212
John McCall3a7f6922010-10-27 20:58:56 +00001213 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001214
John McCalla8ec7eb2013-03-07 21:37:17 +00001215 if (Ty->isAtomicType()) {
1216 EmitAtomicStore(RValue::get(Value),
1217 LValue::MakeAddr(Addr, Ty,
1218 CharUnits::fromQuantity(Alignment),
1219 getContext(), TBAAInfo),
1220 isInit);
1221 return;
1222 }
1223
Daniel Dunbar03816342010-08-21 02:24:36 +00001224 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1225 if (Alignment)
1226 Store->setAlignment(Alignment);
Manman Renc451e572013-04-04 21:53:22 +00001227 if (TBAAInfo) {
1228 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1229 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001230 if (TBAAPath)
1231 CGM.DecorateInstruction(Store, TBAAPath, false/*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001232 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001233}
1234
David Chisnallfa35df62012-01-16 17:27:18 +00001235void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001236 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001237 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +00001238 lvalue.getAlignment().getQuantity(), lvalue.getType(),
Manman Renc451e572013-04-04 21:53:22 +00001239 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1240 lvalue.getTBAAOffset());
John McCall1553b192011-06-16 04:16:24 +00001241}
1242
Mike Stump4a3999f2009-09-09 13:00:44 +00001243/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1244/// method emits the address of the lvalue, then loads the result as an rvalue,
1245/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001246RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001247 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001248 // load of a __weak object.
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001249 llvm::Value *AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001250 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1251 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001252 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001253 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1254 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1255 Object = EmitObjCConsumeObject(LV.getType(), Object);
1256 return RValue::get(Object);
1257 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001258
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001259 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001260 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001261
John McCalla1dee5302010-08-22 10:59:02 +00001262 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001263 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001264 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001265
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001266 if (LV.isVectorElt()) {
Eli Friedman610bb872012-03-22 22:36:39 +00001267 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1268 LV.isVolatileQualified());
1269 Load->setAlignment(LV.getAlignment().getQuantity());
1270 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001271 "vecext"));
1272 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001273
1274 // If this is a reference to a subset of the elements of a vector, either
1275 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001276 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001277 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001278
John McCallc109a252011-11-07 03:59:57 +00001279 assert(LV.isBitField() && "Unknown LValue type!");
1280 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001281}
1282
John McCall55e1fbc2011-06-25 02:11:03 +00001283RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001284 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001285
Daniel Dunbar3447a022010-04-13 23:34:15 +00001286 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001287 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001288
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001289 llvm::Value *Ptr = LV.getBitFieldAddr();
1290 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),
1291 "bf.load");
1292 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
Mike Stump4a3999f2009-09-09 13:00:44 +00001293
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001294 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001295 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001296 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1297 if (HighBits)
1298 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1299 if (Info.Offset + HighBits)
1300 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1301 } else {
1302 if (Info.Offset)
1303 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001304 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001305 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1306 Info.Size),
1307 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001308 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001309 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001310
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001311 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001312}
1313
Nate Begemanb699c9b2009-01-18 06:42:49 +00001314// If this is a reference to a subset of the elements of a vector, create an
1315// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001316RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
Eli Friedman610bb872012-03-22 22:36:39 +00001317 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1318 LV.isVolatileQualified());
1319 Load->setAlignment(LV.getAlignment().getQuantity());
1320 llvm::Value *Vec = Load;
Mike Stump4a3999f2009-09-09 13:00:44 +00001321
Nate Begemanf322eab2008-05-09 06:41:27 +00001322 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001323
1324 // If the result of the expression is a non-vector type, we must be extracting
1325 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001326 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001327 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001328 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattner5e016ae2010-06-27 07:15:29 +00001329 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001330 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001331 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001332
1333 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001334 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001335
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001336 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001337 for (unsigned i = 0; i != NumResultElts; ++i)
1338 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001339
Chris Lattner91c08ad2011-02-15 00:14:06 +00001340 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1341 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001342 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001343 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001344}
1345
1346
Chris Lattner9369a562007-06-29 16:31:29 +00001347
Chris Lattner8394d792007-06-05 20:53:16 +00001348/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1349/// lvalue, where both are guaranteed to the have the same type, and that type
1350/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001351void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1352 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001353 if (!Dst.isSimple()) {
1354 if (Dst.isVectorElt()) {
1355 // Read/modify/write the vector, inserting the new element.
Eli Friedman610bb872012-03-22 22:36:39 +00001356 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1357 Dst.isVolatileQualified());
1358 Load->setAlignment(Dst.getAlignment().getQuantity());
1359 llvm::Value *Vec = Load;
Chris Lattner4647a212007-08-31 22:49:20 +00001360 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001361 Dst.getVectorIdx(), "vecins");
Eli Friedman610bb872012-03-22 22:36:39 +00001362 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1363 Dst.isVolatileQualified());
1364 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001365 return;
1366 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001367
Nate Begemance4d7fc2008-04-18 23:10:10 +00001368 // If this is an update of extended vector elements, insert them as
1369 // appropriate.
1370 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001371 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001372
John McCallc109a252011-11-07 03:59:57 +00001373 assert(Dst.isBitField() && "Unknown LValue type");
1374 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001375 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001376
John McCall31168b02011-06-15 23:02:42 +00001377 // There's special magic for assigning into an ARC-qualified l-value.
1378 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1379 switch (Lifetime) {
1380 case Qualifiers::OCL_None:
1381 llvm_unreachable("present but none");
1382
1383 case Qualifiers::OCL_ExplicitNone:
1384 // nothing special
1385 break;
1386
1387 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001388 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001389 return;
1390
1391 case Qualifiers::OCL_Weak:
1392 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1393 return;
1394
1395 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001396 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1397 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001398 // fall into the normal path
1399 break;
1400 }
1401 }
1402
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001403 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001404 // load of a __weak object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001405 llvm::Value *LvalueDst = Dst.getAddress();
1406 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001407 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001408 return;
1409 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001410
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001411 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001412 // load of a __strong object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001413 llvm::Value *LvalueDst = Dst.getAddress();
1414 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001415 if (Dst.isObjCIvar()) {
1416 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00001417 llvm::Type *ResultType = ConvertType(getContext().LongTy);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001418 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001419 llvm::Value *dst = RHS;
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001420 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001421 llvm::Value *LHS =
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001422 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1423 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001424 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001425 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001426 } else if (Dst.isGlobalObjCRef()) {
1427 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1428 Dst.isThreadLocalRef());
1429 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001430 else
1431 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001432 return;
1433 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001434
Chris Lattner6278e6a2007-08-11 00:04:45 +00001435 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001436 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001437}
1438
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001439void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001440 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001441 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001442 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001443 llvm::Value *Ptr = Dst.getBitFieldAddr();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001444
Daniel Dunbar67aba792010-04-15 03:47:33 +00001445 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001446 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001447
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001448 // Cast the source to the storage type and shift it into place.
1449 SrcVal = Builder.CreateIntCast(SrcVal,
1450 Ptr->getType()->getPointerElementType(),
1451 /*IsSigned=*/false);
1452 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001453
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001454 // See if there are other bits in the bitfield's storage we'll need to load
1455 // and mask together with source before storing.
1456 if (Info.StorageSize != Info.Size) {
1457 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1458 llvm::Value *Val = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
1459 "bf.load");
1460 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1461
1462 // Mask the source value as needed.
1463 if (!hasBooleanRepresentation(Dst.getType()))
1464 SrcVal = Builder.CreateAnd(SrcVal,
1465 llvm::APInt::getLowBitsSet(Info.StorageSize,
1466 Info.Size),
1467 "bf.value");
1468 MaskedVal = SrcVal;
1469 if (Info.Offset)
1470 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1471
1472 // Mask out the original value.
1473 Val = Builder.CreateAnd(Val,
1474 ~llvm::APInt::getBitsSet(Info.StorageSize,
1475 Info.Offset,
1476 Info.Offset + Info.Size),
1477 "bf.clear");
1478
1479 // Or together the unchanged values and the source value.
1480 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1481 } else {
1482 assert(Info.Offset == 0);
1483 }
1484
1485 // Write the new value back out.
1486 llvm::StoreInst *Store = Builder.CreateStore(SrcVal, Ptr,
1487 Dst.isVolatileQualified());
1488 Store->setAlignment(Info.StorageAlignment);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001489
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001490 // Return the new value of the bit-field, if requested.
1491 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001492 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001493
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001494 // Sign extend the value if needed.
1495 if (Info.IsSigned) {
1496 assert(Info.Size <= Info.StorageSize);
1497 unsigned HighBits = Info.StorageSize - Info.Size;
1498 if (HighBits) {
1499 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1500 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1501 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001502 }
1503
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001504 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1505 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001506 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001507 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001508}
1509
Nate Begemance4d7fc2008-04-18 23:10:10 +00001510void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001511 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001512 // This access turns into a read/modify/write of the vector. Load the input
1513 // value now.
Eli Friedman610bb872012-03-22 22:36:39 +00001514 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1515 Dst.isVolatileQualified());
1516 Load->setAlignment(Dst.getAlignment().getQuantity());
1517 llvm::Value *Vec = Load;
Nate Begemanf322eab2008-05-09 06:41:27 +00001518 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001519
Chris Lattner4647a212007-08-31 22:49:20 +00001520 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001521
John McCall55e1fbc2011-06-25 02:11:03 +00001522 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001523 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001524 unsigned NumDstElts =
1525 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1526 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001527 // Use shuffle vector is the src and destination are the same number of
1528 // elements and restore the vector mask since it is on the side it will be
1529 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001530 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001531 for (unsigned i = 0; i != NumSrcElts; ++i)
1532 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001533
Chris Lattner91c08ad2011-02-15 00:14:06 +00001534 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001535 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001536 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001537 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001538 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001539 // Extended the source vector to the same length and then shuffle it
1540 // into the destination.
1541 // FIXME: since we're shuffling with undef, can we just use the indices
1542 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001543 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001544 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001545 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001546 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001547 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001548 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001549 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001550 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001551 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001552 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001553 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001554 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001555 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001556
Joey Goulycf4143b2013-11-21 17:09:05 +00001557 // When the vector size is odd and .odd or .hi is used, the last element
1558 // of the Elts constant array will be one past the size of the vector.
1559 // Ignore the last element here, if it is greater than the mask size.
1560 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1561 NumSrcElts--;
1562
Nate Begemanb699c9b2009-01-18 06:42:49 +00001563 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001564 for (unsigned i = 0; i != NumSrcElts; ++i)
1565 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001566 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001567 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001568 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001569 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001570 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001571 }
1572 } else {
1573 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001574 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001575 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001576 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001577 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001578
Eli Friedman610bb872012-03-22 22:36:39 +00001579 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1580 Dst.isVolatileQualified());
1581 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001582}
1583
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001584// setObjCGCLValueClass - sets class of he lvalue for the purpose of
1585// generating write-barries API. It is currently a global, ivar,
1586// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001587static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001588 LValue &LV,
1589 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001590 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001591 return;
Craig Topper99e79272013-07-26 05:59:26 +00001592
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001593 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001594 QualType ExpTy = E->getType();
1595 if (IsMemberAccess && ExpTy->isPointerType()) {
1596 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001597 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001598 // writer-barrier conservatively.
1599 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1600 if (ExpTy->isRecordType()) {
1601 LV.setObjCIvar(false);
1602 return;
1603 }
1604 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001605 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001606 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001607 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001608 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001609 return;
1610 }
Craig Topper99e79272013-07-26 05:59:26 +00001611
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001612 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1613 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001614 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001615 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001616 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001617 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001618 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001619 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001620 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001621 }
Craig Topper99e79272013-07-26 05:59:26 +00001622
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001623 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001624 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001625 return;
1626 }
Craig Topper99e79272013-07-26 05:59:26 +00001627
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001628 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001629 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001630 if (LV.isObjCIvar()) {
1631 // If cast is to a structure pointer, follow gcc's behavior and make it
1632 // a non-ivar write-barrier.
1633 QualType ExpTy = E->getType();
1634 if (ExpTy->isPointerType())
1635 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1636 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001637 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001638 }
1639 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001640 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001641
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001642 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001643 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1644 return;
1645 }
1646
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001647 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001648 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001649 return;
1650 }
Craig Topper99e79272013-07-26 05:59:26 +00001651
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001652 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001653 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001654 return;
1655 }
John McCall31168b02011-06-15 23:02:42 +00001656
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001657 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001658 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001659 return;
1660 }
1661
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001662 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001663 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001664 if (LV.isObjCIvar() && !LV.isObjCArray())
1665 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001666 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001667 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001668 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001669 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001670 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001671 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001672 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001673 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001674
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001675 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001676 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001677 // We don't know if member is an 'ivar', but this flag is looked at
1678 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001679 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001680 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001681 }
1682}
1683
Chris Lattner3f32d692011-07-12 06:52:18 +00001684static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001685EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001686 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001687 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001688 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001689 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001690}
1691
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001692static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1693 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001694 QualType T = E->getType();
1695
1696 // If it's thread_local, emit a call to its wrapper function instead.
1697 if (VD->getTLSKind() == VarDecl::TLS_Dynamic)
1698 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1699
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001700 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001701 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1702 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001703 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001704 LValue LV;
1705 if (VD->getType()->isReferenceType()) {
1706 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001707 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001708 V = LI;
1709 LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1710 } else {
Richard Smith0f383742014-03-26 22:48:22 +00001711 LV = CGF.MakeAddrLValue(V, T, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001712 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001713 setObjCGCLValueClass(CGF.getContext(), E, LV);
1714 return LV;
1715}
1716
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001717static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001718 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001719 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001720 if (!FD->hasPrototype()) {
1721 if (const FunctionProtoType *Proto =
1722 FD->getType()->getAs<FunctionProtoType>()) {
1723 // Ugly case: for a K&R-style definition, the type of the definition
1724 // isn't the same as the type of a use. Correct for this with a
1725 // bitcast.
1726 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00001727 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001728 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001729 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001730 }
1731 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001732 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Daniel Dunbar5c816372010-08-21 04:20:22 +00001733 return CGF.MakeAddrLValue(V, E->getType(), Alignment);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001734}
1735
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00001736static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
1737 llvm::Value *ThisValue) {
1738 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
1739 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
1740 return CGF.EmitLValueForField(LV, FD);
1741}
1742
Chris Lattnerd7f58862007-06-02 05:24:33 +00001743LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001744 const NamedDecl *ND = E->getDecl();
Eli Friedmana0544d62011-12-03 04:14:32 +00001745 CharUnits Alignment = getContext().getDeclAlign(ND);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001746 QualType T = E->getType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001747
Richard Smith5a1104b2012-10-20 01:38:33 +00001748 // A DeclRefExpr for a reference initialized by a constant expression can
1749 // appear without being odr-used. Directly emit the constant initializer.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001750 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Richard Smith5a1104b2012-10-20 01:38:33 +00001751 const Expr *Init = VD->getAnyInitializer(VD);
1752 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
1753 VD->isUsableInConstantExpressions(getContext()) &&
1754 VD->checkInitIsICE()) {
1755 llvm::Constant *Val =
1756 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
1757 assert(Val && "failed to emit reference constant expression");
1758 // FIXME: Eventually we will want to emit vector element references.
1759 return MakeAddrLValue(Val, T, Alignment);
1760 }
1761 }
1762
Eli Friedman5720e342012-01-21 04:52:58 +00001763 // FIXME: We should be able to assert this for FunctionDecls as well!
1764 // FIXME: We should be able to assert this for all DeclRefExprs, not just
1765 // those with a valid source location.
1766 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1767 !E->getLocation().isValid()) &&
1768 "Should not use decl without marking it used!");
1769
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001770 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001771 const auto *VD = cast<ValueDecl>(ND);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001772 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
Richard Smith5a1104b2012-10-20 01:38:33 +00001773 return MakeAddrLValue(Aliasee, T, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001774 }
1775
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001776 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001777 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00001778 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001779 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00001780
John McCall113bee02012-03-10 09:33:50 +00001781 bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1782
Nick Lewycky230203c2013-01-10 01:46:29 +00001783 llvm::Value *V = LocalDeclMap.lookup(VD);
Craig Topper99e79272013-07-26 05:59:26 +00001784 if (!V && VD->isStaticLocal())
Fariborz Jahanian4d55b2d2010-04-19 18:15:02 +00001785 V = CGM.getStaticLocalDeclAddress(VD);
Eli Friedman9fbeba02012-02-11 02:57:39 +00001786
1787 // Use special handling for lambdas.
John McCall113bee02012-03-10 09:33:50 +00001788 if (!V) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00001789 if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00001790 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
1791 } else if (CapturedStmtInfo) {
1792 if (const FieldDecl *FD = CapturedStmtInfo->lookup(VD))
1793 return EmitCapturedFieldLValue(*this, FD,
1794 CapturedStmtInfo->getContextValue());
Eli Friedman7f1ff602012-04-16 03:54:45 +00001795 }
Eli Friedman9fbeba02012-02-11 02:57:39 +00001796
John McCall113bee02012-03-10 09:33:50 +00001797 assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
John McCall113bee02012-03-10 09:33:50 +00001798 return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
Richard Smith5a1104b2012-10-20 01:38:33 +00001799 T, Alignment);
John McCall113bee02012-03-10 09:33:50 +00001800 }
1801
Anders Carlsson6eee9722009-11-07 22:46:42 +00001802 assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1803
John McCall113bee02012-03-10 09:33:50 +00001804 if (isBlockVariable)
Fariborz Jahanian2f2fa722011-01-26 23:08:27 +00001805 V = BuildBlockByrefAddress(V, VD);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001806
Eli Friedmand20adbd2011-11-16 00:42:57 +00001807 LValue LV;
1808 if (VD->getType()->isReferenceType()) {
1809 llvm::LoadInst *LI = Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001810 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001811 V = LI;
1812 LV = MakeNaturalAlignAddrLValue(V, T);
1813 } else {
1814 LV = MakeAddrLValue(V, T, Alignment);
1815 }
Chris Lattner3f32d692011-07-12 06:52:18 +00001816
John McCallcdda29c2013-03-13 03:10:54 +00001817 bool isLocalStorage = VD->hasLocalStorage();
1818
1819 bool NonGCable = isLocalStorage &&
1820 !VD->getType()->isReferenceType() &&
1821 !isBlockVariable;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001822 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00001823 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00001824 LV.setNonGC(true);
1825 }
John McCallcdda29c2013-03-13 03:10:54 +00001826
1827 bool isImpreciseLifetime =
1828 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
1829 if (isImpreciseLifetime)
1830 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001831 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00001832 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001833 }
John McCallf3a88602011-02-03 08:15:49 +00001834
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001835 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00001836 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00001837
David Blaikie83d382b2011-09-23 05:06:16 +00001838 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001839}
Chris Lattnere47e4402007-06-01 18:02:12 +00001840
Chris Lattner8394d792007-06-05 20:53:16 +00001841LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1842 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00001843 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00001844 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001845
Chris Lattner0f398c42008-07-26 22:37:01 +00001846 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00001847 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001848 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00001849 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001850 QualType T = E->getSubExpr()->getType()->getPointeeType();
1851 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00001852
Chris Lattner2415357a2011-12-19 21:16:08 +00001853 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001854 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00001855
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001856 // We should not generate __weak write barrier on indirect reference
1857 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1858 // But, we continue to generate __strong write barrier on indirect write
1859 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00001860 if (getLangOpts().ObjC1 &&
1861 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001862 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00001863 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001864 return LV;
1865 }
John McCalle3027922010-08-25 11:45:40 +00001866 case UO_Real:
1867 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00001868 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00001869 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1870 llvm::Value *Addr = LV.getAddress();
1871
Richard Smith0b6b8e42012-02-18 20:53:32 +00001872 // __real is valid on scalars. This is a faster way of testing that.
1873 // __imag can only produce an rvalue on scalars.
1874 if (E->getOpcode() == UO_Real &&
1875 !cast<llvm::PointerType>(Addr->getType())
John McCalla2342eb2010-12-05 02:00:02 +00001876 ->getElementType()->isStructTy()) {
1877 assert(E->getSubExpr()->getType()->isArithmeticType());
1878 return LV;
1879 }
1880
1881 assert(E->getSubExpr()->getType()->isAnyComplexType());
1882
John McCalle3027922010-08-25 11:45:40 +00001883 unsigned Idx = E->getOpcode() == UO_Imag;
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001884 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
John McCalla2342eb2010-12-05 02:00:02 +00001885 Idx, "idx"),
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001886 ExprTy);
Chris Lattner595db862007-10-30 22:53:42 +00001887 }
John McCalle3027922010-08-25 11:45:40 +00001888 case UO_PreInc:
1889 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001890 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00001891 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00001892
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001893 if (E->getType()->isAnyComplexType())
1894 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1895 else
1896 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1897 return LV;
1898 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00001899 }
Chris Lattner8394d792007-06-05 20:53:16 +00001900}
1901
Chris Lattner4347e3692007-06-06 04:54:52 +00001902LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001903 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1904 E->getType());
Chris Lattner4347e3692007-06-06 04:54:52 +00001905}
1906
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001907LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001908 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1909 E->getType());
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001910}
1911
Nico Weber3a691a32012-06-23 02:07:59 +00001912static llvm::Constant*
1913GetAddrOfConstantWideString(StringRef Str,
1914 const char *GlobalName,
1915 ASTContext &Context,
1916 QualType Ty, SourceLocation Loc,
1917 CodeGenModule &CGM) {
1918
1919 StringLiteral *SL = StringLiteral::Create(Context,
1920 Str,
1921 StringLiteral::Wide,
1922 /*Pascal = */false,
1923 Ty, Loc);
1924 llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001925 auto *GV = new llvm::GlobalVariable(
1926 CGM.getModule(), C->getType(), !CGM.getLangOpts().WritableStrings,
1927 llvm::GlobalValue::PrivateLinkage, C, GlobalName);
Nico Weber3a691a32012-06-23 02:07:59 +00001928 const unsigned WideAlignment =
1929 Context.getTypeAlignInChars(Ty).getQuantity();
1930 GV->setAlignment(WideAlignment);
1931 return GV;
1932}
1933
Nico Weber3a691a32012-06-23 02:07:59 +00001934static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
1935 SmallString<32>& Target) {
1936 Target.resize(CharByteWidth * (Source.size() + 1));
Richard Smith639b8d02012-09-08 07:16:20 +00001937 char *ResultPtr = &Target[0];
1938 const UTF8 *ErrorPtr;
1939 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
Matt Beaumont-Gay36af16af2012-07-03 03:55:58 +00001940 (void)success;
Nico Weber4b18c3f2012-07-03 02:24:52 +00001941 assert(success);
Nico Weber3a691a32012-06-23 02:07:59 +00001942 Target.resize(ResultPtr - &Target[0]);
1943}
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001944
Mike Stump4a3999f2009-09-09 13:00:44 +00001945LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Daniel Dunbarb3517472008-10-17 21:58:32 +00001946 switch (E->getIdentType()) {
1947 default:
1948 return EmitUnsupportedLValue(E, "predefined expression");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001949
Daniel Dunbarb3517472008-10-17 21:58:32 +00001950 case PredefinedExpr::Func:
1951 case PredefinedExpr::Function:
Nico Weber3a691a32012-06-23 02:07:59 +00001952 case PredefinedExpr::LFunction:
David Majnemerbed356a2013-11-06 23:31:56 +00001953 case PredefinedExpr::FuncDName:
Reid Kleckner52eddda2014-04-08 18:13:24 +00001954 case PredefinedExpr::FuncSig:
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001955 case PredefinedExpr::PrettyFunction: {
Benjamin Kramer90f54222013-08-21 11:45:27 +00001956 PredefinedExpr::IdentType IdentType = E->getIdentType();
Reid Kleckner52eddda2014-04-08 18:13:24 +00001957 std::string GVName;
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001958
Reid Kleckner52eddda2014-04-08 18:13:24 +00001959 // FIXME: We should use the string literal mangling for the Microsoft C++
1960 // ABI so that strings get merged.
Nico Weber3a691a32012-06-23 02:07:59 +00001961 switch (IdentType) {
David Blaikie83d382b2011-09-23 05:06:16 +00001962 default: llvm_unreachable("Invalid type");
Reid Kleckner52eddda2014-04-08 18:13:24 +00001963 case PredefinedExpr::Func: GVName = "__func__."; break;
1964 case PredefinedExpr::Function: GVName = "__FUNCTION__."; break;
1965 case PredefinedExpr::FuncDName: GVName = "__FUNCDNAME__."; break;
1966 case PredefinedExpr::FuncSig: GVName = "__FUNCSIG__."; break;
1967 case PredefinedExpr::LFunction: GVName = "L__FUNCTION__."; break;
1968 case PredefinedExpr::PrettyFunction: GVName = "__PRETTY_FUNCTION__."; break;
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001969 }
1970
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001971 StringRef FnName = CurFn->getName();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001972 if (FnName.startswith("\01"))
1973 FnName = FnName.substr(1);
Reid Kleckner52eddda2014-04-08 18:13:24 +00001974 GVName += FnName;
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001975
Benjamin Kramer90f54222013-08-21 11:45:27 +00001976 // If this is outside of a function use the top level decl.
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001977 const Decl *CurDecl = CurCodeDecl;
Benjamin Kramer90f54222013-08-21 11:45:27 +00001978 if (CurDecl == 0 || isa<VarDecl>(CurDecl))
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001979 CurDecl = getContext().getTranslationUnitDecl();
1980
Benjamin Kramer90f54222013-08-21 11:45:27 +00001981 const Type *ElemType = E->getType()->getArrayElementTypeNoTypeQual();
1982 std::string FunctionName;
1983 if (isa<BlockDecl>(CurDecl)) {
1984 // Blocks use the mangled function name.
1985 // FIXME: ComputeName should handle blocks.
1986 FunctionName = FnName.str();
Wei Pan8d6b19a2013-08-26 14:27:34 +00001987 } else if (isa<CapturedDecl>(CurDecl)) {
1988 // For a captured statement, the function name is its enclosing
1989 // function name not the one compiler generated.
1990 FunctionName = PredefinedExpr::ComputeName(IdentType, CurDecl);
Benjamin Kramer90f54222013-08-21 11:45:27 +00001991 } else {
1992 FunctionName = PredefinedExpr::ComputeName(IdentType, CurDecl);
1993 assert(cast<ConstantArrayType>(E->getType())->getSize() - 1 ==
1994 FunctionName.size() &&
1995 "Computed __func__ length differs from type!");
1996 }
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001997
Nico Weber3a691a32012-06-23 02:07:59 +00001998 llvm::Constant *C;
1999 if (ElemType->isWideCharType()) {
2000 SmallString<32> RawChars;
2001 ConvertUTF8ToWideString(
2002 getContext().getTypeSizeInChars(ElemType).getQuantity(),
2003 FunctionName, RawChars);
2004 C = GetAddrOfConstantWideString(RawChars,
Reid Kleckner52eddda2014-04-08 18:13:24 +00002005 GVName.c_str(),
Nico Weber3a691a32012-06-23 02:07:59 +00002006 getContext(),
2007 E->getType(),
2008 E->getLocation(),
2009 CGM);
2010 } else {
Reid Kleckner52eddda2014-04-08 18:13:24 +00002011 C = CGM.GetAddrOfConstantCString(FunctionName, GVName.c_str(), 1);
Nico Weber3a691a32012-06-23 02:07:59 +00002012 }
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002013 return MakeAddrLValue(C, E->getType());
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00002014 }
Daniel Dunbarb3517472008-10-17 21:58:32 +00002015 }
Anders Carlsson625bfc82007-07-21 05:21:51 +00002016}
2017
Richard Smithe30752c2012-10-09 19:52:38 +00002018/// Emit a type description suitable for use by a runtime sanitizer library. The
2019/// format of a type descriptor is
2020///
2021/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002022/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002023/// \endcode
2024///
Richard Smith683398a2012-10-09 23:55:19 +00002025/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2026/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002027llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002028 // Only emit each type's descriptor once.
2029 if (llvm::Constant *C = CGM.getTypeDescriptor(T))
2030 return C;
2031
Richard Smithe30752c2012-10-09 19:52:38 +00002032 uint16_t TypeKind = -1;
2033 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002034
Richard Smithe30752c2012-10-09 19:52:38 +00002035 if (T->isIntegerType()) {
2036 TypeKind = 0;
2037 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002038 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002039 } else if (T->isFloatingType()) {
2040 TypeKind = 1;
2041 TypeInfo = getContext().getTypeSize(T);
2042 }
2043
2044 // Format the type name as if for a diagnostic, including quotes and
2045 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002046 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002047 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2048 (intptr_t)T.getAsOpaquePtr(),
2049 0, 0, 0, 0, 0, 0, Buffer,
2050 ArrayRef<intptr_t>());
2051
2052 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002053 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2054 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002055 };
2056 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2057
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002058 auto *GV = new llvm::GlobalVariable(
2059 CGM.getModule(), Descriptor->getType(),
2060 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Richard Smithe30752c2012-10-09 19:52:38 +00002061 GV->setUnnamedAddr(true);
Will Dietz949ec542013-11-08 01:09:22 +00002062
2063 // Remember the descriptor for this type.
2064 CGM.setTypeDescriptor(T, GV);
2065
Richard Smithe30752c2012-10-09 19:52:38 +00002066 return GV;
2067}
2068
2069llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2070 llvm::Type *TargetTy = IntPtrTy;
2071
Richard Smith48366f72013-03-22 00:47:07 +00002072 // Floating-point types which fit into intptr_t are bitcast to integers
2073 // and then passed directly (after zero-extension, if necessary).
2074 if (V->getType()->isFloatingPointTy()) {
2075 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2076 if (Bits <= TargetTy->getIntegerBitWidth())
2077 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2078 Bits));
2079 }
2080
Richard Smithe30752c2012-10-09 19:52:38 +00002081 // Integers which fit in intptr_t are zero-extended and passed directly.
2082 if (V->getType()->isIntegerTy() &&
2083 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2084 return Builder.CreateZExt(V, TargetTy);
2085
2086 // Pointers are passed directly, everything else is passed by address.
2087 if (!V->getType()->isPointerTy()) {
Richard Smith48366f72013-03-22 00:47:07 +00002088 llvm::Value *Ptr = CreateTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002089 Builder.CreateStore(V, Ptr);
2090 V = Ptr;
2091 }
2092 return Builder.CreatePtrToInt(V, TargetTy);
2093}
2094
2095/// \brief Emit a representation of a SourceLocation for passing to a handler
2096/// in a sanitizer runtime library. The format for this data is:
2097/// \code
2098/// struct SourceLocation {
2099/// const char *Filename;
2100/// int32_t Line, Column;
2101/// };
2102/// \endcode
2103/// For an invalid SourceLocation, the Filename pointer is null.
2104llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2105 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2106
2107 llvm::Constant *Data[] = {
Will Dietz949ec542013-11-08 01:09:22 +00002108 PLoc.isValid() ? CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src")
Richard Smithe30752c2012-10-09 19:52:38 +00002109 : llvm::Constant::getNullValue(Int8PtrTy),
Evgeniy Stepanova98799f2013-09-11 12:33:58 +00002110 Builder.getInt32(PLoc.isValid() ? PLoc.getLine() : 0),
2111 Builder.getInt32(PLoc.isValid() ? PLoc.getColumn() : 0)
Richard Smithe30752c2012-10-09 19:52:38 +00002112 };
2113
2114 return llvm::ConstantStruct::getAnon(Data);
2115}
2116
2117void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002118 ArrayRef<llvm::Constant *> StaticArgs,
2119 ArrayRef<llvm::Value *> DynamicArgs,
Will Dietz88e02332012-12-02 19:50:33 +00002120 CheckRecoverableKind RecoverKind) {
Will Dietzf54319c2013-01-18 11:30:38 +00002121 assert(SanOpts != &SanitizerOptions::Disabled);
Chad Rosierae229d52013-01-29 23:31:22 +00002122
2123 if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) {
2124 assert (RecoverKind != CRK_AlwaysRecoverable &&
2125 "Runtime call required for AlwaysRecoverable kind!");
2126 return EmitTrapCheck(Checked);
2127 }
2128
Richard Smith4d1458e2012-09-08 02:08:36 +00002129 llvm::BasicBlock *Cont = createBasicBlock("cont");
2130
Richard Smithe30752c2012-10-09 19:52:38 +00002131 llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
Will Dietzddd282a2012-12-15 01:39:14 +00002132
2133 llvm::Instruction *Branch = Builder.CreateCondBr(Checked, Cont, Handler);
2134
2135 // Give hint that we very much don't expect to execute the handler
2136 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2137 llvm::MDBuilder MDHelper(getLLVMContext());
2138 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2139 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2140
Richard Smithe30752c2012-10-09 19:52:38 +00002141 EmitBlock(Handler);
2142
2143 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002144 auto *InfoPtr =
Will Dietz450f1a12013-01-09 03:39:41 +00002145 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
Richard Smithe30752c2012-10-09 19:52:38 +00002146 llvm::GlobalVariable::PrivateLinkage, Info);
2147 InfoPtr->setUnnamedAddr(true);
2148
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002149 SmallVector<llvm::Value *, 4> Args;
2150 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002151 Args.reserve(DynamicArgs.size() + 1);
2152 ArgTypes.reserve(DynamicArgs.size() + 1);
2153
2154 // Handler functions take an i8* pointing to the (handler-specific) static
2155 // information block, followed by a sequence of intptr_t arguments
2156 // representing operand values.
2157 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2158 ArgTypes.push_back(Int8PtrTy);
2159 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2160 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2161 ArgTypes.push_back(IntPtrTy);
2162 }
2163
Will Dietz88e02332012-12-02 19:50:33 +00002164 bool Recover = (RecoverKind == CRK_AlwaysRecoverable) ||
2165 ((RecoverKind == CRK_Recoverable) &&
2166 CGM.getCodeGenOpts().SanitizeRecover);
2167
Richard Smithe30752c2012-10-09 19:52:38 +00002168 llvm::FunctionType *FnType =
2169 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Bill Wendlinga514ebc2012-10-15 20:36:26 +00002170 llvm::AttrBuilder B;
Will Dietz88e02332012-12-02 19:50:33 +00002171 if (!Recover) {
Bill Wendling207f0532012-12-20 19:27:06 +00002172 B.addAttribute(llvm::Attribute::NoReturn)
2173 .addAttribute(llvm::Attribute::NoUnwind);
Richard Smith4d3110a2012-10-25 02:14:12 +00002174 }
Bill Wendling207f0532012-12-20 19:27:06 +00002175 B.addAttribute(llvm::Attribute::UWTable);
Will Dietz88e02332012-12-02 19:50:33 +00002176
2177 // Checks that have two variants use a suffix to differentiate them
2178 bool NeedsAbortSuffix = (RecoverKind != CRK_Unrecoverable) &&
2179 !CGM.getCodeGenOpts().SanitizeRecover;
Richard Smith78f6b032012-12-03 22:39:14 +00002180 std::string FunctionName = ("__ubsan_handle_" + CheckName +
2181 (NeedsAbortSuffix? "_abort" : "")).str();
2182 llvm::Value *Fn =
2183 CGM.CreateRuntimeFunction(FnType, FunctionName,
Bill Wendling8594fcb2013-01-31 00:30:05 +00002184 llvm::AttributeSet::get(getLLVMContext(),
2185 llvm::AttributeSet::FunctionIndex,
2186 B));
John McCall882987f2013-02-28 19:01:20 +00002187 llvm::CallInst *HandlerCall = EmitNounwindRuntimeCall(Fn, Args);
Will Dietz88e02332012-12-02 19:50:33 +00002188 if (Recover) {
Richard Smith4d3110a2012-10-25 02:14:12 +00002189 Builder.CreateBr(Cont);
2190 } else {
2191 HandlerCall->setDoesNotReturn();
Richard Smith4d3110a2012-10-25 02:14:12 +00002192 Builder.CreateUnreachable();
2193 }
Richard Smithe30752c2012-10-09 19:52:38 +00002194
Richard Smith4d1458e2012-09-08 02:08:36 +00002195 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002196}
2197
Chad Rosierae229d52013-01-29 23:31:22 +00002198void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002199 llvm::BasicBlock *Cont = createBasicBlock("cont");
2200
2201 // If we're optimizing, collapse all calls to trap down to just one per
2202 // function to save on code size.
2203 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2204 TrapBB = createBasicBlock("trap");
2205 Builder.CreateCondBr(Checked, Cont, TrapBB);
2206 EmitBlock(TrapBB);
2207 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
2208 llvm::CallInst *TrapCall = Builder.CreateCall(F);
2209 TrapCall->setDoesNotReturn();
2210 TrapCall->setDoesNotThrow();
2211 Builder.CreateUnreachable();
2212 } else {
2213 Builder.CreateCondBr(Checked, Cont, TrapBB);
2214 }
2215
2216 EmitBlock(Cont);
2217}
2218
Chris Lattner6c5abe82010-06-26 23:03:20 +00002219/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2220/// array to pointer, return the array subexpression.
2221static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2222 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002223 const auto *CE = dyn_cast<CastExpr>(E);
John McCalle3027922010-08-25 11:45:40 +00002224 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
Chris Lattner6c5abe82010-06-26 23:03:20 +00002225 return 0;
Craig Topper99e79272013-07-26 05:59:26 +00002226
Chris Lattner6c5abe82010-06-26 23:03:20 +00002227 // If this is a decay from variable width array, bail out.
2228 const Expr *SubExpr = CE->getSubExpr();
2229 if (SubExpr->getType()->isVariableArrayType())
2230 return 0;
Craig Topper99e79272013-07-26 05:59:26 +00002231
Chris Lattner6c5abe82010-06-26 23:03:20 +00002232 return SubExpr;
2233}
2234
Richard Smith539e4a72013-02-23 02:53:19 +00002235LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2236 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002237 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002238 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002239 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002240 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002241
Richard Smith6b53e222013-10-22 22:51:04 +00002242 if (SanOpts->ArrayBounds)
Richard Smith539e4a72013-02-23 02:53:19 +00002243 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2244
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002245 // If the base is a vector type, then we are forming a vector element lvalue
2246 // with this subscript.
Eli Friedman327944b2008-06-13 23:01:12 +00002247 if (E->getBase()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002248 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002249 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002250 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
John McCallad7c5c12011-02-08 08:22:06 +00002251 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
Eli Friedman327944b2008-06-13 23:01:12 +00002252 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
Eli Friedman610bb872012-03-22 22:36:39 +00002253 E->getBase()->getType(), LHS.getAlignment());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002254 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002255
Ted Kremenekc81614d2007-08-20 16:18:38 +00002256 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002257 if (Idx->getType() != IntPtrTy)
2258 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002259
Mike Stump4a3999f2009-09-09 13:00:44 +00002260 // We know that the pointer points to a type of the correct size, unless the
2261 // size is a VLA or Objective-C interface.
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002262 llvm::Value *Address = 0;
Eli Friedmana0544d62011-12-03 04:14:32 +00002263 CharUnits ArrayAlignment;
John McCall23c29fe2011-06-24 21:55:10 +00002264 if (const VariableArrayType *vla =
Anders Carlsson3d312f82008-12-21 00:11:23 +00002265 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002266 // The base must be a pointer, which is not an aggregate. Emit
2267 // it. It needs to be emitted first in case it's what captures
2268 // the VLA bounds.
2269 Address = EmitScalarExpr(E->getBase());
Mike Stump4a3999f2009-09-09 13:00:44 +00002270
John McCall23c29fe2011-06-24 21:55:10 +00002271 // The element count here is the total number of non-VLA elements.
2272 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002273
John McCall77527a82011-06-25 01:32:37 +00002274 // Effectively, the multiply by the VLA size is part of the GEP.
2275 // GEP indexes are signed, and scaling an index isn't permitted to
2276 // signed-overflow, so we use the same semantics for our explicit
2277 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002278 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002279 Idx = Builder.CreateMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00002280 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00002281 } else {
2282 Idx = Builder.CreateNSWMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00002283 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00002284 }
Chris Lattner6c5abe82010-06-26 23:03:20 +00002285 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2286 // Indexing over an interface, as in "NSString *P; P[4];"
Mike Stump4a3999f2009-09-09 13:00:44 +00002287 llvm::Value *InterfaceSize =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002288 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck40775002010-01-11 17:06:35 +00002289 getContext().getTypeSizeInChars(OIT).getQuantity());
Mike Stump4a3999f2009-09-09 13:00:44 +00002290
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002291 Idx = Builder.CreateMul(Idx, InterfaceSize);
2292
Chris Lattner6c5abe82010-06-26 23:03:20 +00002293 // The base must be a pointer, which is not an aggregate. Emit it.
2294 llvm::Value *Base = EmitScalarExpr(E->getBase());
John McCallad7c5c12011-02-08 08:22:06 +00002295 Address = EmitCastToVoidPtr(Base);
2296 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002297 Address = Builder.CreateBitCast(Address, Base->getType());
Chris Lattner6c5abe82010-06-26 23:03:20 +00002298 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2299 // If this is A[i] where A is an array, the frontend will have decayed the
2300 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2301 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2302 // "gep x, i" here. Emit one "gep A, 0, i".
2303 assert(Array->getType()->isArrayType() &&
2304 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002305 LValue ArrayLV;
2306 // For simple multidimensional array indexing, set the 'accessed' flag for
2307 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002308 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002309 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2310 else
2311 ArrayLV = EmitLValue(Array);
Daniel Dunbar82634272011-04-01 00:49:43 +00002312 llvm::Value *ArrayPtr = ArrayLV.getAddress();
Chris Lattner6c5abe82010-06-26 23:03:20 +00002313 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2314 llvm::Value *Args[] = { Zero, Idx };
Craig Topper99e79272013-07-26 05:59:26 +00002315
Daniel Dunbar82634272011-04-01 00:49:43 +00002316 // Propagate the alignment from the array itself to the result.
2317 ArrayAlignment = ArrayLV.getAlignment();
2318
Richard Smith9c6890a2012-11-01 22:30:59 +00002319 if (getLangOpts().isSignedOverflowDefined())
Jay Foad040dd822011-07-22 08:16:57 +00002320 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Chris Lattner2e72da942011-03-01 00:03:48 +00002321 else
Jay Foad040dd822011-07-22 08:16:57 +00002322 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002323 } else {
Chris Lattner6c5abe82010-06-26 23:03:20 +00002324 // The base must be a pointer, which is not an aggregate. Emit it.
2325 llvm::Value *Base = EmitScalarExpr(E->getBase());
Richard Smith9c6890a2012-11-01 22:30:59 +00002326 if (getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002327 Address = Builder.CreateGEP(Base, Idx, "arrayidx");
2328 else
2329 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
Anders Carlsson3d312f82008-12-21 00:11:23 +00002330 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002331
Steve Naroff7cae42b2009-07-10 23:34:53 +00002332 QualType T = E->getBase()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00002333 assert(!T.isNull() &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00002334 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002335
Craig Topper99e79272013-07-26 05:59:26 +00002336
Daniel Dunbar82634272011-04-01 00:49:43 +00002337 // Limit the alignment to that of the result type.
Chris Lattner36bc4f42012-01-04 22:35:55 +00002338 LValue LV;
Eli Friedmana0544d62011-12-03 04:14:32 +00002339 if (!ArrayAlignment.isZero()) {
2340 CharUnits Align = getContext().getTypeAlignInChars(T);
Daniel Dunbar82634272011-04-01 00:49:43 +00002341 ArrayAlignment = std::min(Align, ArrayAlignment);
Chris Lattner36bc4f42012-01-04 22:35:55 +00002342 LV = MakeAddrLValue(Address, T, ArrayAlignment);
2343 } else {
2344 LV = MakeNaturalAlignAddrLValue(Address, T);
Daniel Dunbar82634272011-04-01 00:49:43 +00002345 }
2346
Daniel Dunbarf166a522010-08-21 03:44:13 +00002347 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002348
Richard Smith9c6890a2012-11-01 22:30:59 +00002349 if (getLangOpts().ObjC1 &&
2350 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002351 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002352 setObjCGCLValueClass(getContext(), E, LV);
2353 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002354 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002355}
2356
Mike Stump4a3999f2009-09-09 13:00:44 +00002357static
NAKAMURA Takumiccca11a2012-01-25 08:58:21 +00002358llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
Craig Topper5603df42013-07-05 19:34:19 +00002359 SmallVectorImpl<unsigned> &Elts) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002360 SmallVector<llvm::Constant*, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002361 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002362 CElts.push_back(Builder.getInt32(Elts[i]));
Nate Begemand3862152008-05-13 21:03:02 +00002363
Chris Lattner91c08ad2011-02-15 00:14:06 +00002364 return llvm::ConstantVector::get(CElts);
Nate Begemand3862152008-05-13 21:03:02 +00002365}
2366
Chris Lattner9e751ca2007-08-02 23:37:31 +00002367LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002368EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002369 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002370 LValue Base;
2371
2372 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002373 if (E->isArrow()) {
2374 // If it is a pointer to a vector, emit the address and form an lvalue with
2375 // it.
Chris Lattnerb8211f62009-02-16 22:14:05 +00002376 llvm::Value *Ptr = EmitScalarExpr(E->getBase());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002377 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Daniel Dunbarf166a522010-08-21 03:44:13 +00002378 Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2379 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002380 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002381 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2382 // emit the base as an lvalue.
2383 assert(E->getBase()->getType()->isVectorType());
2384 Base = EmitLValue(E->getBase());
2385 } else {
2386 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002387 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002388 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002389 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00002390
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002391 // Store the vector to memory (because LValue wants an address).
Daniel Dunbara7566f12010-02-09 02:48:28 +00002392 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002393 Builder.CreateStore(Vec, VecMem);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002394 Base = MakeAddrLValue(VecMem, E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002395 }
John McCall1553b192011-06-16 04:16:24 +00002396
2397 QualType type =
2398 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00002399
Nate Begemand3862152008-05-13 21:03:02 +00002400 // Encode the element access list into a vector of unsigned indices.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002401 SmallVector<unsigned, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002402 E->getEncodedElementAccess(Indices);
2403
2404 if (Base.isSimple()) {
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002405 llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002406 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2407 Base.getAlignment());
Nate Begemand3862152008-05-13 21:03:02 +00002408 }
2409 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2410
2411 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002412 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002413
Chris Lattner595ba3a2012-01-30 06:20:36 +00002414 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2415 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002416 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
Eli Friedman610bb872012-03-22 22:36:39 +00002417 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2418 Base.getAlignment());
Chris Lattner9e751ca2007-08-02 23:37:31 +00002419}
2420
Devang Patel30efa2e2007-10-23 20:28:39 +00002421LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00002422 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00002423
Chris Lattner4e4186b2007-12-02 18:52:07 +00002424 // 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 +00002425 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00002426 if (E->isArrow()) {
2427 llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
2428 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Richard Smithe30752c2012-10-09 19:52:38 +00002429 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +00002430 BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
2431 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00002432 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00002433
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002434 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002435 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002436 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002437 setObjCGCLValueClass(getContext(), E, LV);
2438 return LV;
2439 }
Craig Topper99e79272013-07-26 05:59:26 +00002440
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002441 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00002442 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002443
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002444 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002445 return EmitFunctionDeclLValue(*this, E, FD);
2446
David Blaikie83d382b2011-09-23 05:06:16 +00002447 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00002448}
Devang Patel30efa2e2007-10-23 20:28:39 +00002449
John McCalldec348f72013-05-03 07:33:41 +00002450/// Given that we are currently emitting a lambda, emit an l-value for
2451/// one of its members.
2452LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
2453 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
2454 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
2455 QualType LambdaTagType =
2456 getContext().getTagDeclType(Field->getParent());
2457 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
2458 return EmitLValueForField(LambdaLV, Field);
2459}
2460
Eli Friedman7f1ff602012-04-16 03:54:45 +00002461LValue CodeGenFunction::EmitLValueForField(LValue base,
2462 const FieldDecl *field) {
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002463 if (field->isBitField()) {
2464 const CGRecordLayout &RL =
2465 CGM.getTypes().getCGRecordLayout(field->getParent());
2466 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002467 llvm::Value *Addr = base.getAddress();
2468 unsigned Idx = RL.getLLVMFieldNo(field);
2469 if (Idx != 0)
2470 // For structs, we GEP to the field that the record layout suggests.
2471 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
2472 // Get the access type.
2473 llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
2474 getLLVMContext(), Info.StorageSize,
2475 CGM.getContext().getTargetAddressSpace(base.getType()));
2476 if (Addr->getType() != PtrTy)
2477 Addr = Builder.CreateBitCast(Addr, PtrTy);
2478
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002479 QualType fieldType =
2480 field->getType().withCVRQualifiers(base.getVRQualifiers());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002481 return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002482 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002483
John McCall53fcbd22011-02-26 08:07:02 +00002484 const RecordDecl *rec = field->getParent();
2485 QualType type = field->getType();
Eli Friedmana0544d62011-12-03 04:14:32 +00002486 CharUnits alignment = getContext().getDeclAlign(field);
Eli Friedman133e8042008-05-29 11:33:25 +00002487
Eli Friedman7f1ff602012-04-16 03:54:45 +00002488 // FIXME: It should be impossible to have an LValue without alignment for a
2489 // complete type.
2490 if (!base.getAlignment().isZero())
2491 alignment = std::min(alignment, base.getAlignment());
2492
John McCall53fcbd22011-02-26 08:07:02 +00002493 bool mayAlias = rec->hasAttr<MayAliasAttr>();
2494
Eli Friedman7f1ff602012-04-16 03:54:45 +00002495 llvm::Value *addr = base.getAddress();
2496 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00002497 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00002498 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00002499 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00002500 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00002501 // TODO: handle path-aware TBAA for union.
2502 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00002503 } else {
2504 // For structs, we GEP to the field that the record layout suggests.
2505 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
Chris Lattner13ee4f42011-07-10 05:34:54 +00002506 addr = Builder.CreateStructGEP(addr, idx, field->getName());
John McCall53fcbd22011-02-26 08:07:02 +00002507
2508 // If this is a reference field, load the reference right now.
2509 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2510 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2511 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
Eli Friedmana0544d62011-12-03 04:14:32 +00002512 load->setAlignment(alignment.getQuantity());
John McCall53fcbd22011-02-26 08:07:02 +00002513
Manman Renc451e572013-04-04 21:53:22 +00002514 // Loading the reference will disable path-aware TBAA.
2515 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00002516 if (CGM.shouldUseTBAA()) {
2517 llvm::MDNode *tbaa;
2518 if (mayAlias)
2519 tbaa = CGM.getTBAAInfo(getContext().CharTy);
2520 else
2521 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00002522 if (tbaa)
2523 CGM.DecorateInstruction(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00002524 }
2525
2526 addr = load;
2527 mayAlias = false;
2528 type = refType->getPointeeType();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002529 if (type->isIncompleteType())
Eli Friedmana0544d62011-12-03 04:14:32 +00002530 alignment = CharUnits();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002531 else
Eli Friedmana0544d62011-12-03 04:14:32 +00002532 alignment = getContext().getTypeAlignInChars(type);
John McCall53fcbd22011-02-26 08:07:02 +00002533 cvr = 0; // qualifiers don't recursively apply to referencee
2534 }
Devang Pateled93c3c2007-10-26 19:42:18 +00002535 }
Craig Topper99e79272013-07-26 05:59:26 +00002536
Chris Lattner13ee4f42011-07-10 05:34:54 +00002537 // Make sure that the address is pointing to the right type. This is critical
2538 // for both unions and structs. A union needs a bitcast, a struct element
2539 // will need a bitcast if the LLVM type laid out doesn't match the desired
2540 // type.
Chandler Carruth4678f672011-07-12 08:58:26 +00002541 addr = EmitBitCastOfLValueToProperType(*this, addr,
Chris Lattner3f32d692011-07-12 06:52:18 +00002542 CGM.getTypes().ConvertTypeForMem(type),
2543 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00002544
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002545 if (field->hasAttr<AnnotateAttr>())
2546 addr = EmitFieldAnnotations(field, addr);
2547
John McCall53fcbd22011-02-26 08:07:02 +00002548 LValue LV = MakeAddrLValue(addr, type, alignment);
2549 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00002550 if (TBAAPath) {
2551 const ASTRecordLayout &Layout =
2552 getContext().getASTRecordLayout(field->getParent());
2553 // Set the base type to be the base type of the base LValue and
2554 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00002555 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
2556 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00002557 Layout.getFieldOffset(field->getFieldIndex()) /
2558 getContext().getCharWidth());
2559 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00002560
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002561 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00002562 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2563 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00002564
2565 // Fields of may_alias structs act like 'char' for TBAA purposes.
2566 // FIXME: this should get propagated down through anonymous structs
2567 // and unions.
2568 if (mayAlias && LV.getTBAAInfo())
2569 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2570
Daniel Dunbarf166a522010-08-21 03:44:13 +00002571 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00002572}
2573
Craig Topper99e79272013-07-26 05:59:26 +00002574LValue
2575CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00002576 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002577 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00002578
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002579 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002580 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002581
Daniel Dunbar034299e2010-03-31 01:09:11 +00002582 const CGRecordLayout &RL =
2583 CGM.getTypes().getCGRecordLayout(Field->getParent());
2584 unsigned idx = RL.getLLVMFieldNo(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002585 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002586 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2587
Chris Lattnerd7c59352011-07-10 05:53:24 +00002588 // Make sure that the address is pointing to the right type. This is critical
2589 // for both unions and structs. A union needs a bitcast, a struct element
2590 // will need a bitcast if the LLVM type laid out doesn't match the desired
2591 // type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002592 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002593 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2594
Eli Friedmana0544d62011-12-03 04:14:32 +00002595 CharUnits Alignment = getContext().getDeclAlign(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002596
2597 // FIXME: It should be impossible to have an LValue without alignment for a
2598 // complete type.
2599 if (!Base.getAlignment().isZero())
2600 Alignment = std::min(Alignment, Base.getAlignment());
2601
Daniel Dunbar5c816372010-08-21 04:20:22 +00002602 return MakeAddrLValue(V, FieldType, Alignment);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002603}
2604
Chris Lattnerf53c0962010-09-06 00:11:41 +00002605LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00002606 if (E->isFileScope()) {
2607 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2608 return MakeAddrLValue(GlobalPtr, E->getType());
2609 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00002610 if (E->getType()->isVariablyModifiedType())
2611 // make sure to emit the VLA size.
2612 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00002613
Daniel Dunbar27bacaf2010-02-16 19:43:39 +00002614 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00002615 const Expr *InitExpr = E->getInitializer();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002616 LValue Result = MakeAddrLValue(DeclPtr, E->getType());
Eli Friedman9fd8b682008-05-13 23:18:27 +00002617
Chad Rosier615ed1a2012-03-29 17:37:10 +00002618 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2619 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00002620
2621 return Result;
2622}
2623
Richard Smithbb653bd2012-05-14 21:57:21 +00002624LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2625 if (!E->isGLValue())
2626 // Initializing an aggregate temporary in C++11: T{...}.
2627 return EmitAggExprToLValue(E);
2628
2629 // An lvalue initializer list must be initializing a reference.
2630 assert(E->getNumInits() == 1 && "reference init with multiple values");
2631 return EmitLValue(E->getInit(0));
2632}
2633
John McCallc07a0c72011-02-17 10:25:35 +00002634LValue CodeGenFunction::
2635EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2636 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00002637 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00002638 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00002639 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00002640 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00002641 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002642
Eli Friedman59954892012-01-25 05:04:17 +00002643 OpaqueValueMapping binding(*this, expr);
Justin Bogneref512b92014-01-06 22:27:43 +00002644 RegionCounter Cnt = getPGORegionCounter(expr);
Eli Friedman59954892012-01-25 05:04:17 +00002645
John McCallc07a0c72011-02-17 10:25:35 +00002646 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002647 bool CondExprBool;
2648 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00002649 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002650 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00002651
Justin Bogneref512b92014-01-06 22:27:43 +00002652 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00002653 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00002654 if (CondExprBool)
2655 Cnt.beginRegion(Builder);
John McCallc07a0c72011-02-17 10:25:35 +00002656 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00002657 }
John McCall0a6bf2e2011-01-26 19:21:13 +00002658 }
2659
John McCallc07a0c72011-02-17 10:25:35 +00002660 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2661 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2662 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00002663
2664 ConditionalEvaluation eval(*this);
Justin Bogneref512b92014-01-06 22:27:43 +00002665 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, Cnt.getCount());
Craig Topper99e79272013-07-26 05:59:26 +00002666
John McCall0a6bf2e2011-01-26 19:21:13 +00002667 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002668 EmitBlock(lhsBlock);
Justin Bogneref512b92014-01-06 22:27:43 +00002669 Cnt.beginRegion(Builder);
John McCall0a6bf2e2011-01-26 19:21:13 +00002670 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002671 LValue lhs = EmitLValue(expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002672 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00002673
John McCallc07a0c72011-02-17 10:25:35 +00002674 if (!lhs.isSimple())
2675 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00002676
John McCallc07a0c72011-02-17 10:25:35 +00002677 lhsBlock = Builder.GetInsertBlock();
2678 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00002679
John McCall0a6bf2e2011-01-26 19:21:13 +00002680 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002681 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002682 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002683 LValue rhs = EmitLValue(expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002684 eval.end(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002685 if (!rhs.isSimple())
2686 return EmitUnsupportedLValue(expr, "conditional operator");
2687 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00002688
John McCallc07a0c72011-02-17 10:25:35 +00002689 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002690
Jay Foad20c0f022011-03-30 11:28:58 +00002691 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
John McCall0a6bf2e2011-01-26 19:21:13 +00002692 "cond-lvalue");
John McCallc07a0c72011-02-17 10:25:35 +00002693 phi->addIncoming(lhs.getAddress(), lhsBlock);
2694 phi->addIncoming(rhs.getAddress(), rhsBlock);
2695 return MakeAddrLValue(phi, expr->getType());
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002696}
2697
Richard Smithbb653bd2012-05-14 21:57:21 +00002698/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2699/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00002700/// otherwise if a cast is needed by the code generator in an lvalue context,
2701/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00002702/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00002703/// are permitted with aggregate result, including noop aggregate casts, and
2704/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002705LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00002706 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00002707 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00002708 case CK_BitCast:
2709 case CK_ArrayToPointerDecay:
2710 case CK_FunctionToPointerDecay:
2711 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00002712 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00002713 case CK_IntegralToPointer:
2714 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002715 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002716 case CK_VectorSplat:
2717 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00002718 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002719 case CK_IntegralToFloating:
2720 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002721 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002722 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00002723 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002724 case CK_FloatingComplexToReal:
2725 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002726 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002727 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00002728 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002729 case CK_IntegralComplexToReal:
2730 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002731 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002732 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00002733 case CK_DerivedToBaseMemberPointer:
2734 case CK_BaseToDerivedMemberPointer:
2735 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00002736 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00002737 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00002738 case CK_ARCProduceObject:
2739 case CK_ARCConsumeObject:
2740 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00002741 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00002742 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00002743 case CK_AddressSpaceConversion:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00002744 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
2745
2746 case CK_Dependent:
2747 llvm_unreachable("dependent cast kind in IR gen!");
2748
2749 case CK_BuiltinFnToFnPtr:
2750 llvm_unreachable("builtin functions are handled elsewhere");
2751
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002752 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00002753 case CK_NonAtomicToAtomic:
2754 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002755 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00002756
Anders Carlsson8a01a752011-04-11 02:03:26 +00002757 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00002758 LValue LV = EmitLValue(E->getSubExpr());
2759 llvm::Value *V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002760 const auto *DCE = cast<CXXDynamicCastExpr>(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002761 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00002762 }
2763
John McCalle3027922010-08-25 11:45:40 +00002764 case CK_ConstructorConversion:
2765 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00002766 case CK_CPointerToObjCPointerCast:
2767 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00002768 case CK_NoOp:
2769 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002770 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00002771
John McCalle3027922010-08-25 11:45:40 +00002772 case CK_UncheckedDerivedToBase:
2773 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00002774 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00002775 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002776 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00002777
Anders Carlssond95f9602009-09-12 16:16:49 +00002778 LValue LV = EmitLValue(E->getSubExpr());
John McCalle26a8722010-12-04 08:14:53 +00002779 llvm::Value *This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00002780
Anders Carlssond95f9602009-09-12 16:16:49 +00002781 // Perform the derived-to-base conversion
Craig Topper99e79272013-07-26 05:59:26 +00002782 llvm::Value *Base =
2783 GetAddressOfBaseClass(This, DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002784 E->path_begin(), E->path_end(),
2785 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00002786
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002787 return MakeAddrLValue(Base, E->getType());
Anders Carlssond95f9602009-09-12 16:16:49 +00002788 }
John McCalle3027922010-08-25 11:45:40 +00002789 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00002790 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00002791 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00002792 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002793 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00002794
Anders Carlsson8c793172009-11-23 17:57:54 +00002795 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00002796
Anders Carlsson8c793172009-11-23 17:57:54 +00002797 // Perform the base-to-derived conversion
Craig Topper99e79272013-07-26 05:59:26 +00002798 llvm::Value *Derived =
2799 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002800 E->path_begin(), E->path_end(),
2801 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00002802
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00002803 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
2804 // performed and the object is not of the derived type.
2805 if (SanitizePerformTypeCheck)
2806 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
2807 Derived, E->getType());
2808
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002809 return MakeAddrLValue(Derived, E->getType());
Eli Friedman8c98dff2009-11-16 05:48:01 +00002810 }
John McCalle3027922010-08-25 11:45:40 +00002811 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00002812 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002813 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00002814
Anders Carlsson50cb3212009-11-14 21:21:42 +00002815 LValue LV = EmitLValue(E->getSubExpr());
2816 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2817 ConvertType(CE->getTypeAsWritten()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002818 return MakeAddrLValue(V, E->getType());
Anders Carlsson50cb3212009-11-14 21:21:42 +00002819 }
John McCalle3027922010-08-25 11:45:40 +00002820 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002821 LValue LV = EmitLValue(E->getSubExpr());
2822 QualType ToType = getContext().getLValueReferenceType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00002823 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002824 ConvertType(ToType));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002825 return MakeAddrLValue(V, E->getType());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002826 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002827 case CK_ZeroToOCLEvent:
2828 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00002829 }
Craig Topper99e79272013-07-26 05:59:26 +00002830
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002831 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002832}
2833
John McCall1bf58462011-02-16 08:02:54 +00002834LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00002835 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00002836 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00002837}
2838
Eli Friedman7f1ff602012-04-16 03:54:45 +00002839RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002840 const FieldDecl *FD,
2841 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002842 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00002843 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00002844 switch (getEvaluationKind(FT)) {
2845 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002846 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00002847 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00002848 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00002849 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002850 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00002851 }
2852 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002853}
Douglas Gregorfe314812011-06-21 17:03:29 +00002854
Chris Lattnere47e4402007-06-01 18:02:12 +00002855//===--------------------------------------------------------------------===//
2856// Expression Emission
2857//===--------------------------------------------------------------------===//
2858
Craig Topper99e79272013-07-26 05:59:26 +00002859RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00002860 ReturnValueSlot ReturnValue) {
Adrian Prantlc7822422013-03-12 20:43:25 +00002861 if (CGDebugInfo *DI = getDebugInfo()) {
2862 SourceLocation Loc = E->getLocStart();
Adrian Prantl5acf8a32013-03-15 17:09:05 +00002863 // Force column info to be generated so we can differentiate
2864 // multiple call sites on the same line in the debug info.
2865 const FunctionDecl* Callee = E->getDirectCallee();
2866 bool ForceColumnInfo = Callee && Callee->isInlineSpecified();
2867 DI->EmitLocation(Builder, Loc, ForceColumnInfo);
Adrian Prantlc7822422013-03-12 20:43:25 +00002868 }
Devang Pateld3a6b0f2011-03-04 18:54:42 +00002869
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002870 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002871 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00002872 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002873
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002874 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002875 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002876
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002877 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00002878 return EmitCUDAKernelCallExpr(CE, ReturnValue);
2879
Douglas Gregore0e96302011-09-06 21:41:04 +00002880 const Decl *TargetDecl = E->getCalleeDecl();
2881 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2882 if (unsigned builtinID = FD->getBuiltinID())
2883 return EmitBuiltinExpr(FD, builtinID, E);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002884 }
2885
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002886 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00002887 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002888 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002889
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002890 if (const auto *PseudoDtor =
2891 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00002892 QualType DestroyedType = PseudoDtor->getDestroyedType();
Richard Smith9c6890a2012-11-01 22:30:59 +00002893 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002894 DestroyedType->isObjCLifetimeType() &&
2895 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2896 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002897 // Automatic Reference Counting:
2898 // If the pseudo-expression names a retainable object with weak or
2899 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00002900 Expr *BaseExpr = PseudoDtor->getBase();
2901 llvm::Value *BaseValue = NULL;
2902 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00002903
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002904 // 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 +00002905 if (PseudoDtor->isArrow()) {
2906 BaseValue = EmitScalarExpr(BaseExpr);
2907 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2908 BaseQuals = PTy->getPointeeType().getQualifiers();
2909 } else {
2910 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00002911 BaseValue = BaseLV.getAddress();
2912 QualType BaseTy = BaseExpr->getType();
2913 BaseQuals = BaseTy.getQualifiers();
2914 }
Craig Topper99e79272013-07-26 05:59:26 +00002915
John McCall31168b02011-06-15 23:02:42 +00002916 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2917 case Qualifiers::OCL_None:
2918 case Qualifiers::OCL_ExplicitNone:
2919 case Qualifiers::OCL_Autoreleasing:
2920 break;
Craig Topper99e79272013-07-26 05:59:26 +00002921
John McCall31168b02011-06-15 23:02:42 +00002922 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00002923 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002924 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00002925 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00002926 break;
2927
2928 case Qualifiers::OCL_Weak:
2929 EmitARCDestroyWeak(BaseValue);
2930 break;
2931 }
2932 } else {
2933 // C++ [expr.pseudo]p1:
2934 // The result shall only be used as the operand for the function call
2935 // operator (), and the result of such a call has type void. The only
2936 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00002937 // arrow.
John McCall31168b02011-06-15 23:02:42 +00002938 EmitScalarExpr(E->getCallee());
2939 }
Craig Topper99e79272013-07-26 05:59:26 +00002940
Douglas Gregorad8a3362009-09-04 17:36:40 +00002941 return RValue::get(0);
2942 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002943
Chris Lattner2da04b32007-08-24 05:35:26 +00002944 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002945 return EmitCall(E->getCallee()->getType(), Callee, E->getLocStart(),
2946 ReturnValue, E->arg_begin(), E->arg_end(), TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00002947}
2948
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002949LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00002950 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00002951 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00002952 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00002953 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00002954 return EmitLValue(E->getRHS());
2955 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002956
John McCalle3027922010-08-25 11:45:40 +00002957 if (E->getOpcode() == BO_PtrMemD ||
2958 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002959 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002960
John McCalla2342eb2010-12-05 02:00:02 +00002961 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00002962
2963 // Note that in all of these cases, __block variables need the RHS
2964 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00002965
2966 switch (getEvaluationKind(E->getType())) {
2967 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00002968 switch (E->getLHS()->getType().getObjCLifetime()) {
2969 case Qualifiers::OCL_Strong:
2970 return EmitARCStoreStrong(E, /*ignored*/ false).first;
2971
2972 case Qualifiers::OCL_Autoreleasing:
2973 return EmitARCStoreAutoreleasing(E).first;
2974
2975 // No reason to do any of these differently.
2976 case Qualifiers::OCL_None:
2977 case Qualifiers::OCL_ExplicitNone:
2978 case Qualifiers::OCL_Weak:
2979 break;
2980 }
2981
John McCalld0a30012010-12-06 06:10:02 +00002982 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00002983 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00002984 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002985 return LV;
2986 }
John McCall4f29b492010-11-16 23:07:28 +00002987
John McCall47fb9502013-03-07 21:37:08 +00002988 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00002989 return EmitComplexAssignmentLValue(E);
2990
John McCall47fb9502013-03-07 21:37:08 +00002991 case TEK_Aggregate:
2992 return EmitAggExprToLValue(E);
2993 }
2994 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002995}
2996
Christopher Lambd91c3d42007-12-29 05:02:41 +00002997LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00002998 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00002999
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003000 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003001 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003002
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003003 assert(E->getCallReturnType()->isReferenceType() &&
3004 "Can't have a scalar return unless the return type is a "
3005 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003006
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003007 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003008}
3009
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003010LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3011 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003012 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003013}
3014
Anders Carlsson3be22e22009-05-30 23:23:33 +00003015LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003016 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3017 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003018 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003019 EmitCXXConstructExpr(E, Slot);
3020 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlsson3be22e22009-05-30 23:23:33 +00003021}
3022
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003023LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003024CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003025 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003026}
3027
Nico Webercf4ff5862012-10-11 10:13:44 +00003028llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
David Majnemerbbecd092013-08-15 19:59:14 +00003029 return Builder.CreateBitCast(CGM.GetAddrOfUuidDescriptor(E),
3030 ConvertType(E->getType())->getPointerTo());
Nico Webercf4ff5862012-10-11 10:13:44 +00003031}
3032
3033LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
3034 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
3035}
3036
Mike Stumpc9b231c2009-11-15 08:09:41 +00003037LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003038CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003039 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003040 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003041 EmitAggExpr(E->getSubExpr(), Slot);
Peter Collingbourne702b2842011-11-27 22:09:22 +00003042 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
John McCall8ea46b62010-09-18 00:58:34 +00003043 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003044}
3045
Eli Friedman5bc17122012-02-08 05:34:55 +00003046LValue
3047CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003048 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003049 EmitLambdaExpr(E, Slot);
Eli Friedman5bc17122012-02-08 05:34:55 +00003050 return MakeAddrLValue(Slot.getAddr(), E->getType());
3051}
3052
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003053LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003054 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003055
Anders Carlsson280e61f12010-06-21 20:59:55 +00003056 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003057 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003058
Alp Toker314cc812014-01-25 16:55:45 +00003059 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003060 "Can't have a scalar return unless the return type is a "
3061 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003062
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003063 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003064}
3065
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003066LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
Craig Topper99e79272013-07-26 05:59:26 +00003067 llvm::Value *V =
John McCall882987f2013-02-28 19:01:20 +00003068 CGM.getObjCRuntime().GetSelector(*this, E->getSelector(), true);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003069 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003070}
3071
Daniel Dunbar722f4242009-04-22 05:08:15 +00003072llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003073 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003074 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003075}
3076
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003077LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3078 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003079 const ObjCIvarDecl *Ivar,
3080 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003081 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003082 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003083}
3084
3085LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003086 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
3087 llvm::Value *BaseValue = 0;
3088 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003089 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003090 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003091 if (E->isArrow()) {
3092 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003093 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003094 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003095 } else {
3096 LValue BaseLV = EmitLValue(BaseExpr);
3097 // FIXME: this isn't right for bitfields.
3098 BaseValue = BaseLV.getAddress();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003099 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003100 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003101 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003102
Craig Topper99e79272013-07-26 05:59:26 +00003103 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003104 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3105 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003106 setObjCGCLValueClass(getContext(), E, LV);
3107 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003108}
3109
Chris Lattnera4185c52009-04-25 19:35:26 +00003110LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003111 // Can only get l-value for message expression returning aggregate type
3112 RValue RV = EmitAnyExprToTemp(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003113 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnera4185c52009-04-25 19:35:26 +00003114}
3115
Anders Carlsson0435ed52009-12-24 19:08:58 +00003116RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003117 SourceLocation CallLoc,
Anders Carlsson17490832009-12-24 20:40:36 +00003118 ReturnValueSlot ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00003119 CallExpr::const_arg_iterator ArgBeg,
3120 CallExpr::const_arg_iterator ArgEnd,
3121 const Decl *TargetDecl) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003122 // Get the actual function type. The callee type will always be a pointer to
3123 // function type or a block pointer type.
3124 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003125 "Call must have function pointer type!");
3126
John McCall6fd4c232009-10-23 08:22:42 +00003127 CalleeType = getContext().getCanonicalType(CalleeType);
3128
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003129 const auto *FnType =
3130 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00003131
Adrian Prantlca64c3e2013-07-26 20:42:57 +00003132 // Force column info to differentiate multiple inlined call sites on
3133 // the same line, analoguous to EmitCallExpr.
3134 bool ForceColumnInfo = false;
3135 if (const FunctionDecl* FD = dyn_cast_or_null<const FunctionDecl>(TargetDecl))
3136 ForceColumnInfo = FD->isInlineSpecified();
3137
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003138 if (getLangOpts().CPlusPlus && SanOpts->Function &&
3139 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3140 if (llvm::Constant *PrefixSig =
3141 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
3142 llvm::Constant *FTRTTIConst =
3143 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
3144 llvm::Type *PrefixStructTyElems[] = {
3145 PrefixSig->getType(),
3146 FTRTTIConst->getType()
3147 };
3148 llvm::StructType *PrefixStructTy = llvm::StructType::get(
3149 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
3150
3151 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
3152 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
3153 llvm::Value *CalleeSigPtr =
3154 Builder.CreateConstGEP2_32(CalleePrefixStruct, 0, 0);
3155 llvm::Value *CalleeSig = Builder.CreateLoad(CalleeSigPtr);
3156 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
3157
3158 llvm::BasicBlock *Cont = createBasicBlock("cont");
3159 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
3160 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
3161
3162 EmitBlock(TypeCheck);
3163 llvm::Value *CalleeRTTIPtr =
3164 Builder.CreateConstGEP2_32(CalleePrefixStruct, 0, 1);
3165 llvm::Value *CalleeRTTI = Builder.CreateLoad(CalleeRTTIPtr);
3166 llvm::Value *CalleeRTTIMatch =
3167 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
3168 llvm::Constant *StaticData[] = {
3169 EmitCheckSourceLocation(CallLoc),
3170 EmitCheckTypeDescriptor(CalleeType)
3171 };
3172 EmitCheck(CalleeRTTIMatch,
3173 "function_type_mismatch",
3174 StaticData,
3175 Callee,
3176 CRK_Recoverable);
3177
3178 Builder.CreateBr(Cont);
3179 EmitBlock(Cont);
3180 }
3181 }
3182
Daniel Dunbarc722b852008-08-30 03:02:31 +00003183 CallArgList Args;
Adrian Prantlca64c3e2013-07-26 20:42:57 +00003184 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd,
3185 ForceColumnInfo);
Daniel Dunbarc722b852008-08-30 03:02:31 +00003186
John McCalla729c622012-02-17 03:33:10 +00003187 const CGFunctionInfo &FnInfo =
John McCall8dda7b22012-07-07 06:41:13 +00003188 CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
John McCallcbc038a2011-09-21 08:08:30 +00003189
3190 // C99 6.5.2.2p6:
3191 // If the expression that denotes the called function has a type
3192 // that does not include a prototype, [the default argument
3193 // promotions are performed]. If the number of arguments does not
3194 // equal the number of parameters, the behavior is undefined. If
3195 // the function is defined with a type that includes a prototype,
3196 // and either the prototype ends with an ellipsis (, ...) or the
3197 // types of the arguments after promotion are not compatible with
3198 // the types of the parameters, the behavior is undefined. If the
3199 // function is defined with a type that does not include a
3200 // prototype, and the types of the arguments after promotion are
3201 // not compatible with those of the parameters after promotion,
3202 // the behavior is undefined [except in some trivial cases].
3203 // That is, in the general case, we should assume that a call
3204 // through an unprototyped function type works like a *non-variadic*
3205 // call. The way we make this work is to cast to the exact type
3206 // of the promoted arguments.
John McCallc818bbb2012-12-07 07:03:17 +00003207 if (isa<FunctionNoProtoType>(FnType)) {
John McCalla729c622012-02-17 03:33:10 +00003208 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00003209 CalleeTy = CalleeTy->getPointerTo();
3210 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3211 }
3212
3213 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00003214}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003215
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003216LValue CodeGenFunction::
3217EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
Eli Friedman928a5672009-11-18 05:01:17 +00003218 llvm::Value *BaseV;
John McCalle3027922010-08-25 11:45:40 +00003219 if (E->getOpcode() == BO_PtrMemI)
Eli Friedman928a5672009-11-18 05:01:17 +00003220 BaseV = EmitScalarExpr(E->getLHS());
3221 else
3222 BaseV = EmitLValue(E->getLHS()).getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003223
John McCallc134eb52010-08-31 21:07:20 +00003224 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3225
3226 const MemberPointerType *MPT
3227 = E->getRHS()->getType()->getAs<MemberPointerType>();
3228
David Majnemer2b0d66d2014-02-20 23:22:07 +00003229 llvm::Value *AddV = CGM.getCXXABI().EmitMemberDataPointerAddress(
3230 *this, E, BaseV, OffsetV, MPT);
John McCallc134eb52010-08-31 21:07:20 +00003231
3232 return MakeAddrLValue(AddV, MPT->getPointeeType());
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003233}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003234
John McCall47fb9502013-03-07 21:37:08 +00003235/// Given the address of a temporary variable, produce an r-value of
3236/// its type.
3237RValue CodeGenFunction::convertTempToRValue(llvm::Value *addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003238 QualType type,
3239 SourceLocation loc) {
John McCall47fb9502013-03-07 21:37:08 +00003240 LValue lvalue = MakeNaturalAlignAddrLValue(addr, type);
3241 switch (getEvaluationKind(type)) {
3242 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003243 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003244 case TEK_Aggregate:
3245 return lvalue.asAggregateRValue();
3246 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003247 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003248 }
3249 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003250}
3251
Duncan Sandse81111c2012-04-10 08:23:07 +00003252void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003253 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003254 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003255 return;
3256
Duncan Sands65229ed2012-04-16 16:29:47 +00003257 llvm::MDBuilder MDHelper(getLLVMContext());
3258 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003259
Duncan Sands6fc46192012-04-14 12:37:26 +00003260 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003261}
John McCallfe96e0b2011-11-06 09:01:30 +00003262
3263namespace {
3264 struct LValueOrRValue {
3265 LValue LV;
3266 RValue RV;
3267 };
3268}
3269
3270static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3271 const PseudoObjectExpr *E,
3272 bool forLValue,
3273 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003274 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00003275
3276 // Find the result expression, if any.
3277 const Expr *resultExpr = E->getResultExpr();
3278 LValueOrRValue result;
3279
3280 for (PseudoObjectExpr::const_semantics_iterator
3281 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3282 const Expr *semantic = *i;
3283
3284 // If this semantic expression is an opaque value, bind it
3285 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003286 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00003287
3288 // If this is the result expression, we may need to evaluate
3289 // directly into the slot.
3290 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3291 OVMA opaqueData;
3292 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00003293 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00003294 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3295
3296 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3297 opaqueData = OVMA::bind(CGF, ov, LV);
3298 result.RV = slot.asRValue();
3299
3300 // Otherwise, emit as normal.
3301 } else {
3302 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3303
3304 // If this is the result, also evaluate the result now.
3305 if (ov == resultExpr) {
3306 if (forLValue)
3307 result.LV = CGF.EmitLValue(ov);
3308 else
3309 result.RV = CGF.EmitAnyExpr(ov, slot);
3310 }
3311 }
3312
3313 opaques.push_back(opaqueData);
3314
3315 // Otherwise, if the expression is the result, evaluate it
3316 // and remember the result.
3317 } else if (semantic == resultExpr) {
3318 if (forLValue)
3319 result.LV = CGF.EmitLValue(semantic);
3320 else
3321 result.RV = CGF.EmitAnyExpr(semantic, slot);
3322
3323 // Otherwise, evaluate the expression in an ignored context.
3324 } else {
3325 CGF.EmitIgnoredExpr(semantic);
3326 }
3327 }
3328
3329 // Unbind all the opaques now.
3330 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3331 opaques[i].unbind(CGF);
3332
3333 return result;
3334}
3335
3336RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3337 AggValueSlot slot) {
3338 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3339}
3340
3341LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3342 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3343}