blob: aad877134d62fb9b9e1fa530825592e0068ed041 [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"
Nico Weber3a691a32012-06-23 02:07:59 +000024#include "clang/Basic/ConvertUTF.h"
Chandler Carruth85098242010-06-15 23:19:56 +000025#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "llvm/ADT/Hashing.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/MDBuilder.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000031using namespace clang;
32using namespace CodeGen;
33
Chris Lattnerd7f58862007-06-02 05:24:33 +000034//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000035// Miscellaneous Helper Methods
36//===--------------------------------------------------------------------===//
37
John McCallad7c5c12011-02-08 08:22:06 +000038llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
39 unsigned addressSpace =
40 cast<llvm::PointerType>(value->getType())->getAddressSpace();
41
Chris Lattner2192fe52011-07-18 04:24:23 +000042 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000043 if (addressSpace)
44 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
45
46 if (value->getType() == destType) return value;
47 return Builder.CreateBitCast(value, destType);
48}
49
Chris Lattnere9a64532007-06-22 21:44:33 +000050/// CreateTempAlloca - This creates a alloca and inserts it into the entry
51/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000052llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000053 const Twine &Name) {
Chris Lattner47640222009-03-22 00:24:14 +000054 if (!Builder.isNamePreserving())
Daniel Dunbarb5aacc22009-10-19 01:21:05 +000055 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
Devang Pateldac79de2009-10-12 22:29:02 +000056 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000057}
Chris Lattner8394d792007-06-05 20:53:16 +000058
John McCall2e6567a2010-04-22 01:10:34 +000059void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
60 llvm::Value *Init) {
61 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
62 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
63 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
64}
65
Chris Lattnerc401de92010-07-05 20:21:00 +000066llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000068 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
69 // FIXME: Should we prefer the preferred type alignment here?
70 CharUnits Align = getContext().getTypeAlignInChars(Ty);
71 Alloc->setAlignment(Align.getQuantity());
72 return Alloc;
73}
74
Chris Lattnerc401de92010-07-05 20:21:00 +000075llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000076 const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000077 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
78 // FIXME: Should we prefer the preferred type alignment here?
79 CharUnits Align = getContext().getTypeAlignInChars(Ty);
80 Alloc->setAlignment(Align.getQuantity());
81 return Alloc;
82}
83
Chris Lattner8394d792007-06-05 20:53:16 +000084/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
85/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000086llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
John McCall7a9aac22010-08-23 01:21:21 +000087 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +000088 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +000089 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +000090 }
John McCall7a9aac22010-08-23 01:21:21 +000091
92 QualType BoolTy = getContext().BoolTy;
Chris Lattnerf3bc75a2008-04-04 16:54:41 +000093 if (!E->getType()->isAnyComplexType())
Chris Lattner268fcce2007-08-26 16:46:58 +000094 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Chris Lattner8394d792007-06-05 20:53:16 +000095
Chris Lattner268fcce2007-08-26 16:46:58 +000096 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Chris Lattnerf0106d22007-06-02 19:33:17 +000097}
98
John McCalla2342eb2010-12-05 02:00:02 +000099/// EmitIgnoredExpr - Emit code to compute the specified expression,
100/// ignoring the result.
101void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
102 if (E->isRValue())
103 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
104
105 // Just emit it as an l-value and drop the result.
106 EmitLValue(E);
107}
108
John McCall7a626f62010-09-15 10:14:12 +0000109/// EmitAnyExpr - Emit code to compute the specified expression which
110/// can have any type. The result is returned as an RValue struct.
111/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000112/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000113RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
114 AggValueSlot aggSlot,
115 bool ignoreResult) {
Chris Lattner4647a212007-08-31 22:49:20 +0000116 if (!hasAggregateLLVMType(E->getType()))
John McCall4e8ca4f2012-07-02 23:58:38 +0000117 return RValue::get(EmitScalarExpr(E, ignoreResult));
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000118 else if (E->getType()->isAnyComplexType())
John McCall4e8ca4f2012-07-02 23:58:38 +0000119 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
Mike Stump4a3999f2009-09-09 13:00:44 +0000120
John McCall4e8ca4f2012-07-02 23:58:38 +0000121 if (!ignoreResult && aggSlot.isIgnored())
122 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
123 EmitAggExpr(E, aggSlot);
124 return aggSlot.asRValue();
Chris Lattner4647a212007-08-31 22:49:20 +0000125}
126
Mike Stump4a3999f2009-09-09 13:00:44 +0000127/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
128/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000129RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
130 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000131
132 if (hasAggregateLLVMType(E->getType()) &&
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000133 !E->getType()->isAnyComplexType())
John McCall7a626f62010-09-15 10:14:12 +0000134 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
135 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000136}
137
John McCall21886962010-04-21 10:05:39 +0000138/// EmitAnyExprToMem - Evaluate an expression into a given memory
139/// location.
140void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
141 llvm::Value *Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000142 Qualifiers Quals,
143 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000144 // FIXME: This function should take an LValue as an argument.
145 if (E->getType()->isAnyComplexType()) {
John McCall31168b02011-06-15 23:02:42 +0000146 EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000147 } else if (hasAggregateLLVMType(E->getType())) {
Eli Friedman38cd36d2011-12-03 02:13:40 +0000148 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000149 EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000150 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000151 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000152 AggValueSlot::IsAliased_t(!IsInit)));
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000153 } else {
John McCall21886962010-04-21 10:05:39 +0000154 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000155 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000156 EmitStoreThroughLValue(RV, LV);
John McCall21886962010-04-21 10:05:39 +0000157 }
158}
159
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000160static llvm::Value *
Chris Lattner24516962011-07-20 04:59:57 +0000161CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000162 const NamedDecl *InitializedDecl) {
163 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
164 if (VD->hasGlobalStorage()) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000165 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000166 llvm::raw_svector_ostream Out(Name);
167 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
168 Out.flush();
169
Chris Lattner2192fe52011-07-18 04:24:23 +0000170 llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
Anders Carlsson18c205e2010-06-27 17:23:46 +0000171
172 // Create the reference temporary.
173 llvm::GlobalValue *RefTemp =
174 new llvm::GlobalVariable(CGF.CGM.getModule(),
175 RefTempTy, /*isConstant=*/false,
176 llvm::GlobalValue::InternalLinkage,
177 llvm::Constant::getNullValue(RefTempTy),
178 Name.str());
179 return RefTemp;
180 }
181 }
182
183 return CGF.CreateMemTemp(Type, "ref.tmp");
184}
185
186static llvm::Value *
Chris Lattnerf53c0962010-09-06 00:11:41 +0000187EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000188 llvm::Value *&ReferenceTemporary,
189 const CXXDestructorDecl *&ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000190 QualType &ObjCARCReferenceLifetimeType,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000191 const NamedDecl *InitializedDecl) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000192 const MaterializeTemporaryExpr *M = NULL;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000193 E = E->findMaterializedTemporary(M);
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000194 // Objective-C++ ARC:
195 // If we are binding a reference to a temporary that has ownership, we
196 // need to perform retain/release operations on the temporary.
Richard Smith9c6890a2012-11-01 22:30:59 +0000197 if (M && CGF.getLangOpts().ObjCAutoRefCount &&
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000198 M->getType()->isObjCLifetimeType() &&
199 (M->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
200 M->getType().getObjCLifetime() == Qualifiers::OCL_Weak ||
201 M->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing))
202 ObjCARCReferenceLifetimeType = M->getType();
Sebastian Redl29526f02011-11-27 16:50:07 +0000203
John McCall08ef4662011-11-10 08:15:53 +0000204 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) {
205 CGF.enterFullExpression(EWC);
John McCallbd309292010-07-06 01:34:17 +0000206 CodeGenFunction::RunCleanupsScope Scope(CGF);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000207
John McCall08ef4662011-11-10 08:15:53 +0000208 return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000209 ReferenceTemporary,
210 ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000211 ObjCARCReferenceLifetimeType,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000212 InitializedDecl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000213 }
214
215 RValue RV;
Douglas Gregor9c399a22011-01-22 02:44:21 +0000216 if (E->isGLValue()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000217 // Emit the expression as an lvalue.
218 LValue LV = CGF.EmitLValue(E);
Chris Lattner13ee4f42011-07-10 05:34:54 +0000219
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000220 if (LV.isSimple())
221 return LV.getAddress();
Anders Carlsson824e0612010-02-04 17:32:58 +0000222
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000223 // We have to load the lvalue.
John McCall55e1fbc2011-06-25 02:11:03 +0000224 RV = CGF.EmitLoadOfLValue(LV);
Eli Friedmanc21cb442009-05-20 02:31:19 +0000225 } else {
Douglas Gregor58df5092011-06-22 16:12:01 +0000226 if (!ObjCARCReferenceLifetimeType.isNull()) {
227 ReferenceTemporary = CreateReferenceTemporary(CGF,
228 ObjCARCReferenceLifetimeType,
229 InitializedDecl);
230
231
232 LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
233 ObjCARCReferenceLifetimeType);
234
235 CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
236 RefTempDst, false);
237
238 bool ExtendsLifeOfTemporary = false;
239 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
240 if (Var->extendsLifetimeOfTemporary())
241 ExtendsLifeOfTemporary = true;
242 } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
243 ExtendsLifeOfTemporary = true;
244 }
245
246 if (!ExtendsLifeOfTemporary) {
247 // Since the lifetime of this temporary isn't going to be extended,
248 // we need to clean it up ourselves at the end of the full expression.
249 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
250 case Qualifiers::OCL_None:
251 case Qualifiers::OCL_ExplicitNone:
252 case Qualifiers::OCL_Autoreleasing:
253 break;
254
John McCall4bd0fb12011-07-12 16:41:08 +0000255 case Qualifiers::OCL_Strong: {
256 assert(!ObjCARCReferenceLifetimeType->isArrayType());
257 CleanupKind cleanupKind = CGF.getARCCleanupKind();
258 CGF.pushDestroy(cleanupKind,
259 ReferenceTemporary,
260 ObjCARCReferenceLifetimeType,
261 CodeGenFunction::destroyARCStrongImprecise,
262 cleanupKind & EHCleanup);
Douglas Gregor58df5092011-06-22 16:12:01 +0000263 break;
John McCall4bd0fb12011-07-12 16:41:08 +0000264 }
Douglas Gregor58df5092011-06-22 16:12:01 +0000265
266 case Qualifiers::OCL_Weak:
John McCall4bd0fb12011-07-12 16:41:08 +0000267 assert(!ObjCARCReferenceLifetimeType->isArrayType());
268 CGF.pushDestroy(NormalAndEHCleanup,
269 ReferenceTemporary,
270 ObjCARCReferenceLifetimeType,
271 CodeGenFunction::destroyARCWeak,
272 /*useEHCleanupForArray*/ true);
Douglas Gregor58df5092011-06-22 16:12:01 +0000273 break;
274 }
275
276 ObjCARCReferenceLifetimeType = QualType();
277 }
278
279 return ReferenceTemporary;
280 }
Rafael Espindolab4136762012-10-27 00:40:06 +0000281
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000282 SmallVector<SubobjectAdjustment, 2> Adjustments;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000283 E = E->skipRValueSubobjectAdjustments(Adjustments);
Rafael Espindolab4136762012-10-27 00:40:06 +0000284 if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
285 if (opaque->getType()->isRecordType())
286 return CGF.EmitOpaqueValueLValue(opaque).getAddress();
Douglas Gregoraae38d62010-05-22 05:17:18 +0000287
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000288 // Create a reference temporary if necessary.
John McCall7a626f62010-09-15 10:14:12 +0000289 AggValueSlot AggSlot = AggValueSlot::ignored();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000290 if (CGF.hasAggregateLLVMType(E->getType()) &&
John McCall7a626f62010-09-15 10:14:12 +0000291 !E->getType()->isAnyComplexType()) {
Anders Carlsson18c205e2010-06-27 17:23:46 +0000292 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
293 InitializedDecl);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000294 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
John McCall8d6fc952011-08-25 20:40:09 +0000295 AggValueSlot::IsDestructed_t isDestructed
296 = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000297 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
298 Qualifiers(), isDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000299 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000300 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000301 }
John McCall31168b02011-06-15 23:02:42 +0000302
Anders Carlsson18c205e2010-06-27 17:23:46 +0000303 if (InitializedDecl) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000304 // Get the destructor for the reference temporary.
305 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
306 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
307 if (!ClassDecl->hasTrivialDestructor())
Douglas Gregorbac74902010-07-01 14:13:13 +0000308 ReferenceTemporaryDtor = ClassDecl->getDestructor();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000309 }
310 }
311
John McCall31168b02011-06-15 23:02:42 +0000312 RV = CGF.EmitAnyExpr(E, AggSlot);
313
Douglas Gregor7c38f152010-05-20 08:36:28 +0000314 // Check if need to perform derived-to-base casts and/or field accesses, to
315 // get from the temporary object we created (and, potentially, for which we
316 // extended the lifetime) to the subobject we're binding the reference to.
317 if (!Adjustments.empty()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000318 llvm::Value *Object = RV.getAggregateAddr();
Douglas Gregor7c38f152010-05-20 08:36:28 +0000319 for (unsigned I = Adjustments.size(); I != 0; --I) {
320 SubobjectAdjustment &Adjustment = Adjustments[I-1];
321 switch (Adjustment.Kind) {
322 case SubobjectAdjustment::DerivedToBaseAdjustment:
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000323 Object =
324 CGF.GetAddressOfBaseClass(Object,
325 Adjustment.DerivedToBase.DerivedClass,
John McCallcf142162010-08-07 06:22:56 +0000326 Adjustment.DerivedToBase.BasePath->path_begin(),
327 Adjustment.DerivedToBase.BasePath->path_end(),
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000328 /*NullCheckValue=*/false);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000329 break;
330
331 case SubobjectAdjustment::FieldAdjustment: {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000332 LValue LV = CGF.MakeAddrLValue(Object, E->getType());
333 LV = CGF.EmitLValueForField(LV, Adjustment.Field);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000334 if (LV.isSimple()) {
335 Object = LV.getAddress();
336 break;
337 }
338
339 // For non-simple lvalues, we actually have to create a copy of
340 // the object we're binding to.
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000341 QualType T = Adjustment.Field->getType().getNonReferenceType()
342 .getUnqualifiedType();
Anders Carlsson3f48c602010-06-27 17:52:15 +0000343 Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000344 LValue TempLV = CGF.MakeAddrLValue(Object,
345 Adjustment.Field->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000346 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000347 break;
348 }
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000349
Eli Friedman13ffdd82012-06-15 23:51:06 +0000350 case SubobjectAdjustment::MemberPointerAdjustment: {
Rafael Espindolae7b11f52012-10-27 00:36:38 +0000351 llvm::Value *Ptr = CGF.EmitScalarExpr(Adjustment.Ptr.RHS);
Eli Friedman13ffdd82012-06-15 23:51:06 +0000352 Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress(
Rafael Espindolae7b11f52012-10-27 00:36:38 +0000353 CGF, Object, Ptr, Adjustment.Ptr.MPT);
Eli Friedman13ffdd82012-06-15 23:51:06 +0000354 break;
355 }
Douglas Gregor7c38f152010-05-20 08:36:28 +0000356 }
357 }
Eli Friedmanb6069252011-03-16 22:34:09 +0000358
359 return Object;
Anders Carlsson66413c22009-10-15 00:51:46 +0000360 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000361 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000362
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000363 if (RV.isAggregate())
364 return RV.getAggregateAddr();
Eli Friedmanc21cb442009-05-20 02:31:19 +0000365
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000366 // Create a temporary variable that we can bind the reference to.
Anders Carlsson18c205e2010-06-27 17:23:46 +0000367 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
368 InitializedDecl);
369
Daniel Dunbar03816342010-08-21 02:24:36 +0000370
371 unsigned Alignment =
372 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000373 if (RV.isScalar())
374 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
Daniel Dunbar03816342010-08-21 02:24:36 +0000375 /*Volatile=*/false, Alignment, E->getType());
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000376 else
377 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
378 /*Volatile=*/false);
379 return ReferenceTemporary;
380}
381
382RValue
Chris Lattnerf53c0962010-09-06 00:11:41 +0000383CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000384 const NamedDecl *InitializedDecl) {
385 llvm::Value *ReferenceTemporary = 0;
386 const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
John McCall31168b02011-06-15 23:02:42 +0000387 QualType ObjCARCReferenceLifetimeType;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000388 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
389 ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000390 ObjCARCReferenceLifetimeType,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000391 InitializedDecl);
Richard Smithb1b0ab42012-11-05 22:21:05 +0000392 if (SanitizePerformTypeCheck && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000393 // C++11 [dcl.ref]p5 (as amended by core issue 453):
394 // If a glvalue to which a reference is directly bound designates neither
395 // an existing object or function of an appropriate type nor a region of
396 // storage of suitable size and alignment to contain an object of the
397 // reference's type, the behavior is undefined.
398 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000399 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000400 }
John McCall31168b02011-06-15 23:02:42 +0000401 if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
Anders Carlsson3f48c602010-06-27 17:52:15 +0000402 return RValue::get(Value);
403
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000404 // Make sure to call the destructor for the reference temporary.
John McCall31168b02011-06-15 23:02:42 +0000405 const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl);
406 if (VD && VD->hasGlobalStorage()) {
407 if (ReferenceTemporaryDtor) {
Anders Carlsson3f48c602010-06-27 17:52:15 +0000408 llvm::Constant *DtorFn =
409 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
John McCallc84ed6a2012-05-01 06:13:13 +0000410 CGM.getCXXABI().registerGlobalDtor(*this, DtorFn,
John McCallad7c5c12011-02-08 08:22:06 +0000411 cast<llvm::Constant>(ReferenceTemporary));
John McCall31168b02011-06-15 23:02:42 +0000412 } else {
413 assert(!ObjCARCReferenceLifetimeType.isNull());
414 // Note: We intentionally do not register a global "destructor" to
415 // release the object.
Anders Carlsson3f48c602010-06-27 17:52:15 +0000416 }
John McCall31168b02011-06-15 23:02:42 +0000417
418 return RValue::get(Value);
Anders Carlsson3f48c602010-06-27 17:52:15 +0000419 }
John McCall8680f872010-07-21 06:29:51 +0000420
John McCall31168b02011-06-15 23:02:42 +0000421 if (ReferenceTemporaryDtor)
422 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
423 else {
424 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
425 case Qualifiers::OCL_None:
David Blaikie83d382b2011-09-23 05:06:16 +0000426 llvm_unreachable(
427 "Not a reference temporary that needs to be deallocated");
John McCall31168b02011-06-15 23:02:42 +0000428 case Qualifiers::OCL_ExplicitNone:
429 case Qualifiers::OCL_Autoreleasing:
430 // Nothing to do.
431 break;
432
John McCall4bd0fb12011-07-12 16:41:08 +0000433 case Qualifiers::OCL_Strong: {
434 bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>();
435 CleanupKind cleanupKind = getARCCleanupKind();
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000436 pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000437 precise ? destroyARCStrongPrecise : destroyARCStrongImprecise,
438 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000439 break;
John McCall4bd0fb12011-07-12 16:41:08 +0000440 }
John McCall31168b02011-06-15 23:02:42 +0000441
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000442 case Qualifiers::OCL_Weak: {
John McCall31168b02011-06-15 23:02:42 +0000443 // __weak objects always get EH cleanups; otherwise, exceptions
444 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000445 pushDestroy(NormalAndEHCleanup, ReferenceTemporary,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000446 ObjCARCReferenceLifetimeType, destroyARCWeak, true);
John McCall31168b02011-06-15 23:02:42 +0000447 break;
448 }
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000449 }
John McCall31168b02011-06-15 23:02:42 +0000450 }
451
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000452 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000453}
454
455
Mike Stump4a3999f2009-09-09 13:00:44 +0000456/// getAccessedFieldNo - Given an encoded value and a result number, return the
457/// input field number being accessed.
458unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000459 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000460 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
461 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000462}
463
Richard Smith4d3110a2012-10-25 02:14:12 +0000464/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
465static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
466 llvm::Value *High) {
467 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
468 llvm::Value *K47 = Builder.getInt64(47);
469 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
470 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
471 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
472 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
473 return Builder.CreateMul(B1, KMul);
474}
475
Richard Smithe30752c2012-10-09 19:52:38 +0000476void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
477 llvm::Value *Address,
Richard Smith4d1458e2012-09-08 02:08:36 +0000478 QualType Ty, CharUnits Alignment) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000479 if (!SanitizePerformTypeCheck)
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000480 return;
481
Richard Smith2d8b2942012-11-01 07:22:08 +0000482 // Don't check pointers outside the default address space. The null check
483 // isn't correct, the object-size check isn't supported by LLVM, and we can't
484 // communicate the addresses to the runtime handler for the vptr check.
485 if (Address->getType()->getPointerAddressSpace())
486 return;
487
Richard Smith69d0d262012-08-24 00:54:33 +0000488 llvm::Value *Cond = 0;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000489
Will Dietzf54319c2013-01-18 11:30:38 +0000490 if (SanOpts->Null) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000491 // The glvalue must not be an empty glvalue.
492 Cond = Builder.CreateICmpNE(
493 Address, llvm::Constant::getNullValue(Address->getType()));
494 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000495
Will Dietzf54319c2013-01-18 11:30:38 +0000496 if (SanOpts->ObjectSize && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000497 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000498
Richard Smith69d0d262012-08-24 00:54:33 +0000499 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000500 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000501 // to check this.
502 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy);
503 llvm::Value *Min = Builder.getFalse();
Richard Smith2d8b2942012-11-01 07:22:08 +0000504 llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000505 llvm::Value *LargeEnough =
Richard Smith2d8b2942012-11-01 07:22:08 +0000506 Builder.CreateICmpUGE(Builder.CreateCall2(F, CastAddr, Min),
Richard Smith69d0d262012-08-24 00:54:33 +0000507 llvm::ConstantInt::get(IntPtrTy, Size));
508 Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough;
Richard Smithe30752c2012-10-09 19:52:38 +0000509 }
Richard Smith69d0d262012-08-24 00:54:33 +0000510
Richard Smithb1b0ab42012-11-05 22:21:05 +0000511 uint64_t AlignVal = 0;
512
Will Dietzf54319c2013-01-18 11:30:38 +0000513 if (SanOpts->Alignment) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000514 AlignVal = Alignment.getQuantity();
515 if (!Ty->isIncompleteType() && !AlignVal)
516 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
517
Richard Smith69d0d262012-08-24 00:54:33 +0000518 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000519 if (AlignVal) {
520 llvm::Value *Align =
521 Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
522 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
523 llvm::Value *Aligned =
524 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
525 Cond = Cond ? Builder.CreateAnd(Cond, Aligned) : Aligned;
526 }
Richard Smith69d0d262012-08-24 00:54:33 +0000527 }
528
Richard Smithe30752c2012-10-09 19:52:38 +0000529 if (Cond) {
530 llvm::Constant *StaticData[] = {
531 EmitCheckSourceLocation(Loc),
532 EmitCheckTypeDescriptor(Ty),
533 llvm::ConstantInt::get(SizeTy, AlignVal),
534 llvm::ConstantInt::get(Int8Ty, TCK)
535 };
Will Dietz88e02332012-12-02 19:50:33 +0000536 EmitCheck(Cond, "type_mismatch", StaticData, Address, CRK_Recoverable);
Richard Smithe30752c2012-10-09 19:52:38 +0000537 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000538
Richard Smithb1b0ab42012-11-05 22:21:05 +0000539 // If possible, check that the vptr indicates that there is a subobject of
540 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000541 //
542 // C++11 [basic.life]p5,6:
543 // [For storage which does not refer to an object within its lifetime]
544 // The program has undefined behavior if:
545 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000546 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000547 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Will Dietzf54319c2013-01-18 11:30:38 +0000548 if (SanOpts->Vptr &&
Richard Smithbe024a82012-12-18 00:22:45 +0000549 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000550 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000551 // Compute a hash of the mangled name of the type.
552 //
553 // FIXME: This is not guaranteed to be deterministic! Move to a
554 // fingerprinting mechanism once LLVM provides one. For the time
555 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000556 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000557 llvm::raw_svector_ostream Out(MangledName);
558 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
559 Out);
560 llvm::hash_code TypeHash = hash_value(Out.str());
561
562 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
563 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
564 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
565 llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
566 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
567 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
568
569 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
570 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
571
572 // Look the hash up in our cache.
573 const int CacheSize = 128;
574 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
575 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
576 "__ubsan_vptr_type_cache");
577 llvm::Value *Slot = Builder.CreateAnd(Hash,
578 llvm::ConstantInt::get(IntPtrTy,
579 CacheSize-1));
580 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
581 llvm::Value *CacheVal =
582 Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
583
584 // If the hash isn't in the cache, call a runtime handler to perform the
585 // hard work of checking whether the vptr is for an object of the right
586 // type. This will either fill in the cache and return, or produce a
587 // diagnostic.
588 llvm::Constant *StaticData[] = {
589 EmitCheckSourceLocation(Loc),
590 EmitCheckTypeDescriptor(Ty),
591 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
592 llvm::ConstantInt::get(Int8Ty, TCK)
593 };
594 llvm::Value *DynamicData[] = { Address, Hash };
595 EmitCheck(Builder.CreateICmpEQ(CacheVal, Hash),
Will Dietz88e02332012-12-02 19:50:33 +0000596 "dynamic_type_cache_miss", StaticData, DynamicData,
597 CRK_AlwaysRecoverable);
Richard Smith4d3110a2012-10-25 02:14:12 +0000598 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000599}
Chris Lattner4647a212007-08-31 22:49:20 +0000600
Chris Lattner116ce8f2010-01-09 21:40:03 +0000601
Chris Lattner116ce8f2010-01-09 21:40:03 +0000602CodeGenFunction::ComplexPairTy CodeGenFunction::
603EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
604 bool isInc, bool isPre) {
605 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
606 LV.isVolatileQualified());
607
608 llvm::Value *NextVal;
609 if (isa<llvm::IntegerType>(InVal.first->getType())) {
610 uint64_t AmountVal = isInc ? 1 : -1;
611 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
612
613 // Add the inc/dec to the real part.
614 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
615 } else {
616 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
617 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
618 if (!isInc)
619 FVal.changeSign();
620 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
621
622 // Add the inc/dec to the real part.
623 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
624 }
625
626 ComplexPairTy IncVal(NextVal, InVal.second);
627
628 // Store the updated result through the lvalue.
629 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
630
631 // If this is a postinc, return the value read from memory, otherwise use the
632 // updated value.
633 return isPre ? IncVal : InVal;
634}
635
636
Chris Lattnera45c5af2007-06-02 19:47:04 +0000637//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000638// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000639//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000640
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000641RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000642 if (Ty->isVoidType())
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000643 return RValue::get(0);
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000644
645 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000646 llvm::Type *EltTy = ConvertType(CTy->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000647 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000648 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000649 }
650
Chris Lattner65526f02010-08-23 05:26:13 +0000651 // If this is a use of an undefined aggregate type, the aggregate must have an
652 // identifiable address. Just because the contents of the value are undefined
653 // doesn't mean that the address can't be taken and compared.
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000654 if (hasAggregateLLVMType(Ty)) {
Chris Lattner65526f02010-08-23 05:26:13 +0000655 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
656 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000657 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000658
659 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000660}
661
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000662RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
663 const char *Name) {
664 ErrorUnsupported(E, Name);
665 return GetUndefRValue(E->getType());
666}
667
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000668LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
669 const char *Name) {
670 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000671 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000672 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000673}
674
Richard Smith4d1458e2012-09-08 02:08:36 +0000675LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000676 LValue LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000677 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
Richard Smithe30752c2012-10-09 19:52:38 +0000678 EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
679 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000680 return LV;
681}
682
Chris Lattner8394d792007-06-05 20:53:16 +0000683/// EmitLValue - Emit code to compute a designator that specifies the location
684/// of the expression.
685///
Mike Stump4a3999f2009-09-09 13:00:44 +0000686/// This can return one of two things: a simple address or a bitfield reference.
687/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
688/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000689///
Mike Stump4a3999f2009-09-09 13:00:44 +0000690/// If this returns a bitfield reference, nothing about the pointee type of the
691/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000692///
Mike Stump4a3999f2009-09-09 13:00:44 +0000693/// If this returns a normal address, and if the lvalue's C type is fixed size,
694/// this method guarantees that the returned pointer type will point to an LLVM
695/// type of the same size of the lvalue's type. If the lvalue has a variable
696/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000697///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000698LValue CodeGenFunction::EmitLValue(const Expr *E) {
699 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000700 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000701
John McCallc109a252011-11-07 03:59:57 +0000702 case Expr::ObjCPropertyRefExprClass:
703 llvm_unreachable("cannot emit a property reference directly");
704
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000705 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000706 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000707 case Expr::ObjCIsaExprClass:
708 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000709 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000710 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
Douglas Gregor914af212010-04-23 04:16:32 +0000711 case Expr::CompoundAssignOperatorClass:
John McCalla2342eb2010-12-05 02:00:02 +0000712 if (!E->getType()->isAnyComplexType())
713 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
714 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000715 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000716 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000717 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000718 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000719 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000720 case Expr::VAArgExprClass:
721 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000722 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000723 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000724 case Expr::ParenExprClass:
725 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000726 case Expr::GenericSelectionExprClass:
727 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000728 case Expr::PredefinedExprClass:
729 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000730 case Expr::StringLiteralClass:
731 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000732 case Expr::ObjCEncodeExprClass:
733 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000734 case Expr::PseudoObjectExprClass:
735 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000736 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000737 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000738 case Expr::CXXTemporaryObjectExprClass:
739 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000740 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
741 case Expr::CXXBindTemporaryExprClass:
742 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000743 case Expr::CXXUuidofExprClass:
744 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000745 case Expr::LambdaExprClass:
746 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000747
748 case Expr::ExprWithCleanupsClass: {
749 const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E);
750 enterFullExpression(cleanups);
751 RunCleanupsScope Scope(*this);
752 return EmitLValue(cleanups->getSubExpr());
753 }
754
Douglas Gregor747eb782010-07-08 06:14:04 +0000755 case Expr::CXXScalarValueInitExprClass:
756 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
Anders Carlsson52ce3bb2009-11-14 01:51:50 +0000757 case Expr::CXXDefaultArgExprClass:
758 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Mike Stumpc9b231c2009-11-15 08:09:41 +0000759 case Expr::CXXTypeidExprClass:
760 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000761
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000762 case Expr::ObjCMessageExprClass:
763 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000764 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +0000765 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +0000766 case Expr::StmtExprClass:
767 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000768 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +0000769 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000770 case Expr::ArraySubscriptExprClass:
771 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +0000772 case Expr::ExtVectorElementExprClass:
773 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000774 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +0000775 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +0000776 case Expr::CompoundLiteralExprClass:
777 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +0000778 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +0000779 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +0000780 case Expr::BinaryConditionalOperatorClass:
781 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +0000782 case Expr::ChooseExprClass:
Eli Friedmane0a5b8b2009-03-04 05:52:32 +0000783 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
John McCall1bf58462011-02-16 08:02:54 +0000784 case Expr::OpaqueValueExprClass:
785 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +0000786 case Expr::SubstNonTypeTemplateParmExprClass:
787 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +0000788 case Expr::ImplicitCastExprClass:
789 case Expr::CStyleCastExprClass:
790 case Expr::CXXFunctionalCastExprClass:
791 case Expr::CXXStaticCastExprClass:
792 case Expr::CXXDynamicCastExprClass:
793 case Expr::CXXReinterpretCastExprClass:
794 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +0000795 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +0000796 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000797
Douglas Gregorfe314812011-06-21 17:03:29 +0000798 case Expr::MaterializeTemporaryExprClass:
799 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000800 }
801}
802
John McCall71335052012-03-10 03:05:10 +0000803/// Given an object of the given canonical type, can we safely copy a
804/// value out of it based on its initializer?
805static bool isConstantEmittableObjectType(QualType type) {
806 assert(type.isCanonical());
807 assert(!type->isReferenceType());
808
809 // Must be const-qualified but non-volatile.
810 Qualifiers qs = type.getLocalQualifiers();
811 if (!qs.hasConst() || qs.hasVolatile()) return false;
812
813 // Otherwise, all object types satisfy this except C++ classes with
814 // mutable subobjects or non-trivial copy/destroy behavior.
815 if (const RecordType *RT = dyn_cast<RecordType>(type))
816 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
817 if (RD->hasMutableFields() || !RD->isTrivial())
818 return false;
819
820 return true;
821}
822
823/// Can we constant-emit a load of a reference to a variable of the
824/// given type? This is different from predicates like
825/// Decl::isUsableInConstantExpressions because we do want it to apply
826/// in situations that don't necessarily satisfy the language's rules
827/// for this (e.g. C++'s ODR-use rules). For example, we want to able
828/// to do this with const float variables even if those variables
829/// aren't marked 'constexpr'.
830enum ConstantEmissionKind {
831 CEK_None,
832 CEK_AsReferenceOnly,
833 CEK_AsValueOrReference,
834 CEK_AsValueOnly
835};
836static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
837 type = type.getCanonicalType();
838 if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) {
839 if (isConstantEmittableObjectType(ref->getPointeeType()))
840 return CEK_AsValueOrReference;
841 return CEK_AsReferenceOnly;
842 }
843 if (isConstantEmittableObjectType(type))
844 return CEK_AsValueOnly;
845 return CEK_None;
846}
847
848/// Try to emit a reference to the given value without producing it as
849/// an l-value. This is actually more than an optimization: we can't
850/// produce an l-value for variables that we never actually captured
851/// in a block or lambda, which means const int variables or constexpr
852/// literals or similar.
853CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +0000854CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
855 ValueDecl *value = refExpr->getDecl();
856
John McCall71335052012-03-10 03:05:10 +0000857 // The value needs to be an enum constant or a constant variable.
858 ConstantEmissionKind CEK;
859 if (isa<ParmVarDecl>(value)) {
860 CEK = CEK_None;
861 } else if (VarDecl *var = dyn_cast<VarDecl>(value)) {
862 CEK = checkVarTypeForConstantEmission(var->getType());
863 } else if (isa<EnumConstantDecl>(value)) {
864 CEK = CEK_AsValueOnly;
865 } else {
866 CEK = CEK_None;
867 }
868 if (CEK == CEK_None) return ConstantEmission();
869
John McCall71335052012-03-10 03:05:10 +0000870 Expr::EvalResult result;
871 bool resultIsReference;
872 QualType resultType;
873
874 // It's best to evaluate all the way as an r-value if that's permitted.
875 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +0000876 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000877 resultIsReference = false;
878 resultType = refExpr->getType();
879
880 // Otherwise, try to evaluate as an l-value.
881 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +0000882 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000883 resultIsReference = true;
884 resultType = value->getType();
885
886 // Failure.
887 } else {
888 return ConstantEmission();
889 }
890
891 // In any case, if the initializer has side-effects, abandon ship.
892 if (result.HasSideEffects)
893 return ConstantEmission();
894
895 // Emit as a constant.
896 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
897
898 // Make sure we emit a debug reference to the global variable.
899 // This should probably fire even for
900 if (isa<VarDecl>(value)) {
901 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
John McCall113bee02012-03-10 09:33:50 +0000902 EmitDeclRefExprDbgValue(refExpr, C);
John McCall71335052012-03-10 03:05:10 +0000903 } else {
904 assert(isa<EnumConstantDecl>(value));
John McCall113bee02012-03-10 09:33:50 +0000905 EmitDeclRefExprDbgValue(refExpr, C);
John McCall71335052012-03-10 03:05:10 +0000906 }
907
908 // If we emitted a reference constant, we need to dereference that.
909 if (resultIsReference)
910 return ConstantEmission::forReference(C);
911
912 return ConstantEmission::forValue(C);
913}
914
John McCall1553b192011-06-16 04:16:24 +0000915llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
916 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +0000917 lvalue.getAlignment().getQuantity(),
918 lvalue.getType(), lvalue.getTBAAInfo());
John McCall1553b192011-06-16 04:16:24 +0000919}
920
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000921static bool hasBooleanRepresentation(QualType Ty) {
922 if (Ty->isBooleanType())
923 return true;
924
925 if (const EnumType *ET = Ty->getAs<EnumType>())
926 return ET->getDecl()->getIntegerType()->isBooleanType();
927
Douglas Gregor298f43d2012-04-12 20:42:30 +0000928 if (const AtomicType *AT = Ty->getAs<AtomicType>())
929 return hasBooleanRepresentation(AT->getValueType());
930
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000931 return false;
932}
933
Richard Smith1629da92012-12-13 07:11:50 +0000934static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
935 llvm::APInt &Min, llvm::APInt &End,
936 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000937 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +0000938 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
939 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000940 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000941 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +0000942 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000943
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000944 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +0000945 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
946 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000947 } else {
948 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +0000949 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000950 unsigned Bitwidth = LTy->getScalarSizeInBits();
951 unsigned NumNegativeBits = ED->getNumNegativeBits();
952 unsigned NumPositiveBits = ED->getNumPositiveBits();
953
954 if (NumNegativeBits) {
955 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
956 assert(NumBits <= Bitwidth);
957 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
958 Min = -End;
959 } else {
960 assert(NumPositiveBits <= Bitwidth);
961 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
962 Min = llvm::APInt(Bitwidth, 0);
963 }
964 }
Richard Smith1629da92012-12-13 07:11:50 +0000965 return true;
966}
967
968llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
969 llvm::APInt Min, End;
970 if (!getRangeForType(*this, Ty, Min, End,
971 CGM.getCodeGenOpts().StrictEnums))
972 return 0;
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000973
Duncan Sandsc720e782012-04-15 18:04:54 +0000974 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +0000975 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000976}
977
Daniel Dunbar1d425462009-02-10 00:57:50 +0000978llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
Dan Gohman947c9af2010-10-14 23:06:10 +0000979 unsigned Alignment, QualType Ty,
980 llvm::MDNode *TBAAInfo) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +0000981
982 // For better performance, handle vector loads differently.
983 if (Ty->isVectorType()) {
984 llvm::Value *V;
985 const llvm::Type *EltTy =
986 cast<llvm::PointerType>(Addr->getType())->getElementType();
987
988 const llvm::VectorType *VTy = cast<llvm::VectorType>(EltTy);
989
990 // Handle vectors of size 3, like size 4 for better performance.
991 if (VTy->getNumElements() == 3) {
992
993 // Bitcast to vec4 type.
994 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
995 4);
996 llvm::PointerType *ptVec4Ty =
997 llvm::PointerType::get(vec4Ty,
998 (cast<llvm::PointerType>(
999 Addr->getType()))->getAddressSpace());
1000 llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
1001 "castToVec4");
1002 // Now load value.
1003 llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001004
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001005 // Shuffle vector to get vec3.
Richard Smithf0480fc2012-12-13 05:41:48 +00001006 llvm::Constant *Mask[] = {
1007 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
1008 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
1009 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
1010 };
1011
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001012 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1013 V = Builder.CreateShuffleVector(LoadVal,
1014 llvm::UndefValue::get(vec4Ty),
1015 MaskV, "extractVec");
1016 return EmitFromMemory(V, Ty);
1017 }
1018 }
1019
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001020 llvm::LoadInst *Load = Builder.CreateLoad(Addr);
Daniel Dunbarc76493a2009-11-29 21:23:36 +00001021 if (Volatile)
1022 Load->setVolatile(true);
Daniel Dunbar03816342010-08-21 02:24:36 +00001023 if (Alignment)
1024 Load->setAlignment(Alignment);
Dan Gohman947c9af2010-10-14 23:06:10 +00001025 if (TBAAInfo)
1026 CGM.DecorateInstruction(Load, TBAAInfo);
David Chisnallfa35df62012-01-16 17:27:18 +00001027 // If this is an atomic type, all normal reads must be atomic
1028 if (Ty->isAtomicType())
1029 Load->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001030
Will Dietzf54319c2013-01-18 11:30:38 +00001031 if ((SanOpts->Bool && hasBooleanRepresentation(Ty)) ||
1032 (SanOpts->Enum && Ty->getAs<EnumType>())) {
Richard Smith1629da92012-12-13 07:11:50 +00001033 llvm::APInt Min, End;
1034 if (getRangeForType(*this, Ty, Min, End, true)) {
1035 --End;
1036 llvm::Value *Check;
1037 if (!Min)
1038 Check = Builder.CreateICmpULE(
1039 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1040 else {
1041 llvm::Value *Upper = Builder.CreateICmpSLE(
1042 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1043 llvm::Value *Lower = Builder.CreateICmpSGE(
1044 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1045 Check = Builder.CreateAnd(Upper, Lower);
1046 }
1047 // FIXME: Provide a SourceLocation.
1048 EmitCheck(Check, "load_invalid_value", EmitCheckTypeDescriptor(Ty),
1049 EmitCheckValue(Load), CRK_Recoverable);
1050 }
1051 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001052 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1053 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001054
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001055 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001056}
1057
John McCall3a7f6922010-10-27 20:58:56 +00001058llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1059 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001060 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001061 // This should really always be an i1, but sometimes it's already
1062 // an i8, and it's awkward to track those cases down.
1063 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001064 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1065 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1066 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001067 }
1068
1069 return Value;
1070}
1071
1072llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1073 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001074 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001075 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1076 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001077 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1078 }
1079
1080 return Value;
1081}
1082
Daniel Dunbar1d425462009-02-10 00:57:50 +00001083void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
Daniel Dunbar03816342010-08-21 02:24:36 +00001084 bool Volatile, unsigned Alignment,
Dan Gohman947c9af2010-10-14 23:06:10 +00001085 QualType Ty,
David Chisnallfa35df62012-01-16 17:27:18 +00001086 llvm::MDNode *TBAAInfo,
1087 bool isInit) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001088
1089 // Handle vectors differently to get better performance.
1090 if (Ty->isVectorType()) {
1091 llvm::Type *SrcTy = Value->getType();
1092 llvm::VectorType *VecTy = cast<llvm::VectorType>(SrcTy);
1093 // Handle vec3 special.
1094 if (VecTy->getNumElements() == 3) {
1095 llvm::LLVMContext &VMContext = getLLVMContext();
1096
1097 // Our source is a vec3, do a shuffle vector to make it a vec4.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001098 SmallVector<llvm::Constant*, 4> Mask;
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001099 Mask.push_back(llvm::ConstantInt::get(
1100 llvm::Type::getInt32Ty(VMContext),
1101 0));
1102 Mask.push_back(llvm::ConstantInt::get(
1103 llvm::Type::getInt32Ty(VMContext),
1104 1));
1105 Mask.push_back(llvm::ConstantInt::get(
1106 llvm::Type::getInt32Ty(VMContext),
1107 2));
1108 Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
1109
1110 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1111 Value = Builder.CreateShuffleVector(Value,
1112 llvm::UndefValue::get(VecTy),
1113 MaskV, "extractVec");
1114 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1115 }
1116 llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
1117 if (DstPtr->getElementType() != SrcTy) {
1118 llvm::Type *MemTy =
1119 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
1120 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
1121 }
1122 }
1123
John McCall3a7f6922010-10-27 20:58:56 +00001124 Value = EmitToMemory(Value, Ty);
Chris Lattner1a5f8972011-07-10 03:38:35 +00001125
Daniel Dunbar03816342010-08-21 02:24:36 +00001126 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1127 if (Alignment)
1128 Store->setAlignment(Alignment);
Dan Gohman947c9af2010-10-14 23:06:10 +00001129 if (TBAAInfo)
1130 CGM.DecorateInstruction(Store, TBAAInfo);
David Chisnallfa35df62012-01-16 17:27:18 +00001131 if (!isInit && Ty->isAtomicType())
1132 Store->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001133}
1134
David Chisnallfa35df62012-01-16 17:27:18 +00001135void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1136 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001137 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +00001138 lvalue.getAlignment().getQuantity(), lvalue.getType(),
David Chisnallfa35df62012-01-16 17:27:18 +00001139 lvalue.getTBAAInfo(), isInit);
John McCall1553b192011-06-16 04:16:24 +00001140}
1141
Mike Stump4a3999f2009-09-09 13:00:44 +00001142/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1143/// method emits the address of the lvalue, then loads the result as an rvalue,
1144/// returning the rvalue.
John McCall55e1fbc2011-06-25 02:11:03 +00001145RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001146 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001147 // load of a __weak object.
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001148 llvm::Value *AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001149 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1150 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001151 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001152 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1153 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1154 Object = EmitObjCConsumeObject(LV.getType(), Object);
1155 return RValue::get(Object);
1156 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001157
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001158 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001159 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001160
John McCalla1dee5302010-08-22 10:59:02 +00001161 // Everything needs a load.
John McCall55e1fbc2011-06-25 02:11:03 +00001162 return RValue::get(EmitLoadOfScalar(LV));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001163 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001164
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001165 if (LV.isVectorElt()) {
Eli Friedman610bb872012-03-22 22:36:39 +00001166 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1167 LV.isVolatileQualified());
1168 Load->setAlignment(LV.getAlignment().getQuantity());
1169 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001170 "vecext"));
1171 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001172
1173 // If this is a reference to a subset of the elements of a vector, either
1174 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001175 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001176 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001177
John McCallc109a252011-11-07 03:59:57 +00001178 assert(LV.isBitField() && "Unknown LValue type!");
1179 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001180}
1181
John McCall55e1fbc2011-06-25 02:11:03 +00001182RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001183 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001184
Daniel Dunbar3447a022010-04-13 23:34:15 +00001185 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001186 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001187
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001188 llvm::Value *Ptr = LV.getBitFieldAddr();
1189 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),
1190 "bf.load");
1191 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
Mike Stump4a3999f2009-09-09 13:00:44 +00001192
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001193 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001194 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001195 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1196 if (HighBits)
1197 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1198 if (Info.Offset + HighBits)
1199 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1200 } else {
1201 if (Info.Offset)
1202 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001203 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001204 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1205 Info.Size),
1206 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001207 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001208 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001209
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001210 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001211}
1212
Nate Begemanb699c9b2009-01-18 06:42:49 +00001213// If this is a reference to a subset of the elements of a vector, create an
1214// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001215RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
Eli Friedman610bb872012-03-22 22:36:39 +00001216 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1217 LV.isVolatileQualified());
1218 Load->setAlignment(LV.getAlignment().getQuantity());
1219 llvm::Value *Vec = Load;
Mike Stump4a3999f2009-09-09 13:00:44 +00001220
Nate Begemanf322eab2008-05-09 06:41:27 +00001221 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001222
1223 // If the result of the expression is a non-vector type, we must be extracting
1224 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001225 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001226 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001227 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattner5e016ae2010-06-27 07:15:29 +00001228 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001229 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001230 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001231
1232 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001233 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001234
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001235 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001236 for (unsigned i = 0; i != NumResultElts; ++i)
1237 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001238
Chris Lattner91c08ad2011-02-15 00:14:06 +00001239 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1240 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001241 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001242 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001243}
1244
1245
Chris Lattner9369a562007-06-29 16:31:29 +00001246
Chris Lattner8394d792007-06-05 20:53:16 +00001247/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1248/// lvalue, where both are guaranteed to the have the same type, and that type
1249/// is 'Ty'.
David Chisnallfa35df62012-01-16 17:27:18 +00001250void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001251 if (!Dst.isSimple()) {
1252 if (Dst.isVectorElt()) {
1253 // Read/modify/write the vector, inserting the new element.
Eli Friedman610bb872012-03-22 22:36:39 +00001254 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1255 Dst.isVolatileQualified());
1256 Load->setAlignment(Dst.getAlignment().getQuantity());
1257 llvm::Value *Vec = Load;
Chris Lattner4647a212007-08-31 22:49:20 +00001258 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001259 Dst.getVectorIdx(), "vecins");
Eli Friedman610bb872012-03-22 22:36:39 +00001260 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1261 Dst.isVolatileQualified());
1262 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001263 return;
1264 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001265
Nate Begemance4d7fc2008-04-18 23:10:10 +00001266 // If this is an update of extended vector elements, insert them as
1267 // appropriate.
1268 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001269 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001270
John McCallc109a252011-11-07 03:59:57 +00001271 assert(Dst.isBitField() && "Unknown LValue type");
1272 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001273 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001274
John McCall31168b02011-06-15 23:02:42 +00001275 // There's special magic for assigning into an ARC-qualified l-value.
1276 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1277 switch (Lifetime) {
1278 case Qualifiers::OCL_None:
1279 llvm_unreachable("present but none");
1280
1281 case Qualifiers::OCL_ExplicitNone:
1282 // nothing special
1283 break;
1284
1285 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001286 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001287 return;
1288
1289 case Qualifiers::OCL_Weak:
1290 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1291 return;
1292
1293 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001294 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1295 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001296 // fall into the normal path
1297 break;
1298 }
1299 }
1300
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001301 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001302 // load of a __weak object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001303 llvm::Value *LvalueDst = Dst.getAddress();
1304 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001305 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001306 return;
1307 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001308
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001309 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001310 // load of a __strong object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001311 llvm::Value *LvalueDst = Dst.getAddress();
1312 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001313 if (Dst.isObjCIvar()) {
1314 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00001315 llvm::Type *ResultType = ConvertType(getContext().LongTy);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001316 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001317 llvm::Value *dst = RHS;
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001318 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1319 llvm::Value *LHS =
1320 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1321 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001322 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001323 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001324 } else if (Dst.isGlobalObjCRef()) {
1325 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1326 Dst.isThreadLocalRef());
1327 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001328 else
1329 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001330 return;
1331 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001332
Chris Lattner6278e6a2007-08-11 00:04:45 +00001333 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001334 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001335}
1336
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001337void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001338 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001339 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001340 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001341 llvm::Value *Ptr = Dst.getBitFieldAddr();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001342
Daniel Dunbar67aba792010-04-15 03:47:33 +00001343 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001344 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001345
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001346 // Cast the source to the storage type and shift it into place.
1347 SrcVal = Builder.CreateIntCast(SrcVal,
1348 Ptr->getType()->getPointerElementType(),
1349 /*IsSigned=*/false);
1350 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001351
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001352 // See if there are other bits in the bitfield's storage we'll need to load
1353 // and mask together with source before storing.
1354 if (Info.StorageSize != Info.Size) {
1355 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1356 llvm::Value *Val = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
1357 "bf.load");
1358 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1359
1360 // Mask the source value as needed.
1361 if (!hasBooleanRepresentation(Dst.getType()))
1362 SrcVal = Builder.CreateAnd(SrcVal,
1363 llvm::APInt::getLowBitsSet(Info.StorageSize,
1364 Info.Size),
1365 "bf.value");
1366 MaskedVal = SrcVal;
1367 if (Info.Offset)
1368 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1369
1370 // Mask out the original value.
1371 Val = Builder.CreateAnd(Val,
1372 ~llvm::APInt::getBitsSet(Info.StorageSize,
1373 Info.Offset,
1374 Info.Offset + Info.Size),
1375 "bf.clear");
1376
1377 // Or together the unchanged values and the source value.
1378 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1379 } else {
1380 assert(Info.Offset == 0);
1381 }
1382
1383 // Write the new value back out.
1384 llvm::StoreInst *Store = Builder.CreateStore(SrcVal, Ptr,
1385 Dst.isVolatileQualified());
1386 Store->setAlignment(Info.StorageAlignment);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001387
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001388 // Return the new value of the bit-field, if requested.
1389 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001390 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001391
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001392 // Sign extend the value if needed.
1393 if (Info.IsSigned) {
1394 assert(Info.Size <= Info.StorageSize);
1395 unsigned HighBits = Info.StorageSize - Info.Size;
1396 if (HighBits) {
1397 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1398 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1399 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001400 }
1401
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001402 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1403 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001404 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001405 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001406}
1407
Nate Begemance4d7fc2008-04-18 23:10:10 +00001408void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001409 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001410 // This access turns into a read/modify/write of the vector. Load the input
1411 // value now.
Eli Friedman610bb872012-03-22 22:36:39 +00001412 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1413 Dst.isVolatileQualified());
1414 Load->setAlignment(Dst.getAlignment().getQuantity());
1415 llvm::Value *Vec = Load;
Nate Begemanf322eab2008-05-09 06:41:27 +00001416 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001417
Chris Lattner4647a212007-08-31 22:49:20 +00001418 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001419
John McCall55e1fbc2011-06-25 02:11:03 +00001420 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001421 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001422 unsigned NumDstElts =
1423 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1424 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001425 // Use shuffle vector is the src and destination are the same number of
1426 // elements and restore the vector mask since it is on the side it will be
1427 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001428 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001429 for (unsigned i = 0; i != NumSrcElts; ++i)
1430 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001431
Chris Lattner91c08ad2011-02-15 00:14:06 +00001432 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001433 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001434 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001435 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001436 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001437 // Extended the source vector to the same length and then shuffle it
1438 // into the destination.
1439 // FIXME: since we're shuffling with undef, can we just use the indices
1440 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001441 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001442 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001443 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001444 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001445 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001446 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001447 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001448 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001449 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001450 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001451 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001452 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001453 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001454
Nate Begemanb699c9b2009-01-18 06:42:49 +00001455 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001456 for (unsigned i = 0; i != NumSrcElts; ++i)
1457 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001458 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001459 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001460 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001461 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001462 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001463 }
1464 } else {
1465 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001466 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001467 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001468 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001469 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001470
Eli Friedman610bb872012-03-22 22:36:39 +00001471 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1472 Dst.isVolatileQualified());
1473 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001474}
1475
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001476// setObjCGCLValueClass - sets class of he lvalue for the purpose of
1477// generating write-barries API. It is currently a global, ivar,
1478// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001479static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001480 LValue &LV,
1481 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001482 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001483 return;
1484
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001485 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001486 QualType ExpTy = E->getType();
1487 if (IsMemberAccess && ExpTy->isPointerType()) {
1488 // If ivar is a structure pointer, assigning to field of
1489 // this struct follows gcc's behavior and makes it a non-ivar
1490 // writer-barrier conservatively.
1491 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1492 if (ExpTy->isRecordType()) {
1493 LV.setObjCIvar(false);
1494 return;
1495 }
1496 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001497 LV.setObjCIvar(true);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001498 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1499 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001500 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001501 return;
1502 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001503
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001504 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1505 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001506 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001507 LV.setGlobalObjCRef(true);
1508 LV.setThreadLocalRef(VD->isThreadSpecified());
Fariborz Jahanian217af242010-07-20 20:30:03 +00001509 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001510 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001511 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001512 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001513 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001514
1515 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001516 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001517 return;
1518 }
1519
1520 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001521 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001522 if (LV.isObjCIvar()) {
1523 // If cast is to a structure pointer, follow gcc's behavior and make it
1524 // a non-ivar write-barrier.
1525 QualType ExpTy = E->getType();
1526 if (ExpTy->isPointerType())
1527 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1528 if (ExpTy->isRecordType())
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001529 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001530 }
1531 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001532 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001533
1534 if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1535 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1536 return;
1537 }
1538
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001539 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001540 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001541 return;
1542 }
1543
1544 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001545 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001546 return;
1547 }
John McCall31168b02011-06-15 23:02:42 +00001548
1549 if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001550 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001551 return;
1552 }
1553
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001554 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001555 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001556 if (LV.isObjCIvar() && !LV.isObjCArray())
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001557 // Using array syntax to assigning to what an ivar points to is not
1558 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001559 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001560 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1561 // Using array syntax to assigning to what global points to is not
1562 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001563 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001564 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001565 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001566
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001567 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001568 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001569 // We don't know if member is an 'ivar', but this flag is looked at
1570 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001571 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001572 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001573 }
1574}
1575
Chris Lattner3f32d692011-07-12 06:52:18 +00001576static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001577EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001578 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001579 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001580 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001581 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001582}
1583
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001584static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1585 const Expr *E, const VarDecl *VD) {
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001586 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001587 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1588 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001589 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001590 QualType T = E->getType();
1591 LValue LV;
1592 if (VD->getType()->isReferenceType()) {
1593 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001594 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001595 V = LI;
1596 LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1597 } else {
1598 LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1599 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001600 setObjCGCLValueClass(CGF.getContext(), E, LV);
1601 return LV;
1602}
1603
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001604static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001605 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001606 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001607 if (!FD->hasPrototype()) {
1608 if (const FunctionProtoType *Proto =
1609 FD->getType()->getAs<FunctionProtoType>()) {
1610 // Ugly case: for a K&R-style definition, the type of the definition
1611 // isn't the same as the type of a use. Correct for this with a
1612 // bitcast.
1613 QualType NoProtoType =
1614 CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1615 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001616 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001617 }
1618 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001619 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Daniel Dunbar5c816372010-08-21 04:20:22 +00001620 return CGF.MakeAddrLValue(V, E->getType(), Alignment);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001621}
1622
Chris Lattnerd7f58862007-06-02 05:24:33 +00001623LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001624 const NamedDecl *ND = E->getDecl();
Eli Friedmana0544d62011-12-03 04:14:32 +00001625 CharUnits Alignment = getContext().getDeclAlign(ND);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001626 QualType T = E->getType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001627
Richard Smith5a1104b2012-10-20 01:38:33 +00001628 // A DeclRefExpr for a reference initialized by a constant expression can
1629 // appear without being odr-used. Directly emit the constant initializer.
1630 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1631 const Expr *Init = VD->getAnyInitializer(VD);
1632 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
1633 VD->isUsableInConstantExpressions(getContext()) &&
1634 VD->checkInitIsICE()) {
1635 llvm::Constant *Val =
1636 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
1637 assert(Val && "failed to emit reference constant expression");
1638 // FIXME: Eventually we will want to emit vector element references.
1639 return MakeAddrLValue(Val, T, Alignment);
1640 }
1641 }
1642
Eli Friedman5720e342012-01-21 04:52:58 +00001643 // FIXME: We should be able to assert this for FunctionDecls as well!
1644 // FIXME: We should be able to assert this for all DeclRefExprs, not just
1645 // those with a valid source location.
1646 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1647 !E->getLocation().isValid()) &&
1648 "Should not use decl without marking it used!");
1649
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001650 if (ND->hasAttr<WeakRefAttr>()) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001651 const ValueDecl *VD = cast<ValueDecl>(ND);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001652 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
Richard Smith5a1104b2012-10-20 01:38:33 +00001653 return MakeAddrLValue(Aliasee, T, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001654 }
1655
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001656 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001657 // Check if this is a global variable.
Nick Lewycky230203c2013-01-10 01:46:29 +00001658 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001659 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00001660
John McCall113bee02012-03-10 09:33:50 +00001661 bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1662
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001663 bool NonGCable = VD->hasLocalStorage() &&
1664 !VD->getType()->isReferenceType() &&
John McCall113bee02012-03-10 09:33:50 +00001665 !isBlockVariable;
Anders Carlsson6eee9722009-11-07 22:46:42 +00001666
Nick Lewycky230203c2013-01-10 01:46:29 +00001667 llvm::Value *V = LocalDeclMap.lookup(VD);
Fariborz Jahanian366a9482010-09-07 23:26:17 +00001668 if (!V && VD->isStaticLocal())
Fariborz Jahanian4d55b2d2010-04-19 18:15:02 +00001669 V = CGM.getStaticLocalDeclAddress(VD);
Eli Friedman9fbeba02012-02-11 02:57:39 +00001670
1671 // Use special handling for lambdas.
John McCall113bee02012-03-10 09:33:50 +00001672 if (!V) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00001673 if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1674 QualType LambdaTagType = getContext().getTagDeclType(FD->getParent());
1675 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
1676 LambdaTagType);
1677 return EmitLValueForField(LambdaLV, FD);
1678 }
Eli Friedman9fbeba02012-02-11 02:57:39 +00001679
John McCall113bee02012-03-10 09:33:50 +00001680 assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
John McCall113bee02012-03-10 09:33:50 +00001681 return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
Richard Smith5a1104b2012-10-20 01:38:33 +00001682 T, Alignment);
John McCall113bee02012-03-10 09:33:50 +00001683 }
1684
Anders Carlsson6eee9722009-11-07 22:46:42 +00001685 assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1686
John McCall113bee02012-03-10 09:33:50 +00001687 if (isBlockVariable)
Fariborz Jahanian2f2fa722011-01-26 23:08:27 +00001688 V = BuildBlockByrefAddress(V, VD);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001689
Eli Friedmand20adbd2011-11-16 00:42:57 +00001690 LValue LV;
1691 if (VD->getType()->isReferenceType()) {
1692 llvm::LoadInst *LI = Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001693 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001694 V = LI;
1695 LV = MakeNaturalAlignAddrLValue(V, T);
1696 } else {
1697 LV = MakeAddrLValue(V, T, Alignment);
1698 }
Chris Lattner3f32d692011-07-12 06:52:18 +00001699
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001700 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00001701 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00001702 LV.setNonGC(true);
1703 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001704 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00001705 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001706 }
John McCallf3a88602011-02-03 08:15:49 +00001707
1708 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1709 return EmitFunctionDeclLValue(*this, E, fn);
1710
David Blaikie83d382b2011-09-23 05:06:16 +00001711 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001712}
Chris Lattnere47e4402007-06-01 18:02:12 +00001713
Chris Lattner8394d792007-06-05 20:53:16 +00001714LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1715 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00001716 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00001717 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001718
Chris Lattner0f398c42008-07-26 22:37:01 +00001719 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00001720 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001721 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00001722 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001723 QualType T = E->getSubExpr()->getType()->getPointeeType();
1724 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00001725
Chris Lattner2415357a2011-12-19 21:16:08 +00001726 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001727 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00001728
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001729 // We should not generate __weak write barrier on indirect reference
1730 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1731 // But, we continue to generate __strong write barrier on indirect write
1732 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00001733 if (getLangOpts().ObjC1 &&
1734 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001735 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00001736 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001737 return LV;
1738 }
John McCalle3027922010-08-25 11:45:40 +00001739 case UO_Real:
1740 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00001741 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00001742 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1743 llvm::Value *Addr = LV.getAddress();
1744
Richard Smith0b6b8e42012-02-18 20:53:32 +00001745 // __real is valid on scalars. This is a faster way of testing that.
1746 // __imag can only produce an rvalue on scalars.
1747 if (E->getOpcode() == UO_Real &&
1748 !cast<llvm::PointerType>(Addr->getType())
John McCalla2342eb2010-12-05 02:00:02 +00001749 ->getElementType()->isStructTy()) {
1750 assert(E->getSubExpr()->getType()->isArithmeticType());
1751 return LV;
1752 }
1753
1754 assert(E->getSubExpr()->getType()->isAnyComplexType());
1755
John McCalle3027922010-08-25 11:45:40 +00001756 unsigned Idx = E->getOpcode() == UO_Imag;
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001757 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
John McCalla2342eb2010-12-05 02:00:02 +00001758 Idx, "idx"),
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001759 ExprTy);
Chris Lattner595db862007-10-30 22:53:42 +00001760 }
John McCalle3027922010-08-25 11:45:40 +00001761 case UO_PreInc:
1762 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001763 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00001764 bool isInc = E->getOpcode() == UO_PreInc;
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001765
1766 if (E->getType()->isAnyComplexType())
1767 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1768 else
1769 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1770 return LV;
1771 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00001772 }
Chris Lattner8394d792007-06-05 20:53:16 +00001773}
1774
Chris Lattner4347e3692007-06-06 04:54:52 +00001775LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001776 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1777 E->getType());
Chris Lattner4347e3692007-06-06 04:54:52 +00001778}
1779
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001780LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001781 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1782 E->getType());
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001783}
1784
Nico Weber3a691a32012-06-23 02:07:59 +00001785static llvm::Constant*
1786GetAddrOfConstantWideString(StringRef Str,
1787 const char *GlobalName,
1788 ASTContext &Context,
1789 QualType Ty, SourceLocation Loc,
1790 CodeGenModule &CGM) {
1791
1792 StringLiteral *SL = StringLiteral::Create(Context,
1793 Str,
1794 StringLiteral::Wide,
1795 /*Pascal = */false,
1796 Ty, Loc);
1797 llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL);
1798 llvm::GlobalVariable *GV =
1799 new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1800 !CGM.getLangOpts().WritableStrings,
1801 llvm::GlobalValue::PrivateLinkage,
1802 C, GlobalName);
1803 const unsigned WideAlignment =
1804 Context.getTypeAlignInChars(Ty).getQuantity();
1805 GV->setAlignment(WideAlignment);
1806 return GV;
1807}
1808
Nico Weber3a691a32012-06-23 02:07:59 +00001809static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
1810 SmallString<32>& Target) {
1811 Target.resize(CharByteWidth * (Source.size() + 1));
Richard Smith639b8d02012-09-08 07:16:20 +00001812 char *ResultPtr = &Target[0];
1813 const UTF8 *ErrorPtr;
1814 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
Matt Beaumont-Gay36af16af2012-07-03 03:55:58 +00001815 (void)success;
Nico Weber4b18c3f2012-07-03 02:24:52 +00001816 assert(success);
Nico Weber3a691a32012-06-23 02:07:59 +00001817 Target.resize(ResultPtr - &Target[0]);
1818}
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001819
Mike Stump4a3999f2009-09-09 13:00:44 +00001820LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Daniel Dunbarb3517472008-10-17 21:58:32 +00001821 switch (E->getIdentType()) {
1822 default:
1823 return EmitUnsupportedLValue(E, "predefined expression");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001824
Daniel Dunbarb3517472008-10-17 21:58:32 +00001825 case PredefinedExpr::Func:
1826 case PredefinedExpr::Function:
Nico Weber3a691a32012-06-23 02:07:59 +00001827 case PredefinedExpr::LFunction:
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001828 case PredefinedExpr::PrettyFunction: {
Nico Weber3a691a32012-06-23 02:07:59 +00001829 unsigned IdentType = E->getIdentType();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001830 std::string GlobalVarName;
1831
Nico Weber3a691a32012-06-23 02:07:59 +00001832 switch (IdentType) {
David Blaikie83d382b2011-09-23 05:06:16 +00001833 default: llvm_unreachable("Invalid type");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001834 case PredefinedExpr::Func:
1835 GlobalVarName = "__func__.";
1836 break;
1837 case PredefinedExpr::Function:
1838 GlobalVarName = "__FUNCTION__.";
1839 break;
Nico Weber3a691a32012-06-23 02:07:59 +00001840 case PredefinedExpr::LFunction:
1841 GlobalVarName = "L__FUNCTION__.";
1842 break;
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001843 case PredefinedExpr::PrettyFunction:
1844 GlobalVarName = "__PRETTY_FUNCTION__.";
1845 break;
1846 }
1847
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001848 StringRef FnName = CurFn->getName();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001849 if (FnName.startswith("\01"))
1850 FnName = FnName.substr(1);
1851 GlobalVarName += FnName;
1852
1853 const Decl *CurDecl = CurCodeDecl;
1854 if (CurDecl == 0)
1855 CurDecl = getContext().getTranslationUnitDecl();
1856
1857 std::string FunctionName =
John McCall351762c2011-02-07 10:33:21 +00001858 (isa<BlockDecl>(CurDecl)
1859 ? FnName.str()
Nico Weber3a691a32012-06-23 02:07:59 +00001860 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType,
1861 CurDecl));
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001862
Nico Weber3a691a32012-06-23 02:07:59 +00001863 const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual();
1864 llvm::Constant *C;
1865 if (ElemType->isWideCharType()) {
1866 SmallString<32> RawChars;
1867 ConvertUTF8ToWideString(
1868 getContext().getTypeSizeInChars(ElemType).getQuantity(),
1869 FunctionName, RawChars);
1870 C = GetAddrOfConstantWideString(RawChars,
1871 GlobalVarName.c_str(),
1872 getContext(),
1873 E->getType(),
1874 E->getLocation(),
1875 CGM);
1876 } else {
1877 C = CGM.GetAddrOfConstantCString(FunctionName,
1878 GlobalVarName.c_str(),
1879 1);
1880 }
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001881 return MakeAddrLValue(C, E->getType());
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001882 }
Daniel Dunbarb3517472008-10-17 21:58:32 +00001883 }
Anders Carlsson625bfc82007-07-21 05:21:51 +00001884}
1885
Richard Smithe30752c2012-10-09 19:52:38 +00001886/// Emit a type description suitable for use by a runtime sanitizer library. The
1887/// format of a type descriptor is
1888///
1889/// \code
Richard Smith683398a2012-10-09 23:55:19 +00001890/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00001891/// \endcode
1892///
Richard Smith683398a2012-10-09 23:55:19 +00001893/// followed by an array of i8 containing the type name. TypeKind is 0 for an
1894/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00001895llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
1896 // FIXME: Only emit each type's descriptor once.
1897 uint16_t TypeKind = -1;
1898 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00001899
Richard Smithe30752c2012-10-09 19:52:38 +00001900 if (T->isIntegerType()) {
1901 TypeKind = 0;
1902 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00001903 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00001904 } else if (T->isFloatingType()) {
1905 TypeKind = 1;
1906 TypeInfo = getContext().getTypeSize(T);
1907 }
1908
1909 // Format the type name as if for a diagnostic, including quotes and
1910 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001911 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00001912 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
1913 (intptr_t)T.getAsOpaquePtr(),
1914 0, 0, 0, 0, 0, 0, Buffer,
1915 ArrayRef<intptr_t>());
1916
1917 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00001918 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
1919 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00001920 };
1921 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
1922
1923 llvm::GlobalVariable *GV =
1924 new llvm::GlobalVariable(CGM.getModule(), Descriptor->getType(),
1925 /*isConstant=*/true,
1926 llvm::GlobalVariable::PrivateLinkage,
1927 Descriptor);
1928 GV->setUnnamedAddr(true);
1929 return GV;
1930}
1931
1932llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
1933 llvm::Type *TargetTy = IntPtrTy;
1934
1935 // Integers which fit in intptr_t are zero-extended and passed directly.
1936 if (V->getType()->isIntegerTy() &&
1937 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
1938 return Builder.CreateZExt(V, TargetTy);
1939
1940 // Pointers are passed directly, everything else is passed by address.
1941 if (!V->getType()->isPointerTy()) {
1942 llvm::Value *Ptr = Builder.CreateAlloca(V->getType());
1943 Builder.CreateStore(V, Ptr);
1944 V = Ptr;
1945 }
1946 return Builder.CreatePtrToInt(V, TargetTy);
1947}
1948
1949/// \brief Emit a representation of a SourceLocation for passing to a handler
1950/// in a sanitizer runtime library. The format for this data is:
1951/// \code
1952/// struct SourceLocation {
1953/// const char *Filename;
1954/// int32_t Line, Column;
1955/// };
1956/// \endcode
1957/// For an invalid SourceLocation, the Filename pointer is null.
1958llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
1959 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
1960
1961 llvm::Constant *Data[] = {
1962 // FIXME: Only emit each file name once.
1963 PLoc.isValid() ? cast<llvm::Constant>(
1964 Builder.CreateGlobalStringPtr(PLoc.getFilename()))
1965 : llvm::Constant::getNullValue(Int8PtrTy),
1966 Builder.getInt32(PLoc.getLine()),
1967 Builder.getInt32(PLoc.getColumn())
1968 };
1969
1970 return llvm::ConstantStruct::getAnon(Data);
1971}
1972
1973void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001974 ArrayRef<llvm::Constant *> StaticArgs,
1975 ArrayRef<llvm::Value *> DynamicArgs,
Will Dietz88e02332012-12-02 19:50:33 +00001976 CheckRecoverableKind RecoverKind) {
Will Dietzf54319c2013-01-18 11:30:38 +00001977 assert(SanOpts != &SanitizerOptions::Disabled);
Chad Rosierae229d52013-01-29 23:31:22 +00001978
1979 if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) {
1980 assert (RecoverKind != CRK_AlwaysRecoverable &&
1981 "Runtime call required for AlwaysRecoverable kind!");
1982 return EmitTrapCheck(Checked);
1983 }
1984
Richard Smith4d1458e2012-09-08 02:08:36 +00001985 llvm::BasicBlock *Cont = createBasicBlock("cont");
1986
Richard Smithe30752c2012-10-09 19:52:38 +00001987 llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
Will Dietzddd282a2012-12-15 01:39:14 +00001988
1989 llvm::Instruction *Branch = Builder.CreateCondBr(Checked, Cont, Handler);
1990
1991 // Give hint that we very much don't expect to execute the handler
1992 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
1993 llvm::MDBuilder MDHelper(getLLVMContext());
1994 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
1995 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
1996
Richard Smithe30752c2012-10-09 19:52:38 +00001997 EmitBlock(Handler);
1998
1999 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2000 llvm::GlobalValue *InfoPtr =
Will Dietz450f1a12013-01-09 03:39:41 +00002001 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
Richard Smithe30752c2012-10-09 19:52:38 +00002002 llvm::GlobalVariable::PrivateLinkage, Info);
2003 InfoPtr->setUnnamedAddr(true);
2004
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002005 SmallVector<llvm::Value *, 4> Args;
2006 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002007 Args.reserve(DynamicArgs.size() + 1);
2008 ArgTypes.reserve(DynamicArgs.size() + 1);
2009
2010 // Handler functions take an i8* pointing to the (handler-specific) static
2011 // information block, followed by a sequence of intptr_t arguments
2012 // representing operand values.
2013 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2014 ArgTypes.push_back(Int8PtrTy);
2015 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2016 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2017 ArgTypes.push_back(IntPtrTy);
2018 }
2019
Will Dietz88e02332012-12-02 19:50:33 +00002020 bool Recover = (RecoverKind == CRK_AlwaysRecoverable) ||
2021 ((RecoverKind == CRK_Recoverable) &&
2022 CGM.getCodeGenOpts().SanitizeRecover);
2023
Richard Smithe30752c2012-10-09 19:52:38 +00002024 llvm::FunctionType *FnType =
2025 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Bill Wendlinga514ebc2012-10-15 20:36:26 +00002026 llvm::AttrBuilder B;
Will Dietz88e02332012-12-02 19:50:33 +00002027 if (!Recover) {
Bill Wendling207f0532012-12-20 19:27:06 +00002028 B.addAttribute(llvm::Attribute::NoReturn)
2029 .addAttribute(llvm::Attribute::NoUnwind);
Richard Smith4d3110a2012-10-25 02:14:12 +00002030 }
Bill Wendling207f0532012-12-20 19:27:06 +00002031 B.addAttribute(llvm::Attribute::UWTable);
Will Dietz88e02332012-12-02 19:50:33 +00002032
2033 // Checks that have two variants use a suffix to differentiate them
2034 bool NeedsAbortSuffix = (RecoverKind != CRK_Unrecoverable) &&
2035 !CGM.getCodeGenOpts().SanitizeRecover;
Richard Smith78f6b032012-12-03 22:39:14 +00002036 std::string FunctionName = ("__ubsan_handle_" + CheckName +
2037 (NeedsAbortSuffix? "_abort" : "")).str();
2038 llvm::Value *Fn =
2039 CGM.CreateRuntimeFunction(FnType, FunctionName,
Bill Wendling207f0532012-12-20 19:27:06 +00002040 llvm::Attribute::get(getLLVMContext(), B));
Richard Smithe30752c2012-10-09 19:52:38 +00002041 llvm::CallInst *HandlerCall = Builder.CreateCall(Fn, Args);
Will Dietz88e02332012-12-02 19:50:33 +00002042 if (Recover) {
Richard Smith4d3110a2012-10-25 02:14:12 +00002043 Builder.CreateBr(Cont);
2044 } else {
2045 HandlerCall->setDoesNotReturn();
2046 HandlerCall->setDoesNotThrow();
2047 Builder.CreateUnreachable();
2048 }
Richard Smithe30752c2012-10-09 19:52:38 +00002049
Richard Smith4d1458e2012-09-08 02:08:36 +00002050 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002051}
2052
Chad Rosierae229d52013-01-29 23:31:22 +00002053void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002054 llvm::BasicBlock *Cont = createBasicBlock("cont");
2055
2056 // If we're optimizing, collapse all calls to trap down to just one per
2057 // function to save on code size.
2058 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2059 TrapBB = createBasicBlock("trap");
2060 Builder.CreateCondBr(Checked, Cont, TrapBB);
2061 EmitBlock(TrapBB);
2062 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
2063 llvm::CallInst *TrapCall = Builder.CreateCall(F);
2064 TrapCall->setDoesNotReturn();
2065 TrapCall->setDoesNotThrow();
2066 Builder.CreateUnreachable();
2067 } else {
2068 Builder.CreateCondBr(Checked, Cont, TrapBB);
2069 }
2070
2071 EmitBlock(Cont);
2072}
2073
Chris Lattner6c5abe82010-06-26 23:03:20 +00002074/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2075/// array to pointer, return the array subexpression.
2076static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2077 // If this isn't just an array->pointer decay, bail out.
2078 const CastExpr *CE = dyn_cast<CastExpr>(E);
John McCalle3027922010-08-25 11:45:40 +00002079 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
Chris Lattner6c5abe82010-06-26 23:03:20 +00002080 return 0;
2081
2082 // If this is a decay from variable width array, bail out.
2083 const Expr *SubExpr = CE->getSubExpr();
2084 if (SubExpr->getType()->isVariableArrayType())
2085 return 0;
2086
2087 return SubExpr;
2088}
2089
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002090LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002091 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002092 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002093 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002094 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002095
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002096 // If the base is a vector type, then we are forming a vector element lvalue
2097 // with this subscript.
Eli Friedman327944b2008-06-13 23:01:12 +00002098 if (E->getBase()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002099 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002100 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002101 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
John McCallad7c5c12011-02-08 08:22:06 +00002102 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
Eli Friedman327944b2008-06-13 23:01:12 +00002103 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
Eli Friedman610bb872012-03-22 22:36:39 +00002104 E->getBase()->getType(), LHS.getAlignment());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002105 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002106
Ted Kremenekc81614d2007-08-20 16:18:38 +00002107 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002108 if (Idx->getType() != IntPtrTy)
2109 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002110
Mike Stump4a3999f2009-09-09 13:00:44 +00002111 // We know that the pointer points to a type of the correct size, unless the
2112 // size is a VLA or Objective-C interface.
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002113 llvm::Value *Address = 0;
Eli Friedmana0544d62011-12-03 04:14:32 +00002114 CharUnits ArrayAlignment;
John McCall23c29fe2011-06-24 21:55:10 +00002115 if (const VariableArrayType *vla =
Anders Carlsson3d312f82008-12-21 00:11:23 +00002116 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002117 // The base must be a pointer, which is not an aggregate. Emit
2118 // it. It needs to be emitted first in case it's what captures
2119 // the VLA bounds.
2120 Address = EmitScalarExpr(E->getBase());
Mike Stump4a3999f2009-09-09 13:00:44 +00002121
John McCall23c29fe2011-06-24 21:55:10 +00002122 // The element count here is the total number of non-VLA elements.
2123 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002124
John McCall77527a82011-06-25 01:32:37 +00002125 // Effectively, the multiply by the VLA size is part of the GEP.
2126 // GEP indexes are signed, and scaling an index isn't permitted to
2127 // signed-overflow, so we use the same semantics for our explicit
2128 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002129 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002130 Idx = Builder.CreateMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00002131 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00002132 } else {
2133 Idx = Builder.CreateNSWMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00002134 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00002135 }
Chris Lattner6c5abe82010-06-26 23:03:20 +00002136 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2137 // Indexing over an interface, as in "NSString *P; P[4];"
Mike Stump4a3999f2009-09-09 13:00:44 +00002138 llvm::Value *InterfaceSize =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002139 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck40775002010-01-11 17:06:35 +00002140 getContext().getTypeSizeInChars(OIT).getQuantity());
Mike Stump4a3999f2009-09-09 13:00:44 +00002141
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002142 Idx = Builder.CreateMul(Idx, InterfaceSize);
2143
Chris Lattner6c5abe82010-06-26 23:03:20 +00002144 // The base must be a pointer, which is not an aggregate. Emit it.
2145 llvm::Value *Base = EmitScalarExpr(E->getBase());
John McCallad7c5c12011-02-08 08:22:06 +00002146 Address = EmitCastToVoidPtr(Base);
2147 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002148 Address = Builder.CreateBitCast(Address, Base->getType());
Chris Lattner6c5abe82010-06-26 23:03:20 +00002149 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2150 // If this is A[i] where A is an array, the frontend will have decayed the
2151 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2152 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2153 // "gep x, i" here. Emit one "gep A, 0, i".
2154 assert(Array->getType()->isArrayType() &&
2155 "Array to pointer decay must have array source type!");
Daniel Dunbar82634272011-04-01 00:49:43 +00002156 LValue ArrayLV = EmitLValue(Array);
2157 llvm::Value *ArrayPtr = ArrayLV.getAddress();
Chris Lattner6c5abe82010-06-26 23:03:20 +00002158 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2159 llvm::Value *Args[] = { Zero, Idx };
2160
Daniel Dunbar82634272011-04-01 00:49:43 +00002161 // Propagate the alignment from the array itself to the result.
2162 ArrayAlignment = ArrayLV.getAlignment();
2163
Richard Smith9c6890a2012-11-01 22:30:59 +00002164 if (getLangOpts().isSignedOverflowDefined())
Jay Foad040dd822011-07-22 08:16:57 +00002165 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Chris Lattner2e72da942011-03-01 00:03:48 +00002166 else
Jay Foad040dd822011-07-22 08:16:57 +00002167 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002168 } else {
Chris Lattner6c5abe82010-06-26 23:03:20 +00002169 // The base must be a pointer, which is not an aggregate. Emit it.
2170 llvm::Value *Base = EmitScalarExpr(E->getBase());
Richard Smith9c6890a2012-11-01 22:30:59 +00002171 if (getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002172 Address = Builder.CreateGEP(Base, Idx, "arrayidx");
2173 else
2174 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
Anders Carlsson3d312f82008-12-21 00:11:23 +00002175 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002176
Steve Naroff7cae42b2009-07-10 23:34:53 +00002177 QualType T = E->getBase()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00002178 assert(!T.isNull() &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00002179 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002180
Chris Lattner36bc4f42012-01-04 22:35:55 +00002181
Daniel Dunbar82634272011-04-01 00:49:43 +00002182 // Limit the alignment to that of the result type.
Chris Lattner36bc4f42012-01-04 22:35:55 +00002183 LValue LV;
Eli Friedmana0544d62011-12-03 04:14:32 +00002184 if (!ArrayAlignment.isZero()) {
2185 CharUnits Align = getContext().getTypeAlignInChars(T);
Daniel Dunbar82634272011-04-01 00:49:43 +00002186 ArrayAlignment = std::min(Align, ArrayAlignment);
Chris Lattner36bc4f42012-01-04 22:35:55 +00002187 LV = MakeAddrLValue(Address, T, ArrayAlignment);
2188 } else {
2189 LV = MakeNaturalAlignAddrLValue(Address, T);
Daniel Dunbar82634272011-04-01 00:49:43 +00002190 }
2191
Daniel Dunbarf166a522010-08-21 03:44:13 +00002192 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002193
Richard Smith9c6890a2012-11-01 22:30:59 +00002194 if (getLangOpts().ObjC1 &&
2195 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002196 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002197 setObjCGCLValueClass(getContext(), E, LV);
2198 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002199 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002200}
2201
Mike Stump4a3999f2009-09-09 13:00:44 +00002202static
NAKAMURA Takumiccca11a2012-01-25 08:58:21 +00002203llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002204 SmallVector<unsigned, 4> &Elts) {
2205 SmallVector<llvm::Constant*, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002206 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002207 CElts.push_back(Builder.getInt32(Elts[i]));
Nate Begemand3862152008-05-13 21:03:02 +00002208
Chris Lattner91c08ad2011-02-15 00:14:06 +00002209 return llvm::ConstantVector::get(CElts);
Nate Begemand3862152008-05-13 21:03:02 +00002210}
2211
Chris Lattner9e751ca2007-08-02 23:37:31 +00002212LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002213EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002214 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002215 LValue Base;
2216
2217 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002218 if (E->isArrow()) {
2219 // If it is a pointer to a vector, emit the address and form an lvalue with
2220 // it.
Chris Lattnerb8211f62009-02-16 22:14:05 +00002221 llvm::Value *Ptr = EmitScalarExpr(E->getBase());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002222 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Daniel Dunbarf166a522010-08-21 03:44:13 +00002223 Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2224 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002225 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002226 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2227 // emit the base as an lvalue.
2228 assert(E->getBase()->getType()->isVectorType());
2229 Base = EmitLValue(E->getBase());
2230 } else {
2231 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002232 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002233 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002234 llvm::Value *Vec = EmitScalarExpr(E->getBase());
2235
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002236 // Store the vector to memory (because LValue wants an address).
Daniel Dunbara7566f12010-02-09 02:48:28 +00002237 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002238 Builder.CreateStore(Vec, VecMem);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002239 Base = MakeAddrLValue(VecMem, E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002240 }
John McCall1553b192011-06-16 04:16:24 +00002241
2242 QualType type =
2243 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002244
Nate Begemand3862152008-05-13 21:03:02 +00002245 // Encode the element access list into a vector of unsigned indices.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002246 SmallVector<unsigned, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002247 E->getEncodedElementAccess(Indices);
2248
2249 if (Base.isSimple()) {
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002250 llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002251 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2252 Base.getAlignment());
Nate Begemand3862152008-05-13 21:03:02 +00002253 }
2254 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2255
2256 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002257 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002258
Chris Lattner595ba3a2012-01-30 06:20:36 +00002259 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2260 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002261 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
Eli Friedman610bb872012-03-22 22:36:39 +00002262 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2263 Base.getAlignment());
Chris Lattner9e751ca2007-08-02 23:37:31 +00002264}
2265
Devang Patel30efa2e2007-10-23 20:28:39 +00002266LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00002267 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00002268
Chris Lattner4e4186b2007-12-02 18:52:07 +00002269 // 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 +00002270 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00002271 if (E->isArrow()) {
2272 llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
2273 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Richard Smithe30752c2012-10-09 19:52:38 +00002274 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +00002275 BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
2276 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00002277 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00002278
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002279 NamedDecl *ND = E->getMemberDecl();
2280 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002281 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002282 setObjCGCLValueClass(getContext(), E, LV);
2283 return LV;
2284 }
2285
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00002286 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
2287 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002288
2289 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
2290 return EmitFunctionDeclLValue(*this, E, FD);
2291
David Blaikie83d382b2011-09-23 05:06:16 +00002292 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00002293}
Devang Patel30efa2e2007-10-23 20:28:39 +00002294
Eli Friedman7f1ff602012-04-16 03:54:45 +00002295LValue CodeGenFunction::EmitLValueForField(LValue base,
2296 const FieldDecl *field) {
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002297 if (field->isBitField()) {
2298 const CGRecordLayout &RL =
2299 CGM.getTypes().getCGRecordLayout(field->getParent());
2300 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002301 llvm::Value *Addr = base.getAddress();
2302 unsigned Idx = RL.getLLVMFieldNo(field);
2303 if (Idx != 0)
2304 // For structs, we GEP to the field that the record layout suggests.
2305 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
2306 // Get the access type.
2307 llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
2308 getLLVMContext(), Info.StorageSize,
2309 CGM.getContext().getTargetAddressSpace(base.getType()));
2310 if (Addr->getType() != PtrTy)
2311 Addr = Builder.CreateBitCast(Addr, PtrTy);
2312
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002313 QualType fieldType =
2314 field->getType().withCVRQualifiers(base.getVRQualifiers());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002315 return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002316 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002317
John McCall53fcbd22011-02-26 08:07:02 +00002318 const RecordDecl *rec = field->getParent();
2319 QualType type = field->getType();
Eli Friedmana0544d62011-12-03 04:14:32 +00002320 CharUnits alignment = getContext().getDeclAlign(field);
Eli Friedman133e8042008-05-29 11:33:25 +00002321
Eli Friedman7f1ff602012-04-16 03:54:45 +00002322 // FIXME: It should be impossible to have an LValue without alignment for a
2323 // complete type.
2324 if (!base.getAlignment().isZero())
2325 alignment = std::min(alignment, base.getAlignment());
2326
John McCall53fcbd22011-02-26 08:07:02 +00002327 bool mayAlias = rec->hasAttr<MayAliasAttr>();
2328
Eli Friedman7f1ff602012-04-16 03:54:45 +00002329 llvm::Value *addr = base.getAddress();
2330 unsigned cvr = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00002331 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00002332 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00002333 assert(!type->isReferenceType() && "union has reference member");
John McCall53fcbd22011-02-26 08:07:02 +00002334 } else {
2335 // For structs, we GEP to the field that the record layout suggests.
2336 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
Chris Lattner13ee4f42011-07-10 05:34:54 +00002337 addr = Builder.CreateStructGEP(addr, idx, field->getName());
John McCall53fcbd22011-02-26 08:07:02 +00002338
2339 // If this is a reference field, load the reference right now.
2340 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2341 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2342 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
Eli Friedmana0544d62011-12-03 04:14:32 +00002343 load->setAlignment(alignment.getQuantity());
John McCall53fcbd22011-02-26 08:07:02 +00002344
2345 if (CGM.shouldUseTBAA()) {
2346 llvm::MDNode *tbaa;
2347 if (mayAlias)
2348 tbaa = CGM.getTBAAInfo(getContext().CharTy);
2349 else
2350 tbaa = CGM.getTBAAInfo(type);
2351 CGM.DecorateInstruction(load, tbaa);
2352 }
2353
2354 addr = load;
2355 mayAlias = false;
2356 type = refType->getPointeeType();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002357 if (type->isIncompleteType())
Eli Friedmana0544d62011-12-03 04:14:32 +00002358 alignment = CharUnits();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002359 else
Eli Friedmana0544d62011-12-03 04:14:32 +00002360 alignment = getContext().getTypeAlignInChars(type);
John McCall53fcbd22011-02-26 08:07:02 +00002361 cvr = 0; // qualifiers don't recursively apply to referencee
2362 }
Devang Pateled93c3c2007-10-26 19:42:18 +00002363 }
Chris Lattner13ee4f42011-07-10 05:34:54 +00002364
2365 // Make sure that the address is pointing to the right type. This is critical
2366 // for both unions and structs. A union needs a bitcast, a struct element
2367 // will need a bitcast if the LLVM type laid out doesn't match the desired
2368 // type.
Chandler Carruth4678f672011-07-12 08:58:26 +00002369 addr = EmitBitCastOfLValueToProperType(*this, addr,
Chris Lattner3f32d692011-07-12 06:52:18 +00002370 CGM.getTypes().ConvertTypeForMem(type),
2371 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00002372
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002373 if (field->hasAttr<AnnotateAttr>())
2374 addr = EmitFieldAnnotations(field, addr);
2375
John McCall53fcbd22011-02-26 08:07:02 +00002376 LValue LV = MakeAddrLValue(addr, type, alignment);
2377 LV.getQuals().addCVRQualifiers(cvr);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002378
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002379 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00002380 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2381 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00002382
2383 // Fields of may_alias structs act like 'char' for TBAA purposes.
2384 // FIXME: this should get propagated down through anonymous structs
2385 // and unions.
2386 if (mayAlias && LV.getTBAAInfo())
2387 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2388
Daniel Dunbarf166a522010-08-21 03:44:13 +00002389 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00002390}
2391
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002392LValue
Eli Friedman7f1ff602012-04-16 03:54:45 +00002393CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2394 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002395 QualType FieldType = Field->getType();
2396
2397 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002398 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002399
Daniel Dunbar034299e2010-03-31 01:09:11 +00002400 const CGRecordLayout &RL =
2401 CGM.getTypes().getCGRecordLayout(Field->getParent());
2402 unsigned idx = RL.getLLVMFieldNo(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002403 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002404 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2405
Chris Lattnerd7c59352011-07-10 05:53:24 +00002406 // Make sure that the address is pointing to the right type. This is critical
2407 // for both unions and structs. A union needs a bitcast, a struct element
2408 // will need a bitcast if the LLVM type laid out doesn't match the desired
2409 // type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002410 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002411 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2412
Eli Friedmana0544d62011-12-03 04:14:32 +00002413 CharUnits Alignment = getContext().getDeclAlign(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002414
2415 // FIXME: It should be impossible to have an LValue without alignment for a
2416 // complete type.
2417 if (!Base.getAlignment().isZero())
2418 Alignment = std::min(Alignment, Base.getAlignment());
2419
Daniel Dunbar5c816372010-08-21 04:20:22 +00002420 return MakeAddrLValue(V, FieldType, Alignment);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002421}
2422
Chris Lattnerf53c0962010-09-06 00:11:41 +00002423LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00002424 if (E->isFileScope()) {
2425 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2426 return MakeAddrLValue(GlobalPtr, E->getType());
2427 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00002428 if (E->getType()->isVariablyModifiedType())
2429 // make sure to emit the VLA size.
2430 EmitVariablyModifiedType(E->getType());
Fariborz Jahanianbbc5bbf2012-06-07 17:07:15 +00002431
Daniel Dunbar27bacaf2010-02-16 19:43:39 +00002432 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00002433 const Expr *InitExpr = E->getInitializer();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002434 LValue Result = MakeAddrLValue(DeclPtr, E->getType());
Eli Friedman9fd8b682008-05-13 23:18:27 +00002435
Chad Rosier615ed1a2012-03-29 17:37:10 +00002436 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2437 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00002438
2439 return Result;
2440}
2441
Richard Smithbb653bd2012-05-14 21:57:21 +00002442LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2443 if (!E->isGLValue())
2444 // Initializing an aggregate temporary in C++11: T{...}.
2445 return EmitAggExprToLValue(E);
2446
2447 // An lvalue initializer list must be initializing a reference.
2448 assert(E->getNumInits() == 1 && "reference init with multiple values");
2449 return EmitLValue(E->getInit(0));
2450}
2451
John McCallc07a0c72011-02-17 10:25:35 +00002452LValue CodeGenFunction::
2453EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2454 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00002455 // ?: here should be an aggregate.
John McCallc07a0c72011-02-17 10:25:35 +00002456 assert((hasAggregateLLVMType(expr->getType()) &&
2457 !expr->getType()->isAnyComplexType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00002458 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00002459 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00002460 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002461
Eli Friedman59954892012-01-25 05:04:17 +00002462 OpaqueValueMapping binding(*this, expr);
2463
John McCallc07a0c72011-02-17 10:25:35 +00002464 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002465 bool CondExprBool;
2466 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00002467 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002468 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00002469
2470 if (!ContainsLabel(dead))
2471 return EmitLValue(live);
John McCall0a6bf2e2011-01-26 19:21:13 +00002472 }
2473
John McCallc07a0c72011-02-17 10:25:35 +00002474 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2475 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2476 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00002477
2478 ConditionalEvaluation eval(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002479 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002480
2481 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002482 EmitBlock(lhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002483 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002484 LValue lhs = EmitLValue(expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002485 eval.end(*this);
2486
John McCallc07a0c72011-02-17 10:25:35 +00002487 if (!lhs.isSimple())
2488 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00002489
John McCallc07a0c72011-02-17 10:25:35 +00002490 lhsBlock = Builder.GetInsertBlock();
2491 Builder.CreateBr(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002492
2493 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002494 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002495 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002496 LValue rhs = EmitLValue(expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002497 eval.end(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002498 if (!rhs.isSimple())
2499 return EmitUnsupportedLValue(expr, "conditional operator");
2500 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00002501
John McCallc07a0c72011-02-17 10:25:35 +00002502 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002503
Jay Foad20c0f022011-03-30 11:28:58 +00002504 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
John McCall0a6bf2e2011-01-26 19:21:13 +00002505 "cond-lvalue");
John McCallc07a0c72011-02-17 10:25:35 +00002506 phi->addIncoming(lhs.getAddress(), lhsBlock);
2507 phi->addIncoming(rhs.getAddress(), rhsBlock);
2508 return MakeAddrLValue(phi, expr->getType());
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002509}
2510
Richard Smithbb653bd2012-05-14 21:57:21 +00002511/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2512/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00002513/// otherwise if a cast is needed by the code generator in an lvalue context,
2514/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00002515/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00002516/// are permitted with aggregate result, including noop aggregate casts, and
2517/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002518LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00002519 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00002520 case CK_ToVoid:
Eli Friedman8c98dff2009-11-16 05:48:01 +00002521 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
John McCall8cb679e2010-11-15 09:13:47 +00002522
2523 case CK_Dependent:
2524 llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00002525
2526 case CK_BuiltinFnToFnPtr:
2527 llvm_unreachable("builtin functions are handled elsewhere");
2528
David Chisnallfa35df62012-01-16 17:27:18 +00002529 // These two casts are currently treated as no-ops, although they could
2530 // potentially be real operations depending on the target's ABI.
2531 case CK_NonAtomicToAtomic:
2532 case CK_AtomicToNonAtomic:
John McCall8cb679e2010-11-15 09:13:47 +00002533
John McCalle3027922010-08-25 11:45:40 +00002534 case CK_NoOp:
Douglas Gregor21d3fca2011-01-27 23:22:05 +00002535 case CK_LValueToRValue:
2536 if (!E->getSubExpr()->Classify(getContext()).isPRValue()
2537 || E->getType()->isRecordType())
John McCalle26a8722010-12-04 08:14:53 +00002538 return EmitLValue(E->getSubExpr());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002539 // Fall through to synthesize a temporary.
John McCall8cb679e2010-11-15 09:13:47 +00002540
John McCalle3027922010-08-25 11:45:40 +00002541 case CK_BitCast:
2542 case CK_ArrayToPointerDecay:
2543 case CK_FunctionToPointerDecay:
2544 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00002545 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00002546 case CK_IntegralToPointer:
2547 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002548 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002549 case CK_VectorSplat:
2550 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00002551 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002552 case CK_IntegralToFloating:
2553 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002554 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002555 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00002556 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002557 case CK_FloatingComplexToReal:
2558 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002559 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002560 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00002561 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002562 case CK_IntegralComplexToReal:
2563 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002564 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002565 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00002566 case CK_DerivedToBaseMemberPointer:
2567 case CK_BaseToDerivedMemberPointer:
2568 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00002569 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00002570 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00002571 case CK_ARCProduceObject:
2572 case CK_ARCConsumeObject:
2573 case CK_ARCReclaimReturnedObject:
Douglas Gregored90df32012-02-22 05:02:47 +00002574 case CK_ARCExtendBlockObject:
2575 case CK_CopyAndAutoreleaseBlockObject: {
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002576 // These casts only produce lvalues when we're binding a reference to a
2577 // temporary realized from a (converted) pure rvalue. Emit the expression
2578 // as a value, copy it into a temporary, and return an lvalue referring to
2579 // that temporary.
2580 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00002581 EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002582 return MakeAddrLValue(V, E->getType());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002583 }
Eli Friedman8c98dff2009-11-16 05:48:01 +00002584
Anders Carlsson8a01a752011-04-11 02:03:26 +00002585 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00002586 LValue LV = EmitLValue(E->getSubExpr());
2587 llvm::Value *V = LV.getAddress();
2588 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002589 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00002590 }
2591
John McCalle3027922010-08-25 11:45:40 +00002592 case CK_ConstructorConversion:
2593 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00002594 case CK_CPointerToObjCPointerCast:
2595 case CK_BlockPointerToObjCPointerCast:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002596 return EmitLValue(E->getSubExpr());
Anders Carlssond95f9602009-09-12 16:16:49 +00002597
John McCalle3027922010-08-25 11:45:40 +00002598 case CK_UncheckedDerivedToBase:
2599 case CK_DerivedToBase: {
Anders Carlssond95f9602009-09-12 16:16:49 +00002600 const RecordType *DerivedClassTy =
2601 E->getSubExpr()->getType()->getAs<RecordType>();
2602 CXXRecordDecl *DerivedClassDecl =
2603 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Anders Carlssond95f9602009-09-12 16:16:49 +00002604
2605 LValue LV = EmitLValue(E->getSubExpr());
John McCalle26a8722010-12-04 08:14:53 +00002606 llvm::Value *This = LV.getAddress();
Anders Carlssond95f9602009-09-12 16:16:49 +00002607
2608 // Perform the derived-to-base conversion
2609 llvm::Value *Base =
Fariborz Jahanian64cda8b2010-06-17 23:00:29 +00002610 GetAddressOfBaseClass(This, DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002611 E->path_begin(), E->path_end(),
2612 /*NullCheckValue=*/false);
Anders Carlssond95f9602009-09-12 16:16:49 +00002613
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002614 return MakeAddrLValue(Base, E->getType());
Anders Carlssond95f9602009-09-12 16:16:49 +00002615 }
John McCalle3027922010-08-25 11:45:40 +00002616 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00002617 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00002618 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00002619 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2620 CXXRecordDecl *DerivedClassDecl =
2621 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2622
2623 LValue LV = EmitLValue(E->getSubExpr());
2624
2625 // Perform the base-to-derived conversion
2626 llvm::Value *Derived =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +00002627 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002628 E->path_begin(), E->path_end(),
2629 /*NullCheckValue=*/false);
Anders Carlsson8c793172009-11-23 17:57:54 +00002630
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002631 return MakeAddrLValue(Derived, E->getType());
Eli Friedman8c98dff2009-11-16 05:48:01 +00002632 }
John McCalle3027922010-08-25 11:45:40 +00002633 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00002634 // This must be a reinterpret_cast (or c-style equivalent).
2635 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
Anders Carlsson50cb3212009-11-14 21:21:42 +00002636
2637 LValue LV = EmitLValue(E->getSubExpr());
2638 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2639 ConvertType(CE->getTypeAsWritten()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002640 return MakeAddrLValue(V, E->getType());
Anders Carlsson50cb3212009-11-14 21:21:42 +00002641 }
John McCalle3027922010-08-25 11:45:40 +00002642 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002643 LValue LV = EmitLValue(E->getSubExpr());
2644 QualType ToType = getContext().getLValueReferenceType(E->getType());
2645 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2646 ConvertType(ToType));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002647 return MakeAddrLValue(V, E->getType());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002648 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002649 case CK_ZeroToOCLEvent:
2650 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00002651 }
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002652
2653 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002654}
2655
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002656LValue CodeGenFunction::EmitNullInitializationLValue(
Douglas Gregor747eb782010-07-08 06:14:04 +00002657 const CXXScalarValueInitExpr *E) {
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002658 QualType Ty = E->getType();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002659 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
Anders Carlssonc0964b62010-05-22 17:35:42 +00002660 EmitNullInitialization(LV.getAddress(), Ty);
Daniel Dunbara7566f12010-02-09 02:48:28 +00002661 return LV;
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002662}
2663
John McCall1bf58462011-02-16 08:02:54 +00002664LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00002665 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00002666 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00002667}
2668
Douglas Gregorfe314812011-06-21 17:03:29 +00002669LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2670 const MaterializeTemporaryExpr *E) {
John McCall17054bd62011-08-26 21:08:13 +00002671 RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
Douglas Gregord410c082011-06-21 18:20:46 +00002672 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Douglas Gregorfe314812011-06-21 17:03:29 +00002673}
2674
Eli Friedman7f1ff602012-04-16 03:54:45 +00002675RValue CodeGenFunction::EmitRValueForField(LValue LV,
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002676 const FieldDecl *FD) {
2677 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00002678 LValue FieldLV = EmitLValueForField(LV, FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002679 if (FT->isAnyComplexType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002680 return RValue::getComplex(
2681 LoadComplexFromAddr(FieldLV.getAddress(),
2682 FieldLV.isVolatileQualified()));
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002683 else if (CodeGenFunction::hasAggregateLLVMType(FT))
Eli Friedman7f1ff602012-04-16 03:54:45 +00002684 return FieldLV.asAggregateRValue();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002685
Eli Friedman7f1ff602012-04-16 03:54:45 +00002686 return EmitLoadOfLValue(FieldLV);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002687}
Douglas Gregorfe314812011-06-21 17:03:29 +00002688
Chris Lattnere47e4402007-06-01 18:02:12 +00002689//===--------------------------------------------------------------------===//
2690// Expression Emission
2691//===--------------------------------------------------------------------===//
2692
Anders Carlsson17490832009-12-24 20:40:36 +00002693RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2694 ReturnValueSlot ReturnValue) {
Eric Christopher7cdf9482011-10-13 21:45:18 +00002695 if (CGDebugInfo *DI = getDebugInfo())
2696 DI->EmitLocation(Builder, E->getLocStart());
Devang Pateld3a6b0f2011-03-04 18:54:42 +00002697
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002698 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002699 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00002700 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002701
Anders Carlssone5fd6f22009-04-03 22:50:24 +00002702 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002703 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002704
Peter Collingbournefe883422011-10-06 18:29:37 +00002705 if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E))
2706 return EmitCUDAKernelCallExpr(CE, ReturnValue);
2707
Douglas Gregore0e96302011-09-06 21:41:04 +00002708 const Decl *TargetDecl = E->getCalleeDecl();
2709 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2710 if (unsigned builtinID = FD->getBuiltinID())
2711 return EmitBuiltinExpr(FD, builtinID, E);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002712 }
2713
Chris Lattner4ca97c32009-06-13 00:26:38 +00002714 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00002715 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002716 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002717
John McCall31168b02011-06-15 23:02:42 +00002718 if (const CXXPseudoDestructorExpr *PseudoDtor
2719 = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2720 QualType DestroyedType = PseudoDtor->getDestroyedType();
Richard Smith9c6890a2012-11-01 22:30:59 +00002721 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002722 DestroyedType->isObjCLifetimeType() &&
2723 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2724 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002725 // Automatic Reference Counting:
2726 // If the pseudo-expression names a retainable object with weak or
2727 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00002728 Expr *BaseExpr = PseudoDtor->getBase();
2729 llvm::Value *BaseValue = NULL;
2730 Qualifiers BaseQuals;
2731
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002732 // 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 +00002733 if (PseudoDtor->isArrow()) {
2734 BaseValue = EmitScalarExpr(BaseExpr);
2735 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2736 BaseQuals = PTy->getPointeeType().getQualifiers();
2737 } else {
2738 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00002739 BaseValue = BaseLV.getAddress();
2740 QualType BaseTy = BaseExpr->getType();
2741 BaseQuals = BaseTy.getQualifiers();
2742 }
2743
2744 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2745 case Qualifiers::OCL_None:
2746 case Qualifiers::OCL_ExplicitNone:
2747 case Qualifiers::OCL_Autoreleasing:
2748 break;
2749
2750 case Qualifiers::OCL_Strong:
2751 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002752 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCall31168b02011-06-15 23:02:42 +00002753 /*precise*/ true);
2754 break;
2755
2756 case Qualifiers::OCL_Weak:
2757 EmitARCDestroyWeak(BaseValue);
2758 break;
2759 }
2760 } else {
2761 // C++ [expr.pseudo]p1:
2762 // The result shall only be used as the operand for the function call
2763 // operator (), and the result of such a call has type void. The only
2764 // effect is the evaluation of the postfix-expression before the dot or
2765 // arrow.
2766 EmitScalarExpr(E->getCallee());
2767 }
2768
Douglas Gregorad8a3362009-09-04 17:36:40 +00002769 return RValue::get(0);
2770 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002771
Chris Lattner2da04b32007-08-24 05:35:26 +00002772 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Anders Carlsson17490832009-12-24 20:40:36 +00002773 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002774 E->arg_begin(), E->arg_end(), TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00002775}
2776
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002777LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00002778 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00002779 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00002780 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00002781 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00002782 return EmitLValue(E->getRHS());
2783 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002784
John McCalle3027922010-08-25 11:45:40 +00002785 if (E->getOpcode() == BO_PtrMemD ||
2786 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002787 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002788
John McCalla2342eb2010-12-05 02:00:02 +00002789 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00002790
2791 // Note that in all of these cases, __block variables need the RHS
2792 // evaluated first just in case the variable gets moved by the RHS.
John McCall4f29b492010-11-16 23:07:28 +00002793
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002794 if (!hasAggregateLLVMType(E->getType())) {
John McCall31168b02011-06-15 23:02:42 +00002795 switch (E->getLHS()->getType().getObjCLifetime()) {
2796 case Qualifiers::OCL_Strong:
2797 return EmitARCStoreStrong(E, /*ignored*/ false).first;
2798
2799 case Qualifiers::OCL_Autoreleasing:
2800 return EmitARCStoreAutoreleasing(E).first;
2801
2802 // No reason to do any of these differently.
2803 case Qualifiers::OCL_None:
2804 case Qualifiers::OCL_ExplicitNone:
2805 case Qualifiers::OCL_Weak:
2806 break;
2807 }
2808
John McCalld0a30012010-12-06 06:10:02 +00002809 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00002810 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00002811 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002812 return LV;
2813 }
John McCall4f29b492010-11-16 23:07:28 +00002814
2815 if (E->getType()->isAnyComplexType())
2816 return EmitComplexAssignmentLValue(E);
2817
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002818 return EmitAggExprToLValue(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002819}
2820
Christopher Lambd91c3d42007-12-29 05:02:41 +00002821LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00002822 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00002823
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002824 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002825 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002826
2827 assert(E->getCallReturnType()->isReferenceType() &&
2828 "Can't have a scalar return unless the return type is a "
2829 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00002830
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002831 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00002832}
2833
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002834LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2835 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002836 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002837}
2838
Anders Carlsson3be22e22009-05-30 23:23:33 +00002839LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002840 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2841 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002842 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00002843 EmitCXXConstructExpr(E, Slot);
2844 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlsson3be22e22009-05-30 23:23:33 +00002845}
2846
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002847LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00002848CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002849 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00002850}
2851
Nico Webercf4ff5862012-10-11 10:13:44 +00002852llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
2853 return CGM.GetAddrOfUuidDescriptor(E);
2854}
2855
2856LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
2857 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
2858}
2859
Mike Stumpc9b231c2009-11-15 08:09:41 +00002860LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002861CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002862 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00002863 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00002864 EmitAggExpr(E->getSubExpr(), Slot);
Peter Collingbourne702b2842011-11-27 22:09:22 +00002865 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
John McCall8ea46b62010-09-18 00:58:34 +00002866 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002867}
2868
Eli Friedman5bc17122012-02-08 05:34:55 +00002869LValue
2870CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00002871 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002872 EmitLambdaExpr(E, Slot);
Eli Friedman5bc17122012-02-08 05:34:55 +00002873 return MakeAddrLValue(Slot.getAddr(), E->getType());
2874}
2875
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002876LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002877 RValue RV = EmitObjCMessageExpr(E);
Anders Carlsson280e61f12010-06-21 20:59:55 +00002878
2879 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002880 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Anders Carlsson280e61f12010-06-21 20:59:55 +00002881
2882 assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2883 "Can't have a scalar return unless the return type is a "
2884 "reference type!");
2885
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002886 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002887}
2888
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00002889LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2890 llvm::Value *V =
2891 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002892 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00002893}
2894
Daniel Dunbar722f4242009-04-22 05:08:15 +00002895llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002896 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002897 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002898}
2899
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002900LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2901 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002902 const ObjCIvarDecl *Ivar,
2903 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00002904 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00002905 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002906}
2907
2908LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002909 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2910 llvm::Value *BaseValue = 0;
2911 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00002912 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002913 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002914 if (E->isArrow()) {
2915 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002916 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002917 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002918 } else {
2919 LValue BaseLV = EmitLValue(BaseExpr);
2920 // FIXME: this isn't right for bitfields.
2921 BaseValue = BaseLV.getAddress();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002922 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00002923 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002924 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002925
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002926 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00002927 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2928 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002929 setObjCGCLValueClass(getContext(), E, LV);
2930 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00002931}
2932
Chris Lattnera4185c52009-04-25 19:35:26 +00002933LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00002934 // Can only get l-value for message expression returning aggregate type
2935 RValue RV = EmitAnyExprToTemp(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002936 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnera4185c52009-04-25 19:35:26 +00002937}
2938
Anders Carlsson0435ed52009-12-24 19:08:58 +00002939RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Anders Carlsson17490832009-12-24 20:40:36 +00002940 ReturnValueSlot ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002941 CallExpr::const_arg_iterator ArgBeg,
2942 CallExpr::const_arg_iterator ArgEnd,
2943 const Decl *TargetDecl) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002944 // Get the actual function type. The callee type will always be a pointer to
2945 // function type or a block pointer type.
2946 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00002947 "Call must have function pointer type!");
2948
John McCall6fd4c232009-10-23 08:22:42 +00002949 CalleeType = getContext().getCanonicalType(CalleeType);
2950
John McCallab26cfa2010-02-05 21:31:56 +00002951 const FunctionType *FnType
2952 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00002953
2954 CallArgList Args;
John McCall6fd4c232009-10-23 08:22:42 +00002955 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
Daniel Dunbarc722b852008-08-30 03:02:31 +00002956
John McCalla729c622012-02-17 03:33:10 +00002957 const CGFunctionInfo &FnInfo =
John McCall8dda7b22012-07-07 06:41:13 +00002958 CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
John McCallcbc038a2011-09-21 08:08:30 +00002959
2960 // C99 6.5.2.2p6:
2961 // If the expression that denotes the called function has a type
2962 // that does not include a prototype, [the default argument
2963 // promotions are performed]. If the number of arguments does not
2964 // equal the number of parameters, the behavior is undefined. If
2965 // the function is defined with a type that includes a prototype,
2966 // and either the prototype ends with an ellipsis (, ...) or the
2967 // types of the arguments after promotion are not compatible with
2968 // the types of the parameters, the behavior is undefined. If the
2969 // function is defined with a type that does not include a
2970 // prototype, and the types of the arguments after promotion are
2971 // not compatible with those of the parameters after promotion,
2972 // the behavior is undefined [except in some trivial cases].
2973 // That is, in the general case, we should assume that a call
2974 // through an unprototyped function type works like a *non-variadic*
2975 // call. The way we make this work is to cast to the exact type
2976 // of the promoted arguments.
John McCallc818bbb2012-12-07 07:03:17 +00002977 if (isa<FunctionNoProtoType>(FnType)) {
John McCalla729c622012-02-17 03:33:10 +00002978 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00002979 CalleeTy = CalleeTy->getPointerTo();
2980 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
2981 }
2982
2983 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00002984}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002985
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002986LValue CodeGenFunction::
2987EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
Eli Friedman928a5672009-11-18 05:01:17 +00002988 llvm::Value *BaseV;
John McCalle3027922010-08-25 11:45:40 +00002989 if (E->getOpcode() == BO_PtrMemI)
Eli Friedman928a5672009-11-18 05:01:17 +00002990 BaseV = EmitScalarExpr(E->getLHS());
2991 else
2992 BaseV = EmitLValue(E->getLHS()).getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002993
John McCallc134eb52010-08-31 21:07:20 +00002994 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2995
2996 const MemberPointerType *MPT
2997 = E->getRHS()->getType()->getAs<MemberPointerType>();
2998
2999 llvm::Value *AddV =
3000 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
3001
3002 return MakeAddrLValue(AddV, MPT->getPointeeType());
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003003}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003004
3005static void
3006EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
3007 llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
3008 uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
Richard Smithfeea8832012-04-12 05:08:17 +00003009 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
3010 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
3011
3012 switch (E->getOp()) {
3013 case AtomicExpr::AO__c11_atomic_init:
3014 llvm_unreachable("Already handled!");
3015
3016 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3017 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3018 case AtomicExpr::AO__atomic_compare_exchange:
3019 case AtomicExpr::AO__atomic_compare_exchange_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003020 // Note that cmpxchg only supports specifying one ordering and
3021 // doesn't support weak cmpxchg, at least at the moment.
3022 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3023 LoadVal1->setAlignment(Align);
3024 llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2);
3025 LoadVal2->setAlignment(Align);
3026 llvm::AtomicCmpXchgInst *CXI =
3027 CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order);
3028 CXI->setVolatile(E->isVolatile());
3029 llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1);
3030 StoreVal1->setAlignment(Align);
3031 llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1);
3032 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
3033 return;
3034 }
3035
Richard Smithfeea8832012-04-12 05:08:17 +00003036 case AtomicExpr::AO__c11_atomic_load:
3037 case AtomicExpr::AO__atomic_load_n:
3038 case AtomicExpr::AO__atomic_load: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003039 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
3040 Load->setAtomic(Order);
3041 Load->setAlignment(Size);
3042 Load->setVolatile(E->isVolatile());
3043 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
3044 StoreDest->setAlignment(Align);
3045 return;
3046 }
3047
Richard Smithfeea8832012-04-12 05:08:17 +00003048 case AtomicExpr::AO__c11_atomic_store:
3049 case AtomicExpr::AO__atomic_store:
3050 case AtomicExpr::AO__atomic_store_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003051 assert(!Dest && "Store does not return a value");
3052 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3053 LoadVal1->setAlignment(Align);
3054 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
3055 Store->setAtomic(Order);
3056 Store->setAlignment(Size);
3057 Store->setVolatile(E->isVolatile());
3058 return;
3059 }
3060
Richard Smithfeea8832012-04-12 05:08:17 +00003061 case AtomicExpr::AO__c11_atomic_exchange:
3062 case AtomicExpr::AO__atomic_exchange_n:
3063 case AtomicExpr::AO__atomic_exchange:
3064 Op = llvm::AtomicRMWInst::Xchg;
3065 break;
3066
3067 case AtomicExpr::AO__atomic_add_fetch:
3068 PostOp = llvm::Instruction::Add;
3069 // Fall through.
3070 case AtomicExpr::AO__c11_atomic_fetch_add:
3071 case AtomicExpr::AO__atomic_fetch_add:
3072 Op = llvm::AtomicRMWInst::Add;
3073 break;
3074
3075 case AtomicExpr::AO__atomic_sub_fetch:
3076 PostOp = llvm::Instruction::Sub;
3077 // Fall through.
3078 case AtomicExpr::AO__c11_atomic_fetch_sub:
3079 case AtomicExpr::AO__atomic_fetch_sub:
3080 Op = llvm::AtomicRMWInst::Sub;
3081 break;
3082
3083 case AtomicExpr::AO__atomic_and_fetch:
3084 PostOp = llvm::Instruction::And;
3085 // Fall through.
3086 case AtomicExpr::AO__c11_atomic_fetch_and:
3087 case AtomicExpr::AO__atomic_fetch_and:
3088 Op = llvm::AtomicRMWInst::And;
3089 break;
3090
3091 case AtomicExpr::AO__atomic_or_fetch:
3092 PostOp = llvm::Instruction::Or;
3093 // Fall through.
3094 case AtomicExpr::AO__c11_atomic_fetch_or:
3095 case AtomicExpr::AO__atomic_fetch_or:
3096 Op = llvm::AtomicRMWInst::Or;
3097 break;
3098
3099 case AtomicExpr::AO__atomic_xor_fetch:
3100 PostOp = llvm::Instruction::Xor;
3101 // Fall through.
3102 case AtomicExpr::AO__c11_atomic_fetch_xor:
3103 case AtomicExpr::AO__atomic_fetch_xor:
3104 Op = llvm::AtomicRMWInst::Xor;
3105 break;
Richard Smithd65cee92012-04-13 06:31:38 +00003106
3107 case AtomicExpr::AO__atomic_nand_fetch:
3108 PostOp = llvm::Instruction::And;
3109 // Fall through.
3110 case AtomicExpr::AO__atomic_fetch_nand:
3111 Op = llvm::AtomicRMWInst::Nand;
3112 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003113 }
Richard Smithfeea8832012-04-12 05:08:17 +00003114
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003115 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3116 LoadVal1->setAlignment(Align);
3117 llvm::AtomicRMWInst *RMWI =
3118 CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
3119 RMWI->setVolatile(E->isVolatile());
Richard Smithfeea8832012-04-12 05:08:17 +00003120
3121 // For __atomic_*_fetch operations, perform the operation again to
3122 // determine the value which was written.
3123 llvm::Value *Result = RMWI;
3124 if (PostOp)
3125 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
Richard Smithd65cee92012-04-13 06:31:38 +00003126 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
3127 Result = CGF.Builder.CreateNot(Result);
Richard Smithfeea8832012-04-12 05:08:17 +00003128 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003129 StoreDest->setAlignment(Align);
3130}
3131
3132// This function emits any expression (scalar, complex, or aggregate)
3133// into a temporary alloca.
3134static llvm::Value *
3135EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
3136 llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00003137 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
3138 /*Init*/ true);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003139 return DeclPtr;
3140}
3141
3142static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty,
3143 llvm::Value *Dest) {
3144 if (Ty->isAnyComplexType())
3145 return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false));
3146 if (CGF.hasAggregateLLVMType(Ty))
3147 return RValue::getAggregate(Dest);
3148 return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty)));
3149}
3150
3151RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
3152 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
Richard Smithfeea8832012-04-12 05:08:17 +00003153 QualType MemTy = AtomicTy;
3154 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
3155 MemTy = AT->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003156 CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
3157 uint64_t Size = sizeChars.getQuantity();
3158 CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
3159 unsigned Align = alignChars.getQuantity();
Benjamin Kramer37196de2012-11-17 17:30:55 +00003160 unsigned MaxInlineWidthInBits =
3161 getContext().getTargetInfo().getMaxAtomicInlineWidth();
3162 bool UseLibcall = (Size != Align ||
3163 getContext().toBits(sizeChars) > MaxInlineWidthInBits);
David Chisnallfa35df62012-01-16 17:27:18 +00003164
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003165 llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
3166 Ptr = EmitScalarExpr(E->getPtr());
David Chisnallfa35df62012-01-16 17:27:18 +00003167
Richard Smithfeea8832012-04-12 05:08:17 +00003168 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
David Chisnallfa35df62012-01-16 17:27:18 +00003169 assert(!Dest && "Init does not return a value");
David Chisnalleb9496e2012-04-11 17:24:05 +00003170 if (!hasAggregateLLVMType(E->getVal1()->getType())) {
Douglas Gregor298f43d2012-04-12 20:42:30 +00003171 QualType PointeeType
3172 = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
3173 EmitScalarInit(EmitScalarExpr(E->getVal1()),
3174 LValue::MakeAddr(Ptr, PointeeType, alignChars,
3175 getContext()));
David Chisnalleb9496e2012-04-11 17:24:05 +00003176 } else if (E->getType()->isAnyComplexType()) {
3177 EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
3178 } else {
3179 AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars,
3180 AtomicTy.getQualifiers(),
3181 AggValueSlot::IsNotDestructed,
3182 AggValueSlot::DoesNotNeedGCBarriers,
3183 AggValueSlot::IsNotAliased);
3184 EmitAggExpr(E->getVal1(), Slot);
3185 }
David Chisnallfa35df62012-01-16 17:27:18 +00003186 return RValue::get(0);
3187 }
3188
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003189 Order = EmitScalarExpr(E->getOrder());
Richard Smithfeea8832012-04-12 05:08:17 +00003190
3191 switch (E->getOp()) {
3192 case AtomicExpr::AO__c11_atomic_init:
3193 llvm_unreachable("Already handled!");
3194
3195 case AtomicExpr::AO__c11_atomic_load:
3196 case AtomicExpr::AO__atomic_load_n:
3197 break;
3198
3199 case AtomicExpr::AO__atomic_load:
3200 Dest = EmitScalarExpr(E->getVal1());
3201 break;
3202
3203 case AtomicExpr::AO__atomic_store:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003204 Val1 = EmitScalarExpr(E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003205 break;
3206
3207 case AtomicExpr::AO__atomic_exchange:
3208 Val1 = EmitScalarExpr(E->getVal1());
3209 Dest = EmitScalarExpr(E->getVal2());
3210 break;
3211
3212 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3213 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3214 case AtomicExpr::AO__atomic_compare_exchange_n:
3215 case AtomicExpr::AO__atomic_compare_exchange:
3216 Val1 = EmitScalarExpr(E->getVal1());
3217 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
3218 Val2 = EmitScalarExpr(E->getVal2());
3219 else
3220 Val2 = EmitValToTemp(*this, E->getVal2());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003221 OrderFail = EmitScalarExpr(E->getOrderFail());
Richard Smithfeea8832012-04-12 05:08:17 +00003222 // Evaluate and discard the 'weak' argument.
3223 if (E->getNumSubExprs() == 6)
3224 EmitScalarExpr(E->getWeak());
3225 break;
3226
3227 case AtomicExpr::AO__c11_atomic_fetch_add:
3228 case AtomicExpr::AO__c11_atomic_fetch_sub:
Richard Smithfeea8832012-04-12 05:08:17 +00003229 if (MemTy->isPointerType()) {
3230 // For pointer arithmetic, we're required to do a bit of math:
3231 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
Richard Smith01ba47d2012-04-13 00:45:38 +00003232 // ... but only for the C11 builtins. The GNU builtins expect the
3233 // user to multiply by sizeof(T).
Richard Smithfeea8832012-04-12 05:08:17 +00003234 QualType Val1Ty = E->getVal1()->getType();
3235 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
3236 CharUnits PointeeIncAmt =
3237 getContext().getTypeSizeInChars(MemTy->getPointeeType());
3238 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
3239 Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
3240 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
3241 break;
3242 }
3243 // Fall through.
Richard Smith01ba47d2012-04-13 00:45:38 +00003244 case AtomicExpr::AO__atomic_fetch_add:
3245 case AtomicExpr::AO__atomic_fetch_sub:
3246 case AtomicExpr::AO__atomic_add_fetch:
3247 case AtomicExpr::AO__atomic_sub_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003248 case AtomicExpr::AO__c11_atomic_store:
3249 case AtomicExpr::AO__c11_atomic_exchange:
3250 case AtomicExpr::AO__atomic_store_n:
3251 case AtomicExpr::AO__atomic_exchange_n:
3252 case AtomicExpr::AO__c11_atomic_fetch_and:
3253 case AtomicExpr::AO__c11_atomic_fetch_or:
3254 case AtomicExpr::AO__c11_atomic_fetch_xor:
3255 case AtomicExpr::AO__atomic_fetch_and:
3256 case AtomicExpr::AO__atomic_fetch_or:
3257 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003258 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003259 case AtomicExpr::AO__atomic_and_fetch:
3260 case AtomicExpr::AO__atomic_or_fetch:
3261 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003262 case AtomicExpr::AO__atomic_nand_fetch:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003263 Val1 = EmitValToTemp(*this, E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003264 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003265 }
3266
Richard Smithfeea8832012-04-12 05:08:17 +00003267 if (!E->getType()->isVoidType() && !Dest)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003268 Dest = CreateMemTemp(E->getType(), ".atomicdst");
3269
David Chisnalldb365f32012-03-29 18:01:11 +00003270 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003271 if (UseLibcall) {
David Chisnalldb365f32012-03-29 18:01:11 +00003272
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003273 SmallVector<QualType, 5> Params;
David Chisnalldb365f32012-03-29 18:01:11 +00003274 CallArgList Args;
3275 // Size is always the first parameter
3276 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
3277 getContext().getSizeType());
3278 // Atomic address is always the second parameter
3279 Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
3280 getContext().VoidPtrTy);
3281
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003282 const char* LibCallName;
David Chisnalldb365f32012-03-29 18:01:11 +00003283 QualType RetTy = getContext().VoidTy;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003284 switch (E->getOp()) {
David Chisnalldb365f32012-03-29 18:01:11 +00003285 // There is only one libcall for compare an exchange, because there is no
3286 // optimisation benefit possible from a libcall version of a weak compare
3287 // and exchange.
3288 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
Richard Smithfeea8832012-04-12 05:08:17 +00003289 // void *desired, int success, int failure)
3290 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3291 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3292 case AtomicExpr::AO__atomic_compare_exchange:
3293 case AtomicExpr::AO__atomic_compare_exchange_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003294 LibCallName = "__atomic_compare_exchange";
3295 RetTy = getContext().BoolTy;
3296 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3297 getContext().VoidPtrTy);
3298 Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
3299 getContext().VoidPtrTy);
3300 Args.add(RValue::get(Order),
3301 getContext().IntTy);
3302 Order = OrderFail;
3303 break;
3304 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
3305 // int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003306 case AtomicExpr::AO__c11_atomic_exchange:
3307 case AtomicExpr::AO__atomic_exchange_n:
3308 case AtomicExpr::AO__atomic_exchange:
David Chisnalldb365f32012-03-29 18:01:11 +00003309 LibCallName = "__atomic_exchange";
3310 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3311 getContext().VoidPtrTy);
3312 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3313 getContext().VoidPtrTy);
3314 break;
3315 // void __atomic_store(size_t size, void *mem, void *val, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003316 case AtomicExpr::AO__c11_atomic_store:
3317 case AtomicExpr::AO__atomic_store:
3318 case AtomicExpr::AO__atomic_store_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003319 LibCallName = "__atomic_store";
3320 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3321 getContext().VoidPtrTy);
3322 break;
3323 // void __atomic_load(size_t size, void *mem, void *return, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003324 case AtomicExpr::AO__c11_atomic_load:
3325 case AtomicExpr::AO__atomic_load:
3326 case AtomicExpr::AO__atomic_load_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003327 LibCallName = "__atomic_load";
3328 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3329 getContext().VoidPtrTy);
3330 break;
3331#if 0
3332 // These are only defined for 1-16 byte integers. It is not clear what
3333 // their semantics would be on anything else...
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003334 case AtomicExpr::Add: LibCallName = "__atomic_fetch_add_generic"; break;
3335 case AtomicExpr::Sub: LibCallName = "__atomic_fetch_sub_generic"; break;
3336 case AtomicExpr::And: LibCallName = "__atomic_fetch_and_generic"; break;
3337 case AtomicExpr::Or: LibCallName = "__atomic_fetch_or_generic"; break;
3338 case AtomicExpr::Xor: LibCallName = "__atomic_fetch_xor_generic"; break;
David Chisnalldb365f32012-03-29 18:01:11 +00003339#endif
3340 default: return EmitUnsupportedRValue(E, "atomic library call");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003341 }
David Chisnalldb365f32012-03-29 18:01:11 +00003342 // order is always the last parameter
3343 Args.add(RValue::get(Order),
3344 getContext().IntTy);
3345
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003346 const CGFunctionInfo &FuncInfo =
John McCall8dda7b22012-07-07 06:41:13 +00003347 CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args,
David Chisnalldb365f32012-03-29 18:01:11 +00003348 FunctionType::ExtInfo(), RequiredArgs::All);
3349 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003350 llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
3351 RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
3352 if (E->isCmpXChg())
3353 return Res;
Richard Smithfeea8832012-04-12 05:08:17 +00003354 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003355 return RValue::get(0);
3356 return ConvertTempToRValue(*this, E->getType(), Dest);
3357 }
David Chisnalldb365f32012-03-29 18:01:11 +00003358
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003359 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
3360 E->getOp() == AtomicExpr::AO__atomic_store ||
3361 E->getOp() == AtomicExpr::AO__atomic_store_n;
3362 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
3363 E->getOp() == AtomicExpr::AO__atomic_load ||
3364 E->getOp() == AtomicExpr::AO__atomic_load_n;
3365
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003366 llvm::Type *IPtrTy =
3367 llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
3368 llvm::Value *OrigDest = Dest;
3369 Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
3370 if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
3371 if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
3372 if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
3373
3374 if (isa<llvm::ConstantInt>(Order)) {
3375 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
3376 switch (ord) {
3377 case 0: // memory_order_relaxed
3378 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3379 llvm::Monotonic);
3380 break;
3381 case 1: // memory_order_consume
3382 case 2: // memory_order_acquire
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003383 if (IsStore)
3384 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003385 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3386 llvm::Acquire);
3387 break;
3388 case 3: // memory_order_release
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003389 if (IsLoad)
3390 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003391 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3392 llvm::Release);
3393 break;
3394 case 4: // memory_order_acq_rel
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003395 if (IsLoad || IsStore)
3396 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003397 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3398 llvm::AcquireRelease);
3399 break;
3400 case 5: // memory_order_seq_cst
3401 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3402 llvm::SequentiallyConsistent);
3403 break;
3404 default: // invalid order
3405 // We should not ever get here normally, but it's hard to
3406 // enforce that in general.
Richard Smithfeea8832012-04-12 05:08:17 +00003407 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003408 }
Richard Smithfeea8832012-04-12 05:08:17 +00003409 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003410 return RValue::get(0);
3411 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3412 }
3413
3414 // Long case, when Order isn't obviously constant.
3415
3416 // Create all the relevant BB's
Eli Friedmanc2025562011-10-11 20:00:47 +00003417 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
3418 *AcqRelBB = 0, *SeqCstBB = 0;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003419 MonotonicBB = createBasicBlock("monotonic", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003420 if (!IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003421 AcquireBB = createBasicBlock("acquire", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003422 if (!IsLoad)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003423 ReleaseBB = createBasicBlock("release", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003424 if (!IsLoad && !IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003425 AcqRelBB = createBasicBlock("acqrel", CurFn);
3426 SeqCstBB = createBasicBlock("seqcst", CurFn);
3427 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
3428
3429 // Create the switch for the split
3430 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
3431 // doesn't matter unless someone is crazy enough to use something that
3432 // doesn't fold to a constant for the ordering.
3433 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
3434 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
3435
3436 // Emit all the different atomics
3437 Builder.SetInsertPoint(MonotonicBB);
3438 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3439 llvm::Monotonic);
3440 Builder.CreateBr(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003441 if (!IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003442 Builder.SetInsertPoint(AcquireBB);
3443 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3444 llvm::Acquire);
3445 Builder.CreateBr(ContBB);
3446 SI->addCase(Builder.getInt32(1), AcquireBB);
3447 SI->addCase(Builder.getInt32(2), AcquireBB);
3448 }
Richard Smithfeea8832012-04-12 05:08:17 +00003449 if (!IsLoad) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003450 Builder.SetInsertPoint(ReleaseBB);
3451 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3452 llvm::Release);
3453 Builder.CreateBr(ContBB);
3454 SI->addCase(Builder.getInt32(3), ReleaseBB);
3455 }
Richard Smithfeea8832012-04-12 05:08:17 +00003456 if (!IsLoad && !IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003457 Builder.SetInsertPoint(AcqRelBB);
3458 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3459 llvm::AcquireRelease);
3460 Builder.CreateBr(ContBB);
3461 SI->addCase(Builder.getInt32(4), AcqRelBB);
3462 }
3463 Builder.SetInsertPoint(SeqCstBB);
3464 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3465 llvm::SequentiallyConsistent);
3466 Builder.CreateBr(ContBB);
3467 SI->addCase(Builder.getInt32(5), SeqCstBB);
3468
3469 // Cleanup and return
3470 Builder.SetInsertPoint(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003471 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003472 return RValue::get(0);
3473 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3474}
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003475
Duncan Sandse81111c2012-04-10 08:23:07 +00003476void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003477 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003478 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003479 return;
3480
Duncan Sands65229ed2012-04-16 16:29:47 +00003481 llvm::MDBuilder MDHelper(getLLVMContext());
3482 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003483
Duncan Sands6fc46192012-04-14 12:37:26 +00003484 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003485}
John McCallfe96e0b2011-11-06 09:01:30 +00003486
3487namespace {
3488 struct LValueOrRValue {
3489 LValue LV;
3490 RValue RV;
3491 };
3492}
3493
3494static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3495 const PseudoObjectExpr *E,
3496 bool forLValue,
3497 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003498 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00003499
3500 // Find the result expression, if any.
3501 const Expr *resultExpr = E->getResultExpr();
3502 LValueOrRValue result;
3503
3504 for (PseudoObjectExpr::const_semantics_iterator
3505 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3506 const Expr *semantic = *i;
3507
3508 // If this semantic expression is an opaque value, bind it
3509 // to the result of its source expression.
3510 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3511
3512 // If this is the result expression, we may need to evaluate
3513 // directly into the slot.
3514 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3515 OVMA opaqueData;
3516 if (ov == resultExpr && ov->isRValue() && !forLValue &&
3517 CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
3518 !ov->getType()->isAnyComplexType()) {
3519 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3520
3521 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3522 opaqueData = OVMA::bind(CGF, ov, LV);
3523 result.RV = slot.asRValue();
3524
3525 // Otherwise, emit as normal.
3526 } else {
3527 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3528
3529 // If this is the result, also evaluate the result now.
3530 if (ov == resultExpr) {
3531 if (forLValue)
3532 result.LV = CGF.EmitLValue(ov);
3533 else
3534 result.RV = CGF.EmitAnyExpr(ov, slot);
3535 }
3536 }
3537
3538 opaques.push_back(opaqueData);
3539
3540 // Otherwise, if the expression is the result, evaluate it
3541 // and remember the result.
3542 } else if (semantic == resultExpr) {
3543 if (forLValue)
3544 result.LV = CGF.EmitLValue(semantic);
3545 else
3546 result.RV = CGF.EmitAnyExpr(semantic, slot);
3547
3548 // Otherwise, evaluate the expression in an ignored context.
3549 } else {
3550 CGF.EmitIgnoredExpr(semantic);
3551 }
3552 }
3553
3554 // Unbind all the opaques now.
3555 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3556 opaques[i].unbind(CGF);
3557
3558 return result;
3559}
3560
3561RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3562 AggValueSlot slot) {
3563 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3564}
3565
3566LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3567 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3568}