blob: cb446dfeb4ab44d440b316537a9bb5cf7ddb665d [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"
Chris Lattnerb6984c42007-06-20 04:44:43 +000015#include "CodeGenModule.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000016#include "CGCall.h"
John McCall5d865c322010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Devang Pateld3a6b0f2011-03-04 18:54:42 +000018#include "CGDebugInfo.h"
Daniel Dunbar034299e2010-03-31 01:09:11 +000019#include "CGRecordLayout.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000020#include "CGObjCRuntime.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"
Nick Lewycky7c6c6cc2011-07-07 03:54:51 +000026#include "llvm/Intrinsics.h"
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +000027#include "llvm/LLVMContext.h"
Duncan Sandsc720e782012-04-15 18:04:54 +000028#include "llvm/Support/MDBuilder.h"
Eli Friedmanf2442dc2008-05-17 20:03:47 +000029#include "llvm/Target/TargetData.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000030using namespace clang;
31using namespace CodeGen;
32
Chris Lattnerd7f58862007-06-02 05:24:33 +000033//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000034// Miscellaneous Helper Methods
35//===--------------------------------------------------------------------===//
36
John McCallad7c5c12011-02-08 08:22:06 +000037llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
38 unsigned addressSpace =
39 cast<llvm::PointerType>(value->getType())->getAddressSpace();
40
Chris Lattner2192fe52011-07-18 04:24:23 +000041 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000042 if (addressSpace)
43 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
44
45 if (value->getType() == destType) return value;
46 return Builder.CreateBitCast(value, destType);
47}
48
Chris Lattnere9a64532007-06-22 21:44:33 +000049/// CreateTempAlloca - This creates a alloca and inserts it into the entry
50/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000051llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000052 const Twine &Name) {
Chris Lattner47640222009-03-22 00:24:14 +000053 if (!Builder.isNamePreserving())
Daniel Dunbarb5aacc22009-10-19 01:21:05 +000054 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
Devang Pateldac79de2009-10-12 22:29:02 +000055 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000056}
Chris Lattner8394d792007-06-05 20:53:16 +000057
John McCall2e6567a2010-04-22 01:10:34 +000058void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
59 llvm::Value *Init) {
60 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
61 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
62 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
63}
64
Chris Lattnerc401de92010-07-05 20:21:00 +000065llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000066 const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000067 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
68 // FIXME: Should we prefer the preferred type alignment here?
69 CharUnits Align = getContext().getTypeAlignInChars(Ty);
70 Alloc->setAlignment(Align.getQuantity());
71 return Alloc;
72}
73
Chris Lattnerc401de92010-07-05 20:21:00 +000074llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000075 const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000076 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
77 // FIXME: Should we prefer the preferred type alignment here?
78 CharUnits Align = getContext().getTypeAlignInChars(Ty);
79 Alloc->setAlignment(Align.getQuantity());
80 return Alloc;
81}
82
Chris Lattner8394d792007-06-05 20:53:16 +000083/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
84/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000085llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
John McCall7a9aac22010-08-23 01:21:21 +000086 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +000087 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +000088 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +000089 }
John McCall7a9aac22010-08-23 01:21:21 +000090
91 QualType BoolTy = getContext().BoolTy;
Chris Lattnerf3bc75a2008-04-04 16:54:41 +000092 if (!E->getType()->isAnyComplexType())
Chris Lattner268fcce2007-08-26 16:46:58 +000093 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Chris Lattner8394d792007-06-05 20:53:16 +000094
Chris Lattner268fcce2007-08-26 16:46:58 +000095 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Chris Lattnerf0106d22007-06-02 19:33:17 +000096}
97
John McCalla2342eb2010-12-05 02:00:02 +000098/// EmitIgnoredExpr - Emit code to compute the specified expression,
99/// ignoring the result.
100void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
101 if (E->isRValue())
102 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
103
104 // Just emit it as an l-value and drop the result.
105 EmitLValue(E);
106}
107
John McCall7a626f62010-09-15 10:14:12 +0000108/// EmitAnyExpr - Emit code to compute the specified expression which
109/// can have any type. The result is returned as an RValue struct.
110/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000111/// result should be returned.
John McCall7a626f62010-09-15 10:14:12 +0000112RValue CodeGenFunction::EmitAnyExpr(const Expr *E, AggValueSlot AggSlot,
113 bool IgnoreResult) {
Chris Lattner4647a212007-08-31 22:49:20 +0000114 if (!hasAggregateLLVMType(E->getType()))
Mike Stumpdf0fe272009-05-29 15:46:01 +0000115 return RValue::get(EmitScalarExpr(E, IgnoreResult));
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000116 else if (E->getType()->isAnyComplexType())
John McCall07bb1962010-11-16 10:08:07 +0000117 return RValue::getComplex(EmitComplexExpr(E, IgnoreResult, IgnoreResult));
Mike Stump4a3999f2009-09-09 13:00:44 +0000118
John McCall7a626f62010-09-15 10:14:12 +0000119 EmitAggExpr(E, AggSlot, IgnoreResult);
120 return AggSlot.asRValue();
Chris Lattner4647a212007-08-31 22:49:20 +0000121}
122
Mike Stump4a3999f2009-09-09 13:00:44 +0000123/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
124/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000125RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
126 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000127
128 if (hasAggregateLLVMType(E->getType()) &&
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000129 !E->getType()->isAnyComplexType())
John McCall7a626f62010-09-15 10:14:12 +0000130 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
131 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000132}
133
John McCall21886962010-04-21 10:05:39 +0000134/// EmitAnyExprToMem - Evaluate an expression into a given memory
135/// location.
136void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
137 llvm::Value *Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000138 Qualifiers Quals,
139 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000140 // FIXME: This function should take an LValue as an argument.
141 if (E->getType()->isAnyComplexType()) {
John McCall31168b02011-06-15 23:02:42 +0000142 EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000143 } else if (hasAggregateLLVMType(E->getType())) {
Eli Friedman38cd36d2011-12-03 02:13:40 +0000144 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000145 EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000146 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000147 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000148 AggValueSlot::IsAliased_t(!IsInit)));
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000149 } else {
John McCall21886962010-04-21 10:05:39 +0000150 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000151 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000152 EmitStoreThroughLValue(RV, LV);
John McCall21886962010-04-21 10:05:39 +0000153 }
154}
155
Benjamin Kramer90b5b682010-11-25 18:29:30 +0000156namespace {
Douglas Gregor7c38f152010-05-20 08:36:28 +0000157/// \brief An adjustment to be made to the temporary created when emitting a
158/// reference binding, which accesses a particular subobject of that temporary.
Benjamin Kramer90b5b682010-11-25 18:29:30 +0000159 struct SubobjectAdjustment {
Eli Friedman13ffdd82012-06-15 23:51:06 +0000160 enum {
161 DerivedToBaseAdjustment,
162 FieldAdjustment,
163 MemberPointerAdjustment
164 } Kind;
Benjamin Kramer90b5b682010-11-25 18:29:30 +0000165
166 union {
167 struct {
168 const CastExpr *BasePath;
169 const CXXRecordDecl *DerivedClass;
170 } DerivedToBase;
171
172 FieldDecl *Field;
Eli Friedman13ffdd82012-06-15 23:51:06 +0000173
174 struct {
175 const MemberPointerType *MPT;
176 llvm::Value *Ptr;
177 } Ptr;
Benjamin Kramer90b5b682010-11-25 18:29:30 +0000178 };
179
180 SubobjectAdjustment(const CastExpr *BasePath,
181 const CXXRecordDecl *DerivedClass)
182 : Kind(DerivedToBaseAdjustment) {
183 DerivedToBase.BasePath = BasePath;
184 DerivedToBase.DerivedClass = DerivedClass;
185 }
186
187 SubobjectAdjustment(FieldDecl *Field)
188 : Kind(FieldAdjustment) {
189 this->Field = Field;
190 }
Eli Friedman13ffdd82012-06-15 23:51:06 +0000191
192 SubobjectAdjustment(const MemberPointerType *MPT, llvm::Value *Ptr)
193 : Kind(MemberPointerAdjustment) {
194 this->Ptr.MPT = MPT;
195 this->Ptr.Ptr = Ptr;
196 }
Douglas Gregor7c38f152010-05-20 08:36:28 +0000197 };
Benjamin Kramer90b5b682010-11-25 18:29:30 +0000198}
Douglas Gregor7c38f152010-05-20 08:36:28 +0000199
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000200static llvm::Value *
Chris Lattner24516962011-07-20 04:59:57 +0000201CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000202 const NamedDecl *InitializedDecl) {
203 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
204 if (VD->hasGlobalStorage()) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000205 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000206 llvm::raw_svector_ostream Out(Name);
207 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
208 Out.flush();
209
Chris Lattner2192fe52011-07-18 04:24:23 +0000210 llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
Anders Carlsson18c205e2010-06-27 17:23:46 +0000211
212 // Create the reference temporary.
213 llvm::GlobalValue *RefTemp =
214 new llvm::GlobalVariable(CGF.CGM.getModule(),
215 RefTempTy, /*isConstant=*/false,
216 llvm::GlobalValue::InternalLinkage,
217 llvm::Constant::getNullValue(RefTempTy),
218 Name.str());
219 return RefTemp;
220 }
221 }
222
223 return CGF.CreateMemTemp(Type, "ref.tmp");
224}
225
226static llvm::Value *
Chris Lattnerf53c0962010-09-06 00:11:41 +0000227EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000228 llvm::Value *&ReferenceTemporary,
229 const CXXDestructorDecl *&ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000230 QualType &ObjCARCReferenceLifetimeType,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000231 const NamedDecl *InitializedDecl) {
Sebastian Redl29526f02011-11-27 16:50:07 +0000232 // Look through single-element init lists that claim to be lvalues. They're
233 // just syntactic wrappers in this case.
234 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E)) {
235 if (ILE->getNumInits() == 1 && ILE->isGLValue())
236 E = ILE->getInit(0);
237 }
238
Douglas Gregorfe314812011-06-21 17:03:29 +0000239 // Look through expressions for materialized temporaries (for now).
Douglas Gregor58df5092011-06-22 16:12:01 +0000240 if (const MaterializeTemporaryExpr *M
241 = dyn_cast<MaterializeTemporaryExpr>(E)) {
242 // Objective-C++ ARC:
243 // If we are binding a reference to a temporary that has ownership, we
244 // need to perform retain/release operations on the temporary.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000245 if (CGF.getContext().getLangOpts().ObjCAutoRefCount &&
Douglas Gregor58df5092011-06-22 16:12:01 +0000246 E->getType()->isObjCLifetimeType() &&
247 (E->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
248 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak ||
249 E->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing))
250 ObjCARCReferenceLifetimeType = E->getType();
251
252 E = M->GetTemporaryExpr();
253 }
Douglas Gregorfe314812011-06-21 17:03:29 +0000254
Eli Friedman357e8c92009-12-19 00:20:10 +0000255 if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
256 E = DAE->getExpr();
Anders Carlsson66413c22009-10-15 00:51:46 +0000257
John McCall08ef4662011-11-10 08:15:53 +0000258 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) {
259 CGF.enterFullExpression(EWC);
John McCallbd309292010-07-06 01:34:17 +0000260 CodeGenFunction::RunCleanupsScope Scope(CGF);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000261
John McCall08ef4662011-11-10 08:15:53 +0000262 return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000263 ReferenceTemporary,
264 ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000265 ObjCARCReferenceLifetimeType,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000266 InitializedDecl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000267 }
268
269 RValue RV;
Douglas Gregor9c399a22011-01-22 02:44:21 +0000270 if (E->isGLValue()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000271 // Emit the expression as an lvalue.
272 LValue LV = CGF.EmitLValue(E);
Chris Lattner13ee4f42011-07-10 05:34:54 +0000273
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000274 if (LV.isSimple())
275 return LV.getAddress();
Anders Carlsson824e0612010-02-04 17:32:58 +0000276
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000277 // We have to load the lvalue.
John McCall55e1fbc2011-06-25 02:11:03 +0000278 RV = CGF.EmitLoadOfLValue(LV);
Eli Friedmanc21cb442009-05-20 02:31:19 +0000279 } else {
Douglas Gregor58df5092011-06-22 16:12:01 +0000280 if (!ObjCARCReferenceLifetimeType.isNull()) {
281 ReferenceTemporary = CreateReferenceTemporary(CGF,
282 ObjCARCReferenceLifetimeType,
283 InitializedDecl);
284
285
286 LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
287 ObjCARCReferenceLifetimeType);
288
289 CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
290 RefTempDst, false);
291
292 bool ExtendsLifeOfTemporary = false;
293 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
294 if (Var->extendsLifetimeOfTemporary())
295 ExtendsLifeOfTemporary = true;
296 } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
297 ExtendsLifeOfTemporary = true;
298 }
299
300 if (!ExtendsLifeOfTemporary) {
301 // Since the lifetime of this temporary isn't going to be extended,
302 // we need to clean it up ourselves at the end of the full expression.
303 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
304 case Qualifiers::OCL_None:
305 case Qualifiers::OCL_ExplicitNone:
306 case Qualifiers::OCL_Autoreleasing:
307 break;
308
John McCall4bd0fb12011-07-12 16:41:08 +0000309 case Qualifiers::OCL_Strong: {
310 assert(!ObjCARCReferenceLifetimeType->isArrayType());
311 CleanupKind cleanupKind = CGF.getARCCleanupKind();
312 CGF.pushDestroy(cleanupKind,
313 ReferenceTemporary,
314 ObjCARCReferenceLifetimeType,
315 CodeGenFunction::destroyARCStrongImprecise,
316 cleanupKind & EHCleanup);
Douglas Gregor58df5092011-06-22 16:12:01 +0000317 break;
John McCall4bd0fb12011-07-12 16:41:08 +0000318 }
Douglas Gregor58df5092011-06-22 16:12:01 +0000319
320 case Qualifiers::OCL_Weak:
John McCall4bd0fb12011-07-12 16:41:08 +0000321 assert(!ObjCARCReferenceLifetimeType->isArrayType());
322 CGF.pushDestroy(NormalAndEHCleanup,
323 ReferenceTemporary,
324 ObjCARCReferenceLifetimeType,
325 CodeGenFunction::destroyARCWeak,
326 /*useEHCleanupForArray*/ true);
Douglas Gregor58df5092011-06-22 16:12:01 +0000327 break;
328 }
329
330 ObjCARCReferenceLifetimeType = QualType();
331 }
332
333 return ReferenceTemporary;
334 }
335
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000336 SmallVector<SubobjectAdjustment, 2> Adjustments;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000337 while (true) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000338 E = E->IgnoreParens();
Douglas Gregoraae38d62010-05-22 05:17:18 +0000339
340 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +0000341 if ((CE->getCastKind() == CK_DerivedToBase ||
342 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
Douglas Gregoraae38d62010-05-22 05:17:18 +0000343 E->getType()->isRecordType()) {
Douglas Gregor7c38f152010-05-20 08:36:28 +0000344 E = CE->getSubExpr();
345 CXXRecordDecl *Derived
346 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
John McCallcf142162010-08-07 06:22:56 +0000347 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
Douglas Gregor7c38f152010-05-20 08:36:28 +0000348 continue;
349 }
Douglas Gregoraae38d62010-05-22 05:17:18 +0000350
John McCalle3027922010-08-25 11:45:40 +0000351 if (CE->getCastKind() == CK_NoOp) {
Douglas Gregoraae38d62010-05-22 05:17:18 +0000352 E = CE->getSubExpr();
353 continue;
354 }
355 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
John McCall086a4642010-11-24 05:12:34 +0000356 if (!ME->isArrow() && ME->getBase()->isRValue()) {
357 assert(ME->getBase()->getType()->isRecordType());
Douglas Gregor7c38f152010-05-20 08:36:28 +0000358 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
359 E = ME->getBase();
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000360 Adjustments.push_back(SubobjectAdjustment(Field));
Douglas Gregor7c38f152010-05-20 08:36:28 +0000361 continue;
362 }
363 }
Eli Friedman13ffdd82012-06-15 23:51:06 +0000364 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
365 if (BO->isPtrMemOp()) {
366 assert(BO->getLHS()->isRValue());
367 E = BO->getLHS();
368 const MemberPointerType *MPT =
369 BO->getRHS()->getType()->getAs<MemberPointerType>();
370 llvm::Value *Ptr = CGF.EmitScalarExpr(BO->getRHS());
371 Adjustments.push_back(SubobjectAdjustment(MPT, Ptr));
372 }
Anders Carlsson66413c22009-10-15 00:51:46 +0000373 }
Douglas Gregoraae38d62010-05-22 05:17:18 +0000374
John McCalle9dab632011-02-21 05:25:38 +0000375 if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
376 if (opaque->getType()->isRecordType())
377 return CGF.EmitOpaqueValueLValue(opaque).getAddress();
378
Douglas Gregoraae38d62010-05-22 05:17:18 +0000379 // Nothing changed.
380 break;
Anders Carlssonb80760b2009-08-16 17:50:25 +0000381 }
Anders Carlsson66413c22009-10-15 00:51:46 +0000382
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000383 // Create a reference temporary if necessary.
John McCall7a626f62010-09-15 10:14:12 +0000384 AggValueSlot AggSlot = AggValueSlot::ignored();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000385 if (CGF.hasAggregateLLVMType(E->getType()) &&
John McCall7a626f62010-09-15 10:14:12 +0000386 !E->getType()->isAnyComplexType()) {
Anders Carlsson18c205e2010-06-27 17:23:46 +0000387 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
388 InitializedDecl);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000389 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
John McCall8d6fc952011-08-25 20:40:09 +0000390 AggValueSlot::IsDestructed_t isDestructed
391 = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000392 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
393 Qualifiers(), isDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000394 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000395 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000396 }
John McCall31168b02011-06-15 23:02:42 +0000397
Anders Carlsson18c205e2010-06-27 17:23:46 +0000398 if (InitializedDecl) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000399 // Get the destructor for the reference temporary.
400 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
401 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
402 if (!ClassDecl->hasTrivialDestructor())
Douglas Gregorbac74902010-07-01 14:13:13 +0000403 ReferenceTemporaryDtor = ClassDecl->getDestructor();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000404 }
405 }
406
John McCall31168b02011-06-15 23:02:42 +0000407 RV = CGF.EmitAnyExpr(E, AggSlot);
408
Douglas Gregor7c38f152010-05-20 08:36:28 +0000409 // Check if need to perform derived-to-base casts and/or field accesses, to
410 // get from the temporary object we created (and, potentially, for which we
411 // extended the lifetime) to the subobject we're binding the reference to.
412 if (!Adjustments.empty()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000413 llvm::Value *Object = RV.getAggregateAddr();
Douglas Gregor7c38f152010-05-20 08:36:28 +0000414 for (unsigned I = Adjustments.size(); I != 0; --I) {
415 SubobjectAdjustment &Adjustment = Adjustments[I-1];
416 switch (Adjustment.Kind) {
417 case SubobjectAdjustment::DerivedToBaseAdjustment:
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000418 Object =
419 CGF.GetAddressOfBaseClass(Object,
420 Adjustment.DerivedToBase.DerivedClass,
John McCallcf142162010-08-07 06:22:56 +0000421 Adjustment.DerivedToBase.BasePath->path_begin(),
422 Adjustment.DerivedToBase.BasePath->path_end(),
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000423 /*NullCheckValue=*/false);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000424 break;
425
426 case SubobjectAdjustment::FieldAdjustment: {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000427 LValue LV = CGF.MakeAddrLValue(Object, E->getType());
428 LV = CGF.EmitLValueForField(LV, Adjustment.Field);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000429 if (LV.isSimple()) {
430 Object = LV.getAddress();
431 break;
432 }
433
434 // For non-simple lvalues, we actually have to create a copy of
435 // the object we're binding to.
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000436 QualType T = Adjustment.Field->getType().getNonReferenceType()
437 .getUnqualifiedType();
Anders Carlsson3f48c602010-06-27 17:52:15 +0000438 Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000439 LValue TempLV = CGF.MakeAddrLValue(Object,
440 Adjustment.Field->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000441 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000442 break;
443 }
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000444
Eli Friedman13ffdd82012-06-15 23:51:06 +0000445 case SubobjectAdjustment::MemberPointerAdjustment: {
446 Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress(
447 CGF, Object, Adjustment.Ptr.Ptr, Adjustment.Ptr.MPT);
448 break;
449 }
Douglas Gregor7c38f152010-05-20 08:36:28 +0000450 }
451 }
Eli Friedmanb6069252011-03-16 22:34:09 +0000452
453 return Object;
Anders Carlsson66413c22009-10-15 00:51:46 +0000454 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000455 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000456
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000457 if (RV.isAggregate())
458 return RV.getAggregateAddr();
Eli Friedmanc21cb442009-05-20 02:31:19 +0000459
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000460 // Create a temporary variable that we can bind the reference to.
Anders Carlsson18c205e2010-06-27 17:23:46 +0000461 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
462 InitializedDecl);
463
Daniel Dunbar03816342010-08-21 02:24:36 +0000464
465 unsigned Alignment =
466 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000467 if (RV.isScalar())
468 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
Daniel Dunbar03816342010-08-21 02:24:36 +0000469 /*Volatile=*/false, Alignment, E->getType());
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000470 else
471 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
472 /*Volatile=*/false);
473 return ReferenceTemporary;
474}
475
476RValue
Chris Lattnerf53c0962010-09-06 00:11:41 +0000477CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000478 const NamedDecl *InitializedDecl) {
479 llvm::Value *ReferenceTemporary = 0;
480 const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
John McCall31168b02011-06-15 23:02:42 +0000481 QualType ObjCARCReferenceLifetimeType;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000482 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
483 ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000484 ObjCARCReferenceLifetimeType,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000485 InitializedDecl);
John McCall31168b02011-06-15 23:02:42 +0000486 if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
Anders Carlsson3f48c602010-06-27 17:52:15 +0000487 return RValue::get(Value);
488
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000489 // Make sure to call the destructor for the reference temporary.
John McCall31168b02011-06-15 23:02:42 +0000490 const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl);
491 if (VD && VD->hasGlobalStorage()) {
492 if (ReferenceTemporaryDtor) {
Anders Carlsson3f48c602010-06-27 17:52:15 +0000493 llvm::Constant *DtorFn =
494 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
John McCallc84ed6a2012-05-01 06:13:13 +0000495 CGM.getCXXABI().registerGlobalDtor(*this, DtorFn,
John McCallad7c5c12011-02-08 08:22:06 +0000496 cast<llvm::Constant>(ReferenceTemporary));
John McCall31168b02011-06-15 23:02:42 +0000497 } else {
498 assert(!ObjCARCReferenceLifetimeType.isNull());
499 // Note: We intentionally do not register a global "destructor" to
500 // release the object.
Anders Carlsson3f48c602010-06-27 17:52:15 +0000501 }
John McCall31168b02011-06-15 23:02:42 +0000502
503 return RValue::get(Value);
Anders Carlsson3f48c602010-06-27 17:52:15 +0000504 }
John McCall8680f872010-07-21 06:29:51 +0000505
John McCall31168b02011-06-15 23:02:42 +0000506 if (ReferenceTemporaryDtor)
507 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
508 else {
509 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
510 case Qualifiers::OCL_None:
David Blaikie83d382b2011-09-23 05:06:16 +0000511 llvm_unreachable(
512 "Not a reference temporary that needs to be deallocated");
John McCall31168b02011-06-15 23:02:42 +0000513 case Qualifiers::OCL_ExplicitNone:
514 case Qualifiers::OCL_Autoreleasing:
515 // Nothing to do.
516 break;
517
John McCall4bd0fb12011-07-12 16:41:08 +0000518 case Qualifiers::OCL_Strong: {
519 bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>();
520 CleanupKind cleanupKind = getARCCleanupKind();
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000521 pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000522 precise ? destroyARCStrongPrecise : destroyARCStrongImprecise,
523 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000524 break;
John McCall4bd0fb12011-07-12 16:41:08 +0000525 }
John McCall31168b02011-06-15 23:02:42 +0000526
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000527 case Qualifiers::OCL_Weak: {
John McCall31168b02011-06-15 23:02:42 +0000528 // __weak objects always get EH cleanups; otherwise, exceptions
529 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000530 pushDestroy(NormalAndEHCleanup, ReferenceTemporary,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000531 ObjCARCReferenceLifetimeType, destroyARCWeak, true);
John McCall31168b02011-06-15 23:02:42 +0000532 break;
533 }
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000534 }
John McCall31168b02011-06-15 23:02:42 +0000535 }
536
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000537 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000538}
539
540
Mike Stump4a3999f2009-09-09 13:00:44 +0000541/// getAccessedFieldNo - Given an encoded value and a result number, return the
542/// input field number being accessed.
543unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000544 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000545 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
546 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000547}
548
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000549void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000550 if (!CatchUndefined)
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000551 return;
552
John McCallad7c5c12011-02-08 08:22:06 +0000553 // This needs to be to the standard address space.
554 Address = Builder.CreateBitCast(Address, Int8PtrTy);
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000555
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000556 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy);
Chris Lattnerbc3be652010-04-10 18:34:14 +0000557
Nuno Lopesddcce0b2012-05-09 15:53:34 +0000558 llvm::Value *Min = Builder.getFalse();
Nuno Lopes2b1ff462012-05-22 15:26:48 +0000559 llvm::Value *C = Builder.CreateCall2(F, Address, Min);
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000560 llvm::BasicBlock *Cont = createBasicBlock();
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000561 Builder.CreateCondBr(Builder.CreateICmpUGE(C,
Chris Lattner5e016ae2010-06-27 07:15:29 +0000562 llvm::ConstantInt::get(IntPtrTy, Size)),
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000563 Cont, getTrapBB());
564 EmitBlock(Cont);
565}
Chris Lattner4647a212007-08-31 22:49:20 +0000566
Chris Lattner116ce8f2010-01-09 21:40:03 +0000567
Chris Lattner116ce8f2010-01-09 21:40:03 +0000568CodeGenFunction::ComplexPairTy CodeGenFunction::
569EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
570 bool isInc, bool isPre) {
571 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
572 LV.isVolatileQualified());
573
574 llvm::Value *NextVal;
575 if (isa<llvm::IntegerType>(InVal.first->getType())) {
576 uint64_t AmountVal = isInc ? 1 : -1;
577 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
578
579 // Add the inc/dec to the real part.
580 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
581 } else {
582 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
583 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
584 if (!isInc)
585 FVal.changeSign();
586 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
587
588 // Add the inc/dec to the real part.
589 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
590 }
591
592 ComplexPairTy IncVal(NextVal, InVal.second);
593
594 // Store the updated result through the lvalue.
595 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
596
597 // If this is a postinc, return the value read from memory, otherwise use the
598 // updated value.
599 return isPre ? IncVal : InVal;
600}
601
602
Chris Lattnera45c5af2007-06-02 19:47:04 +0000603//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000604// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000605//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000606
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000607RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000608 if (Ty->isVoidType())
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000609 return RValue::get(0);
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000610
611 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000612 llvm::Type *EltTy = ConvertType(CTy->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000613 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000614 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000615 }
616
Chris Lattner65526f02010-08-23 05:26:13 +0000617 // If this is a use of an undefined aggregate type, the aggregate must have an
618 // identifiable address. Just because the contents of the value are undefined
619 // doesn't mean that the address can't be taken and compared.
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000620 if (hasAggregateLLVMType(Ty)) {
Chris Lattner65526f02010-08-23 05:26:13 +0000621 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
622 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000623 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000624
625 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000626}
627
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000628RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
629 const char *Name) {
630 ErrorUnsupported(E, Name);
631 return GetUndefRValue(E->getType());
632}
633
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000634LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
635 const char *Name) {
636 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000637 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000638 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000639}
640
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000641LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) {
642 LValue LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000643 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
Ken Dyck705ba072011-01-19 01:58:38 +0000644 EmitCheck(LV.getAddress(),
645 getContext().getTypeSizeInChars(E->getType()).getQuantity());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000646 return LV;
647}
648
Chris Lattner8394d792007-06-05 20:53:16 +0000649/// EmitLValue - Emit code to compute a designator that specifies the location
650/// of the expression.
651///
Mike Stump4a3999f2009-09-09 13:00:44 +0000652/// This can return one of two things: a simple address or a bitfield reference.
653/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
654/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000655///
Mike Stump4a3999f2009-09-09 13:00:44 +0000656/// If this returns a bitfield reference, nothing about the pointee type of the
657/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000658///
Mike Stump4a3999f2009-09-09 13:00:44 +0000659/// If this returns a normal address, and if the lvalue's C type is fixed size,
660/// this method guarantees that the returned pointer type will point to an LLVM
661/// type of the same size of the lvalue's type. If the lvalue has a variable
662/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000663///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000664LValue CodeGenFunction::EmitLValue(const Expr *E) {
665 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000666 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000667
John McCallc109a252011-11-07 03:59:57 +0000668 case Expr::ObjCPropertyRefExprClass:
669 llvm_unreachable("cannot emit a property reference directly");
670
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000671 case Expr::ObjCSelectorExprClass:
672 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000673 case Expr::ObjCIsaExprClass:
674 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000675 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000676 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
Douglas Gregor914af212010-04-23 04:16:32 +0000677 case Expr::CompoundAssignOperatorClass:
John McCalla2342eb2010-12-05 02:00:02 +0000678 if (!E->getType()->isAnyComplexType())
679 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
680 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000681 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000682 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000683 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000684 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000685 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000686 case Expr::VAArgExprClass:
687 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000688 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000689 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000690 case Expr::ParenExprClass:
691 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000692 case Expr::GenericSelectionExprClass:
693 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000694 case Expr::PredefinedExprClass:
695 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000696 case Expr::StringLiteralClass:
697 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000698 case Expr::ObjCEncodeExprClass:
699 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000700 case Expr::PseudoObjectExprClass:
701 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000702 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000703 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000704 case Expr::CXXTemporaryObjectExprClass:
705 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000706 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
707 case Expr::CXXBindTemporaryExprClass:
708 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000709 case Expr::LambdaExprClass:
710 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000711
712 case Expr::ExprWithCleanupsClass: {
713 const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E);
714 enterFullExpression(cleanups);
715 RunCleanupsScope Scope(*this);
716 return EmitLValue(cleanups->getSubExpr());
717 }
718
Douglas Gregor747eb782010-07-08 06:14:04 +0000719 case Expr::CXXScalarValueInitExprClass:
720 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
Anders Carlsson52ce3bb2009-11-14 01:51:50 +0000721 case Expr::CXXDefaultArgExprClass:
722 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Mike Stumpc9b231c2009-11-15 08:09:41 +0000723 case Expr::CXXTypeidExprClass:
724 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000725
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000726 case Expr::ObjCMessageExprClass:
727 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000728 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +0000729 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +0000730 case Expr::StmtExprClass:
731 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000732 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +0000733 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000734 case Expr::ArraySubscriptExprClass:
735 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +0000736 case Expr::ExtVectorElementExprClass:
737 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000738 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +0000739 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +0000740 case Expr::CompoundLiteralExprClass:
741 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +0000742 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +0000743 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +0000744 case Expr::BinaryConditionalOperatorClass:
745 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +0000746 case Expr::ChooseExprClass:
Eli Friedmane0a5b8b2009-03-04 05:52:32 +0000747 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
John McCall1bf58462011-02-16 08:02:54 +0000748 case Expr::OpaqueValueExprClass:
749 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +0000750 case Expr::SubstNonTypeTemplateParmExprClass:
751 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +0000752 case Expr::ImplicitCastExprClass:
753 case Expr::CStyleCastExprClass:
754 case Expr::CXXFunctionalCastExprClass:
755 case Expr::CXXStaticCastExprClass:
756 case Expr::CXXDynamicCastExprClass:
757 case Expr::CXXReinterpretCastExprClass:
758 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +0000759 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +0000760 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000761
Douglas Gregorfe314812011-06-21 17:03:29 +0000762 case Expr::MaterializeTemporaryExprClass:
763 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000764 }
765}
766
John McCall71335052012-03-10 03:05:10 +0000767/// Given an object of the given canonical type, can we safely copy a
768/// value out of it based on its initializer?
769static bool isConstantEmittableObjectType(QualType type) {
770 assert(type.isCanonical());
771 assert(!type->isReferenceType());
772
773 // Must be const-qualified but non-volatile.
774 Qualifiers qs = type.getLocalQualifiers();
775 if (!qs.hasConst() || qs.hasVolatile()) return false;
776
777 // Otherwise, all object types satisfy this except C++ classes with
778 // mutable subobjects or non-trivial copy/destroy behavior.
779 if (const RecordType *RT = dyn_cast<RecordType>(type))
780 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
781 if (RD->hasMutableFields() || !RD->isTrivial())
782 return false;
783
784 return true;
785}
786
787/// Can we constant-emit a load of a reference to a variable of the
788/// given type? This is different from predicates like
789/// Decl::isUsableInConstantExpressions because we do want it to apply
790/// in situations that don't necessarily satisfy the language's rules
791/// for this (e.g. C++'s ODR-use rules). For example, we want to able
792/// to do this with const float variables even if those variables
793/// aren't marked 'constexpr'.
794enum ConstantEmissionKind {
795 CEK_None,
796 CEK_AsReferenceOnly,
797 CEK_AsValueOrReference,
798 CEK_AsValueOnly
799};
800static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
801 type = type.getCanonicalType();
802 if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) {
803 if (isConstantEmittableObjectType(ref->getPointeeType()))
804 return CEK_AsValueOrReference;
805 return CEK_AsReferenceOnly;
806 }
807 if (isConstantEmittableObjectType(type))
808 return CEK_AsValueOnly;
809 return CEK_None;
810}
811
812/// Try to emit a reference to the given value without producing it as
813/// an l-value. This is actually more than an optimization: we can't
814/// produce an l-value for variables that we never actually captured
815/// in a block or lambda, which means const int variables or constexpr
816/// literals or similar.
817CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +0000818CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
819 ValueDecl *value = refExpr->getDecl();
820
John McCall71335052012-03-10 03:05:10 +0000821 // The value needs to be an enum constant or a constant variable.
822 ConstantEmissionKind CEK;
823 if (isa<ParmVarDecl>(value)) {
824 CEK = CEK_None;
825 } else if (VarDecl *var = dyn_cast<VarDecl>(value)) {
826 CEK = checkVarTypeForConstantEmission(var->getType());
827 } else if (isa<EnumConstantDecl>(value)) {
828 CEK = CEK_AsValueOnly;
829 } else {
830 CEK = CEK_None;
831 }
832 if (CEK == CEK_None) return ConstantEmission();
833
John McCall71335052012-03-10 03:05:10 +0000834 Expr::EvalResult result;
835 bool resultIsReference;
836 QualType resultType;
837
838 // It's best to evaluate all the way as an r-value if that's permitted.
839 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +0000840 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000841 resultIsReference = false;
842 resultType = refExpr->getType();
843
844 // Otherwise, try to evaluate as an l-value.
845 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +0000846 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000847 resultIsReference = true;
848 resultType = value->getType();
849
850 // Failure.
851 } else {
852 return ConstantEmission();
853 }
854
855 // In any case, if the initializer has side-effects, abandon ship.
856 if (result.HasSideEffects)
857 return ConstantEmission();
858
859 // Emit as a constant.
860 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
861
862 // Make sure we emit a debug reference to the global variable.
863 // This should probably fire even for
864 if (isa<VarDecl>(value)) {
865 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
John McCall113bee02012-03-10 09:33:50 +0000866 EmitDeclRefExprDbgValue(refExpr, C);
John McCall71335052012-03-10 03:05:10 +0000867 } else {
868 assert(isa<EnumConstantDecl>(value));
John McCall113bee02012-03-10 09:33:50 +0000869 EmitDeclRefExprDbgValue(refExpr, C);
John McCall71335052012-03-10 03:05:10 +0000870 }
871
872 // If we emitted a reference constant, we need to dereference that.
873 if (resultIsReference)
874 return ConstantEmission::forReference(C);
875
876 return ConstantEmission::forValue(C);
877}
878
John McCall1553b192011-06-16 04:16:24 +0000879llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
880 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +0000881 lvalue.getAlignment().getQuantity(),
882 lvalue.getType(), lvalue.getTBAAInfo());
John McCall1553b192011-06-16 04:16:24 +0000883}
884
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000885static bool hasBooleanRepresentation(QualType Ty) {
886 if (Ty->isBooleanType())
887 return true;
888
889 if (const EnumType *ET = Ty->getAs<EnumType>())
890 return ET->getDecl()->getIntegerType()->isBooleanType();
891
Douglas Gregor298f43d2012-04-12 20:42:30 +0000892 if (const AtomicType *AT = Ty->getAs<AtomicType>())
893 return hasBooleanRepresentation(AT->getValueType());
894
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000895 return false;
896}
897
898llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
899 const EnumType *ET = Ty->getAs<EnumType>();
Chandler Carruth8b4140d2012-03-27 23:58:37 +0000900 bool IsRegularCPlusPlusEnum = (getLangOpts().CPlusPlus && ET &&
901 CGM.getCodeGenOpts().StrictEnums &&
902 !ET->getDecl()->isFixed());
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000903 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000904 if (!IsBool && !IsRegularCPlusPlusEnum)
905 return NULL;
906
907 llvm::APInt Min;
908 llvm::APInt End;
909 if (IsBool) {
910 Min = llvm::APInt(8, 0);
911 End = llvm::APInt(8, 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000912 } else {
913 const EnumDecl *ED = ET->getDecl();
Ted Kremenekdb74d0b2012-05-01 17:56:53 +0000914 llvm::Type *LTy = ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000915 unsigned Bitwidth = LTy->getScalarSizeInBits();
916 unsigned NumNegativeBits = ED->getNumNegativeBits();
917 unsigned NumPositiveBits = ED->getNumPositiveBits();
918
919 if (NumNegativeBits) {
920 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
921 assert(NumBits <= Bitwidth);
922 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
923 Min = -End;
924 } else {
925 assert(NumPositiveBits <= Bitwidth);
926 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
927 Min = llvm::APInt(Bitwidth, 0);
928 }
929 }
930
Duncan Sandsc720e782012-04-15 18:04:54 +0000931 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +0000932 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000933}
934
Daniel Dunbar1d425462009-02-10 00:57:50 +0000935llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
Dan Gohman947c9af2010-10-14 23:06:10 +0000936 unsigned Alignment, QualType Ty,
937 llvm::MDNode *TBAAInfo) {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000938 llvm::LoadInst *Load = Builder.CreateLoad(Addr);
Daniel Dunbarc76493a2009-11-29 21:23:36 +0000939 if (Volatile)
940 Load->setVolatile(true);
Daniel Dunbar03816342010-08-21 02:24:36 +0000941 if (Alignment)
942 Load->setAlignment(Alignment);
Dan Gohman947c9af2010-10-14 23:06:10 +0000943 if (TBAAInfo)
944 CGM.DecorateInstruction(Load, TBAAInfo);
David Chisnallfa35df62012-01-16 17:27:18 +0000945 // If this is an atomic type, all normal reads must be atomic
946 if (Ty->isAtomicType())
947 Load->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar1d425462009-02-10 00:57:50 +0000948
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000949 if (CGM.getCodeGenOpts().OptimizationLevel > 0)
950 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
951 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +0000952
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000953 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +0000954}
955
John McCall3a7f6922010-10-27 20:58:56 +0000956llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
957 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000958 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +0000959 // This should really always be an i1, but sometimes it's already
960 // an i8, and it's awkward to track those cases down.
961 if (Value->getType()->isIntegerTy(1))
962 return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool");
963 assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8");
964 }
965
966 return Value;
967}
968
969llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
970 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000971 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +0000972 assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8");
973 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
974 }
975
976 return Value;
977}
978
Daniel Dunbar1d425462009-02-10 00:57:50 +0000979void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
Daniel Dunbar03816342010-08-21 02:24:36 +0000980 bool Volatile, unsigned Alignment,
Dan Gohman947c9af2010-10-14 23:06:10 +0000981 QualType Ty,
David Chisnallfa35df62012-01-16 17:27:18 +0000982 llvm::MDNode *TBAAInfo,
983 bool isInit) {
John McCall3a7f6922010-10-27 20:58:56 +0000984 Value = EmitToMemory(Value, Ty);
Chris Lattner1a5f8972011-07-10 03:38:35 +0000985
Daniel Dunbar03816342010-08-21 02:24:36 +0000986 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
987 if (Alignment)
988 Store->setAlignment(Alignment);
Dan Gohman947c9af2010-10-14 23:06:10 +0000989 if (TBAAInfo)
990 CGM.DecorateInstruction(Store, TBAAInfo);
David Chisnallfa35df62012-01-16 17:27:18 +0000991 if (!isInit && Ty->isAtomicType())
992 Store->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar1d425462009-02-10 00:57:50 +0000993}
994
David Chisnallfa35df62012-01-16 17:27:18 +0000995void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
996 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +0000997 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +0000998 lvalue.getAlignment().getQuantity(), lvalue.getType(),
David Chisnallfa35df62012-01-16 17:27:18 +0000999 lvalue.getTBAAInfo(), isInit);
John McCall1553b192011-06-16 04:16:24 +00001000}
1001
Mike Stump4a3999f2009-09-09 13:00:44 +00001002/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1003/// method emits the address of the lvalue, then loads the result as an rvalue,
1004/// returning the rvalue.
John McCall55e1fbc2011-06-25 02:11:03 +00001005RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001006 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001007 // load of a __weak object.
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001008 llvm::Value *AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001009 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1010 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001011 }
John McCall31168b02011-06-15 23:02:42 +00001012 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak)
1013 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
Mike Stump4a3999f2009-09-09 13:00:44 +00001014
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001015 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001016 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001017
John McCalla1dee5302010-08-22 10:59:02 +00001018 // Everything needs a load.
John McCall55e1fbc2011-06-25 02:11:03 +00001019 return RValue::get(EmitLoadOfScalar(LV));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001020 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001021
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001022 if (LV.isVectorElt()) {
Eli Friedman610bb872012-03-22 22:36:39 +00001023 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1024 LV.isVolatileQualified());
1025 Load->setAlignment(LV.getAlignment().getQuantity());
1026 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001027 "vecext"));
1028 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001029
1030 // If this is a reference to a subset of the elements of a vector, either
1031 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001032 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001033 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001034
John McCallc109a252011-11-07 03:59:57 +00001035 assert(LV.isBitField() && "Unknown LValue type!");
1036 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001037}
1038
John McCall55e1fbc2011-06-25 02:11:03 +00001039RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001040 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001041
Daniel Dunbar3447a022010-04-13 23:34:15 +00001042 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001043 llvm::Type *ResLTy = ConvertType(LV.getType());
Daniel Dunbar3447a022010-04-13 23:34:15 +00001044 unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001045
Daniel Dunbar3447a022010-04-13 23:34:15 +00001046 // Compute the result as an OR of all of the individual component accesses.
1047 llvm::Value *Res = 0;
1048 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
1049 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00001050 CharUnits AccessAlignment = AI.AccessAlignment;
1051 if (!LV.getAlignment().isZero())
1052 AccessAlignment = std::min(AccessAlignment, LV.getAlignment());
Mike Stump4a3999f2009-09-09 13:00:44 +00001053
Daniel Dunbar3447a022010-04-13 23:34:15 +00001054 // Get the field pointer.
1055 llvm::Value *Ptr = LV.getBitFieldBaseAddr();
Mike Stump4a3999f2009-09-09 13:00:44 +00001056
Daniel Dunbar3447a022010-04-13 23:34:15 +00001057 // Only offset by the field index if used, so that incoming values are not
1058 // required to be structures.
1059 if (AI.FieldIndex)
1060 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
Mike Stump4a3999f2009-09-09 13:00:44 +00001061
Daniel Dunbar3447a022010-04-13 23:34:15 +00001062 // Offset by the byte offset, if used.
Ken Dyckf76759c2011-04-24 10:04:59 +00001063 if (!AI.FieldByteOffset.isZero()) {
John McCallad7c5c12011-02-08 08:22:06 +00001064 Ptr = EmitCastToVoidPtr(Ptr);
Ken Dyckf76759c2011-04-24 10:04:59 +00001065 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1066 "bf.field.offs");
Daniel Dunbar3447a022010-04-13 23:34:15 +00001067 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001068
Daniel Dunbar3447a022010-04-13 23:34:15 +00001069 // Cast to the access type.
Chris Lattnerece04092012-02-07 00:39:47 +00001070 llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(), AI.AccessWidth,
John McCall55e1fbc2011-06-25 02:11:03 +00001071 CGM.getContext().getTargetAddressSpace(LV.getType()));
Daniel Dunbar3447a022010-04-13 23:34:15 +00001072 Ptr = Builder.CreateBitCast(Ptr, PTy);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001073
Daniel Dunbar3447a022010-04-13 23:34:15 +00001074 // Perform the load.
1075 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00001076 Load->setAlignment(AccessAlignment.getQuantity());
Daniel Dunbar3447a022010-04-13 23:34:15 +00001077
1078 // Shift out unused low bits and mask out unused high bits.
1079 llvm::Value *Val = Load;
1080 if (AI.FieldBitStart)
Daniel Dunbar67aba792010-04-15 03:47:33 +00001081 Val = Builder.CreateLShr(Load, AI.FieldBitStart);
Daniel Dunbar3447a022010-04-13 23:34:15 +00001082 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
1083 AI.TargetBitWidth),
1084 "bf.clear");
1085
1086 // Extend or truncate to the target size.
1087 if (AI.AccessWidth < ResSizeInBits)
1088 Val = Builder.CreateZExt(Val, ResLTy);
1089 else if (AI.AccessWidth > ResSizeInBits)
1090 Val = Builder.CreateTrunc(Val, ResLTy);
1091
1092 // Shift into place, and OR into the result.
1093 if (AI.TargetBitOffset)
1094 Val = Builder.CreateShl(Val, AI.TargetBitOffset);
1095 Res = Res ? Builder.CreateOr(Res, Val) : Val;
Daniel Dunbaread7c912008-08-06 05:08:45 +00001096 }
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001097
Daniel Dunbar3447a022010-04-13 23:34:15 +00001098 // If the bit-field is signed, perform the sign-extension.
1099 //
1100 // FIXME: This can easily be folded into the load of the high bits, which
1101 // could also eliminate the mask of high bits in some situations.
1102 if (Info.isSigned()) {
Daniel Dunbar67aba792010-04-15 03:47:33 +00001103 unsigned ExtraBits = ResSizeInBits - Info.getSize();
Daniel Dunbar3447a022010-04-13 23:34:15 +00001104 if (ExtraBits)
1105 Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
1106 ExtraBits, "bf.val.sext");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001107 }
Eli Friedmanf2442dc2008-05-17 20:03:47 +00001108
Daniel Dunbar3447a022010-04-13 23:34:15 +00001109 return RValue::get(Res);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001110}
1111
Nate Begemanb699c9b2009-01-18 06:42:49 +00001112// If this is a reference to a subset of the elements of a vector, create an
1113// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001114RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
Eli Friedman610bb872012-03-22 22:36:39 +00001115 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1116 LV.isVolatileQualified());
1117 Load->setAlignment(LV.getAlignment().getQuantity());
1118 llvm::Value *Vec = Load;
Mike Stump4a3999f2009-09-09 13:00:44 +00001119
Nate Begemanf322eab2008-05-09 06:41:27 +00001120 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001121
1122 // If the result of the expression is a non-vector type, we must be extracting
1123 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001124 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001125 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001126 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattner5e016ae2010-06-27 07:15:29 +00001127 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001128 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001129 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001130
1131 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001132 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001133
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001134 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001135 for (unsigned i = 0; i != NumResultElts; ++i)
1136 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001137
Chris Lattner91c08ad2011-02-15 00:14:06 +00001138 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1139 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001140 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001141 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001142}
1143
1144
Chris Lattner9369a562007-06-29 16:31:29 +00001145
Chris Lattner8394d792007-06-05 20:53:16 +00001146/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1147/// lvalue, where both are guaranteed to the have the same type, and that type
1148/// is 'Ty'.
David Chisnallfa35df62012-01-16 17:27:18 +00001149void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001150 if (!Dst.isSimple()) {
1151 if (Dst.isVectorElt()) {
1152 // Read/modify/write the vector, inserting the new element.
Eli Friedman610bb872012-03-22 22:36:39 +00001153 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1154 Dst.isVolatileQualified());
1155 Load->setAlignment(Dst.getAlignment().getQuantity());
1156 llvm::Value *Vec = Load;
Chris Lattner4647a212007-08-31 22:49:20 +00001157 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001158 Dst.getVectorIdx(), "vecins");
Eli Friedman610bb872012-03-22 22:36:39 +00001159 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1160 Dst.isVolatileQualified());
1161 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001162 return;
1163 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001164
Nate Begemance4d7fc2008-04-18 23:10:10 +00001165 // If this is an update of extended vector elements, insert them as
1166 // appropriate.
1167 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001168 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001169
John McCallc109a252011-11-07 03:59:57 +00001170 assert(Dst.isBitField() && "Unknown LValue type");
1171 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001172 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001173
John McCall31168b02011-06-15 23:02:42 +00001174 // There's special magic for assigning into an ARC-qualified l-value.
1175 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1176 switch (Lifetime) {
1177 case Qualifiers::OCL_None:
1178 llvm_unreachable("present but none");
1179
1180 case Qualifiers::OCL_ExplicitNone:
1181 // nothing special
1182 break;
1183
1184 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001185 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001186 return;
1187
1188 case Qualifiers::OCL_Weak:
1189 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1190 return;
1191
1192 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001193 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1194 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001195 // fall into the normal path
1196 break;
1197 }
1198 }
1199
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001200 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001201 // load of a __weak object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001202 llvm::Value *LvalueDst = Dst.getAddress();
1203 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001204 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001205 return;
1206 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001207
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001208 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001209 // load of a __strong object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001210 llvm::Value *LvalueDst = Dst.getAddress();
1211 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001212 if (Dst.isObjCIvar()) {
1213 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00001214 llvm::Type *ResultType = ConvertType(getContext().LongTy);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001215 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001216 llvm::Value *dst = RHS;
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001217 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1218 llvm::Value *LHS =
1219 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1220 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001221 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001222 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001223 } else if (Dst.isGlobalObjCRef()) {
1224 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1225 Dst.isThreadLocalRef());
1226 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001227 else
1228 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001229 return;
1230 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001231
Chris Lattner6278e6a2007-08-11 00:04:45 +00001232 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001233 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001234}
1235
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001236void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001237 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001238 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001239
Daniel Dunbar67aba792010-04-15 03:47:33 +00001240 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001241 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
Daniel Dunbar67aba792010-04-15 03:47:33 +00001242 unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
Daniel Dunbaread7c912008-08-06 05:08:45 +00001243
Daniel Dunbar67aba792010-04-15 03:47:33 +00001244 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001245 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001246
Douglas Gregor298f43d2012-04-12 20:42:30 +00001247 if (hasBooleanRepresentation(Dst.getType()))
Anders Carlsson8345a702010-04-17 21:52:22 +00001248 SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
1249
Daniel Dunbar67aba792010-04-15 03:47:33 +00001250 SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
1251 Info.getSize()),
1252 "bf.value");
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001253
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001254 // Return the new value of the bit-field, if requested.
1255 if (Result) {
1256 // Cast back to the proper type for result.
Chris Lattner2192fe52011-07-18 04:24:23 +00001257 llvm::Type *SrcTy = Src.getScalarVal()->getType();
Daniel Dunbar67aba792010-04-15 03:47:33 +00001258 llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
1259 "bf.reload.val");
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001260
1261 // Sign extend if necessary.
Daniel Dunbar67aba792010-04-15 03:47:33 +00001262 if (Info.isSigned()) {
1263 unsigned ExtraBits = ResSizeInBits - Info.getSize();
1264 if (ExtraBits)
1265 ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
1266 ExtraBits, "bf.reload.sext");
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001267 }
1268
Daniel Dunbar67aba792010-04-15 03:47:33 +00001269 *Result = ReloadVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001270 }
1271
Daniel Dunbar67aba792010-04-15 03:47:33 +00001272 // Iterate over the components, writing each piece to memory.
1273 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
1274 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00001275 CharUnits AccessAlignment = AI.AccessAlignment;
1276 if (!Dst.getAlignment().isZero())
1277 AccessAlignment = std::min(AccessAlignment, Dst.getAlignment());
Eli Friedmanf2442dc2008-05-17 20:03:47 +00001278
Daniel Dunbar67aba792010-04-15 03:47:33 +00001279 // Get the field pointer.
1280 llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
John McCallad7c5c12011-02-08 08:22:06 +00001281 unsigned addressSpace =
1282 cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
Mike Stump4a3999f2009-09-09 13:00:44 +00001283
Daniel Dunbar67aba792010-04-15 03:47:33 +00001284 // Only offset by the field index if used, so that incoming values are not
1285 // required to be structures.
1286 if (AI.FieldIndex)
1287 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
Mike Stump4a3999f2009-09-09 13:00:44 +00001288
Daniel Dunbar67aba792010-04-15 03:47:33 +00001289 // Offset by the byte offset, if used.
Ken Dyckf76759c2011-04-24 10:04:59 +00001290 if (!AI.FieldByteOffset.isZero()) {
John McCallad7c5c12011-02-08 08:22:06 +00001291 Ptr = EmitCastToVoidPtr(Ptr);
Ken Dyckf76759c2011-04-24 10:04:59 +00001292 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1293 "bf.field.offs");
Daniel Dunbar67aba792010-04-15 03:47:33 +00001294 }
Eli Friedmanf2442dc2008-05-17 20:03:47 +00001295
Daniel Dunbar67aba792010-04-15 03:47:33 +00001296 // Cast to the access type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001297 llvm::Type *AccessLTy =
John McCallad7c5c12011-02-08 08:22:06 +00001298 llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth);
1299
Chris Lattner2192fe52011-07-18 04:24:23 +00001300 llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace);
Daniel Dunbar67aba792010-04-15 03:47:33 +00001301 Ptr = Builder.CreateBitCast(Ptr, PTy);
Mike Stump4a3999f2009-09-09 13:00:44 +00001302
Daniel Dunbar67aba792010-04-15 03:47:33 +00001303 // Extract the piece of the bit-field value to write in this access, limited
1304 // to the values that are part of this access.
1305 llvm::Value *Val = SrcVal;
1306 if (AI.TargetBitOffset)
1307 Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
1308 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
1309 AI.TargetBitWidth));
Mike Stump4a3999f2009-09-09 13:00:44 +00001310
Daniel Dunbar67aba792010-04-15 03:47:33 +00001311 // Extend or truncate to the access size.
Daniel Dunbar67aba792010-04-15 03:47:33 +00001312 if (ResSizeInBits < AI.AccessWidth)
1313 Val = Builder.CreateZExt(Val, AccessLTy);
1314 else if (ResSizeInBits > AI.AccessWidth)
1315 Val = Builder.CreateTrunc(Val, AccessLTy);
Mike Stump4a3999f2009-09-09 13:00:44 +00001316
Daniel Dunbar67aba792010-04-15 03:47:33 +00001317 // Shift into the position in memory.
1318 if (AI.FieldBitStart)
1319 Val = Builder.CreateShl(Val, AI.FieldBitStart);
1320
1321 // If necessary, load and OR in bits that are outside of the bit-field.
1322 if (AI.TargetBitWidth != AI.AccessWidth) {
1323 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00001324 Load->setAlignment(AccessAlignment.getQuantity());
Daniel Dunbar67aba792010-04-15 03:47:33 +00001325
1326 // Compute the mask for zeroing the bits that are part of the bit-field.
1327 llvm::APInt InvMask =
1328 ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
1329 AI.FieldBitStart + AI.TargetBitWidth);
1330
1331 // Apply the mask and OR in to the value to write.
1332 Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
1333 }
1334
1335 // Write the value.
1336 llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
1337 Dst.isVolatileQualified());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00001338 Store->setAlignment(AccessAlignment.getQuantity());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001339 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001340}
1341
Nate Begemance4d7fc2008-04-18 23:10:10 +00001342void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001343 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001344 // This access turns into a read/modify/write of the vector. Load the input
1345 // value now.
Eli Friedman610bb872012-03-22 22:36:39 +00001346 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1347 Dst.isVolatileQualified());
1348 Load->setAlignment(Dst.getAlignment().getQuantity());
1349 llvm::Value *Vec = Load;
Nate Begemanf322eab2008-05-09 06:41:27 +00001350 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001351
Chris Lattner4647a212007-08-31 22:49:20 +00001352 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001353
John McCall55e1fbc2011-06-25 02:11:03 +00001354 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001355 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001356 unsigned NumDstElts =
1357 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1358 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001359 // Use shuffle vector is the src and destination are the same number of
1360 // elements and restore the vector mask since it is on the side it will be
1361 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001362 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001363 for (unsigned i = 0; i != NumSrcElts; ++i)
1364 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001365
Chris Lattner91c08ad2011-02-15 00:14:06 +00001366 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001367 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001368 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001369 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001370 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001371 // Extended the source vector to the same length and then shuffle it
1372 // into the destination.
1373 // FIXME: since we're shuffling with undef, can we just use the indices
1374 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001375 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001376 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001377 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001378 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001379 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001380 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001381 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001382 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001383 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001384 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001385 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001386 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001387 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001388
Nate Begemanb699c9b2009-01-18 06:42:49 +00001389 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001390 for (unsigned i = 0; i != NumSrcElts; ++i)
1391 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001392 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001393 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001394 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001395 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001396 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001397 }
1398 } else {
1399 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001400 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001401 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001402 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001403 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001404
Eli Friedman610bb872012-03-22 22:36:39 +00001405 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1406 Dst.isVolatileQualified());
1407 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001408}
1409
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001410// setObjCGCLValueClass - sets class of he lvalue for the purpose of
1411// generating write-barries API. It is currently a global, ivar,
1412// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001413static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001414 LValue &LV,
1415 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001416 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001417 return;
1418
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001419 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001420 QualType ExpTy = E->getType();
1421 if (IsMemberAccess && ExpTy->isPointerType()) {
1422 // If ivar is a structure pointer, assigning to field of
1423 // this struct follows gcc's behavior and makes it a non-ivar
1424 // writer-barrier conservatively.
1425 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1426 if (ExpTy->isRecordType()) {
1427 LV.setObjCIvar(false);
1428 return;
1429 }
1430 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001431 LV.setObjCIvar(true);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001432 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1433 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001434 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001435 return;
1436 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001437
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001438 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1439 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001440 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001441 LV.setGlobalObjCRef(true);
1442 LV.setThreadLocalRef(VD->isThreadSpecified());
Fariborz Jahanian217af242010-07-20 20:30:03 +00001443 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001444 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001445 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001446 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001447 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001448
1449 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001450 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001451 return;
1452 }
1453
1454 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001455 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001456 if (LV.isObjCIvar()) {
1457 // If cast is to a structure pointer, follow gcc's behavior and make it
1458 // a non-ivar write-barrier.
1459 QualType ExpTy = E->getType();
1460 if (ExpTy->isPointerType())
1461 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1462 if (ExpTy->isRecordType())
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001463 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001464 }
1465 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001466 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001467
1468 if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1469 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1470 return;
1471 }
1472
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001473 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001474 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001475 return;
1476 }
1477
1478 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001479 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001480 return;
1481 }
John McCall31168b02011-06-15 23:02:42 +00001482
1483 if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001484 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001485 return;
1486 }
1487
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001488 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001489 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001490 if (LV.isObjCIvar() && !LV.isObjCArray())
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001491 // Using array syntax to assigning to what an ivar points to is not
1492 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001493 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001494 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1495 // Using array syntax to assigning to what global points to is not
1496 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001497 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001498 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001499 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001500
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001501 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001502 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001503 // We don't know if member is an 'ivar', but this flag is looked at
1504 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001505 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001506 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001507 }
1508}
1509
Chris Lattner3f32d692011-07-12 06:52:18 +00001510static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001511EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001512 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001513 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001514 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001515 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001516}
1517
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001518static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1519 const Expr *E, const VarDecl *VD) {
Daniel Dunbar7e215ea2009-11-08 09:46:46 +00001520 assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001521 "Var decl must have external storage or be a file var decl!");
1522
1523 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001524 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1525 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001526 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001527 QualType T = E->getType();
1528 LValue LV;
1529 if (VD->getType()->isReferenceType()) {
1530 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001531 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001532 V = LI;
1533 LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1534 } else {
1535 LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1536 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001537 setObjCGCLValueClass(CGF.getContext(), E, LV);
1538 return LV;
1539}
1540
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001541static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001542 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001543 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001544 if (!FD->hasPrototype()) {
1545 if (const FunctionProtoType *Proto =
1546 FD->getType()->getAs<FunctionProtoType>()) {
1547 // Ugly case: for a K&R-style definition, the type of the definition
1548 // isn't the same as the type of a use. Correct for this with a
1549 // bitcast.
1550 QualType NoProtoType =
1551 CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1552 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001553 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001554 }
1555 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001556 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Daniel Dunbar5c816372010-08-21 04:20:22 +00001557 return CGF.MakeAddrLValue(V, E->getType(), Alignment);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001558}
1559
Chris Lattnerd7f58862007-06-02 05:24:33 +00001560LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001561 const NamedDecl *ND = E->getDecl();
Eli Friedmana0544d62011-12-03 04:14:32 +00001562 CharUnits Alignment = getContext().getDeclAlign(ND);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001563 QualType T = E->getType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001564
Eli Friedman5720e342012-01-21 04:52:58 +00001565 // FIXME: We should be able to assert this for FunctionDecls as well!
1566 // FIXME: We should be able to assert this for all DeclRefExprs, not just
1567 // those with a valid source location.
1568 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1569 !E->getLocation().isValid()) &&
1570 "Should not use decl without marking it used!");
1571
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001572 if (ND->hasAttr<WeakRefAttr>()) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001573 const ValueDecl *VD = cast<ValueDecl>(ND);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001574 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
Daniel Dunbar5c816372010-08-21 04:20:22 +00001575 return MakeAddrLValue(Aliasee, E->getType(), Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001576 }
1577
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001578 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001579 // Check if this is a global variable.
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001580 if (VD->hasExternalStorage() || VD->isFileVarDecl())
1581 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00001582
John McCall113bee02012-03-10 09:33:50 +00001583 bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1584
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001585 bool NonGCable = VD->hasLocalStorage() &&
1586 !VD->getType()->isReferenceType() &&
John McCall113bee02012-03-10 09:33:50 +00001587 !isBlockVariable;
Anders Carlsson6eee9722009-11-07 22:46:42 +00001588
1589 llvm::Value *V = LocalDeclMap[VD];
Fariborz Jahanian366a9482010-09-07 23:26:17 +00001590 if (!V && VD->isStaticLocal())
Fariborz Jahanian4d55b2d2010-04-19 18:15:02 +00001591 V = CGM.getStaticLocalDeclAddress(VD);
Eli Friedman9fbeba02012-02-11 02:57:39 +00001592
1593 // Use special handling for lambdas.
John McCall113bee02012-03-10 09:33:50 +00001594 if (!V) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00001595 if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1596 QualType LambdaTagType = getContext().getTagDeclType(FD->getParent());
1597 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
1598 LambdaTagType);
1599 return EmitLValueForField(LambdaLV, FD);
1600 }
Eli Friedman9fbeba02012-02-11 02:57:39 +00001601
John McCall113bee02012-03-10 09:33:50 +00001602 assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
1603 CharUnits alignment = getContext().getDeclAlign(VD);
1604 return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
1605 E->getType(), alignment);
1606 }
1607
Anders Carlsson6eee9722009-11-07 22:46:42 +00001608 assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1609
John McCall113bee02012-03-10 09:33:50 +00001610 if (isBlockVariable)
Fariborz Jahanian2f2fa722011-01-26 23:08:27 +00001611 V = BuildBlockByrefAddress(V, VD);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001612
Eli Friedmand20adbd2011-11-16 00:42:57 +00001613 LValue LV;
1614 if (VD->getType()->isReferenceType()) {
1615 llvm::LoadInst *LI = Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001616 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001617 V = LI;
1618 LV = MakeNaturalAlignAddrLValue(V, T);
1619 } else {
1620 LV = MakeAddrLValue(V, T, Alignment);
1621 }
Chris Lattner3f32d692011-07-12 06:52:18 +00001622
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001623 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00001624 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00001625 LV.setNonGC(true);
1626 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001627 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00001628 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001629 }
John McCallf3a88602011-02-03 08:15:49 +00001630
1631 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1632 return EmitFunctionDeclLValue(*this, E, fn);
1633
David Blaikie83d382b2011-09-23 05:06:16 +00001634 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001635}
Chris Lattnere47e4402007-06-01 18:02:12 +00001636
Chris Lattner8394d792007-06-05 20:53:16 +00001637LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1638 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00001639 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00001640 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001641
Chris Lattner0f398c42008-07-26 22:37:01 +00001642 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00001643 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001644 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00001645 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001646 QualType T = E->getSubExpr()->getType()->getPointeeType();
1647 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00001648
Chris Lattner2415357a2011-12-19 21:16:08 +00001649 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001650 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00001651
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001652 // We should not generate __weak write barrier on indirect reference
1653 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1654 // But, we continue to generate __strong write barrier on indirect write
1655 // into a pointer to object.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001656 if (getContext().getLangOpts().ObjC1 &&
1657 getContext().getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001658 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00001659 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001660 return LV;
1661 }
John McCalle3027922010-08-25 11:45:40 +00001662 case UO_Real:
1663 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00001664 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00001665 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1666 llvm::Value *Addr = LV.getAddress();
1667
Richard Smith0b6b8e42012-02-18 20:53:32 +00001668 // __real is valid on scalars. This is a faster way of testing that.
1669 // __imag can only produce an rvalue on scalars.
1670 if (E->getOpcode() == UO_Real &&
1671 !cast<llvm::PointerType>(Addr->getType())
John McCalla2342eb2010-12-05 02:00:02 +00001672 ->getElementType()->isStructTy()) {
1673 assert(E->getSubExpr()->getType()->isArithmeticType());
1674 return LV;
1675 }
1676
1677 assert(E->getSubExpr()->getType()->isAnyComplexType());
1678
John McCalle3027922010-08-25 11:45:40 +00001679 unsigned Idx = E->getOpcode() == UO_Imag;
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001680 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
John McCalla2342eb2010-12-05 02:00:02 +00001681 Idx, "idx"),
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001682 ExprTy);
Chris Lattner595db862007-10-30 22:53:42 +00001683 }
John McCalle3027922010-08-25 11:45:40 +00001684 case UO_PreInc:
1685 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001686 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00001687 bool isInc = E->getOpcode() == UO_PreInc;
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001688
1689 if (E->getType()->isAnyComplexType())
1690 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1691 else
1692 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1693 return LV;
1694 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00001695 }
Chris Lattner8394d792007-06-05 20:53:16 +00001696}
1697
Chris Lattner4347e3692007-06-06 04:54:52 +00001698LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001699 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1700 E->getType());
Chris Lattner4347e3692007-06-06 04:54:52 +00001701}
1702
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001703LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001704 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1705 E->getType());
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001706}
1707
Nico Weber3a691a32012-06-23 02:07:59 +00001708static llvm::Constant*
1709GetAddrOfConstantWideString(StringRef Str,
1710 const char *GlobalName,
1711 ASTContext &Context,
1712 QualType Ty, SourceLocation Loc,
1713 CodeGenModule &CGM) {
1714
1715 StringLiteral *SL = StringLiteral::Create(Context,
1716 Str,
1717 StringLiteral::Wide,
1718 /*Pascal = */false,
1719 Ty, Loc);
1720 llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL);
1721 llvm::GlobalVariable *GV =
1722 new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1723 !CGM.getLangOpts().WritableStrings,
1724 llvm::GlobalValue::PrivateLinkage,
1725 C, GlobalName);
1726 const unsigned WideAlignment =
1727 Context.getTypeAlignInChars(Ty).getQuantity();
1728 GV->setAlignment(WideAlignment);
1729 return GV;
1730}
1731
1732// FIXME: Mostly copied from StringLiteralParser::CopyStringFragment
1733static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
1734 SmallString<32>& Target) {
1735 Target.resize(CharByteWidth * (Source.size() + 1));
1736 char* ResultPtr = &Target[0];
1737
1738 assert(CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4);
1739 ConversionResult result = conversionOK;
1740 // Copy the character span over.
1741 if (CharByteWidth == 1) {
1742 if (!isLegalUTF8String(reinterpret_cast<const UTF8*>(&*Source.begin()),
1743 reinterpret_cast<const UTF8*>(&*Source.end())))
1744 result = sourceIllegal;
1745 memcpy(ResultPtr, Source.data(), Source.size());
1746 ResultPtr += Source.size();
1747 } else if (CharByteWidth == 2) {
1748 UTF8 const *sourceStart = (UTF8 const *)Source.data();
1749 // FIXME: Make the type of the result buffer correct instead of
1750 // using reinterpret_cast.
1751 UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
1752 ConversionFlags flags = strictConversion;
1753 result = ConvertUTF8toUTF16(
1754 &sourceStart,sourceStart + Source.size(),
1755 &targetStart,targetStart + 2*Source.size(),flags);
1756 if (result==conversionOK)
1757 ResultPtr = reinterpret_cast<char*>(targetStart);
1758 } else if (CharByteWidth == 4) {
1759 UTF8 const *sourceStart = (UTF8 const *)Source.data();
1760 // FIXME: Make the type of the result buffer correct instead of
1761 // using reinterpret_cast.
1762 UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
1763 ConversionFlags flags = strictConversion;
1764 result = ConvertUTF8toUTF32(
1765 &sourceStart,sourceStart + Source.size(),
1766 &targetStart,targetStart + 4*Source.size(),flags);
1767 if (result==conversionOK)
1768 ResultPtr = reinterpret_cast<char*>(targetStart);
1769 }
1770 assert((result != targetExhausted)
1771 && "ConvertUTF8toUTFXX exhausted target buffer");
1772 assert(result == conversionOK);
1773 Target.resize(ResultPtr - &Target[0]);
1774}
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001775
Mike Stump4a3999f2009-09-09 13:00:44 +00001776LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Daniel Dunbarb3517472008-10-17 21:58:32 +00001777 switch (E->getIdentType()) {
1778 default:
1779 return EmitUnsupportedLValue(E, "predefined expression");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001780
Daniel Dunbarb3517472008-10-17 21:58:32 +00001781 case PredefinedExpr::Func:
1782 case PredefinedExpr::Function:
Nico Weber3a691a32012-06-23 02:07:59 +00001783 case PredefinedExpr::LFunction:
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001784 case PredefinedExpr::PrettyFunction: {
Nico Weber3a691a32012-06-23 02:07:59 +00001785 unsigned IdentType = E->getIdentType();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001786 std::string GlobalVarName;
1787
Nico Weber3a691a32012-06-23 02:07:59 +00001788 switch (IdentType) {
David Blaikie83d382b2011-09-23 05:06:16 +00001789 default: llvm_unreachable("Invalid type");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001790 case PredefinedExpr::Func:
1791 GlobalVarName = "__func__.";
1792 break;
1793 case PredefinedExpr::Function:
1794 GlobalVarName = "__FUNCTION__.";
1795 break;
Nico Weber3a691a32012-06-23 02:07:59 +00001796 case PredefinedExpr::LFunction:
1797 GlobalVarName = "L__FUNCTION__.";
1798 break;
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001799 case PredefinedExpr::PrettyFunction:
1800 GlobalVarName = "__PRETTY_FUNCTION__.";
1801 break;
1802 }
1803
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001804 StringRef FnName = CurFn->getName();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001805 if (FnName.startswith("\01"))
1806 FnName = FnName.substr(1);
1807 GlobalVarName += FnName;
1808
1809 const Decl *CurDecl = CurCodeDecl;
1810 if (CurDecl == 0)
1811 CurDecl = getContext().getTranslationUnitDecl();
1812
1813 std::string FunctionName =
John McCall351762c2011-02-07 10:33:21 +00001814 (isa<BlockDecl>(CurDecl)
1815 ? FnName.str()
Nico Weber3a691a32012-06-23 02:07:59 +00001816 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType,
1817 CurDecl));
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001818
Nico Weber3a691a32012-06-23 02:07:59 +00001819 const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual();
1820 llvm::Constant *C;
1821 if (ElemType->isWideCharType()) {
1822 SmallString<32> RawChars;
1823 ConvertUTF8ToWideString(
1824 getContext().getTypeSizeInChars(ElemType).getQuantity(),
1825 FunctionName, RawChars);
1826 C = GetAddrOfConstantWideString(RawChars,
1827 GlobalVarName.c_str(),
1828 getContext(),
1829 E->getType(),
1830 E->getLocation(),
1831 CGM);
1832 } else {
1833 C = CGM.GetAddrOfConstantCString(FunctionName,
1834 GlobalVarName.c_str(),
1835 1);
1836 }
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001837 return MakeAddrLValue(C, E->getType());
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001838 }
Daniel Dunbarb3517472008-10-17 21:58:32 +00001839 }
Anders Carlsson625bfc82007-07-21 05:21:51 +00001840}
1841
Mike Stumpcf16d2c2009-12-15 01:22:35 +00001842llvm::BasicBlock *CodeGenFunction::getTrapBB() {
Mike Stump9a4e0122009-12-15 00:59:40 +00001843 const CodeGenOptions &GCO = CGM.getCodeGenOpts();
1844
1845 // If we are not optimzing, don't collapse all calls to trap in the function
1846 // to the same call, that way, in the debugger they can see which operation
Chris Lattner26008e02010-07-20 20:19:24 +00001847 // did in fact fail. If we are optimizing, we collapse all calls to trap down
Mike Stump9a4e0122009-12-15 00:59:40 +00001848 // to just one per function to save on codesize.
Chris Lattner26008e02010-07-20 20:19:24 +00001849 if (GCO.OptimizationLevel && TrapBB)
Mike Stumpe8c3b3e2009-12-15 00:35:12 +00001850 return TrapBB;
Mike Stumpd9546382009-12-12 01:27:46 +00001851
1852 llvm::BasicBlock *Cont = 0;
1853 if (HaveInsertPoint()) {
1854 Cont = createBasicBlock("cont");
1855 EmitBranch(Cont);
1856 }
Mike Stumpe8c3b3e2009-12-15 00:35:12 +00001857 TrapBB = createBasicBlock("trap");
1858 EmitBlock(TrapBB);
1859
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00001860 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
Mike Stumpe8c3b3e2009-12-15 00:35:12 +00001861 llvm::CallInst *TrapCall = Builder.CreateCall(F);
1862 TrapCall->setDoesNotReturn();
1863 TrapCall->setDoesNotThrow();
Mike Stumpd9546382009-12-12 01:27:46 +00001864 Builder.CreateUnreachable();
1865
1866 if (Cont)
1867 EmitBlock(Cont);
Mike Stumpe8c3b3e2009-12-15 00:35:12 +00001868 return TrapBB;
Mike Stumpd9546382009-12-12 01:27:46 +00001869}
1870
Chris Lattner6c5abe82010-06-26 23:03:20 +00001871/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
1872/// array to pointer, return the array subexpression.
1873static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
1874 // If this isn't just an array->pointer decay, bail out.
1875 const CastExpr *CE = dyn_cast<CastExpr>(E);
John McCalle3027922010-08-25 11:45:40 +00001876 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
Chris Lattner6c5abe82010-06-26 23:03:20 +00001877 return 0;
1878
1879 // If this is a decay from variable width array, bail out.
1880 const Expr *SubExpr = CE->getSubExpr();
1881 if (SubExpr->getType()->isVariableArrayType())
1882 return 0;
1883
1884 return SubExpr;
1885}
1886
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001887LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00001888 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00001889 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00001890 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001891 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00001892
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001893 // If the base is a vector type, then we are forming a vector element lvalue
1894 // with this subscript.
Eli Friedman327944b2008-06-13 23:01:12 +00001895 if (E->getBase()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001896 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00001897 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00001898 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
John McCallad7c5c12011-02-08 08:22:06 +00001899 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
Eli Friedman327944b2008-06-13 23:01:12 +00001900 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
Eli Friedman610bb872012-03-22 22:36:39 +00001901 E->getBase()->getType(), LHS.getAlignment());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001902 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001903
Ted Kremenekc81614d2007-08-20 16:18:38 +00001904 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00001905 if (Idx->getType() != IntPtrTy)
1906 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00001907
Mike Stump4a3999f2009-09-09 13:00:44 +00001908 // We know that the pointer points to a type of the correct size, unless the
1909 // size is a VLA or Objective-C interface.
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001910 llvm::Value *Address = 0;
Eli Friedmana0544d62011-12-03 04:14:32 +00001911 CharUnits ArrayAlignment;
John McCall23c29fe2011-06-24 21:55:10 +00001912 if (const VariableArrayType *vla =
Anders Carlsson3d312f82008-12-21 00:11:23 +00001913 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00001914 // The base must be a pointer, which is not an aggregate. Emit
1915 // it. It needs to be emitted first in case it's what captures
1916 // the VLA bounds.
1917 Address = EmitScalarExpr(E->getBase());
Mike Stump4a3999f2009-09-09 13:00:44 +00001918
John McCall23c29fe2011-06-24 21:55:10 +00001919 // The element count here is the total number of non-VLA elements.
1920 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00001921
John McCall77527a82011-06-25 01:32:37 +00001922 // Effectively, the multiply by the VLA size is part of the GEP.
1923 // GEP indexes are signed, and scaling an index isn't permitted to
1924 // signed-overflow, so we use the same semantics for our explicit
1925 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001926 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00001927 Idx = Builder.CreateMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00001928 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00001929 } else {
1930 Idx = Builder.CreateNSWMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00001931 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00001932 }
Chris Lattner6c5abe82010-06-26 23:03:20 +00001933 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
1934 // Indexing over an interface, as in "NSString *P; P[4];"
Mike Stump4a3999f2009-09-09 13:00:44 +00001935 llvm::Value *InterfaceSize =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001936 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck40775002010-01-11 17:06:35 +00001937 getContext().getTypeSizeInChars(OIT).getQuantity());
Mike Stump4a3999f2009-09-09 13:00:44 +00001938
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001939 Idx = Builder.CreateMul(Idx, InterfaceSize);
1940
Chris Lattner6c5abe82010-06-26 23:03:20 +00001941 // The base must be a pointer, which is not an aggregate. Emit it.
1942 llvm::Value *Base = EmitScalarExpr(E->getBase());
John McCallad7c5c12011-02-08 08:22:06 +00001943 Address = EmitCastToVoidPtr(Base);
1944 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001945 Address = Builder.CreateBitCast(Address, Base->getType());
Chris Lattner6c5abe82010-06-26 23:03:20 +00001946 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
1947 // If this is A[i] where A is an array, the frontend will have decayed the
1948 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
1949 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
1950 // "gep x, i" here. Emit one "gep A, 0, i".
1951 assert(Array->getType()->isArrayType() &&
1952 "Array to pointer decay must have array source type!");
Daniel Dunbar82634272011-04-01 00:49:43 +00001953 LValue ArrayLV = EmitLValue(Array);
1954 llvm::Value *ArrayPtr = ArrayLV.getAddress();
Chris Lattner6c5abe82010-06-26 23:03:20 +00001955 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
1956 llvm::Value *Args[] = { Zero, Idx };
1957
Daniel Dunbar82634272011-04-01 00:49:43 +00001958 // Propagate the alignment from the array itself to the result.
1959 ArrayAlignment = ArrayLV.getAlignment();
1960
David Blaikiebbafb8a2012-03-11 07:00:24 +00001961 if (getContext().getLangOpts().isSignedOverflowDefined())
Jay Foad040dd822011-07-22 08:16:57 +00001962 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Chris Lattner2e72da942011-03-01 00:03:48 +00001963 else
Jay Foad040dd822011-07-22 08:16:57 +00001964 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001965 } else {
Chris Lattner6c5abe82010-06-26 23:03:20 +00001966 // The base must be a pointer, which is not an aggregate. Emit it.
1967 llvm::Value *Base = EmitScalarExpr(E->getBase());
David Blaikiebbafb8a2012-03-11 07:00:24 +00001968 if (getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001969 Address = Builder.CreateGEP(Base, Idx, "arrayidx");
1970 else
1971 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
Anders Carlsson3d312f82008-12-21 00:11:23 +00001972 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001973
Steve Naroff7cae42b2009-07-10 23:34:53 +00001974 QualType T = E->getBase()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001975 assert(!T.isNull() &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00001976 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
Mike Stump4a3999f2009-09-09 13:00:44 +00001977
Chris Lattner36bc4f42012-01-04 22:35:55 +00001978
Daniel Dunbar82634272011-04-01 00:49:43 +00001979 // Limit the alignment to that of the result type.
Chris Lattner36bc4f42012-01-04 22:35:55 +00001980 LValue LV;
Eli Friedmana0544d62011-12-03 04:14:32 +00001981 if (!ArrayAlignment.isZero()) {
1982 CharUnits Align = getContext().getTypeAlignInChars(T);
Daniel Dunbar82634272011-04-01 00:49:43 +00001983 ArrayAlignment = std::min(Align, ArrayAlignment);
Chris Lattner36bc4f42012-01-04 22:35:55 +00001984 LV = MakeAddrLValue(Address, T, ArrayAlignment);
1985 } else {
1986 LV = MakeNaturalAlignAddrLValue(Address, T);
Daniel Dunbar82634272011-04-01 00:49:43 +00001987 }
1988
Daniel Dunbarf166a522010-08-21 03:44:13 +00001989 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00001990
David Blaikiebbafb8a2012-03-11 07:00:24 +00001991 if (getContext().getLangOpts().ObjC1 &&
1992 getContext().getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00001993 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001994 setObjCGCLValueClass(getContext(), E, LV);
1995 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00001996 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001997}
1998
Mike Stump4a3999f2009-09-09 13:00:44 +00001999static
NAKAMURA Takumiccca11a2012-01-25 08:58:21 +00002000llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002001 SmallVector<unsigned, 4> &Elts) {
2002 SmallVector<llvm::Constant*, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002003 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002004 CElts.push_back(Builder.getInt32(Elts[i]));
Nate Begemand3862152008-05-13 21:03:02 +00002005
Chris Lattner91c08ad2011-02-15 00:14:06 +00002006 return llvm::ConstantVector::get(CElts);
Nate Begemand3862152008-05-13 21:03:02 +00002007}
2008
Chris Lattner9e751ca2007-08-02 23:37:31 +00002009LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002010EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002011 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002012 LValue Base;
2013
2014 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002015 if (E->isArrow()) {
2016 // If it is a pointer to a vector, emit the address and form an lvalue with
2017 // it.
Chris Lattnerb8211f62009-02-16 22:14:05 +00002018 llvm::Value *Ptr = EmitScalarExpr(E->getBase());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002019 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Daniel Dunbarf166a522010-08-21 03:44:13 +00002020 Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2021 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002022 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002023 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2024 // emit the base as an lvalue.
2025 assert(E->getBase()->getType()->isVectorType());
2026 Base = EmitLValue(E->getBase());
2027 } else {
2028 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002029 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002030 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002031 llvm::Value *Vec = EmitScalarExpr(E->getBase());
2032
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002033 // Store the vector to memory (because LValue wants an address).
Daniel Dunbara7566f12010-02-09 02:48:28 +00002034 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002035 Builder.CreateStore(Vec, VecMem);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002036 Base = MakeAddrLValue(VecMem, E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002037 }
John McCall1553b192011-06-16 04:16:24 +00002038
2039 QualType type =
2040 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002041
Nate Begemand3862152008-05-13 21:03:02 +00002042 // Encode the element access list into a vector of unsigned indices.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002043 SmallVector<unsigned, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002044 E->getEncodedElementAccess(Indices);
2045
2046 if (Base.isSimple()) {
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002047 llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002048 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2049 Base.getAlignment());
Nate Begemand3862152008-05-13 21:03:02 +00002050 }
2051 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2052
2053 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002054 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002055
Chris Lattner595ba3a2012-01-30 06:20:36 +00002056 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2057 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002058 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
Eli Friedman610bb872012-03-22 22:36:39 +00002059 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2060 Base.getAlignment());
Chris Lattner9e751ca2007-08-02 23:37:31 +00002061}
2062
Devang Patel30efa2e2007-10-23 20:28:39 +00002063LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00002064 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00002065
Chris Lattner4e4186b2007-12-02 18:52:07 +00002066 // 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 +00002067 LValue BaseLV;
2068 if (E->isArrow())
2069 BaseLV = MakeNaturalAlignAddrLValue(EmitScalarExpr(BaseExpr),
2070 BaseExpr->getType()->getPointeeType());
2071 else
2072 BaseLV = EmitLValue(BaseExpr);
Devang Patel30efa2e2007-10-23 20:28:39 +00002073
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002074 NamedDecl *ND = E->getMemberDecl();
2075 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002076 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002077 setObjCGCLValueClass(getContext(), E, LV);
2078 return LV;
2079 }
2080
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00002081 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
2082 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002083
2084 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
2085 return EmitFunctionDeclLValue(*this, E, FD);
2086
David Blaikie83d382b2011-09-23 05:06:16 +00002087 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00002088}
Devang Patel30efa2e2007-10-23 20:28:39 +00002089
John McCallc4094932010-05-21 01:18:57 +00002090/// EmitLValueForAnonRecordField - Given that the field is a member of
2091/// an anonymous struct or union buried inside a record, and given
2092/// that the base value is a pointer to the enclosing record, derive
2093/// an lvalue for the ultimate field.
2094LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue,
Francois Pichetd583da02010-12-04 09:14:42 +00002095 const IndirectFieldDecl *Field,
John McCallc4094932010-05-21 01:18:57 +00002096 unsigned CVRQualifiers) {
Francois Pichetd583da02010-12-04 09:14:42 +00002097 IndirectFieldDecl::chain_iterator I = Field->chain_begin(),
2098 IEnd = Field->chain_end();
John McCallc4094932010-05-21 01:18:57 +00002099 while (true) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002100 QualType RecordTy =
2101 getContext().getTypeDeclType(cast<FieldDecl>(*I)->getParent());
2102 LValue LV = EmitLValueForField(MakeAddrLValue(BaseValue, RecordTy),
2103 cast<FieldDecl>(*I));
Francois Pichetd583da02010-12-04 09:14:42 +00002104 if (++I == IEnd) return LV;
John McCallc4094932010-05-21 01:18:57 +00002105
2106 assert(LV.isSimple());
2107 BaseValue = LV.getAddress();
2108 CVRQualifiers |= LV.getVRQualifiers();
2109 }
2110}
2111
Eli Friedman7f1ff602012-04-16 03:54:45 +00002112LValue CodeGenFunction::EmitLValueForField(LValue base,
2113 const FieldDecl *field) {
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002114 if (field->isBitField()) {
2115 const CGRecordLayout &RL =
2116 CGM.getTypes().getCGRecordLayout(field->getParent());
2117 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
2118 QualType fieldType =
2119 field->getType().withCVRQualifiers(base.getVRQualifiers());
2120 return LValue::MakeBitfield(base.getAddress(), Info, fieldType,
2121 base.getAlignment());
2122 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002123
John McCall53fcbd22011-02-26 08:07:02 +00002124 const RecordDecl *rec = field->getParent();
2125 QualType type = field->getType();
Eli Friedmana0544d62011-12-03 04:14:32 +00002126 CharUnits alignment = getContext().getDeclAlign(field);
Eli Friedman133e8042008-05-29 11:33:25 +00002127
Eli Friedman7f1ff602012-04-16 03:54:45 +00002128 // FIXME: It should be impossible to have an LValue without alignment for a
2129 // complete type.
2130 if (!base.getAlignment().isZero())
2131 alignment = std::min(alignment, base.getAlignment());
2132
John McCall53fcbd22011-02-26 08:07:02 +00002133 bool mayAlias = rec->hasAttr<MayAliasAttr>();
2134
Eli Friedman7f1ff602012-04-16 03:54:45 +00002135 llvm::Value *addr = base.getAddress();
2136 unsigned cvr = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00002137 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00002138 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00002139 assert(!type->isReferenceType() && "union has reference member");
John McCall53fcbd22011-02-26 08:07:02 +00002140 } else {
2141 // For structs, we GEP to the field that the record layout suggests.
2142 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
Chris Lattner13ee4f42011-07-10 05:34:54 +00002143 addr = Builder.CreateStructGEP(addr, idx, field->getName());
John McCall53fcbd22011-02-26 08:07:02 +00002144
2145 // If this is a reference field, load the reference right now.
2146 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2147 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2148 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
Eli Friedmana0544d62011-12-03 04:14:32 +00002149 load->setAlignment(alignment.getQuantity());
John McCall53fcbd22011-02-26 08:07:02 +00002150
2151 if (CGM.shouldUseTBAA()) {
2152 llvm::MDNode *tbaa;
2153 if (mayAlias)
2154 tbaa = CGM.getTBAAInfo(getContext().CharTy);
2155 else
2156 tbaa = CGM.getTBAAInfo(type);
2157 CGM.DecorateInstruction(load, tbaa);
2158 }
2159
2160 addr = load;
2161 mayAlias = false;
2162 type = refType->getPointeeType();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002163 if (type->isIncompleteType())
Eli Friedmana0544d62011-12-03 04:14:32 +00002164 alignment = CharUnits();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002165 else
Eli Friedmana0544d62011-12-03 04:14:32 +00002166 alignment = getContext().getTypeAlignInChars(type);
John McCall53fcbd22011-02-26 08:07:02 +00002167 cvr = 0; // qualifiers don't recursively apply to referencee
2168 }
Devang Pateled93c3c2007-10-26 19:42:18 +00002169 }
Chris Lattner13ee4f42011-07-10 05:34:54 +00002170
2171 // Make sure that the address is pointing to the right type. This is critical
2172 // for both unions and structs. A union needs a bitcast, a struct element
2173 // will need a bitcast if the LLVM type laid out doesn't match the desired
2174 // type.
Chandler Carruth4678f672011-07-12 08:58:26 +00002175 addr = EmitBitCastOfLValueToProperType(*this, addr,
Chris Lattner3f32d692011-07-12 06:52:18 +00002176 CGM.getTypes().ConvertTypeForMem(type),
2177 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00002178
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002179 if (field->hasAttr<AnnotateAttr>())
2180 addr = EmitFieldAnnotations(field, addr);
2181
John McCall53fcbd22011-02-26 08:07:02 +00002182 LValue LV = MakeAddrLValue(addr, type, alignment);
2183 LV.getQuals().addCVRQualifiers(cvr);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002184
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002185 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00002186 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2187 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00002188
2189 // Fields of may_alias structs act like 'char' for TBAA purposes.
2190 // FIXME: this should get propagated down through anonymous structs
2191 // and unions.
2192 if (mayAlias && LV.getTBAAInfo())
2193 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2194
Daniel Dunbarf166a522010-08-21 03:44:13 +00002195 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00002196}
2197
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002198LValue
Eli Friedman7f1ff602012-04-16 03:54:45 +00002199CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2200 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002201 QualType FieldType = Field->getType();
2202
2203 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002204 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002205
Daniel Dunbar034299e2010-03-31 01:09:11 +00002206 const CGRecordLayout &RL =
2207 CGM.getTypes().getCGRecordLayout(Field->getParent());
2208 unsigned idx = RL.getLLVMFieldNo(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002209 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002210 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2211
Chris Lattnerd7c59352011-07-10 05:53:24 +00002212 // Make sure that the address is pointing to the right type. This is critical
2213 // for both unions and structs. A union needs a bitcast, a struct element
2214 // will need a bitcast if the LLVM type laid out doesn't match the desired
2215 // type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002216 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002217 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2218
Eli Friedmana0544d62011-12-03 04:14:32 +00002219 CharUnits Alignment = getContext().getDeclAlign(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002220
2221 // FIXME: It should be impossible to have an LValue without alignment for a
2222 // complete type.
2223 if (!Base.getAlignment().isZero())
2224 Alignment = std::min(Alignment, Base.getAlignment());
2225
Daniel Dunbar5c816372010-08-21 04:20:22 +00002226 return MakeAddrLValue(V, FieldType, Alignment);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002227}
2228
Chris Lattnerf53c0962010-09-06 00:11:41 +00002229LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00002230 if (E->isFileScope()) {
2231 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2232 return MakeAddrLValue(GlobalPtr, E->getType());
2233 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00002234 if (E->getType()->isVariablyModifiedType())
2235 // make sure to emit the VLA size.
2236 EmitVariablyModifiedType(E->getType());
Fariborz Jahanianbbc5bbf2012-06-07 17:07:15 +00002237
Daniel Dunbar27bacaf2010-02-16 19:43:39 +00002238 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00002239 const Expr *InitExpr = E->getInitializer();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002240 LValue Result = MakeAddrLValue(DeclPtr, E->getType());
Eli Friedman9fd8b682008-05-13 23:18:27 +00002241
Chad Rosier615ed1a2012-03-29 17:37:10 +00002242 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2243 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00002244
2245 return Result;
2246}
2247
Richard Smithbb653bd2012-05-14 21:57:21 +00002248LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2249 if (!E->isGLValue())
2250 // Initializing an aggregate temporary in C++11: T{...}.
2251 return EmitAggExprToLValue(E);
2252
2253 // An lvalue initializer list must be initializing a reference.
2254 assert(E->getNumInits() == 1 && "reference init with multiple values");
2255 return EmitLValue(E->getInit(0));
2256}
2257
John McCallc07a0c72011-02-17 10:25:35 +00002258LValue CodeGenFunction::
2259EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2260 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00002261 // ?: here should be an aggregate.
John McCallc07a0c72011-02-17 10:25:35 +00002262 assert((hasAggregateLLVMType(expr->getType()) &&
2263 !expr->getType()->isAnyComplexType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00002264 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00002265 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00002266 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002267
Eli Friedman59954892012-01-25 05:04:17 +00002268 OpaqueValueMapping binding(*this, expr);
2269
John McCallc07a0c72011-02-17 10:25:35 +00002270 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002271 bool CondExprBool;
2272 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00002273 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002274 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00002275
2276 if (!ContainsLabel(dead))
2277 return EmitLValue(live);
John McCall0a6bf2e2011-01-26 19:21:13 +00002278 }
2279
John McCallc07a0c72011-02-17 10:25:35 +00002280 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2281 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2282 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00002283
2284 ConditionalEvaluation eval(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002285 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002286
2287 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002288 EmitBlock(lhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002289 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002290 LValue lhs = EmitLValue(expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002291 eval.end(*this);
2292
John McCallc07a0c72011-02-17 10:25:35 +00002293 if (!lhs.isSimple())
2294 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00002295
John McCallc07a0c72011-02-17 10:25:35 +00002296 lhsBlock = Builder.GetInsertBlock();
2297 Builder.CreateBr(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002298
2299 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002300 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002301 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002302 LValue rhs = EmitLValue(expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002303 eval.end(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002304 if (!rhs.isSimple())
2305 return EmitUnsupportedLValue(expr, "conditional operator");
2306 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00002307
John McCallc07a0c72011-02-17 10:25:35 +00002308 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002309
Jay Foad20c0f022011-03-30 11:28:58 +00002310 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
John McCall0a6bf2e2011-01-26 19:21:13 +00002311 "cond-lvalue");
John McCallc07a0c72011-02-17 10:25:35 +00002312 phi->addIncoming(lhs.getAddress(), lhsBlock);
2313 phi->addIncoming(rhs.getAddress(), rhsBlock);
2314 return MakeAddrLValue(phi, expr->getType());
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002315}
2316
Richard Smithbb653bd2012-05-14 21:57:21 +00002317/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2318/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00002319/// otherwise if a cast is needed by the code generator in an lvalue context,
2320/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00002321/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00002322/// are permitted with aggregate result, including noop aggregate casts, and
2323/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002324LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00002325 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00002326 case CK_ToVoid:
Eli Friedman8c98dff2009-11-16 05:48:01 +00002327 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
John McCall8cb679e2010-11-15 09:13:47 +00002328
2329 case CK_Dependent:
2330 llvm_unreachable("dependent cast kind in IR gen!");
David Chisnallfa35df62012-01-16 17:27:18 +00002331
2332 // These two casts are currently treated as no-ops, although they could
2333 // potentially be real operations depending on the target's ABI.
2334 case CK_NonAtomicToAtomic:
2335 case CK_AtomicToNonAtomic:
John McCall8cb679e2010-11-15 09:13:47 +00002336
John McCalle3027922010-08-25 11:45:40 +00002337 case CK_NoOp:
Douglas Gregor21d3fca2011-01-27 23:22:05 +00002338 case CK_LValueToRValue:
2339 if (!E->getSubExpr()->Classify(getContext()).isPRValue()
2340 || E->getType()->isRecordType())
John McCalle26a8722010-12-04 08:14:53 +00002341 return EmitLValue(E->getSubExpr());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002342 // Fall through to synthesize a temporary.
John McCall8cb679e2010-11-15 09:13:47 +00002343
John McCalle3027922010-08-25 11:45:40 +00002344 case CK_BitCast:
2345 case CK_ArrayToPointerDecay:
2346 case CK_FunctionToPointerDecay:
2347 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00002348 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00002349 case CK_IntegralToPointer:
2350 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002351 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002352 case CK_VectorSplat:
2353 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00002354 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002355 case CK_IntegralToFloating:
2356 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002357 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002358 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00002359 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002360 case CK_FloatingComplexToReal:
2361 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002362 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002363 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00002364 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002365 case CK_IntegralComplexToReal:
2366 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002367 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002368 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00002369 case CK_DerivedToBaseMemberPointer:
2370 case CK_BaseToDerivedMemberPointer:
2371 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00002372 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00002373 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00002374 case CK_ARCProduceObject:
2375 case CK_ARCConsumeObject:
2376 case CK_ARCReclaimReturnedObject:
Douglas Gregored90df32012-02-22 05:02:47 +00002377 case CK_ARCExtendBlockObject:
2378 case CK_CopyAndAutoreleaseBlockObject: {
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002379 // These casts only produce lvalues when we're binding a reference to a
2380 // temporary realized from a (converted) pure rvalue. Emit the expression
2381 // as a value, copy it into a temporary, and return an lvalue referring to
2382 // that temporary.
2383 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00002384 EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002385 return MakeAddrLValue(V, E->getType());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002386 }
Eli Friedman8c98dff2009-11-16 05:48:01 +00002387
Anders Carlsson8a01a752011-04-11 02:03:26 +00002388 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00002389 LValue LV = EmitLValue(E->getSubExpr());
2390 llvm::Value *V = LV.getAddress();
2391 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002392 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00002393 }
2394
John McCalle3027922010-08-25 11:45:40 +00002395 case CK_ConstructorConversion:
2396 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00002397 case CK_CPointerToObjCPointerCast:
2398 case CK_BlockPointerToObjCPointerCast:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002399 return EmitLValue(E->getSubExpr());
Anders Carlssond95f9602009-09-12 16:16:49 +00002400
John McCalle3027922010-08-25 11:45:40 +00002401 case CK_UncheckedDerivedToBase:
2402 case CK_DerivedToBase: {
Anders Carlssond95f9602009-09-12 16:16:49 +00002403 const RecordType *DerivedClassTy =
2404 E->getSubExpr()->getType()->getAs<RecordType>();
2405 CXXRecordDecl *DerivedClassDecl =
2406 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Anders Carlssond95f9602009-09-12 16:16:49 +00002407
2408 LValue LV = EmitLValue(E->getSubExpr());
John McCalle26a8722010-12-04 08:14:53 +00002409 llvm::Value *This = LV.getAddress();
Anders Carlssond95f9602009-09-12 16:16:49 +00002410
2411 // Perform the derived-to-base conversion
2412 llvm::Value *Base =
Fariborz Jahanian64cda8b2010-06-17 23:00:29 +00002413 GetAddressOfBaseClass(This, DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002414 E->path_begin(), E->path_end(),
2415 /*NullCheckValue=*/false);
Anders Carlssond95f9602009-09-12 16:16:49 +00002416
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002417 return MakeAddrLValue(Base, E->getType());
Anders Carlssond95f9602009-09-12 16:16:49 +00002418 }
John McCalle3027922010-08-25 11:45:40 +00002419 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00002420 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00002421 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00002422 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2423 CXXRecordDecl *DerivedClassDecl =
2424 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2425
2426 LValue LV = EmitLValue(E->getSubExpr());
2427
2428 // Perform the base-to-derived conversion
2429 llvm::Value *Derived =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +00002430 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002431 E->path_begin(), E->path_end(),
2432 /*NullCheckValue=*/false);
Anders Carlsson8c793172009-11-23 17:57:54 +00002433
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002434 return MakeAddrLValue(Derived, E->getType());
Eli Friedman8c98dff2009-11-16 05:48:01 +00002435 }
John McCalle3027922010-08-25 11:45:40 +00002436 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00002437 // This must be a reinterpret_cast (or c-style equivalent).
2438 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
Anders Carlsson50cb3212009-11-14 21:21:42 +00002439
2440 LValue LV = EmitLValue(E->getSubExpr());
2441 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2442 ConvertType(CE->getTypeAsWritten()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002443 return MakeAddrLValue(V, E->getType());
Anders Carlsson50cb3212009-11-14 21:21:42 +00002444 }
John McCalle3027922010-08-25 11:45:40 +00002445 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002446 LValue LV = EmitLValue(E->getSubExpr());
2447 QualType ToType = getContext().getLValueReferenceType(E->getType());
2448 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2449 ConvertType(ToType));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002450 return MakeAddrLValue(V, E->getType());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002451 }
Anders Carlssond95f9602009-09-12 16:16:49 +00002452 }
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002453
2454 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002455}
2456
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002457LValue CodeGenFunction::EmitNullInitializationLValue(
Douglas Gregor747eb782010-07-08 06:14:04 +00002458 const CXXScalarValueInitExpr *E) {
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002459 QualType Ty = E->getType();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002460 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
Anders Carlssonc0964b62010-05-22 17:35:42 +00002461 EmitNullInitialization(LV.getAddress(), Ty);
Daniel Dunbara7566f12010-02-09 02:48:28 +00002462 return LV;
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002463}
2464
John McCall1bf58462011-02-16 08:02:54 +00002465LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00002466 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00002467 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00002468}
2469
Douglas Gregorfe314812011-06-21 17:03:29 +00002470LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2471 const MaterializeTemporaryExpr *E) {
John McCall17054bd62011-08-26 21:08:13 +00002472 RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
Douglas Gregord410c082011-06-21 18:20:46 +00002473 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Douglas Gregorfe314812011-06-21 17:03:29 +00002474}
2475
Eli Friedman7f1ff602012-04-16 03:54:45 +00002476RValue CodeGenFunction::EmitRValueForField(LValue LV,
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002477 const FieldDecl *FD) {
2478 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00002479 LValue FieldLV = EmitLValueForField(LV, FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002480 if (FT->isAnyComplexType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002481 return RValue::getComplex(
2482 LoadComplexFromAddr(FieldLV.getAddress(),
2483 FieldLV.isVolatileQualified()));
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002484 else if (CodeGenFunction::hasAggregateLLVMType(FT))
Eli Friedman7f1ff602012-04-16 03:54:45 +00002485 return FieldLV.asAggregateRValue();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002486
Eli Friedman7f1ff602012-04-16 03:54:45 +00002487 return EmitLoadOfLValue(FieldLV);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002488}
Douglas Gregorfe314812011-06-21 17:03:29 +00002489
Chris Lattnere47e4402007-06-01 18:02:12 +00002490//===--------------------------------------------------------------------===//
2491// Expression Emission
2492//===--------------------------------------------------------------------===//
2493
Anders Carlsson17490832009-12-24 20:40:36 +00002494RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2495 ReturnValueSlot ReturnValue) {
Eric Christopher7cdf9482011-10-13 21:45:18 +00002496 if (CGDebugInfo *DI = getDebugInfo())
2497 DI->EmitLocation(Builder, E->getLocStart());
Devang Pateld3a6b0f2011-03-04 18:54:42 +00002498
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002499 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002500 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00002501 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002502
Anders Carlssone5fd6f22009-04-03 22:50:24 +00002503 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002504 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002505
Peter Collingbournefe883422011-10-06 18:29:37 +00002506 if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E))
2507 return EmitCUDAKernelCallExpr(CE, ReturnValue);
2508
Douglas Gregore0e96302011-09-06 21:41:04 +00002509 const Decl *TargetDecl = E->getCalleeDecl();
2510 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2511 if (unsigned builtinID = FD->getBuiltinID())
2512 return EmitBuiltinExpr(FD, builtinID, E);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002513 }
2514
Chris Lattner4ca97c32009-06-13 00:26:38 +00002515 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00002516 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002517 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002518
John McCall31168b02011-06-15 23:02:42 +00002519 if (const CXXPseudoDestructorExpr *PseudoDtor
2520 = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2521 QualType DestroyedType = PseudoDtor->getDestroyedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002522 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002523 DestroyedType->isObjCLifetimeType() &&
2524 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2525 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002526 // Automatic Reference Counting:
2527 // If the pseudo-expression names a retainable object with weak or
2528 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00002529 Expr *BaseExpr = PseudoDtor->getBase();
2530 llvm::Value *BaseValue = NULL;
2531 Qualifiers BaseQuals;
2532
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002533 // 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 +00002534 if (PseudoDtor->isArrow()) {
2535 BaseValue = EmitScalarExpr(BaseExpr);
2536 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2537 BaseQuals = PTy->getPointeeType().getQualifiers();
2538 } else {
2539 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00002540 BaseValue = BaseLV.getAddress();
2541 QualType BaseTy = BaseExpr->getType();
2542 BaseQuals = BaseTy.getQualifiers();
2543 }
2544
2545 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2546 case Qualifiers::OCL_None:
2547 case Qualifiers::OCL_ExplicitNone:
2548 case Qualifiers::OCL_Autoreleasing:
2549 break;
2550
2551 case Qualifiers::OCL_Strong:
2552 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002553 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCall31168b02011-06-15 23:02:42 +00002554 /*precise*/ true);
2555 break;
2556
2557 case Qualifiers::OCL_Weak:
2558 EmitARCDestroyWeak(BaseValue);
2559 break;
2560 }
2561 } else {
2562 // C++ [expr.pseudo]p1:
2563 // The result shall only be used as the operand for the function call
2564 // operator (), and the result of such a call has type void. The only
2565 // effect is the evaluation of the postfix-expression before the dot or
2566 // arrow.
2567 EmitScalarExpr(E->getCallee());
2568 }
2569
Douglas Gregorad8a3362009-09-04 17:36:40 +00002570 return RValue::get(0);
2571 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002572
Chris Lattner2da04b32007-08-24 05:35:26 +00002573 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Anders Carlsson17490832009-12-24 20:40:36 +00002574 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002575 E->arg_begin(), E->arg_end(), TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00002576}
2577
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002578LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00002579 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00002580 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00002581 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00002582 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00002583 return EmitLValue(E->getRHS());
2584 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002585
John McCalle3027922010-08-25 11:45:40 +00002586 if (E->getOpcode() == BO_PtrMemD ||
2587 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002588 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002589
John McCalla2342eb2010-12-05 02:00:02 +00002590 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00002591
2592 // Note that in all of these cases, __block variables need the RHS
2593 // evaluated first just in case the variable gets moved by the RHS.
John McCall4f29b492010-11-16 23:07:28 +00002594
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002595 if (!hasAggregateLLVMType(E->getType())) {
John McCall31168b02011-06-15 23:02:42 +00002596 switch (E->getLHS()->getType().getObjCLifetime()) {
2597 case Qualifiers::OCL_Strong:
2598 return EmitARCStoreStrong(E, /*ignored*/ false).first;
2599
2600 case Qualifiers::OCL_Autoreleasing:
2601 return EmitARCStoreAutoreleasing(E).first;
2602
2603 // No reason to do any of these differently.
2604 case Qualifiers::OCL_None:
2605 case Qualifiers::OCL_ExplicitNone:
2606 case Qualifiers::OCL_Weak:
2607 break;
2608 }
2609
John McCalld0a30012010-12-06 06:10:02 +00002610 RValue RV = EmitAnyExpr(E->getRHS());
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002611 LValue LV = EmitLValue(E->getLHS());
John McCall55e1fbc2011-06-25 02:11:03 +00002612 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002613 return LV;
2614 }
John McCall4f29b492010-11-16 23:07:28 +00002615
2616 if (E->getType()->isAnyComplexType())
2617 return EmitComplexAssignmentLValue(E);
2618
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002619 return EmitAggExprToLValue(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002620}
2621
Christopher Lambd91c3d42007-12-29 05:02:41 +00002622LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00002623 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00002624
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002625 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002626 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002627
2628 assert(E->getCallReturnType()->isReferenceType() &&
2629 "Can't have a scalar return unless the return type is a "
2630 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00002631
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002632 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00002633}
2634
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002635LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2636 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002637 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002638}
2639
Anders Carlsson3be22e22009-05-30 23:23:33 +00002640LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002641 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2642 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002643 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00002644 EmitCXXConstructExpr(E, Slot);
2645 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlsson3be22e22009-05-30 23:23:33 +00002646}
2647
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002648LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00002649CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002650 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00002651}
2652
2653LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002654CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002655 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00002656 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00002657 EmitAggExpr(E->getSubExpr(), Slot);
Peter Collingbourne702b2842011-11-27 22:09:22 +00002658 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
John McCall8ea46b62010-09-18 00:58:34 +00002659 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002660}
2661
Eli Friedman5bc17122012-02-08 05:34:55 +00002662LValue
2663CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00002664 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002665 EmitLambdaExpr(E, Slot);
Eli Friedman5bc17122012-02-08 05:34:55 +00002666 return MakeAddrLValue(Slot.getAddr(), E->getType());
2667}
2668
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002669LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002670 RValue RV = EmitObjCMessageExpr(E);
Anders Carlsson280e61f12010-06-21 20:59:55 +00002671
2672 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002673 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Anders Carlsson280e61f12010-06-21 20:59:55 +00002674
2675 assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2676 "Can't have a scalar return unless the return type is a "
2677 "reference type!");
2678
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002679 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002680}
2681
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00002682LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2683 llvm::Value *V =
2684 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002685 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00002686}
2687
Daniel Dunbar722f4242009-04-22 05:08:15 +00002688llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002689 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002690 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002691}
2692
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002693LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2694 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002695 const ObjCIvarDecl *Ivar,
2696 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00002697 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00002698 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002699}
2700
2701LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002702 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2703 llvm::Value *BaseValue = 0;
2704 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00002705 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002706 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002707 if (E->isArrow()) {
2708 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002709 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002710 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002711 } else {
2712 LValue BaseLV = EmitLValue(BaseExpr);
2713 // FIXME: this isn't right for bitfields.
2714 BaseValue = BaseLV.getAddress();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002715 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00002716 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002717 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002718
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002719 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00002720 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2721 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002722 setObjCGCLValueClass(getContext(), E, LV);
2723 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00002724}
2725
Chris Lattnera4185c52009-04-25 19:35:26 +00002726LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00002727 // Can only get l-value for message expression returning aggregate type
2728 RValue RV = EmitAnyExprToTemp(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002729 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnera4185c52009-04-25 19:35:26 +00002730}
2731
Anders Carlsson0435ed52009-12-24 19:08:58 +00002732RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Anders Carlsson17490832009-12-24 20:40:36 +00002733 ReturnValueSlot ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002734 CallExpr::const_arg_iterator ArgBeg,
2735 CallExpr::const_arg_iterator ArgEnd,
2736 const Decl *TargetDecl) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002737 // Get the actual function type. The callee type will always be a pointer to
2738 // function type or a block pointer type.
2739 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00002740 "Call must have function pointer type!");
2741
John McCall6fd4c232009-10-23 08:22:42 +00002742 CalleeType = getContext().getCanonicalType(CalleeType);
2743
John McCallab26cfa2010-02-05 21:31:56 +00002744 const FunctionType *FnType
2745 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00002746
2747 CallArgList Args;
John McCall6fd4c232009-10-23 08:22:42 +00002748 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
Daniel Dunbarc722b852008-08-30 03:02:31 +00002749
John McCalla729c622012-02-17 03:33:10 +00002750 const CGFunctionInfo &FnInfo =
2751 CGM.getTypes().arrangeFunctionCall(Args, FnType);
John McCallcbc038a2011-09-21 08:08:30 +00002752
2753 // C99 6.5.2.2p6:
2754 // If the expression that denotes the called function has a type
2755 // that does not include a prototype, [the default argument
2756 // promotions are performed]. If the number of arguments does not
2757 // equal the number of parameters, the behavior is undefined. If
2758 // the function is defined with a type that includes a prototype,
2759 // and either the prototype ends with an ellipsis (, ...) or the
2760 // types of the arguments after promotion are not compatible with
2761 // the types of the parameters, the behavior is undefined. If the
2762 // function is defined with a type that does not include a
2763 // prototype, and the types of the arguments after promotion are
2764 // not compatible with those of the parameters after promotion,
2765 // the behavior is undefined [except in some trivial cases].
2766 // That is, in the general case, we should assume that a call
2767 // through an unprototyped function type works like a *non-variadic*
2768 // call. The way we make this work is to cast to the exact type
2769 // of the promoted arguments.
John McCalla729c622012-02-17 03:33:10 +00002770 if (isa<FunctionNoProtoType>(FnType) && !FnInfo.isVariadic()) {
2771 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00002772 CalleeTy = CalleeTy->getPointerTo();
2773 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
2774 }
2775
2776 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00002777}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002778
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002779LValue CodeGenFunction::
2780EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
Eli Friedman928a5672009-11-18 05:01:17 +00002781 llvm::Value *BaseV;
John McCalle3027922010-08-25 11:45:40 +00002782 if (E->getOpcode() == BO_PtrMemI)
Eli Friedman928a5672009-11-18 05:01:17 +00002783 BaseV = EmitScalarExpr(E->getLHS());
2784 else
2785 BaseV = EmitLValue(E->getLHS()).getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002786
John McCallc134eb52010-08-31 21:07:20 +00002787 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2788
2789 const MemberPointerType *MPT
2790 = E->getRHS()->getType()->getAs<MemberPointerType>();
2791
2792 llvm::Value *AddV =
2793 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
2794
2795 return MakeAddrLValue(AddV, MPT->getPointeeType());
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002796}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002797
2798static void
2799EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
2800 llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
2801 uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
Richard Smithfeea8832012-04-12 05:08:17 +00002802 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
2803 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
2804
2805 switch (E->getOp()) {
2806 case AtomicExpr::AO__c11_atomic_init:
2807 llvm_unreachable("Already handled!");
2808
2809 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2810 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2811 case AtomicExpr::AO__atomic_compare_exchange:
2812 case AtomicExpr::AO__atomic_compare_exchange_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002813 // Note that cmpxchg only supports specifying one ordering and
2814 // doesn't support weak cmpxchg, at least at the moment.
2815 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
2816 LoadVal1->setAlignment(Align);
2817 llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2);
2818 LoadVal2->setAlignment(Align);
2819 llvm::AtomicCmpXchgInst *CXI =
2820 CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order);
2821 CXI->setVolatile(E->isVolatile());
2822 llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1);
2823 StoreVal1->setAlignment(Align);
2824 llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1);
2825 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
2826 return;
2827 }
2828
Richard Smithfeea8832012-04-12 05:08:17 +00002829 case AtomicExpr::AO__c11_atomic_load:
2830 case AtomicExpr::AO__atomic_load_n:
2831 case AtomicExpr::AO__atomic_load: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002832 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
2833 Load->setAtomic(Order);
2834 Load->setAlignment(Size);
2835 Load->setVolatile(E->isVolatile());
2836 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
2837 StoreDest->setAlignment(Align);
2838 return;
2839 }
2840
Richard Smithfeea8832012-04-12 05:08:17 +00002841 case AtomicExpr::AO__c11_atomic_store:
2842 case AtomicExpr::AO__atomic_store:
2843 case AtomicExpr::AO__atomic_store_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002844 assert(!Dest && "Store does not return a value");
2845 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
2846 LoadVal1->setAlignment(Align);
2847 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
2848 Store->setAtomic(Order);
2849 Store->setAlignment(Size);
2850 Store->setVolatile(E->isVolatile());
2851 return;
2852 }
2853
Richard Smithfeea8832012-04-12 05:08:17 +00002854 case AtomicExpr::AO__c11_atomic_exchange:
2855 case AtomicExpr::AO__atomic_exchange_n:
2856 case AtomicExpr::AO__atomic_exchange:
2857 Op = llvm::AtomicRMWInst::Xchg;
2858 break;
2859
2860 case AtomicExpr::AO__atomic_add_fetch:
2861 PostOp = llvm::Instruction::Add;
2862 // Fall through.
2863 case AtomicExpr::AO__c11_atomic_fetch_add:
2864 case AtomicExpr::AO__atomic_fetch_add:
2865 Op = llvm::AtomicRMWInst::Add;
2866 break;
2867
2868 case AtomicExpr::AO__atomic_sub_fetch:
2869 PostOp = llvm::Instruction::Sub;
2870 // Fall through.
2871 case AtomicExpr::AO__c11_atomic_fetch_sub:
2872 case AtomicExpr::AO__atomic_fetch_sub:
2873 Op = llvm::AtomicRMWInst::Sub;
2874 break;
2875
2876 case AtomicExpr::AO__atomic_and_fetch:
2877 PostOp = llvm::Instruction::And;
2878 // Fall through.
2879 case AtomicExpr::AO__c11_atomic_fetch_and:
2880 case AtomicExpr::AO__atomic_fetch_and:
2881 Op = llvm::AtomicRMWInst::And;
2882 break;
2883
2884 case AtomicExpr::AO__atomic_or_fetch:
2885 PostOp = llvm::Instruction::Or;
2886 // Fall through.
2887 case AtomicExpr::AO__c11_atomic_fetch_or:
2888 case AtomicExpr::AO__atomic_fetch_or:
2889 Op = llvm::AtomicRMWInst::Or;
2890 break;
2891
2892 case AtomicExpr::AO__atomic_xor_fetch:
2893 PostOp = llvm::Instruction::Xor;
2894 // Fall through.
2895 case AtomicExpr::AO__c11_atomic_fetch_xor:
2896 case AtomicExpr::AO__atomic_fetch_xor:
2897 Op = llvm::AtomicRMWInst::Xor;
2898 break;
Richard Smithd65cee92012-04-13 06:31:38 +00002899
2900 case AtomicExpr::AO__atomic_nand_fetch:
2901 PostOp = llvm::Instruction::And;
2902 // Fall through.
2903 case AtomicExpr::AO__atomic_fetch_nand:
2904 Op = llvm::AtomicRMWInst::Nand;
2905 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002906 }
Richard Smithfeea8832012-04-12 05:08:17 +00002907
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002908 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
2909 LoadVal1->setAlignment(Align);
2910 llvm::AtomicRMWInst *RMWI =
2911 CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
2912 RMWI->setVolatile(E->isVolatile());
Richard Smithfeea8832012-04-12 05:08:17 +00002913
2914 // For __atomic_*_fetch operations, perform the operation again to
2915 // determine the value which was written.
2916 llvm::Value *Result = RMWI;
2917 if (PostOp)
2918 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
Richard Smithd65cee92012-04-13 06:31:38 +00002919 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
2920 Result = CGF.Builder.CreateNot(Result);
Richard Smithfeea8832012-04-12 05:08:17 +00002921 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002922 StoreDest->setAlignment(Align);
2923}
2924
2925// This function emits any expression (scalar, complex, or aggregate)
2926// into a temporary alloca.
2927static llvm::Value *
2928EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
2929 llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00002930 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
2931 /*Init*/ true);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002932 return DeclPtr;
2933}
2934
2935static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty,
2936 llvm::Value *Dest) {
2937 if (Ty->isAnyComplexType())
2938 return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false));
2939 if (CGF.hasAggregateLLVMType(Ty))
2940 return RValue::getAggregate(Dest);
2941 return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty)));
2942}
2943
2944RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
2945 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
Richard Smithfeea8832012-04-12 05:08:17 +00002946 QualType MemTy = AtomicTy;
2947 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
2948 MemTy = AT->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002949 CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
2950 uint64_t Size = sizeChars.getQuantity();
2951 CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
2952 unsigned Align = alignChars.getQuantity();
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002953 unsigned MaxInlineWidth =
2954 getContext().getTargetInfo().getMaxAtomicInlineWidth();
2955 bool UseLibcall = (Size != Align || Size > MaxInlineWidth);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002956
David Chisnallfa35df62012-01-16 17:27:18 +00002957
2958
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002959 llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
2960 Ptr = EmitScalarExpr(E->getPtr());
David Chisnallfa35df62012-01-16 17:27:18 +00002961
Richard Smithfeea8832012-04-12 05:08:17 +00002962 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
David Chisnallfa35df62012-01-16 17:27:18 +00002963 assert(!Dest && "Init does not return a value");
David Chisnalleb9496e2012-04-11 17:24:05 +00002964 if (!hasAggregateLLVMType(E->getVal1()->getType())) {
Douglas Gregor298f43d2012-04-12 20:42:30 +00002965 QualType PointeeType
2966 = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
2967 EmitScalarInit(EmitScalarExpr(E->getVal1()),
2968 LValue::MakeAddr(Ptr, PointeeType, alignChars,
2969 getContext()));
David Chisnalleb9496e2012-04-11 17:24:05 +00002970 } else if (E->getType()->isAnyComplexType()) {
2971 EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
2972 } else {
2973 AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars,
2974 AtomicTy.getQualifiers(),
2975 AggValueSlot::IsNotDestructed,
2976 AggValueSlot::DoesNotNeedGCBarriers,
2977 AggValueSlot::IsNotAliased);
2978 EmitAggExpr(E->getVal1(), Slot);
2979 }
David Chisnallfa35df62012-01-16 17:27:18 +00002980 return RValue::get(0);
2981 }
2982
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002983 Order = EmitScalarExpr(E->getOrder());
Richard Smithfeea8832012-04-12 05:08:17 +00002984
2985 switch (E->getOp()) {
2986 case AtomicExpr::AO__c11_atomic_init:
2987 llvm_unreachable("Already handled!");
2988
2989 case AtomicExpr::AO__c11_atomic_load:
2990 case AtomicExpr::AO__atomic_load_n:
2991 break;
2992
2993 case AtomicExpr::AO__atomic_load:
2994 Dest = EmitScalarExpr(E->getVal1());
2995 break;
2996
2997 case AtomicExpr::AO__atomic_store:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002998 Val1 = EmitScalarExpr(E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00002999 break;
3000
3001 case AtomicExpr::AO__atomic_exchange:
3002 Val1 = EmitScalarExpr(E->getVal1());
3003 Dest = EmitScalarExpr(E->getVal2());
3004 break;
3005
3006 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3007 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3008 case AtomicExpr::AO__atomic_compare_exchange_n:
3009 case AtomicExpr::AO__atomic_compare_exchange:
3010 Val1 = EmitScalarExpr(E->getVal1());
3011 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
3012 Val2 = EmitScalarExpr(E->getVal2());
3013 else
3014 Val2 = EmitValToTemp(*this, E->getVal2());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003015 OrderFail = EmitScalarExpr(E->getOrderFail());
Richard Smithfeea8832012-04-12 05:08:17 +00003016 // Evaluate and discard the 'weak' argument.
3017 if (E->getNumSubExprs() == 6)
3018 EmitScalarExpr(E->getWeak());
3019 break;
3020
3021 case AtomicExpr::AO__c11_atomic_fetch_add:
3022 case AtomicExpr::AO__c11_atomic_fetch_sub:
Richard Smithfeea8832012-04-12 05:08:17 +00003023 if (MemTy->isPointerType()) {
3024 // For pointer arithmetic, we're required to do a bit of math:
3025 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
Richard Smith01ba47d2012-04-13 00:45:38 +00003026 // ... but only for the C11 builtins. The GNU builtins expect the
3027 // user to multiply by sizeof(T).
Richard Smithfeea8832012-04-12 05:08:17 +00003028 QualType Val1Ty = E->getVal1()->getType();
3029 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
3030 CharUnits PointeeIncAmt =
3031 getContext().getTypeSizeInChars(MemTy->getPointeeType());
3032 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
3033 Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
3034 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
3035 break;
3036 }
3037 // Fall through.
Richard Smith01ba47d2012-04-13 00:45:38 +00003038 case AtomicExpr::AO__atomic_fetch_add:
3039 case AtomicExpr::AO__atomic_fetch_sub:
3040 case AtomicExpr::AO__atomic_add_fetch:
3041 case AtomicExpr::AO__atomic_sub_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003042 case AtomicExpr::AO__c11_atomic_store:
3043 case AtomicExpr::AO__c11_atomic_exchange:
3044 case AtomicExpr::AO__atomic_store_n:
3045 case AtomicExpr::AO__atomic_exchange_n:
3046 case AtomicExpr::AO__c11_atomic_fetch_and:
3047 case AtomicExpr::AO__c11_atomic_fetch_or:
3048 case AtomicExpr::AO__c11_atomic_fetch_xor:
3049 case AtomicExpr::AO__atomic_fetch_and:
3050 case AtomicExpr::AO__atomic_fetch_or:
3051 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003052 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003053 case AtomicExpr::AO__atomic_and_fetch:
3054 case AtomicExpr::AO__atomic_or_fetch:
3055 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003056 case AtomicExpr::AO__atomic_nand_fetch:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003057 Val1 = EmitValToTemp(*this, E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003058 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003059 }
3060
Richard Smithfeea8832012-04-12 05:08:17 +00003061 if (!E->getType()->isVoidType() && !Dest)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003062 Dest = CreateMemTemp(E->getType(), ".atomicdst");
3063
David Chisnalldb365f32012-03-29 18:01:11 +00003064 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003065 if (UseLibcall) {
David Chisnalldb365f32012-03-29 18:01:11 +00003066
3067 llvm::SmallVector<QualType, 5> Params;
3068 CallArgList Args;
3069 // Size is always the first parameter
3070 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
3071 getContext().getSizeType());
3072 // Atomic address is always the second parameter
3073 Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
3074 getContext().VoidPtrTy);
3075
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003076 const char* LibCallName;
David Chisnalldb365f32012-03-29 18:01:11 +00003077 QualType RetTy = getContext().VoidTy;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003078 switch (E->getOp()) {
David Chisnalldb365f32012-03-29 18:01:11 +00003079 // There is only one libcall for compare an exchange, because there is no
3080 // optimisation benefit possible from a libcall version of a weak compare
3081 // and exchange.
3082 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
Richard Smithfeea8832012-04-12 05:08:17 +00003083 // void *desired, int success, int failure)
3084 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3085 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3086 case AtomicExpr::AO__atomic_compare_exchange:
3087 case AtomicExpr::AO__atomic_compare_exchange_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003088 LibCallName = "__atomic_compare_exchange";
3089 RetTy = getContext().BoolTy;
3090 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3091 getContext().VoidPtrTy);
3092 Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
3093 getContext().VoidPtrTy);
3094 Args.add(RValue::get(Order),
3095 getContext().IntTy);
3096 Order = OrderFail;
3097 break;
3098 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
3099 // int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003100 case AtomicExpr::AO__c11_atomic_exchange:
3101 case AtomicExpr::AO__atomic_exchange_n:
3102 case AtomicExpr::AO__atomic_exchange:
David Chisnalldb365f32012-03-29 18:01:11 +00003103 LibCallName = "__atomic_exchange";
3104 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3105 getContext().VoidPtrTy);
3106 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3107 getContext().VoidPtrTy);
3108 break;
3109 // void __atomic_store(size_t size, void *mem, void *val, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003110 case AtomicExpr::AO__c11_atomic_store:
3111 case AtomicExpr::AO__atomic_store:
3112 case AtomicExpr::AO__atomic_store_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003113 LibCallName = "__atomic_store";
3114 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3115 getContext().VoidPtrTy);
3116 break;
3117 // void __atomic_load(size_t size, void *mem, void *return, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003118 case AtomicExpr::AO__c11_atomic_load:
3119 case AtomicExpr::AO__atomic_load:
3120 case AtomicExpr::AO__atomic_load_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003121 LibCallName = "__atomic_load";
3122 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3123 getContext().VoidPtrTy);
3124 break;
3125#if 0
3126 // These are only defined for 1-16 byte integers. It is not clear what
3127 // their semantics would be on anything else...
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003128 case AtomicExpr::Add: LibCallName = "__atomic_fetch_add_generic"; break;
3129 case AtomicExpr::Sub: LibCallName = "__atomic_fetch_sub_generic"; break;
3130 case AtomicExpr::And: LibCallName = "__atomic_fetch_and_generic"; break;
3131 case AtomicExpr::Or: LibCallName = "__atomic_fetch_or_generic"; break;
3132 case AtomicExpr::Xor: LibCallName = "__atomic_fetch_xor_generic"; break;
David Chisnalldb365f32012-03-29 18:01:11 +00003133#endif
3134 default: return EmitUnsupportedRValue(E, "atomic library call");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003135 }
David Chisnalldb365f32012-03-29 18:01:11 +00003136 // order is always the last parameter
3137 Args.add(RValue::get(Order),
3138 getContext().IntTy);
3139
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003140 const CGFunctionInfo &FuncInfo =
David Chisnalldb365f32012-03-29 18:01:11 +00003141 CGM.getTypes().arrangeFunctionCall(RetTy, Args,
3142 FunctionType::ExtInfo(), RequiredArgs::All);
3143 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003144 llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
3145 RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
3146 if (E->isCmpXChg())
3147 return Res;
Richard Smithfeea8832012-04-12 05:08:17 +00003148 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003149 return RValue::get(0);
3150 return ConvertTempToRValue(*this, E->getType(), Dest);
3151 }
David Chisnalldb365f32012-03-29 18:01:11 +00003152
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003153 llvm::Type *IPtrTy =
3154 llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
3155 llvm::Value *OrigDest = Dest;
3156 Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
3157 if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
3158 if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
3159 if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
3160
3161 if (isa<llvm::ConstantInt>(Order)) {
3162 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
3163 switch (ord) {
3164 case 0: // memory_order_relaxed
3165 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3166 llvm::Monotonic);
3167 break;
3168 case 1: // memory_order_consume
3169 case 2: // memory_order_acquire
3170 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3171 llvm::Acquire);
3172 break;
3173 case 3: // memory_order_release
3174 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3175 llvm::Release);
3176 break;
3177 case 4: // memory_order_acq_rel
3178 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3179 llvm::AcquireRelease);
3180 break;
3181 case 5: // memory_order_seq_cst
3182 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3183 llvm::SequentiallyConsistent);
3184 break;
3185 default: // invalid order
3186 // We should not ever get here normally, but it's hard to
3187 // enforce that in general.
Richard Smithfeea8832012-04-12 05:08:17 +00003188 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003189 }
Richard Smithfeea8832012-04-12 05:08:17 +00003190 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003191 return RValue::get(0);
3192 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3193 }
3194
3195 // Long case, when Order isn't obviously constant.
3196
Richard Smithfeea8832012-04-12 05:08:17 +00003197 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
3198 E->getOp() == AtomicExpr::AO__atomic_store ||
3199 E->getOp() == AtomicExpr::AO__atomic_store_n;
3200 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
3201 E->getOp() == AtomicExpr::AO__atomic_load ||
3202 E->getOp() == AtomicExpr::AO__atomic_load_n;
3203
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003204 // Create all the relevant BB's
Eli Friedmanc2025562011-10-11 20:00:47 +00003205 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
3206 *AcqRelBB = 0, *SeqCstBB = 0;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003207 MonotonicBB = createBasicBlock("monotonic", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003208 if (!IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003209 AcquireBB = createBasicBlock("acquire", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003210 if (!IsLoad)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003211 ReleaseBB = createBasicBlock("release", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003212 if (!IsLoad && !IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003213 AcqRelBB = createBasicBlock("acqrel", CurFn);
3214 SeqCstBB = createBasicBlock("seqcst", CurFn);
3215 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
3216
3217 // Create the switch for the split
3218 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
3219 // doesn't matter unless someone is crazy enough to use something that
3220 // doesn't fold to a constant for the ordering.
3221 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
3222 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
3223
3224 // Emit all the different atomics
3225 Builder.SetInsertPoint(MonotonicBB);
3226 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3227 llvm::Monotonic);
3228 Builder.CreateBr(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003229 if (!IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003230 Builder.SetInsertPoint(AcquireBB);
3231 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3232 llvm::Acquire);
3233 Builder.CreateBr(ContBB);
3234 SI->addCase(Builder.getInt32(1), AcquireBB);
3235 SI->addCase(Builder.getInt32(2), AcquireBB);
3236 }
Richard Smithfeea8832012-04-12 05:08:17 +00003237 if (!IsLoad) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003238 Builder.SetInsertPoint(ReleaseBB);
3239 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3240 llvm::Release);
3241 Builder.CreateBr(ContBB);
3242 SI->addCase(Builder.getInt32(3), ReleaseBB);
3243 }
Richard Smithfeea8832012-04-12 05:08:17 +00003244 if (!IsLoad && !IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003245 Builder.SetInsertPoint(AcqRelBB);
3246 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3247 llvm::AcquireRelease);
3248 Builder.CreateBr(ContBB);
3249 SI->addCase(Builder.getInt32(4), AcqRelBB);
3250 }
3251 Builder.SetInsertPoint(SeqCstBB);
3252 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3253 llvm::SequentiallyConsistent);
3254 Builder.CreateBr(ContBB);
3255 SI->addCase(Builder.getInt32(5), SeqCstBB);
3256
3257 // Cleanup and return
3258 Builder.SetInsertPoint(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003259 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003260 return RValue::get(0);
3261 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3262}
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003263
Duncan Sandse81111c2012-04-10 08:23:07 +00003264void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003265 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003266 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003267 return;
3268
Duncan Sands65229ed2012-04-16 16:29:47 +00003269 llvm::MDBuilder MDHelper(getLLVMContext());
3270 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003271
Duncan Sands6fc46192012-04-14 12:37:26 +00003272 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003273}
John McCallfe96e0b2011-11-06 09:01:30 +00003274
3275namespace {
3276 struct LValueOrRValue {
3277 LValue LV;
3278 RValue RV;
3279 };
3280}
3281
3282static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3283 const PseudoObjectExpr *E,
3284 bool forLValue,
3285 AggValueSlot slot) {
3286 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3287
3288 // Find the result expression, if any.
3289 const Expr *resultExpr = E->getResultExpr();
3290 LValueOrRValue result;
3291
3292 for (PseudoObjectExpr::const_semantics_iterator
3293 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3294 const Expr *semantic = *i;
3295
3296 // If this semantic expression is an opaque value, bind it
3297 // to the result of its source expression.
3298 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3299
3300 // If this is the result expression, we may need to evaluate
3301 // directly into the slot.
3302 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3303 OVMA opaqueData;
3304 if (ov == resultExpr && ov->isRValue() && !forLValue &&
3305 CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
3306 !ov->getType()->isAnyComplexType()) {
3307 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3308
3309 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3310 opaqueData = OVMA::bind(CGF, ov, LV);
3311 result.RV = slot.asRValue();
3312
3313 // Otherwise, emit as normal.
3314 } else {
3315 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3316
3317 // If this is the result, also evaluate the result now.
3318 if (ov == resultExpr) {
3319 if (forLValue)
3320 result.LV = CGF.EmitLValue(ov);
3321 else
3322 result.RV = CGF.EmitAnyExpr(ov, slot);
3323 }
3324 }
3325
3326 opaques.push_back(opaqueData);
3327
3328 // Otherwise, if the expression is the result, evaluate it
3329 // and remember the result.
3330 } else if (semantic == resultExpr) {
3331 if (forLValue)
3332 result.LV = CGF.EmitLValue(semantic);
3333 else
3334 result.RV = CGF.EmitAnyExpr(semantic, slot);
3335
3336 // Otherwise, evaluate the expression in an ignored context.
3337 } else {
3338 CGF.EmitIgnoredExpr(semantic);
3339 }
3340 }
3341
3342 // Unbind all the opaques now.
3343 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3344 opaques[i].unbind(CGF);
3345
3346 return result;
3347}
3348
3349RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3350 AggValueSlot slot) {
3351 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3352}
3353
3354LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3355 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3356}