blob: c8563d6044e7ee8653b70a8f406e76646fb2ef79 [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);
Mike Stump4a3999f2009-09-09 13:00:44 +00001050
Daniel Dunbar3447a022010-04-13 23:34:15 +00001051 // Get the field pointer.
1052 llvm::Value *Ptr = LV.getBitFieldBaseAddr();
Mike Stump4a3999f2009-09-09 13:00:44 +00001053
Daniel Dunbar3447a022010-04-13 23:34:15 +00001054 // Only offset by the field index if used, so that incoming values are not
1055 // required to be structures.
1056 if (AI.FieldIndex)
1057 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
Mike Stump4a3999f2009-09-09 13:00:44 +00001058
Daniel Dunbar3447a022010-04-13 23:34:15 +00001059 // Offset by the byte offset, if used.
Ken Dyckf76759c2011-04-24 10:04:59 +00001060 if (!AI.FieldByteOffset.isZero()) {
John McCallad7c5c12011-02-08 08:22:06 +00001061 Ptr = EmitCastToVoidPtr(Ptr);
Ken Dyckf76759c2011-04-24 10:04:59 +00001062 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1063 "bf.field.offs");
Daniel Dunbar3447a022010-04-13 23:34:15 +00001064 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001065
Daniel Dunbar3447a022010-04-13 23:34:15 +00001066 // Cast to the access type.
Chris Lattnerece04092012-02-07 00:39:47 +00001067 llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(), AI.AccessWidth,
John McCall55e1fbc2011-06-25 02:11:03 +00001068 CGM.getContext().getTargetAddressSpace(LV.getType()));
Daniel Dunbar3447a022010-04-13 23:34:15 +00001069 Ptr = Builder.CreateBitCast(Ptr, PTy);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001070
Daniel Dunbar3447a022010-04-13 23:34:15 +00001071 // Perform the load.
1072 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
Ken Dyck27337a82011-04-24 10:13:17 +00001073 if (!AI.AccessAlignment.isZero())
1074 Load->setAlignment(AI.AccessAlignment.getQuantity());
Daniel Dunbar3447a022010-04-13 23:34:15 +00001075
1076 // Shift out unused low bits and mask out unused high bits.
1077 llvm::Value *Val = Load;
1078 if (AI.FieldBitStart)
Daniel Dunbar67aba792010-04-15 03:47:33 +00001079 Val = Builder.CreateLShr(Load, AI.FieldBitStart);
Daniel Dunbar3447a022010-04-13 23:34:15 +00001080 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
1081 AI.TargetBitWidth),
1082 "bf.clear");
1083
1084 // Extend or truncate to the target size.
1085 if (AI.AccessWidth < ResSizeInBits)
1086 Val = Builder.CreateZExt(Val, ResLTy);
1087 else if (AI.AccessWidth > ResSizeInBits)
1088 Val = Builder.CreateTrunc(Val, ResLTy);
1089
1090 // Shift into place, and OR into the result.
1091 if (AI.TargetBitOffset)
1092 Val = Builder.CreateShl(Val, AI.TargetBitOffset);
1093 Res = Res ? Builder.CreateOr(Res, Val) : Val;
Daniel Dunbaread7c912008-08-06 05:08:45 +00001094 }
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001095
Daniel Dunbar3447a022010-04-13 23:34:15 +00001096 // If the bit-field is signed, perform the sign-extension.
1097 //
1098 // FIXME: This can easily be folded into the load of the high bits, which
1099 // could also eliminate the mask of high bits in some situations.
1100 if (Info.isSigned()) {
Daniel Dunbar67aba792010-04-15 03:47:33 +00001101 unsigned ExtraBits = ResSizeInBits - Info.getSize();
Daniel Dunbar3447a022010-04-13 23:34:15 +00001102 if (ExtraBits)
1103 Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
1104 ExtraBits, "bf.val.sext");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001105 }
Eli Friedmanf2442dc2008-05-17 20:03:47 +00001106
Daniel Dunbar3447a022010-04-13 23:34:15 +00001107 return RValue::get(Res);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001108}
1109
Nate Begemanb699c9b2009-01-18 06:42:49 +00001110// If this is a reference to a subset of the elements of a vector, create an
1111// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001112RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
Eli Friedman610bb872012-03-22 22:36:39 +00001113 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1114 LV.isVolatileQualified());
1115 Load->setAlignment(LV.getAlignment().getQuantity());
1116 llvm::Value *Vec = Load;
Mike Stump4a3999f2009-09-09 13:00:44 +00001117
Nate Begemanf322eab2008-05-09 06:41:27 +00001118 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001119
1120 // If the result of the expression is a non-vector type, we must be extracting
1121 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001122 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001123 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001124 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattner5e016ae2010-06-27 07:15:29 +00001125 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001126 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001127 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001128
1129 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001130 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001131
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001132 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001133 for (unsigned i = 0; i != NumResultElts; ++i)
1134 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001135
Chris Lattner91c08ad2011-02-15 00:14:06 +00001136 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1137 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001138 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001139 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001140}
1141
1142
Chris Lattner9369a562007-06-29 16:31:29 +00001143
Chris Lattner8394d792007-06-05 20:53:16 +00001144/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1145/// lvalue, where both are guaranteed to the have the same type, and that type
1146/// is 'Ty'.
David Chisnallfa35df62012-01-16 17:27:18 +00001147void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001148 if (!Dst.isSimple()) {
1149 if (Dst.isVectorElt()) {
1150 // Read/modify/write the vector, inserting the new element.
Eli Friedman610bb872012-03-22 22:36:39 +00001151 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1152 Dst.isVolatileQualified());
1153 Load->setAlignment(Dst.getAlignment().getQuantity());
1154 llvm::Value *Vec = Load;
Chris Lattner4647a212007-08-31 22:49:20 +00001155 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001156 Dst.getVectorIdx(), "vecins");
Eli Friedman610bb872012-03-22 22:36:39 +00001157 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1158 Dst.isVolatileQualified());
1159 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001160 return;
1161 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001162
Nate Begemance4d7fc2008-04-18 23:10:10 +00001163 // If this is an update of extended vector elements, insert them as
1164 // appropriate.
1165 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001166 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001167
John McCallc109a252011-11-07 03:59:57 +00001168 assert(Dst.isBitField() && "Unknown LValue type");
1169 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001170 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001171
John McCall31168b02011-06-15 23:02:42 +00001172 // There's special magic for assigning into an ARC-qualified l-value.
1173 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1174 switch (Lifetime) {
1175 case Qualifiers::OCL_None:
1176 llvm_unreachable("present but none");
1177
1178 case Qualifiers::OCL_ExplicitNone:
1179 // nothing special
1180 break;
1181
1182 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001183 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001184 return;
1185
1186 case Qualifiers::OCL_Weak:
1187 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1188 return;
1189
1190 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001191 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1192 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001193 // fall into the normal path
1194 break;
1195 }
1196 }
1197
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001198 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001199 // load of a __weak object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001200 llvm::Value *LvalueDst = Dst.getAddress();
1201 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001202 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001203 return;
1204 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001205
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001206 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001207 // load of a __strong object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001208 llvm::Value *LvalueDst = Dst.getAddress();
1209 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001210 if (Dst.isObjCIvar()) {
1211 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00001212 llvm::Type *ResultType = ConvertType(getContext().LongTy);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001213 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001214 llvm::Value *dst = RHS;
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001215 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1216 llvm::Value *LHS =
1217 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1218 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001219 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001220 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001221 } else if (Dst.isGlobalObjCRef()) {
1222 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1223 Dst.isThreadLocalRef());
1224 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001225 else
1226 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001227 return;
1228 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001229
Chris Lattner6278e6a2007-08-11 00:04:45 +00001230 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001231 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001232}
1233
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001234void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001235 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001236 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001237
Daniel Dunbar67aba792010-04-15 03:47:33 +00001238 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001239 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
Daniel Dunbar67aba792010-04-15 03:47:33 +00001240 unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
Daniel Dunbaread7c912008-08-06 05:08:45 +00001241
Daniel Dunbar67aba792010-04-15 03:47:33 +00001242 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001243 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001244
Douglas Gregor298f43d2012-04-12 20:42:30 +00001245 if (hasBooleanRepresentation(Dst.getType()))
Anders Carlsson8345a702010-04-17 21:52:22 +00001246 SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
1247
Daniel Dunbar67aba792010-04-15 03:47:33 +00001248 SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
1249 Info.getSize()),
1250 "bf.value");
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001251
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001252 // Return the new value of the bit-field, if requested.
1253 if (Result) {
1254 // Cast back to the proper type for result.
Chris Lattner2192fe52011-07-18 04:24:23 +00001255 llvm::Type *SrcTy = Src.getScalarVal()->getType();
Daniel Dunbar67aba792010-04-15 03:47:33 +00001256 llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
1257 "bf.reload.val");
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001258
1259 // Sign extend if necessary.
Daniel Dunbar67aba792010-04-15 03:47:33 +00001260 if (Info.isSigned()) {
1261 unsigned ExtraBits = ResSizeInBits - Info.getSize();
1262 if (ExtraBits)
1263 ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
1264 ExtraBits, "bf.reload.sext");
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001265 }
1266
Daniel Dunbar67aba792010-04-15 03:47:33 +00001267 *Result = ReloadVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001268 }
1269
Daniel Dunbar67aba792010-04-15 03:47:33 +00001270 // Iterate over the components, writing each piece to memory.
1271 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
1272 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
Eli Friedmanf2442dc2008-05-17 20:03:47 +00001273
Daniel Dunbar67aba792010-04-15 03:47:33 +00001274 // Get the field pointer.
1275 llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
John McCallad7c5c12011-02-08 08:22:06 +00001276 unsigned addressSpace =
1277 cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
Mike Stump4a3999f2009-09-09 13:00:44 +00001278
Daniel Dunbar67aba792010-04-15 03:47:33 +00001279 // Only offset by the field index if used, so that incoming values are not
1280 // required to be structures.
1281 if (AI.FieldIndex)
1282 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
Mike Stump4a3999f2009-09-09 13:00:44 +00001283
Daniel Dunbar67aba792010-04-15 03:47:33 +00001284 // Offset by the byte offset, if used.
Ken Dyckf76759c2011-04-24 10:04:59 +00001285 if (!AI.FieldByteOffset.isZero()) {
John McCallad7c5c12011-02-08 08:22:06 +00001286 Ptr = EmitCastToVoidPtr(Ptr);
Ken Dyckf76759c2011-04-24 10:04:59 +00001287 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1288 "bf.field.offs");
Daniel Dunbar67aba792010-04-15 03:47:33 +00001289 }
Eli Friedmanf2442dc2008-05-17 20:03:47 +00001290
Daniel Dunbar67aba792010-04-15 03:47:33 +00001291 // Cast to the access type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001292 llvm::Type *AccessLTy =
John McCallad7c5c12011-02-08 08:22:06 +00001293 llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth);
1294
Chris Lattner2192fe52011-07-18 04:24:23 +00001295 llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace);
Daniel Dunbar67aba792010-04-15 03:47:33 +00001296 Ptr = Builder.CreateBitCast(Ptr, PTy);
Mike Stump4a3999f2009-09-09 13:00:44 +00001297
Daniel Dunbar67aba792010-04-15 03:47:33 +00001298 // Extract the piece of the bit-field value to write in this access, limited
1299 // to the values that are part of this access.
1300 llvm::Value *Val = SrcVal;
1301 if (AI.TargetBitOffset)
1302 Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
1303 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
1304 AI.TargetBitWidth));
Mike Stump4a3999f2009-09-09 13:00:44 +00001305
Daniel Dunbar67aba792010-04-15 03:47:33 +00001306 // Extend or truncate to the access size.
Daniel Dunbar67aba792010-04-15 03:47:33 +00001307 if (ResSizeInBits < AI.AccessWidth)
1308 Val = Builder.CreateZExt(Val, AccessLTy);
1309 else if (ResSizeInBits > AI.AccessWidth)
1310 Val = Builder.CreateTrunc(Val, AccessLTy);
Mike Stump4a3999f2009-09-09 13:00:44 +00001311
Daniel Dunbar67aba792010-04-15 03:47:33 +00001312 // Shift into the position in memory.
1313 if (AI.FieldBitStart)
1314 Val = Builder.CreateShl(Val, AI.FieldBitStart);
1315
1316 // If necessary, load and OR in bits that are outside of the bit-field.
1317 if (AI.TargetBitWidth != AI.AccessWidth) {
1318 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
Ken Dyck27337a82011-04-24 10:13:17 +00001319 if (!AI.AccessAlignment.isZero())
1320 Load->setAlignment(AI.AccessAlignment.getQuantity());
Daniel Dunbar67aba792010-04-15 03:47:33 +00001321
1322 // Compute the mask for zeroing the bits that are part of the bit-field.
1323 llvm::APInt InvMask =
1324 ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
1325 AI.FieldBitStart + AI.TargetBitWidth);
1326
1327 // Apply the mask and OR in to the value to write.
1328 Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
1329 }
1330
1331 // Write the value.
1332 llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
1333 Dst.isVolatileQualified());
Ken Dyck27337a82011-04-24 10:13:17 +00001334 if (!AI.AccessAlignment.isZero())
1335 Store->setAlignment(AI.AccessAlignment.getQuantity());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001336 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001337}
1338
Nate Begemance4d7fc2008-04-18 23:10:10 +00001339void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001340 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001341 // This access turns into a read/modify/write of the vector. Load the input
1342 // value now.
Eli Friedman610bb872012-03-22 22:36:39 +00001343 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1344 Dst.isVolatileQualified());
1345 Load->setAlignment(Dst.getAlignment().getQuantity());
1346 llvm::Value *Vec = Load;
Nate Begemanf322eab2008-05-09 06:41:27 +00001347 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001348
Chris Lattner4647a212007-08-31 22:49:20 +00001349 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001350
John McCall55e1fbc2011-06-25 02:11:03 +00001351 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001352 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001353 unsigned NumDstElts =
1354 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1355 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001356 // Use shuffle vector is the src and destination are the same number of
1357 // elements and restore the vector mask since it is on the side it will be
1358 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001359 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001360 for (unsigned i = 0; i != NumSrcElts; ++i)
1361 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001362
Chris Lattner91c08ad2011-02-15 00:14:06 +00001363 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001364 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001365 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001366 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001367 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001368 // Extended the source vector to the same length and then shuffle it
1369 // into the destination.
1370 // FIXME: since we're shuffling with undef, can we just use the indices
1371 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001372 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001373 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001374 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001375 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001376 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001377 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001378 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001379 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001380 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001381 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001382 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001383 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001384 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001385
Nate Begemanb699c9b2009-01-18 06:42:49 +00001386 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001387 for (unsigned i = 0; i != NumSrcElts; ++i)
1388 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001389 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001390 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001391 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001392 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001393 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001394 }
1395 } else {
1396 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001397 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001398 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001399 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001400 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001401
Eli Friedman610bb872012-03-22 22:36:39 +00001402 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1403 Dst.isVolatileQualified());
1404 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001405}
1406
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001407// setObjCGCLValueClass - sets class of he lvalue for the purpose of
1408// generating write-barries API. It is currently a global, ivar,
1409// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001410static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001411 LValue &LV,
1412 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001413 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001414 return;
1415
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001416 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001417 QualType ExpTy = E->getType();
1418 if (IsMemberAccess && ExpTy->isPointerType()) {
1419 // If ivar is a structure pointer, assigning to field of
1420 // this struct follows gcc's behavior and makes it a non-ivar
1421 // writer-barrier conservatively.
1422 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1423 if (ExpTy->isRecordType()) {
1424 LV.setObjCIvar(false);
1425 return;
1426 }
1427 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001428 LV.setObjCIvar(true);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001429 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1430 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001431 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001432 return;
1433 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001434
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001435 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1436 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001437 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001438 LV.setGlobalObjCRef(true);
1439 LV.setThreadLocalRef(VD->isThreadSpecified());
Fariborz Jahanian217af242010-07-20 20:30:03 +00001440 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001441 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001442 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001443 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001444 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001445
1446 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001447 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001448 return;
1449 }
1450
1451 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001452 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001453 if (LV.isObjCIvar()) {
1454 // If cast is to a structure pointer, follow gcc's behavior and make it
1455 // a non-ivar write-barrier.
1456 QualType ExpTy = E->getType();
1457 if (ExpTy->isPointerType())
1458 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1459 if (ExpTy->isRecordType())
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001460 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001461 }
1462 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001463 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001464
1465 if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1466 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1467 return;
1468 }
1469
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001470 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001471 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001472 return;
1473 }
1474
1475 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001476 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001477 return;
1478 }
John McCall31168b02011-06-15 23:02:42 +00001479
1480 if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001481 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001482 return;
1483 }
1484
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001485 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001486 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001487 if (LV.isObjCIvar() && !LV.isObjCArray())
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001488 // Using array syntax to assigning to what an ivar points to is not
1489 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001490 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001491 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1492 // Using array syntax to assigning to what global points to is not
1493 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001494 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001495 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001496 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001497
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001498 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001499 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001500 // We don't know if member is an 'ivar', but this flag is looked at
1501 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001502 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001503 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001504 }
1505}
1506
Chris Lattner3f32d692011-07-12 06:52:18 +00001507static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001508EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001509 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001510 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001511 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001512 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001513}
1514
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001515static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1516 const Expr *E, const VarDecl *VD) {
Daniel Dunbar7e215ea2009-11-08 09:46:46 +00001517 assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001518 "Var decl must have external storage or be a file var decl!");
1519
1520 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001521 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1522 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001523 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001524 QualType T = E->getType();
1525 LValue LV;
1526 if (VD->getType()->isReferenceType()) {
1527 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001528 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001529 V = LI;
1530 LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1531 } else {
1532 LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1533 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001534 setObjCGCLValueClass(CGF.getContext(), E, LV);
1535 return LV;
1536}
1537
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001538static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001539 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001540 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001541 if (!FD->hasPrototype()) {
1542 if (const FunctionProtoType *Proto =
1543 FD->getType()->getAs<FunctionProtoType>()) {
1544 // Ugly case: for a K&R-style definition, the type of the definition
1545 // isn't the same as the type of a use. Correct for this with a
1546 // bitcast.
1547 QualType NoProtoType =
1548 CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1549 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001550 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001551 }
1552 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001553 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Daniel Dunbar5c816372010-08-21 04:20:22 +00001554 return CGF.MakeAddrLValue(V, E->getType(), Alignment);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001555}
1556
Chris Lattnerd7f58862007-06-02 05:24:33 +00001557LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001558 const NamedDecl *ND = E->getDecl();
Eli Friedmana0544d62011-12-03 04:14:32 +00001559 CharUnits Alignment = getContext().getDeclAlign(ND);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001560 QualType T = E->getType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001561
Eli Friedman5720e342012-01-21 04:52:58 +00001562 // FIXME: We should be able to assert this for FunctionDecls as well!
1563 // FIXME: We should be able to assert this for all DeclRefExprs, not just
1564 // those with a valid source location.
1565 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1566 !E->getLocation().isValid()) &&
1567 "Should not use decl without marking it used!");
1568
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001569 if (ND->hasAttr<WeakRefAttr>()) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001570 const ValueDecl *VD = cast<ValueDecl>(ND);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001571 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
Daniel Dunbar5c816372010-08-21 04:20:22 +00001572 return MakeAddrLValue(Aliasee, E->getType(), Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001573 }
1574
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001575 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001576 // Check if this is a global variable.
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001577 if (VD->hasExternalStorage() || VD->isFileVarDecl())
1578 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00001579
John McCall113bee02012-03-10 09:33:50 +00001580 bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1581
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001582 bool NonGCable = VD->hasLocalStorage() &&
1583 !VD->getType()->isReferenceType() &&
John McCall113bee02012-03-10 09:33:50 +00001584 !isBlockVariable;
Anders Carlsson6eee9722009-11-07 22:46:42 +00001585
1586 llvm::Value *V = LocalDeclMap[VD];
Fariborz Jahanian366a9482010-09-07 23:26:17 +00001587 if (!V && VD->isStaticLocal())
Fariborz Jahanian4d55b2d2010-04-19 18:15:02 +00001588 V = CGM.getStaticLocalDeclAddress(VD);
Eli Friedman9fbeba02012-02-11 02:57:39 +00001589
1590 // Use special handling for lambdas.
John McCall113bee02012-03-10 09:33:50 +00001591 if (!V) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00001592 if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1593 QualType LambdaTagType = getContext().getTagDeclType(FD->getParent());
1594 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
1595 LambdaTagType);
1596 return EmitLValueForField(LambdaLV, FD);
1597 }
Eli Friedman9fbeba02012-02-11 02:57:39 +00001598
John McCall113bee02012-03-10 09:33:50 +00001599 assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
1600 CharUnits alignment = getContext().getDeclAlign(VD);
1601 return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
1602 E->getType(), alignment);
1603 }
1604
Anders Carlsson6eee9722009-11-07 22:46:42 +00001605 assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1606
John McCall113bee02012-03-10 09:33:50 +00001607 if (isBlockVariable)
Fariborz Jahanian2f2fa722011-01-26 23:08:27 +00001608 V = BuildBlockByrefAddress(V, VD);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001609
Eli Friedmand20adbd2011-11-16 00:42:57 +00001610 LValue LV;
1611 if (VD->getType()->isReferenceType()) {
1612 llvm::LoadInst *LI = Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001613 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001614 V = LI;
1615 LV = MakeNaturalAlignAddrLValue(V, T);
1616 } else {
1617 LV = MakeAddrLValue(V, T, Alignment);
1618 }
Chris Lattner3f32d692011-07-12 06:52:18 +00001619
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001620 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00001621 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00001622 LV.setNonGC(true);
1623 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001624 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00001625 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001626 }
John McCallf3a88602011-02-03 08:15:49 +00001627
1628 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1629 return EmitFunctionDeclLValue(*this, E, fn);
1630
David Blaikie83d382b2011-09-23 05:06:16 +00001631 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001632}
Chris Lattnere47e4402007-06-01 18:02:12 +00001633
Chris Lattner8394d792007-06-05 20:53:16 +00001634LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1635 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00001636 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00001637 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001638
Chris Lattner0f398c42008-07-26 22:37:01 +00001639 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00001640 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001641 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00001642 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001643 QualType T = E->getSubExpr()->getType()->getPointeeType();
1644 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00001645
Chris Lattner2415357a2011-12-19 21:16:08 +00001646 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001647 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00001648
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001649 // We should not generate __weak write barrier on indirect reference
1650 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1651 // But, we continue to generate __strong write barrier on indirect write
1652 // into a pointer to object.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001653 if (getContext().getLangOpts().ObjC1 &&
1654 getContext().getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001655 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00001656 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001657 return LV;
1658 }
John McCalle3027922010-08-25 11:45:40 +00001659 case UO_Real:
1660 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00001661 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00001662 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1663 llvm::Value *Addr = LV.getAddress();
1664
Richard Smith0b6b8e42012-02-18 20:53:32 +00001665 // __real is valid on scalars. This is a faster way of testing that.
1666 // __imag can only produce an rvalue on scalars.
1667 if (E->getOpcode() == UO_Real &&
1668 !cast<llvm::PointerType>(Addr->getType())
John McCalla2342eb2010-12-05 02:00:02 +00001669 ->getElementType()->isStructTy()) {
1670 assert(E->getSubExpr()->getType()->isArithmeticType());
1671 return LV;
1672 }
1673
1674 assert(E->getSubExpr()->getType()->isAnyComplexType());
1675
John McCalle3027922010-08-25 11:45:40 +00001676 unsigned Idx = E->getOpcode() == UO_Imag;
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001677 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
John McCalla2342eb2010-12-05 02:00:02 +00001678 Idx, "idx"),
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001679 ExprTy);
Chris Lattner595db862007-10-30 22:53:42 +00001680 }
John McCalle3027922010-08-25 11:45:40 +00001681 case UO_PreInc:
1682 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001683 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00001684 bool isInc = E->getOpcode() == UO_PreInc;
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001685
1686 if (E->getType()->isAnyComplexType())
1687 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1688 else
1689 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1690 return LV;
1691 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00001692 }
Chris Lattner8394d792007-06-05 20:53:16 +00001693}
1694
Chris Lattner4347e3692007-06-06 04:54:52 +00001695LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001696 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1697 E->getType());
Chris Lattner4347e3692007-06-06 04:54:52 +00001698}
1699
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001700LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001701 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1702 E->getType());
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001703}
1704
Nico Weber3a691a32012-06-23 02:07:59 +00001705static llvm::Constant*
1706GetAddrOfConstantWideString(StringRef Str,
1707 const char *GlobalName,
1708 ASTContext &Context,
1709 QualType Ty, SourceLocation Loc,
1710 CodeGenModule &CGM) {
1711
1712 StringLiteral *SL = StringLiteral::Create(Context,
1713 Str,
1714 StringLiteral::Wide,
1715 /*Pascal = */false,
1716 Ty, Loc);
1717 llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL);
1718 llvm::GlobalVariable *GV =
1719 new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1720 !CGM.getLangOpts().WritableStrings,
1721 llvm::GlobalValue::PrivateLinkage,
1722 C, GlobalName);
1723 const unsigned WideAlignment =
1724 Context.getTypeAlignInChars(Ty).getQuantity();
1725 GV->setAlignment(WideAlignment);
1726 return GV;
1727}
1728
1729// FIXME: Mostly copied from StringLiteralParser::CopyStringFragment
1730static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
1731 SmallString<32>& Target) {
1732 Target.resize(CharByteWidth * (Source.size() + 1));
1733 char* ResultPtr = &Target[0];
1734
1735 assert(CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4);
1736 ConversionResult result = conversionOK;
1737 // Copy the character span over.
1738 if (CharByteWidth == 1) {
1739 if (!isLegalUTF8String(reinterpret_cast<const UTF8*>(&*Source.begin()),
1740 reinterpret_cast<const UTF8*>(&*Source.end())))
1741 result = sourceIllegal;
1742 memcpy(ResultPtr, Source.data(), Source.size());
1743 ResultPtr += Source.size();
1744 } else if (CharByteWidth == 2) {
1745 UTF8 const *sourceStart = (UTF8 const *)Source.data();
1746 // FIXME: Make the type of the result buffer correct instead of
1747 // using reinterpret_cast.
1748 UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
1749 ConversionFlags flags = strictConversion;
1750 result = ConvertUTF8toUTF16(
1751 &sourceStart,sourceStart + Source.size(),
1752 &targetStart,targetStart + 2*Source.size(),flags);
1753 if (result==conversionOK)
1754 ResultPtr = reinterpret_cast<char*>(targetStart);
1755 } else if (CharByteWidth == 4) {
1756 UTF8 const *sourceStart = (UTF8 const *)Source.data();
1757 // FIXME: Make the type of the result buffer correct instead of
1758 // using reinterpret_cast.
1759 UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
1760 ConversionFlags flags = strictConversion;
1761 result = ConvertUTF8toUTF32(
1762 &sourceStart,sourceStart + Source.size(),
1763 &targetStart,targetStart + 4*Source.size(),flags);
1764 if (result==conversionOK)
1765 ResultPtr = reinterpret_cast<char*>(targetStart);
1766 }
1767 assert((result != targetExhausted)
1768 && "ConvertUTF8toUTFXX exhausted target buffer");
1769 assert(result == conversionOK);
1770 Target.resize(ResultPtr - &Target[0]);
1771}
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001772
Mike Stump4a3999f2009-09-09 13:00:44 +00001773LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Daniel Dunbarb3517472008-10-17 21:58:32 +00001774 switch (E->getIdentType()) {
1775 default:
1776 return EmitUnsupportedLValue(E, "predefined expression");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001777
Daniel Dunbarb3517472008-10-17 21:58:32 +00001778 case PredefinedExpr::Func:
1779 case PredefinedExpr::Function:
Nico Weber3a691a32012-06-23 02:07:59 +00001780 case PredefinedExpr::LFunction:
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001781 case PredefinedExpr::PrettyFunction: {
Nico Weber3a691a32012-06-23 02:07:59 +00001782 unsigned IdentType = E->getIdentType();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001783 std::string GlobalVarName;
1784
Nico Weber3a691a32012-06-23 02:07:59 +00001785 switch (IdentType) {
David Blaikie83d382b2011-09-23 05:06:16 +00001786 default: llvm_unreachable("Invalid type");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001787 case PredefinedExpr::Func:
1788 GlobalVarName = "__func__.";
1789 break;
1790 case PredefinedExpr::Function:
1791 GlobalVarName = "__FUNCTION__.";
1792 break;
Nico Weber3a691a32012-06-23 02:07:59 +00001793 case PredefinedExpr::LFunction:
1794 GlobalVarName = "L__FUNCTION__.";
1795 break;
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001796 case PredefinedExpr::PrettyFunction:
1797 GlobalVarName = "__PRETTY_FUNCTION__.";
1798 break;
1799 }
1800
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001801 StringRef FnName = CurFn->getName();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001802 if (FnName.startswith("\01"))
1803 FnName = FnName.substr(1);
1804 GlobalVarName += FnName;
1805
1806 const Decl *CurDecl = CurCodeDecl;
1807 if (CurDecl == 0)
1808 CurDecl = getContext().getTranslationUnitDecl();
1809
1810 std::string FunctionName =
John McCall351762c2011-02-07 10:33:21 +00001811 (isa<BlockDecl>(CurDecl)
1812 ? FnName.str()
Nico Weber3a691a32012-06-23 02:07:59 +00001813 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType,
1814 CurDecl));
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001815
Nico Weber3a691a32012-06-23 02:07:59 +00001816 const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual();
1817 llvm::Constant *C;
1818 if (ElemType->isWideCharType()) {
1819 SmallString<32> RawChars;
1820 ConvertUTF8ToWideString(
1821 getContext().getTypeSizeInChars(ElemType).getQuantity(),
1822 FunctionName, RawChars);
1823 C = GetAddrOfConstantWideString(RawChars,
1824 GlobalVarName.c_str(),
1825 getContext(),
1826 E->getType(),
1827 E->getLocation(),
1828 CGM);
1829 } else {
1830 C = CGM.GetAddrOfConstantCString(FunctionName,
1831 GlobalVarName.c_str(),
1832 1);
1833 }
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001834 return MakeAddrLValue(C, E->getType());
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001835 }
Daniel Dunbarb3517472008-10-17 21:58:32 +00001836 }
Anders Carlsson625bfc82007-07-21 05:21:51 +00001837}
1838
Mike Stumpcf16d2c2009-12-15 01:22:35 +00001839llvm::BasicBlock *CodeGenFunction::getTrapBB() {
Mike Stump9a4e0122009-12-15 00:59:40 +00001840 const CodeGenOptions &GCO = CGM.getCodeGenOpts();
1841
1842 // If we are not optimzing, don't collapse all calls to trap in the function
1843 // to the same call, that way, in the debugger they can see which operation
Chris Lattner26008e02010-07-20 20:19:24 +00001844 // did in fact fail. If we are optimizing, we collapse all calls to trap down
Mike Stump9a4e0122009-12-15 00:59:40 +00001845 // to just one per function to save on codesize.
Chris Lattner26008e02010-07-20 20:19:24 +00001846 if (GCO.OptimizationLevel && TrapBB)
Mike Stumpe8c3b3e2009-12-15 00:35:12 +00001847 return TrapBB;
Mike Stumpd9546382009-12-12 01:27:46 +00001848
1849 llvm::BasicBlock *Cont = 0;
1850 if (HaveInsertPoint()) {
1851 Cont = createBasicBlock("cont");
1852 EmitBranch(Cont);
1853 }
Mike Stumpe8c3b3e2009-12-15 00:35:12 +00001854 TrapBB = createBasicBlock("trap");
1855 EmitBlock(TrapBB);
1856
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00001857 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
Mike Stumpe8c3b3e2009-12-15 00:35:12 +00001858 llvm::CallInst *TrapCall = Builder.CreateCall(F);
1859 TrapCall->setDoesNotReturn();
1860 TrapCall->setDoesNotThrow();
Mike Stumpd9546382009-12-12 01:27:46 +00001861 Builder.CreateUnreachable();
1862
1863 if (Cont)
1864 EmitBlock(Cont);
Mike Stumpe8c3b3e2009-12-15 00:35:12 +00001865 return TrapBB;
Mike Stumpd9546382009-12-12 01:27:46 +00001866}
1867
Chris Lattner6c5abe82010-06-26 23:03:20 +00001868/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
1869/// array to pointer, return the array subexpression.
1870static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
1871 // If this isn't just an array->pointer decay, bail out.
1872 const CastExpr *CE = dyn_cast<CastExpr>(E);
John McCalle3027922010-08-25 11:45:40 +00001873 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
Chris Lattner6c5abe82010-06-26 23:03:20 +00001874 return 0;
1875
1876 // If this is a decay from variable width array, bail out.
1877 const Expr *SubExpr = CE->getSubExpr();
1878 if (SubExpr->getType()->isVariableArrayType())
1879 return 0;
1880
1881 return SubExpr;
1882}
1883
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001884LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00001885 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00001886 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00001887 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001888 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00001889
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001890 // If the base is a vector type, then we are forming a vector element lvalue
1891 // with this subscript.
Eli Friedman327944b2008-06-13 23:01:12 +00001892 if (E->getBase()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001893 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00001894 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00001895 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
John McCallad7c5c12011-02-08 08:22:06 +00001896 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
Eli Friedman327944b2008-06-13 23:01:12 +00001897 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
Eli Friedman610bb872012-03-22 22:36:39 +00001898 E->getBase()->getType(), LHS.getAlignment());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001899 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001900
Ted Kremenekc81614d2007-08-20 16:18:38 +00001901 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00001902 if (Idx->getType() != IntPtrTy)
1903 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00001904
Mike Stump4a3999f2009-09-09 13:00:44 +00001905 // We know that the pointer points to a type of the correct size, unless the
1906 // size is a VLA or Objective-C interface.
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001907 llvm::Value *Address = 0;
Eli Friedmana0544d62011-12-03 04:14:32 +00001908 CharUnits ArrayAlignment;
John McCall23c29fe2011-06-24 21:55:10 +00001909 if (const VariableArrayType *vla =
Anders Carlsson3d312f82008-12-21 00:11:23 +00001910 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00001911 // The base must be a pointer, which is not an aggregate. Emit
1912 // it. It needs to be emitted first in case it's what captures
1913 // the VLA bounds.
1914 Address = EmitScalarExpr(E->getBase());
Mike Stump4a3999f2009-09-09 13:00:44 +00001915
John McCall23c29fe2011-06-24 21:55:10 +00001916 // The element count here is the total number of non-VLA elements.
1917 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00001918
John McCall77527a82011-06-25 01:32:37 +00001919 // Effectively, the multiply by the VLA size is part of the GEP.
1920 // GEP indexes are signed, and scaling an index isn't permitted to
1921 // signed-overflow, so we use the same semantics for our explicit
1922 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001923 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00001924 Idx = Builder.CreateMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00001925 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00001926 } else {
1927 Idx = Builder.CreateNSWMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00001928 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00001929 }
Chris Lattner6c5abe82010-06-26 23:03:20 +00001930 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
1931 // Indexing over an interface, as in "NSString *P; P[4];"
Mike Stump4a3999f2009-09-09 13:00:44 +00001932 llvm::Value *InterfaceSize =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001933 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck40775002010-01-11 17:06:35 +00001934 getContext().getTypeSizeInChars(OIT).getQuantity());
Mike Stump4a3999f2009-09-09 13:00:44 +00001935
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001936 Idx = Builder.CreateMul(Idx, InterfaceSize);
1937
Chris Lattner6c5abe82010-06-26 23:03:20 +00001938 // The base must be a pointer, which is not an aggregate. Emit it.
1939 llvm::Value *Base = EmitScalarExpr(E->getBase());
John McCallad7c5c12011-02-08 08:22:06 +00001940 Address = EmitCastToVoidPtr(Base);
1941 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001942 Address = Builder.CreateBitCast(Address, Base->getType());
Chris Lattner6c5abe82010-06-26 23:03:20 +00001943 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
1944 // If this is A[i] where A is an array, the frontend will have decayed the
1945 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
1946 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
1947 // "gep x, i" here. Emit one "gep A, 0, i".
1948 assert(Array->getType()->isArrayType() &&
1949 "Array to pointer decay must have array source type!");
Daniel Dunbar82634272011-04-01 00:49:43 +00001950 LValue ArrayLV = EmitLValue(Array);
1951 llvm::Value *ArrayPtr = ArrayLV.getAddress();
Chris Lattner6c5abe82010-06-26 23:03:20 +00001952 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
1953 llvm::Value *Args[] = { Zero, Idx };
1954
Daniel Dunbar82634272011-04-01 00:49:43 +00001955 // Propagate the alignment from the array itself to the result.
1956 ArrayAlignment = ArrayLV.getAlignment();
1957
David Blaikiebbafb8a2012-03-11 07:00:24 +00001958 if (getContext().getLangOpts().isSignedOverflowDefined())
Jay Foad040dd822011-07-22 08:16:57 +00001959 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Chris Lattner2e72da942011-03-01 00:03:48 +00001960 else
Jay Foad040dd822011-07-22 08:16:57 +00001961 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001962 } else {
Chris Lattner6c5abe82010-06-26 23:03:20 +00001963 // The base must be a pointer, which is not an aggregate. Emit it.
1964 llvm::Value *Base = EmitScalarExpr(E->getBase());
David Blaikiebbafb8a2012-03-11 07:00:24 +00001965 if (getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001966 Address = Builder.CreateGEP(Base, Idx, "arrayidx");
1967 else
1968 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
Anders Carlsson3d312f82008-12-21 00:11:23 +00001969 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001970
Steve Naroff7cae42b2009-07-10 23:34:53 +00001971 QualType T = E->getBase()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001972 assert(!T.isNull() &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00001973 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
Mike Stump4a3999f2009-09-09 13:00:44 +00001974
Chris Lattner36bc4f42012-01-04 22:35:55 +00001975
Daniel Dunbar82634272011-04-01 00:49:43 +00001976 // Limit the alignment to that of the result type.
Chris Lattner36bc4f42012-01-04 22:35:55 +00001977 LValue LV;
Eli Friedmana0544d62011-12-03 04:14:32 +00001978 if (!ArrayAlignment.isZero()) {
1979 CharUnits Align = getContext().getTypeAlignInChars(T);
Daniel Dunbar82634272011-04-01 00:49:43 +00001980 ArrayAlignment = std::min(Align, ArrayAlignment);
Chris Lattner36bc4f42012-01-04 22:35:55 +00001981 LV = MakeAddrLValue(Address, T, ArrayAlignment);
1982 } else {
1983 LV = MakeNaturalAlignAddrLValue(Address, T);
Daniel Dunbar82634272011-04-01 00:49:43 +00001984 }
1985
Daniel Dunbarf166a522010-08-21 03:44:13 +00001986 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00001987
David Blaikiebbafb8a2012-03-11 07:00:24 +00001988 if (getContext().getLangOpts().ObjC1 &&
1989 getContext().getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00001990 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001991 setObjCGCLValueClass(getContext(), E, LV);
1992 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00001993 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001994}
1995
Mike Stump4a3999f2009-09-09 13:00:44 +00001996static
NAKAMURA Takumiccca11a2012-01-25 08:58:21 +00001997llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001998 SmallVector<unsigned, 4> &Elts) {
1999 SmallVector<llvm::Constant*, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002000 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002001 CElts.push_back(Builder.getInt32(Elts[i]));
Nate Begemand3862152008-05-13 21:03:02 +00002002
Chris Lattner91c08ad2011-02-15 00:14:06 +00002003 return llvm::ConstantVector::get(CElts);
Nate Begemand3862152008-05-13 21:03:02 +00002004}
2005
Chris Lattner9e751ca2007-08-02 23:37:31 +00002006LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002007EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002008 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002009 LValue Base;
2010
2011 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002012 if (E->isArrow()) {
2013 // If it is a pointer to a vector, emit the address and form an lvalue with
2014 // it.
Chris Lattnerb8211f62009-02-16 22:14:05 +00002015 llvm::Value *Ptr = EmitScalarExpr(E->getBase());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002016 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Daniel Dunbarf166a522010-08-21 03:44:13 +00002017 Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2018 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002019 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002020 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2021 // emit the base as an lvalue.
2022 assert(E->getBase()->getType()->isVectorType());
2023 Base = EmitLValue(E->getBase());
2024 } else {
2025 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002026 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002027 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002028 llvm::Value *Vec = EmitScalarExpr(E->getBase());
2029
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002030 // Store the vector to memory (because LValue wants an address).
Daniel Dunbara7566f12010-02-09 02:48:28 +00002031 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002032 Builder.CreateStore(Vec, VecMem);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002033 Base = MakeAddrLValue(VecMem, E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002034 }
John McCall1553b192011-06-16 04:16:24 +00002035
2036 QualType type =
2037 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002038
Nate Begemand3862152008-05-13 21:03:02 +00002039 // Encode the element access list into a vector of unsigned indices.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002040 SmallVector<unsigned, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002041 E->getEncodedElementAccess(Indices);
2042
2043 if (Base.isSimple()) {
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002044 llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002045 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2046 Base.getAlignment());
Nate Begemand3862152008-05-13 21:03:02 +00002047 }
2048 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2049
2050 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002051 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002052
Chris Lattner595ba3a2012-01-30 06:20:36 +00002053 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2054 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002055 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
Eli Friedman610bb872012-03-22 22:36:39 +00002056 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2057 Base.getAlignment());
Chris Lattner9e751ca2007-08-02 23:37:31 +00002058}
2059
Devang Patel30efa2e2007-10-23 20:28:39 +00002060LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00002061 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00002062
Chris Lattner4e4186b2007-12-02 18:52:07 +00002063 // 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 +00002064 LValue BaseLV;
2065 if (E->isArrow())
2066 BaseLV = MakeNaturalAlignAddrLValue(EmitScalarExpr(BaseExpr),
2067 BaseExpr->getType()->getPointeeType());
2068 else
2069 BaseLV = EmitLValue(BaseExpr);
Devang Patel30efa2e2007-10-23 20:28:39 +00002070
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002071 NamedDecl *ND = E->getMemberDecl();
2072 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002073 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002074 setObjCGCLValueClass(getContext(), E, LV);
2075 return LV;
2076 }
2077
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00002078 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
2079 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002080
2081 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
2082 return EmitFunctionDeclLValue(*this, E, FD);
2083
David Blaikie83d382b2011-09-23 05:06:16 +00002084 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00002085}
Devang Patel30efa2e2007-10-23 20:28:39 +00002086
Chris Lattnerf53c0962010-09-06 00:11:41 +00002087LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value *BaseValue,
2088 const FieldDecl *Field,
Fariborz Jahanian712bfa62009-02-03 19:03:09 +00002089 unsigned CVRQualifiers) {
Daniel Dunbar034299e2010-03-31 01:09:11 +00002090 const CGRecordLayout &RL =
2091 CGM.getTypes().getCGRecordLayout(Field->getParent());
Daniel Dunbarcd3d5e72010-04-05 16:20:44 +00002092 const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
Daniel Dunbarc75c8bd2010-04-08 02:59:45 +00002093 return LValue::MakeBitfield(BaseValue, Info,
John McCall1553b192011-06-16 04:16:24 +00002094 Field->getType().withCVRQualifiers(CVRQualifiers));
Fariborz Jahanianb517e902008-12-15 20:35:07 +00002095}
2096
John McCallc4094932010-05-21 01:18:57 +00002097/// EmitLValueForAnonRecordField - Given that the field is a member of
2098/// an anonymous struct or union buried inside a record, and given
2099/// that the base value is a pointer to the enclosing record, derive
2100/// an lvalue for the ultimate field.
2101LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue,
Francois Pichetd583da02010-12-04 09:14:42 +00002102 const IndirectFieldDecl *Field,
John McCallc4094932010-05-21 01:18:57 +00002103 unsigned CVRQualifiers) {
Francois Pichetd583da02010-12-04 09:14:42 +00002104 IndirectFieldDecl::chain_iterator I = Field->chain_begin(),
2105 IEnd = Field->chain_end();
John McCallc4094932010-05-21 01:18:57 +00002106 while (true) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002107 QualType RecordTy =
2108 getContext().getTypeDeclType(cast<FieldDecl>(*I)->getParent());
2109 LValue LV = EmitLValueForField(MakeAddrLValue(BaseValue, RecordTy),
2110 cast<FieldDecl>(*I));
Francois Pichetd583da02010-12-04 09:14:42 +00002111 if (++I == IEnd) return LV;
John McCallc4094932010-05-21 01:18:57 +00002112
2113 assert(LV.isSimple());
2114 BaseValue = LV.getAddress();
2115 CVRQualifiers |= LV.getVRQualifiers();
2116 }
2117}
2118
Eli Friedman7f1ff602012-04-16 03:54:45 +00002119LValue CodeGenFunction::EmitLValueForField(LValue base,
2120 const FieldDecl *field) {
John McCall53fcbd22011-02-26 08:07:02 +00002121 if (field->isBitField())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002122 return EmitLValueForBitfield(base.getAddress(), field,
2123 base.getVRQualifiers());
Mike Stump4a3999f2009-09-09 13:00:44 +00002124
John McCall53fcbd22011-02-26 08:07:02 +00002125 const RecordDecl *rec = field->getParent();
2126 QualType type = field->getType();
Eli Friedmana0544d62011-12-03 04:14:32 +00002127 CharUnits alignment = getContext().getDeclAlign(field);
Eli Friedman133e8042008-05-29 11:33:25 +00002128
Eli Friedman7f1ff602012-04-16 03:54:45 +00002129 // FIXME: It should be impossible to have an LValue without alignment for a
2130 // complete type.
2131 if (!base.getAlignment().isZero())
2132 alignment = std::min(alignment, base.getAlignment());
2133
John McCall53fcbd22011-02-26 08:07:02 +00002134 bool mayAlias = rec->hasAttr<MayAliasAttr>();
2135
Eli Friedman7f1ff602012-04-16 03:54:45 +00002136 llvm::Value *addr = base.getAddress();
2137 unsigned cvr = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00002138 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00002139 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00002140 assert(!type->isReferenceType() && "union has reference member");
John McCall53fcbd22011-02-26 08:07:02 +00002141 } else {
2142 // For structs, we GEP to the field that the record layout suggests.
2143 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
Chris Lattner13ee4f42011-07-10 05:34:54 +00002144 addr = Builder.CreateStructGEP(addr, idx, field->getName());
John McCall53fcbd22011-02-26 08:07:02 +00002145
2146 // If this is a reference field, load the reference right now.
2147 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2148 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2149 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
Eli Friedmana0544d62011-12-03 04:14:32 +00002150 load->setAlignment(alignment.getQuantity());
John McCall53fcbd22011-02-26 08:07:02 +00002151
2152 if (CGM.shouldUseTBAA()) {
2153 llvm::MDNode *tbaa;
2154 if (mayAlias)
2155 tbaa = CGM.getTBAAInfo(getContext().CharTy);
2156 else
2157 tbaa = CGM.getTBAAInfo(type);
2158 CGM.DecorateInstruction(load, tbaa);
2159 }
2160
2161 addr = load;
2162 mayAlias = false;
2163 type = refType->getPointeeType();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002164 if (type->isIncompleteType())
Eli Friedmana0544d62011-12-03 04:14:32 +00002165 alignment = CharUnits();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002166 else
Eli Friedmana0544d62011-12-03 04:14:32 +00002167 alignment = getContext().getTypeAlignInChars(type);
John McCall53fcbd22011-02-26 08:07:02 +00002168 cvr = 0; // qualifiers don't recursively apply to referencee
2169 }
Devang Pateled93c3c2007-10-26 19:42:18 +00002170 }
Chris Lattner13ee4f42011-07-10 05:34:54 +00002171
2172 // Make sure that the address is pointing to the right type. This is critical
2173 // for both unions and structs. A union needs a bitcast, a struct element
2174 // will need a bitcast if the LLVM type laid out doesn't match the desired
2175 // type.
Chandler Carruth4678f672011-07-12 08:58:26 +00002176 addr = EmitBitCastOfLValueToProperType(*this, addr,
Chris Lattner3f32d692011-07-12 06:52:18 +00002177 CGM.getTypes().ConvertTypeForMem(type),
2178 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00002179
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002180 if (field->hasAttr<AnnotateAttr>())
2181 addr = EmitFieldAnnotations(field, addr);
2182
John McCall53fcbd22011-02-26 08:07:02 +00002183 LValue LV = MakeAddrLValue(addr, type, alignment);
2184 LV.getQuals().addCVRQualifiers(cvr);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002185
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002186 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00002187 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2188 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00002189
2190 // Fields of may_alias structs act like 'char' for TBAA purposes.
2191 // FIXME: this should get propagated down through anonymous structs
2192 // and unions.
2193 if (mayAlias && LV.getTBAAInfo())
2194 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2195
Daniel Dunbarf166a522010-08-21 03:44:13 +00002196 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00002197}
2198
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002199LValue
Eli Friedman7f1ff602012-04-16 03:54:45 +00002200CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2201 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002202 QualType FieldType = Field->getType();
2203
2204 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002205 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002206
Daniel Dunbar034299e2010-03-31 01:09:11 +00002207 const CGRecordLayout &RL =
2208 CGM.getTypes().getCGRecordLayout(Field->getParent());
2209 unsigned idx = RL.getLLVMFieldNo(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002210 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002211 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2212
Chris Lattnerd7c59352011-07-10 05:53:24 +00002213 // Make sure that the address is pointing to the right type. This is critical
2214 // for both unions and structs. A union needs a bitcast, a struct element
2215 // will need a bitcast if the LLVM type laid out doesn't match the desired
2216 // type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002217 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002218 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2219
Eli Friedmana0544d62011-12-03 04:14:32 +00002220 CharUnits Alignment = getContext().getDeclAlign(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002221
2222 // FIXME: It should be impossible to have an LValue without alignment for a
2223 // complete type.
2224 if (!Base.getAlignment().isZero())
2225 Alignment = std::min(Alignment, Base.getAlignment());
2226
Daniel Dunbar5c816372010-08-21 04:20:22 +00002227 return MakeAddrLValue(V, FieldType, Alignment);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002228}
2229
Chris Lattnerf53c0962010-09-06 00:11:41 +00002230LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00002231 if (E->isFileScope()) {
2232 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2233 return MakeAddrLValue(GlobalPtr, E->getType());
2234 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00002235 if (E->getType()->isVariablyModifiedType())
2236 // make sure to emit the VLA size.
2237 EmitVariablyModifiedType(E->getType());
Fariborz Jahanianbbc5bbf2012-06-07 17:07:15 +00002238
Daniel Dunbar27bacaf2010-02-16 19:43:39 +00002239 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00002240 const Expr *InitExpr = E->getInitializer();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002241 LValue Result = MakeAddrLValue(DeclPtr, E->getType());
Eli Friedman9fd8b682008-05-13 23:18:27 +00002242
Chad Rosier615ed1a2012-03-29 17:37:10 +00002243 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2244 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00002245
2246 return Result;
2247}
2248
Richard Smithbb653bd2012-05-14 21:57:21 +00002249LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2250 if (!E->isGLValue())
2251 // Initializing an aggregate temporary in C++11: T{...}.
2252 return EmitAggExprToLValue(E);
2253
2254 // An lvalue initializer list must be initializing a reference.
2255 assert(E->getNumInits() == 1 && "reference init with multiple values");
2256 return EmitLValue(E->getInit(0));
2257}
2258
John McCallc07a0c72011-02-17 10:25:35 +00002259LValue CodeGenFunction::
2260EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2261 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00002262 // ?: here should be an aggregate.
John McCallc07a0c72011-02-17 10:25:35 +00002263 assert((hasAggregateLLVMType(expr->getType()) &&
2264 !expr->getType()->isAnyComplexType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00002265 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00002266 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00002267 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002268
Eli Friedman59954892012-01-25 05:04:17 +00002269 OpaqueValueMapping binding(*this, expr);
2270
John McCallc07a0c72011-02-17 10:25:35 +00002271 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002272 bool CondExprBool;
2273 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00002274 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002275 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00002276
2277 if (!ContainsLabel(dead))
2278 return EmitLValue(live);
John McCall0a6bf2e2011-01-26 19:21:13 +00002279 }
2280
John McCallc07a0c72011-02-17 10:25:35 +00002281 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2282 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2283 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00002284
2285 ConditionalEvaluation eval(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002286 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002287
2288 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002289 EmitBlock(lhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002290 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002291 LValue lhs = EmitLValue(expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002292 eval.end(*this);
2293
John McCallc07a0c72011-02-17 10:25:35 +00002294 if (!lhs.isSimple())
2295 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00002296
John McCallc07a0c72011-02-17 10:25:35 +00002297 lhsBlock = Builder.GetInsertBlock();
2298 Builder.CreateBr(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002299
2300 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002301 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002302 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002303 LValue rhs = EmitLValue(expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002304 eval.end(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002305 if (!rhs.isSimple())
2306 return EmitUnsupportedLValue(expr, "conditional operator");
2307 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00002308
John McCallc07a0c72011-02-17 10:25:35 +00002309 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002310
Jay Foad20c0f022011-03-30 11:28:58 +00002311 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
John McCall0a6bf2e2011-01-26 19:21:13 +00002312 "cond-lvalue");
John McCallc07a0c72011-02-17 10:25:35 +00002313 phi->addIncoming(lhs.getAddress(), lhsBlock);
2314 phi->addIncoming(rhs.getAddress(), rhsBlock);
2315 return MakeAddrLValue(phi, expr->getType());
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002316}
2317
Richard Smithbb653bd2012-05-14 21:57:21 +00002318/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2319/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00002320/// otherwise if a cast is needed by the code generator in an lvalue context,
2321/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00002322/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00002323/// are permitted with aggregate result, including noop aggregate casts, and
2324/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002325LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00002326 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00002327 case CK_ToVoid:
Eli Friedman8c98dff2009-11-16 05:48:01 +00002328 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
John McCall8cb679e2010-11-15 09:13:47 +00002329
2330 case CK_Dependent:
2331 llvm_unreachable("dependent cast kind in IR gen!");
David Chisnallfa35df62012-01-16 17:27:18 +00002332
2333 // These two casts are currently treated as no-ops, although they could
2334 // potentially be real operations depending on the target's ABI.
2335 case CK_NonAtomicToAtomic:
2336 case CK_AtomicToNonAtomic:
John McCall8cb679e2010-11-15 09:13:47 +00002337
John McCalle3027922010-08-25 11:45:40 +00002338 case CK_NoOp:
Douglas Gregor21d3fca2011-01-27 23:22:05 +00002339 case CK_LValueToRValue:
2340 if (!E->getSubExpr()->Classify(getContext()).isPRValue()
2341 || E->getType()->isRecordType())
John McCalle26a8722010-12-04 08:14:53 +00002342 return EmitLValue(E->getSubExpr());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002343 // Fall through to synthesize a temporary.
John McCall8cb679e2010-11-15 09:13:47 +00002344
John McCalle3027922010-08-25 11:45:40 +00002345 case CK_BitCast:
2346 case CK_ArrayToPointerDecay:
2347 case CK_FunctionToPointerDecay:
2348 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00002349 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00002350 case CK_IntegralToPointer:
2351 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002352 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002353 case CK_VectorSplat:
2354 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00002355 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002356 case CK_IntegralToFloating:
2357 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002358 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002359 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00002360 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002361 case CK_FloatingComplexToReal:
2362 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002363 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002364 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00002365 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002366 case CK_IntegralComplexToReal:
2367 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002368 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002369 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00002370 case CK_DerivedToBaseMemberPointer:
2371 case CK_BaseToDerivedMemberPointer:
2372 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00002373 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00002374 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00002375 case CK_ARCProduceObject:
2376 case CK_ARCConsumeObject:
2377 case CK_ARCReclaimReturnedObject:
Douglas Gregored90df32012-02-22 05:02:47 +00002378 case CK_ARCExtendBlockObject:
2379 case CK_CopyAndAutoreleaseBlockObject: {
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002380 // These casts only produce lvalues when we're binding a reference to a
2381 // temporary realized from a (converted) pure rvalue. Emit the expression
2382 // as a value, copy it into a temporary, and return an lvalue referring to
2383 // that temporary.
2384 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00002385 EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002386 return MakeAddrLValue(V, E->getType());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002387 }
Eli Friedman8c98dff2009-11-16 05:48:01 +00002388
Anders Carlsson8a01a752011-04-11 02:03:26 +00002389 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00002390 LValue LV = EmitLValue(E->getSubExpr());
2391 llvm::Value *V = LV.getAddress();
2392 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002393 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00002394 }
2395
John McCalle3027922010-08-25 11:45:40 +00002396 case CK_ConstructorConversion:
2397 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00002398 case CK_CPointerToObjCPointerCast:
2399 case CK_BlockPointerToObjCPointerCast:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002400 return EmitLValue(E->getSubExpr());
Anders Carlssond95f9602009-09-12 16:16:49 +00002401
John McCalle3027922010-08-25 11:45:40 +00002402 case CK_UncheckedDerivedToBase:
2403 case CK_DerivedToBase: {
Anders Carlssond95f9602009-09-12 16:16:49 +00002404 const RecordType *DerivedClassTy =
2405 E->getSubExpr()->getType()->getAs<RecordType>();
2406 CXXRecordDecl *DerivedClassDecl =
2407 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Anders Carlssond95f9602009-09-12 16:16:49 +00002408
2409 LValue LV = EmitLValue(E->getSubExpr());
John McCalle26a8722010-12-04 08:14:53 +00002410 llvm::Value *This = LV.getAddress();
Anders Carlssond95f9602009-09-12 16:16:49 +00002411
2412 // Perform the derived-to-base conversion
2413 llvm::Value *Base =
Fariborz Jahanian64cda8b2010-06-17 23:00:29 +00002414 GetAddressOfBaseClass(This, DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002415 E->path_begin(), E->path_end(),
2416 /*NullCheckValue=*/false);
Anders Carlssond95f9602009-09-12 16:16:49 +00002417
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002418 return MakeAddrLValue(Base, E->getType());
Anders Carlssond95f9602009-09-12 16:16:49 +00002419 }
John McCalle3027922010-08-25 11:45:40 +00002420 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00002421 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00002422 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00002423 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2424 CXXRecordDecl *DerivedClassDecl =
2425 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2426
2427 LValue LV = EmitLValue(E->getSubExpr());
2428
2429 // Perform the base-to-derived conversion
2430 llvm::Value *Derived =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +00002431 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002432 E->path_begin(), E->path_end(),
2433 /*NullCheckValue=*/false);
Anders Carlsson8c793172009-11-23 17:57:54 +00002434
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002435 return MakeAddrLValue(Derived, E->getType());
Eli Friedman8c98dff2009-11-16 05:48:01 +00002436 }
John McCalle3027922010-08-25 11:45:40 +00002437 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00002438 // This must be a reinterpret_cast (or c-style equivalent).
2439 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
Anders Carlsson50cb3212009-11-14 21:21:42 +00002440
2441 LValue LV = EmitLValue(E->getSubExpr());
2442 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2443 ConvertType(CE->getTypeAsWritten()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002444 return MakeAddrLValue(V, E->getType());
Anders Carlsson50cb3212009-11-14 21:21:42 +00002445 }
John McCalle3027922010-08-25 11:45:40 +00002446 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002447 LValue LV = EmitLValue(E->getSubExpr());
2448 QualType ToType = getContext().getLValueReferenceType(E->getType());
2449 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2450 ConvertType(ToType));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002451 return MakeAddrLValue(V, E->getType());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002452 }
Anders Carlssond95f9602009-09-12 16:16:49 +00002453 }
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002454
2455 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002456}
2457
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002458LValue CodeGenFunction::EmitNullInitializationLValue(
Douglas Gregor747eb782010-07-08 06:14:04 +00002459 const CXXScalarValueInitExpr *E) {
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002460 QualType Ty = E->getType();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002461 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
Anders Carlssonc0964b62010-05-22 17:35:42 +00002462 EmitNullInitialization(LV.getAddress(), Ty);
Daniel Dunbara7566f12010-02-09 02:48:28 +00002463 return LV;
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002464}
2465
John McCall1bf58462011-02-16 08:02:54 +00002466LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00002467 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00002468 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00002469}
2470
Douglas Gregorfe314812011-06-21 17:03:29 +00002471LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2472 const MaterializeTemporaryExpr *E) {
John McCall17054bd62011-08-26 21:08:13 +00002473 RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
Douglas Gregord410c082011-06-21 18:20:46 +00002474 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Douglas Gregorfe314812011-06-21 17:03:29 +00002475}
2476
Eli Friedman7f1ff602012-04-16 03:54:45 +00002477RValue CodeGenFunction::EmitRValueForField(LValue LV,
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002478 const FieldDecl *FD) {
2479 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00002480 LValue FieldLV = EmitLValueForField(LV, FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002481 if (FT->isAnyComplexType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002482 return RValue::getComplex(
2483 LoadComplexFromAddr(FieldLV.getAddress(),
2484 FieldLV.isVolatileQualified()));
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002485 else if (CodeGenFunction::hasAggregateLLVMType(FT))
Eli Friedman7f1ff602012-04-16 03:54:45 +00002486 return FieldLV.asAggregateRValue();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002487
Eli Friedman7f1ff602012-04-16 03:54:45 +00002488 return EmitLoadOfLValue(FieldLV);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002489}
Douglas Gregorfe314812011-06-21 17:03:29 +00002490
Chris Lattnere47e4402007-06-01 18:02:12 +00002491//===--------------------------------------------------------------------===//
2492// Expression Emission
2493//===--------------------------------------------------------------------===//
2494
Anders Carlsson17490832009-12-24 20:40:36 +00002495RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2496 ReturnValueSlot ReturnValue) {
Eric Christopher7cdf9482011-10-13 21:45:18 +00002497 if (CGDebugInfo *DI = getDebugInfo())
2498 DI->EmitLocation(Builder, E->getLocStart());
Devang Pateld3a6b0f2011-03-04 18:54:42 +00002499
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002500 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002501 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00002502 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002503
Anders Carlssone5fd6f22009-04-03 22:50:24 +00002504 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002505 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002506
Peter Collingbournefe883422011-10-06 18:29:37 +00002507 if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E))
2508 return EmitCUDAKernelCallExpr(CE, ReturnValue);
2509
Douglas Gregore0e96302011-09-06 21:41:04 +00002510 const Decl *TargetDecl = E->getCalleeDecl();
2511 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2512 if (unsigned builtinID = FD->getBuiltinID())
2513 return EmitBuiltinExpr(FD, builtinID, E);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002514 }
2515
Chris Lattner4ca97c32009-06-13 00:26:38 +00002516 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00002517 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002518 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002519
John McCall31168b02011-06-15 23:02:42 +00002520 if (const CXXPseudoDestructorExpr *PseudoDtor
2521 = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2522 QualType DestroyedType = PseudoDtor->getDestroyedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002523 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002524 DestroyedType->isObjCLifetimeType() &&
2525 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2526 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002527 // Automatic Reference Counting:
2528 // If the pseudo-expression names a retainable object with weak or
2529 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00002530 Expr *BaseExpr = PseudoDtor->getBase();
2531 llvm::Value *BaseValue = NULL;
2532 Qualifiers BaseQuals;
2533
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002534 // 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 +00002535 if (PseudoDtor->isArrow()) {
2536 BaseValue = EmitScalarExpr(BaseExpr);
2537 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2538 BaseQuals = PTy->getPointeeType().getQualifiers();
2539 } else {
2540 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00002541 BaseValue = BaseLV.getAddress();
2542 QualType BaseTy = BaseExpr->getType();
2543 BaseQuals = BaseTy.getQualifiers();
2544 }
2545
2546 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2547 case Qualifiers::OCL_None:
2548 case Qualifiers::OCL_ExplicitNone:
2549 case Qualifiers::OCL_Autoreleasing:
2550 break;
2551
2552 case Qualifiers::OCL_Strong:
2553 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002554 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCall31168b02011-06-15 23:02:42 +00002555 /*precise*/ true);
2556 break;
2557
2558 case Qualifiers::OCL_Weak:
2559 EmitARCDestroyWeak(BaseValue);
2560 break;
2561 }
2562 } else {
2563 // C++ [expr.pseudo]p1:
2564 // The result shall only be used as the operand for the function call
2565 // operator (), and the result of such a call has type void. The only
2566 // effect is the evaluation of the postfix-expression before the dot or
2567 // arrow.
2568 EmitScalarExpr(E->getCallee());
2569 }
2570
Douglas Gregorad8a3362009-09-04 17:36:40 +00002571 return RValue::get(0);
2572 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002573
Chris Lattner2da04b32007-08-24 05:35:26 +00002574 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Anders Carlsson17490832009-12-24 20:40:36 +00002575 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002576 E->arg_begin(), E->arg_end(), TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00002577}
2578
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002579LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00002580 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00002581 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00002582 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00002583 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00002584 return EmitLValue(E->getRHS());
2585 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002586
John McCalle3027922010-08-25 11:45:40 +00002587 if (E->getOpcode() == BO_PtrMemD ||
2588 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002589 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002590
John McCalla2342eb2010-12-05 02:00:02 +00002591 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00002592
2593 // Note that in all of these cases, __block variables need the RHS
2594 // evaluated first just in case the variable gets moved by the RHS.
John McCall4f29b492010-11-16 23:07:28 +00002595
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002596 if (!hasAggregateLLVMType(E->getType())) {
John McCall31168b02011-06-15 23:02:42 +00002597 switch (E->getLHS()->getType().getObjCLifetime()) {
2598 case Qualifiers::OCL_Strong:
2599 return EmitARCStoreStrong(E, /*ignored*/ false).first;
2600
2601 case Qualifiers::OCL_Autoreleasing:
2602 return EmitARCStoreAutoreleasing(E).first;
2603
2604 // No reason to do any of these differently.
2605 case Qualifiers::OCL_None:
2606 case Qualifiers::OCL_ExplicitNone:
2607 case Qualifiers::OCL_Weak:
2608 break;
2609 }
2610
John McCalld0a30012010-12-06 06:10:02 +00002611 RValue RV = EmitAnyExpr(E->getRHS());
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002612 LValue LV = EmitLValue(E->getLHS());
John McCall55e1fbc2011-06-25 02:11:03 +00002613 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002614 return LV;
2615 }
John McCall4f29b492010-11-16 23:07:28 +00002616
2617 if (E->getType()->isAnyComplexType())
2618 return EmitComplexAssignmentLValue(E);
2619
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002620 return EmitAggExprToLValue(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002621}
2622
Christopher Lambd91c3d42007-12-29 05:02:41 +00002623LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00002624 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00002625
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002626 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002627 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002628
2629 assert(E->getCallReturnType()->isReferenceType() &&
2630 "Can't have a scalar return unless the return type is a "
2631 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00002632
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002633 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00002634}
2635
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002636LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2637 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002638 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002639}
2640
Anders Carlsson3be22e22009-05-30 23:23:33 +00002641LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002642 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2643 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002644 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00002645 EmitCXXConstructExpr(E, Slot);
2646 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlsson3be22e22009-05-30 23:23:33 +00002647}
2648
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002649LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00002650CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002651 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00002652}
2653
2654LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002655CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002656 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00002657 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00002658 EmitAggExpr(E->getSubExpr(), Slot);
Peter Collingbourne702b2842011-11-27 22:09:22 +00002659 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
John McCall8ea46b62010-09-18 00:58:34 +00002660 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002661}
2662
Eli Friedman5bc17122012-02-08 05:34:55 +00002663LValue
2664CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00002665 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002666 EmitLambdaExpr(E, Slot);
Eli Friedman5bc17122012-02-08 05:34:55 +00002667 return MakeAddrLValue(Slot.getAddr(), E->getType());
2668}
2669
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002670LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002671 RValue RV = EmitObjCMessageExpr(E);
Anders Carlsson280e61f12010-06-21 20:59:55 +00002672
2673 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002674 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Anders Carlsson280e61f12010-06-21 20:59:55 +00002675
2676 assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2677 "Can't have a scalar return unless the return type is a "
2678 "reference type!");
2679
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002680 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002681}
2682
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00002683LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2684 llvm::Value *V =
2685 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002686 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00002687}
2688
Daniel Dunbar722f4242009-04-22 05:08:15 +00002689llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002690 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002691 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002692}
2693
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002694LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2695 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002696 const ObjCIvarDecl *Ivar,
2697 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00002698 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00002699 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002700}
2701
2702LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002703 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2704 llvm::Value *BaseValue = 0;
2705 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00002706 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002707 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002708 if (E->isArrow()) {
2709 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002710 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002711 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002712 } else {
2713 LValue BaseLV = EmitLValue(BaseExpr);
2714 // FIXME: this isn't right for bitfields.
2715 BaseValue = BaseLV.getAddress();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002716 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00002717 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002718 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002719
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002720 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00002721 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2722 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002723 setObjCGCLValueClass(getContext(), E, LV);
2724 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00002725}
2726
Chris Lattnera4185c52009-04-25 19:35:26 +00002727LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00002728 // Can only get l-value for message expression returning aggregate type
2729 RValue RV = EmitAnyExprToTemp(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002730 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnera4185c52009-04-25 19:35:26 +00002731}
2732
Anders Carlsson0435ed52009-12-24 19:08:58 +00002733RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Anders Carlsson17490832009-12-24 20:40:36 +00002734 ReturnValueSlot ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002735 CallExpr::const_arg_iterator ArgBeg,
2736 CallExpr::const_arg_iterator ArgEnd,
2737 const Decl *TargetDecl) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002738 // Get the actual function type. The callee type will always be a pointer to
2739 // function type or a block pointer type.
2740 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00002741 "Call must have function pointer type!");
2742
John McCall6fd4c232009-10-23 08:22:42 +00002743 CalleeType = getContext().getCanonicalType(CalleeType);
2744
John McCallab26cfa2010-02-05 21:31:56 +00002745 const FunctionType *FnType
2746 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00002747
2748 CallArgList Args;
John McCall6fd4c232009-10-23 08:22:42 +00002749 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
Daniel Dunbarc722b852008-08-30 03:02:31 +00002750
John McCalla729c622012-02-17 03:33:10 +00002751 const CGFunctionInfo &FnInfo =
2752 CGM.getTypes().arrangeFunctionCall(Args, FnType);
John McCallcbc038a2011-09-21 08:08:30 +00002753
2754 // C99 6.5.2.2p6:
2755 // If the expression that denotes the called function has a type
2756 // that does not include a prototype, [the default argument
2757 // promotions are performed]. If the number of arguments does not
2758 // equal the number of parameters, the behavior is undefined. If
2759 // the function is defined with a type that includes a prototype,
2760 // and either the prototype ends with an ellipsis (, ...) or the
2761 // types of the arguments after promotion are not compatible with
2762 // the types of the parameters, the behavior is undefined. If the
2763 // function is defined with a type that does not include a
2764 // prototype, and the types of the arguments after promotion are
2765 // not compatible with those of the parameters after promotion,
2766 // the behavior is undefined [except in some trivial cases].
2767 // That is, in the general case, we should assume that a call
2768 // through an unprototyped function type works like a *non-variadic*
2769 // call. The way we make this work is to cast to the exact type
2770 // of the promoted arguments.
John McCalla729c622012-02-17 03:33:10 +00002771 if (isa<FunctionNoProtoType>(FnType) && !FnInfo.isVariadic()) {
2772 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00002773 CalleeTy = CalleeTy->getPointerTo();
2774 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
2775 }
2776
2777 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00002778}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002779
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002780LValue CodeGenFunction::
2781EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
Eli Friedman928a5672009-11-18 05:01:17 +00002782 llvm::Value *BaseV;
John McCalle3027922010-08-25 11:45:40 +00002783 if (E->getOpcode() == BO_PtrMemI)
Eli Friedman928a5672009-11-18 05:01:17 +00002784 BaseV = EmitScalarExpr(E->getLHS());
2785 else
2786 BaseV = EmitLValue(E->getLHS()).getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002787
John McCallc134eb52010-08-31 21:07:20 +00002788 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2789
2790 const MemberPointerType *MPT
2791 = E->getRHS()->getType()->getAs<MemberPointerType>();
2792
2793 llvm::Value *AddV =
2794 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
2795
2796 return MakeAddrLValue(AddV, MPT->getPointeeType());
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002797}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002798
2799static void
2800EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
2801 llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
2802 uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
Richard Smithfeea8832012-04-12 05:08:17 +00002803 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
2804 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
2805
2806 switch (E->getOp()) {
2807 case AtomicExpr::AO__c11_atomic_init:
2808 llvm_unreachable("Already handled!");
2809
2810 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2811 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2812 case AtomicExpr::AO__atomic_compare_exchange:
2813 case AtomicExpr::AO__atomic_compare_exchange_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002814 // Note that cmpxchg only supports specifying one ordering and
2815 // doesn't support weak cmpxchg, at least at the moment.
2816 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
2817 LoadVal1->setAlignment(Align);
2818 llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2);
2819 LoadVal2->setAlignment(Align);
2820 llvm::AtomicCmpXchgInst *CXI =
2821 CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order);
2822 CXI->setVolatile(E->isVolatile());
2823 llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1);
2824 StoreVal1->setAlignment(Align);
2825 llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1);
2826 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
2827 return;
2828 }
2829
Richard Smithfeea8832012-04-12 05:08:17 +00002830 case AtomicExpr::AO__c11_atomic_load:
2831 case AtomicExpr::AO__atomic_load_n:
2832 case AtomicExpr::AO__atomic_load: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002833 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
2834 Load->setAtomic(Order);
2835 Load->setAlignment(Size);
2836 Load->setVolatile(E->isVolatile());
2837 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
2838 StoreDest->setAlignment(Align);
2839 return;
2840 }
2841
Richard Smithfeea8832012-04-12 05:08:17 +00002842 case AtomicExpr::AO__c11_atomic_store:
2843 case AtomicExpr::AO__atomic_store:
2844 case AtomicExpr::AO__atomic_store_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002845 assert(!Dest && "Store does not return a value");
2846 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
2847 LoadVal1->setAlignment(Align);
2848 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
2849 Store->setAtomic(Order);
2850 Store->setAlignment(Size);
2851 Store->setVolatile(E->isVolatile());
2852 return;
2853 }
2854
Richard Smithfeea8832012-04-12 05:08:17 +00002855 case AtomicExpr::AO__c11_atomic_exchange:
2856 case AtomicExpr::AO__atomic_exchange_n:
2857 case AtomicExpr::AO__atomic_exchange:
2858 Op = llvm::AtomicRMWInst::Xchg;
2859 break;
2860
2861 case AtomicExpr::AO__atomic_add_fetch:
2862 PostOp = llvm::Instruction::Add;
2863 // Fall through.
2864 case AtomicExpr::AO__c11_atomic_fetch_add:
2865 case AtomicExpr::AO__atomic_fetch_add:
2866 Op = llvm::AtomicRMWInst::Add;
2867 break;
2868
2869 case AtomicExpr::AO__atomic_sub_fetch:
2870 PostOp = llvm::Instruction::Sub;
2871 // Fall through.
2872 case AtomicExpr::AO__c11_atomic_fetch_sub:
2873 case AtomicExpr::AO__atomic_fetch_sub:
2874 Op = llvm::AtomicRMWInst::Sub;
2875 break;
2876
2877 case AtomicExpr::AO__atomic_and_fetch:
2878 PostOp = llvm::Instruction::And;
2879 // Fall through.
2880 case AtomicExpr::AO__c11_atomic_fetch_and:
2881 case AtomicExpr::AO__atomic_fetch_and:
2882 Op = llvm::AtomicRMWInst::And;
2883 break;
2884
2885 case AtomicExpr::AO__atomic_or_fetch:
2886 PostOp = llvm::Instruction::Or;
2887 // Fall through.
2888 case AtomicExpr::AO__c11_atomic_fetch_or:
2889 case AtomicExpr::AO__atomic_fetch_or:
2890 Op = llvm::AtomicRMWInst::Or;
2891 break;
2892
2893 case AtomicExpr::AO__atomic_xor_fetch:
2894 PostOp = llvm::Instruction::Xor;
2895 // Fall through.
2896 case AtomicExpr::AO__c11_atomic_fetch_xor:
2897 case AtomicExpr::AO__atomic_fetch_xor:
2898 Op = llvm::AtomicRMWInst::Xor;
2899 break;
Richard Smithd65cee92012-04-13 06:31:38 +00002900
2901 case AtomicExpr::AO__atomic_nand_fetch:
2902 PostOp = llvm::Instruction::And;
2903 // Fall through.
2904 case AtomicExpr::AO__atomic_fetch_nand:
2905 Op = llvm::AtomicRMWInst::Nand;
2906 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002907 }
Richard Smithfeea8832012-04-12 05:08:17 +00002908
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002909 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
2910 LoadVal1->setAlignment(Align);
2911 llvm::AtomicRMWInst *RMWI =
2912 CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
2913 RMWI->setVolatile(E->isVolatile());
Richard Smithfeea8832012-04-12 05:08:17 +00002914
2915 // For __atomic_*_fetch operations, perform the operation again to
2916 // determine the value which was written.
2917 llvm::Value *Result = RMWI;
2918 if (PostOp)
2919 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
Richard Smithd65cee92012-04-13 06:31:38 +00002920 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
2921 Result = CGF.Builder.CreateNot(Result);
Richard Smithfeea8832012-04-12 05:08:17 +00002922 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002923 StoreDest->setAlignment(Align);
2924}
2925
2926// This function emits any expression (scalar, complex, or aggregate)
2927// into a temporary alloca.
2928static llvm::Value *
2929EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
2930 llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00002931 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
2932 /*Init*/ true);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002933 return DeclPtr;
2934}
2935
2936static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty,
2937 llvm::Value *Dest) {
2938 if (Ty->isAnyComplexType())
2939 return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false));
2940 if (CGF.hasAggregateLLVMType(Ty))
2941 return RValue::getAggregate(Dest);
2942 return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty)));
2943}
2944
2945RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
2946 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
Richard Smithfeea8832012-04-12 05:08:17 +00002947 QualType MemTy = AtomicTy;
2948 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
2949 MemTy = AT->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002950 CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
2951 uint64_t Size = sizeChars.getQuantity();
2952 CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
2953 unsigned Align = alignChars.getQuantity();
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002954 unsigned MaxInlineWidth =
2955 getContext().getTargetInfo().getMaxAtomicInlineWidth();
2956 bool UseLibcall = (Size != Align || Size > MaxInlineWidth);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002957
David Chisnallfa35df62012-01-16 17:27:18 +00002958
2959
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002960 llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
2961 Ptr = EmitScalarExpr(E->getPtr());
David Chisnallfa35df62012-01-16 17:27:18 +00002962
Richard Smithfeea8832012-04-12 05:08:17 +00002963 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
David Chisnallfa35df62012-01-16 17:27:18 +00002964 assert(!Dest && "Init does not return a value");
David Chisnalleb9496e2012-04-11 17:24:05 +00002965 if (!hasAggregateLLVMType(E->getVal1()->getType())) {
Douglas Gregor298f43d2012-04-12 20:42:30 +00002966 QualType PointeeType
2967 = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
2968 EmitScalarInit(EmitScalarExpr(E->getVal1()),
2969 LValue::MakeAddr(Ptr, PointeeType, alignChars,
2970 getContext()));
David Chisnalleb9496e2012-04-11 17:24:05 +00002971 } else if (E->getType()->isAnyComplexType()) {
2972 EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
2973 } else {
2974 AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars,
2975 AtomicTy.getQualifiers(),
2976 AggValueSlot::IsNotDestructed,
2977 AggValueSlot::DoesNotNeedGCBarriers,
2978 AggValueSlot::IsNotAliased);
2979 EmitAggExpr(E->getVal1(), Slot);
2980 }
David Chisnallfa35df62012-01-16 17:27:18 +00002981 return RValue::get(0);
2982 }
2983
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002984 Order = EmitScalarExpr(E->getOrder());
Richard Smithfeea8832012-04-12 05:08:17 +00002985
2986 switch (E->getOp()) {
2987 case AtomicExpr::AO__c11_atomic_init:
2988 llvm_unreachable("Already handled!");
2989
2990 case AtomicExpr::AO__c11_atomic_load:
2991 case AtomicExpr::AO__atomic_load_n:
2992 break;
2993
2994 case AtomicExpr::AO__atomic_load:
2995 Dest = EmitScalarExpr(E->getVal1());
2996 break;
2997
2998 case AtomicExpr::AO__atomic_store:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002999 Val1 = EmitScalarExpr(E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003000 break;
3001
3002 case AtomicExpr::AO__atomic_exchange:
3003 Val1 = EmitScalarExpr(E->getVal1());
3004 Dest = EmitScalarExpr(E->getVal2());
3005 break;
3006
3007 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3008 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3009 case AtomicExpr::AO__atomic_compare_exchange_n:
3010 case AtomicExpr::AO__atomic_compare_exchange:
3011 Val1 = EmitScalarExpr(E->getVal1());
3012 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
3013 Val2 = EmitScalarExpr(E->getVal2());
3014 else
3015 Val2 = EmitValToTemp(*this, E->getVal2());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003016 OrderFail = EmitScalarExpr(E->getOrderFail());
Richard Smithfeea8832012-04-12 05:08:17 +00003017 // Evaluate and discard the 'weak' argument.
3018 if (E->getNumSubExprs() == 6)
3019 EmitScalarExpr(E->getWeak());
3020 break;
3021
3022 case AtomicExpr::AO__c11_atomic_fetch_add:
3023 case AtomicExpr::AO__c11_atomic_fetch_sub:
Richard Smithfeea8832012-04-12 05:08:17 +00003024 if (MemTy->isPointerType()) {
3025 // For pointer arithmetic, we're required to do a bit of math:
3026 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
Richard Smith01ba47d2012-04-13 00:45:38 +00003027 // ... but only for the C11 builtins. The GNU builtins expect the
3028 // user to multiply by sizeof(T).
Richard Smithfeea8832012-04-12 05:08:17 +00003029 QualType Val1Ty = E->getVal1()->getType();
3030 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
3031 CharUnits PointeeIncAmt =
3032 getContext().getTypeSizeInChars(MemTy->getPointeeType());
3033 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
3034 Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
3035 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
3036 break;
3037 }
3038 // Fall through.
Richard Smith01ba47d2012-04-13 00:45:38 +00003039 case AtomicExpr::AO__atomic_fetch_add:
3040 case AtomicExpr::AO__atomic_fetch_sub:
3041 case AtomicExpr::AO__atomic_add_fetch:
3042 case AtomicExpr::AO__atomic_sub_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003043 case AtomicExpr::AO__c11_atomic_store:
3044 case AtomicExpr::AO__c11_atomic_exchange:
3045 case AtomicExpr::AO__atomic_store_n:
3046 case AtomicExpr::AO__atomic_exchange_n:
3047 case AtomicExpr::AO__c11_atomic_fetch_and:
3048 case AtomicExpr::AO__c11_atomic_fetch_or:
3049 case AtomicExpr::AO__c11_atomic_fetch_xor:
3050 case AtomicExpr::AO__atomic_fetch_and:
3051 case AtomicExpr::AO__atomic_fetch_or:
3052 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003053 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003054 case AtomicExpr::AO__atomic_and_fetch:
3055 case AtomicExpr::AO__atomic_or_fetch:
3056 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003057 case AtomicExpr::AO__atomic_nand_fetch:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003058 Val1 = EmitValToTemp(*this, E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003059 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003060 }
3061
Richard Smithfeea8832012-04-12 05:08:17 +00003062 if (!E->getType()->isVoidType() && !Dest)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003063 Dest = CreateMemTemp(E->getType(), ".atomicdst");
3064
David Chisnalldb365f32012-03-29 18:01:11 +00003065 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003066 if (UseLibcall) {
David Chisnalldb365f32012-03-29 18:01:11 +00003067
3068 llvm::SmallVector<QualType, 5> Params;
3069 CallArgList Args;
3070 // Size is always the first parameter
3071 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
3072 getContext().getSizeType());
3073 // Atomic address is always the second parameter
3074 Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
3075 getContext().VoidPtrTy);
3076
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003077 const char* LibCallName;
David Chisnalldb365f32012-03-29 18:01:11 +00003078 QualType RetTy = getContext().VoidTy;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003079 switch (E->getOp()) {
David Chisnalldb365f32012-03-29 18:01:11 +00003080 // There is only one libcall for compare an exchange, because there is no
3081 // optimisation benefit possible from a libcall version of a weak compare
3082 // and exchange.
3083 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
Richard Smithfeea8832012-04-12 05:08:17 +00003084 // void *desired, int success, int failure)
3085 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3086 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3087 case AtomicExpr::AO__atomic_compare_exchange:
3088 case AtomicExpr::AO__atomic_compare_exchange_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003089 LibCallName = "__atomic_compare_exchange";
3090 RetTy = getContext().BoolTy;
3091 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3092 getContext().VoidPtrTy);
3093 Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
3094 getContext().VoidPtrTy);
3095 Args.add(RValue::get(Order),
3096 getContext().IntTy);
3097 Order = OrderFail;
3098 break;
3099 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
3100 // int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003101 case AtomicExpr::AO__c11_atomic_exchange:
3102 case AtomicExpr::AO__atomic_exchange_n:
3103 case AtomicExpr::AO__atomic_exchange:
David Chisnalldb365f32012-03-29 18:01:11 +00003104 LibCallName = "__atomic_exchange";
3105 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3106 getContext().VoidPtrTy);
3107 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3108 getContext().VoidPtrTy);
3109 break;
3110 // void __atomic_store(size_t size, void *mem, void *val, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003111 case AtomicExpr::AO__c11_atomic_store:
3112 case AtomicExpr::AO__atomic_store:
3113 case AtomicExpr::AO__atomic_store_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003114 LibCallName = "__atomic_store";
3115 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3116 getContext().VoidPtrTy);
3117 break;
3118 // void __atomic_load(size_t size, void *mem, void *return, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003119 case AtomicExpr::AO__c11_atomic_load:
3120 case AtomicExpr::AO__atomic_load:
3121 case AtomicExpr::AO__atomic_load_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003122 LibCallName = "__atomic_load";
3123 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3124 getContext().VoidPtrTy);
3125 break;
3126#if 0
3127 // These are only defined for 1-16 byte integers. It is not clear what
3128 // their semantics would be on anything else...
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003129 case AtomicExpr::Add: LibCallName = "__atomic_fetch_add_generic"; break;
3130 case AtomicExpr::Sub: LibCallName = "__atomic_fetch_sub_generic"; break;
3131 case AtomicExpr::And: LibCallName = "__atomic_fetch_and_generic"; break;
3132 case AtomicExpr::Or: LibCallName = "__atomic_fetch_or_generic"; break;
3133 case AtomicExpr::Xor: LibCallName = "__atomic_fetch_xor_generic"; break;
David Chisnalldb365f32012-03-29 18:01:11 +00003134#endif
3135 default: return EmitUnsupportedRValue(E, "atomic library call");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003136 }
David Chisnalldb365f32012-03-29 18:01:11 +00003137 // order is always the last parameter
3138 Args.add(RValue::get(Order),
3139 getContext().IntTy);
3140
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003141 const CGFunctionInfo &FuncInfo =
David Chisnalldb365f32012-03-29 18:01:11 +00003142 CGM.getTypes().arrangeFunctionCall(RetTy, Args,
3143 FunctionType::ExtInfo(), RequiredArgs::All);
3144 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003145 llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
3146 RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
3147 if (E->isCmpXChg())
3148 return Res;
Richard Smithfeea8832012-04-12 05:08:17 +00003149 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003150 return RValue::get(0);
3151 return ConvertTempToRValue(*this, E->getType(), Dest);
3152 }
David Chisnalldb365f32012-03-29 18:01:11 +00003153
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003154 llvm::Type *IPtrTy =
3155 llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
3156 llvm::Value *OrigDest = Dest;
3157 Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
3158 if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
3159 if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
3160 if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
3161
3162 if (isa<llvm::ConstantInt>(Order)) {
3163 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
3164 switch (ord) {
3165 case 0: // memory_order_relaxed
3166 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3167 llvm::Monotonic);
3168 break;
3169 case 1: // memory_order_consume
3170 case 2: // memory_order_acquire
3171 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3172 llvm::Acquire);
3173 break;
3174 case 3: // memory_order_release
3175 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3176 llvm::Release);
3177 break;
3178 case 4: // memory_order_acq_rel
3179 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3180 llvm::AcquireRelease);
3181 break;
3182 case 5: // memory_order_seq_cst
3183 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3184 llvm::SequentiallyConsistent);
3185 break;
3186 default: // invalid order
3187 // We should not ever get here normally, but it's hard to
3188 // enforce that in general.
Richard Smithfeea8832012-04-12 05:08:17 +00003189 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003190 }
Richard Smithfeea8832012-04-12 05:08:17 +00003191 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003192 return RValue::get(0);
3193 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3194 }
3195
3196 // Long case, when Order isn't obviously constant.
3197
Richard Smithfeea8832012-04-12 05:08:17 +00003198 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
3199 E->getOp() == AtomicExpr::AO__atomic_store ||
3200 E->getOp() == AtomicExpr::AO__atomic_store_n;
3201 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
3202 E->getOp() == AtomicExpr::AO__atomic_load ||
3203 E->getOp() == AtomicExpr::AO__atomic_load_n;
3204
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003205 // Create all the relevant BB's
Eli Friedmanc2025562011-10-11 20:00:47 +00003206 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
3207 *AcqRelBB = 0, *SeqCstBB = 0;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003208 MonotonicBB = createBasicBlock("monotonic", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003209 if (!IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003210 AcquireBB = createBasicBlock("acquire", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003211 if (!IsLoad)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003212 ReleaseBB = createBasicBlock("release", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003213 if (!IsLoad && !IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003214 AcqRelBB = createBasicBlock("acqrel", CurFn);
3215 SeqCstBB = createBasicBlock("seqcst", CurFn);
3216 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
3217
3218 // Create the switch for the split
3219 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
3220 // doesn't matter unless someone is crazy enough to use something that
3221 // doesn't fold to a constant for the ordering.
3222 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
3223 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
3224
3225 // Emit all the different atomics
3226 Builder.SetInsertPoint(MonotonicBB);
3227 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3228 llvm::Monotonic);
3229 Builder.CreateBr(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003230 if (!IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003231 Builder.SetInsertPoint(AcquireBB);
3232 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3233 llvm::Acquire);
3234 Builder.CreateBr(ContBB);
3235 SI->addCase(Builder.getInt32(1), AcquireBB);
3236 SI->addCase(Builder.getInt32(2), AcquireBB);
3237 }
Richard Smithfeea8832012-04-12 05:08:17 +00003238 if (!IsLoad) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003239 Builder.SetInsertPoint(ReleaseBB);
3240 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3241 llvm::Release);
3242 Builder.CreateBr(ContBB);
3243 SI->addCase(Builder.getInt32(3), ReleaseBB);
3244 }
Richard Smithfeea8832012-04-12 05:08:17 +00003245 if (!IsLoad && !IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003246 Builder.SetInsertPoint(AcqRelBB);
3247 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3248 llvm::AcquireRelease);
3249 Builder.CreateBr(ContBB);
3250 SI->addCase(Builder.getInt32(4), AcqRelBB);
3251 }
3252 Builder.SetInsertPoint(SeqCstBB);
3253 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3254 llvm::SequentiallyConsistent);
3255 Builder.CreateBr(ContBB);
3256 SI->addCase(Builder.getInt32(5), SeqCstBB);
3257
3258 // Cleanup and return
3259 Builder.SetInsertPoint(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003260 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003261 return RValue::get(0);
3262 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3263}
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003264
Duncan Sandse81111c2012-04-10 08:23:07 +00003265void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003266 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003267 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003268 return;
3269
Duncan Sands65229ed2012-04-16 16:29:47 +00003270 llvm::MDBuilder MDHelper(getLLVMContext());
3271 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003272
Duncan Sands6fc46192012-04-14 12:37:26 +00003273 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003274}
John McCallfe96e0b2011-11-06 09:01:30 +00003275
3276namespace {
3277 struct LValueOrRValue {
3278 LValue LV;
3279 RValue RV;
3280 };
3281}
3282
3283static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3284 const PseudoObjectExpr *E,
3285 bool forLValue,
3286 AggValueSlot slot) {
3287 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3288
3289 // Find the result expression, if any.
3290 const Expr *resultExpr = E->getResultExpr();
3291 LValueOrRValue result;
3292
3293 for (PseudoObjectExpr::const_semantics_iterator
3294 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3295 const Expr *semantic = *i;
3296
3297 // If this semantic expression is an opaque value, bind it
3298 // to the result of its source expression.
3299 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3300
3301 // If this is the result expression, we may need to evaluate
3302 // directly into the slot.
3303 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3304 OVMA opaqueData;
3305 if (ov == resultExpr && ov->isRValue() && !forLValue &&
3306 CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
3307 !ov->getType()->isAnyComplexType()) {
3308 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3309
3310 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3311 opaqueData = OVMA::bind(CGF, ov, LV);
3312 result.RV = slot.asRValue();
3313
3314 // Otherwise, emit as normal.
3315 } else {
3316 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3317
3318 // If this is the result, also evaluate the result now.
3319 if (ov == resultExpr) {
3320 if (forLValue)
3321 result.LV = CGF.EmitLValue(ov);
3322 else
3323 result.RV = CGF.EmitAnyExpr(ov, slot);
3324 }
3325 }
3326
3327 opaques.push_back(opaqueData);
3328
3329 // Otherwise, if the expression is the result, evaluate it
3330 // and remember the result.
3331 } else if (semantic == resultExpr) {
3332 if (forLValue)
3333 result.LV = CGF.EmitLValue(semantic);
3334 else
3335 result.RV = CGF.EmitAnyExpr(semantic, slot);
3336
3337 // Otherwise, evaluate the expression in an ignored context.
3338 } else {
3339 CGF.EmitIgnoredExpr(semantic);
3340 }
3341 }
3342
3343 // Unbind all the opaques now.
3344 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3345 opaques[i].unbind(CGF);
3346
3347 return result;
3348}
3349
3350RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3351 AggValueSlot slot) {
3352 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3353}
3354
3355LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3356 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3357}