blob: d5d3a68b97662c6522e0f5c457f985a3d5c33f79 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000016#include "CGCall.h"
John McCall4c40d982010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Devang Patel79bfb4b2011-03-04 18:54:42 +000018#include "CGDebugInfo.h"
Daniel Dunbar198bcb42010-03-31 01:09:11 +000019#include "CGRecordLayout.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
John McCall01f151e2011-09-21 08:08:30 +000021#include "TargetInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Nico Weber28ad0632012-06-23 02:07:59 +000024#include "clang/Basic/ConvertUTF.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000025#include "clang/Frontend/CodeGenOptions.h"
Nick Lewyckye4330722011-07-07 03:54:51 +000026#include "llvm/Intrinsics.h"
Peter Collingbournec5096cb2011-10-27 19:19:51 +000027#include "llvm/LLVMContext.h"
Chandler Carruth6bebe5a2012-07-15 23:28:01 +000028#include "llvm/MDBuilder.h"
Micah Villmow25a6a842012-10-08 16:25:52 +000029#include "llvm/DataLayout.h"
Richard Smith8e1cee62012-10-25 02:14:12 +000030#include "llvm/ADT/Hashing.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32using namespace CodeGen;
33
34//===--------------------------------------------------------------------===//
35// Miscellaneous Helper Methods
36//===--------------------------------------------------------------------===//
37
John McCalld16c2cf2011-02-08 08:22:06 +000038llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
39 unsigned addressSpace =
40 cast<llvm::PointerType>(value->getType())->getAddressSpace();
41
Chris Lattner2acc6e32011-07-18 04:24:23 +000042 llvm::PointerType *destType = Int8PtrTy;
John McCalld16c2cf2011-02-08 08:22:06 +000043 if (addressSpace)
44 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
45
46 if (value->getType() == destType) return value;
47 return Builder.CreateBitCast(value, destType);
48}
49
Reid Spencer5f016e22007-07-11 17:01:13 +000050/// CreateTempAlloca - This creates a alloca and inserts it into the entry
51/// block.
Chris Lattner2acc6e32011-07-18 04:24:23 +000052llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +000053 const Twine &Name) {
Chris Lattnerf1466842009-03-22 00:24:14 +000054 if (!Builder.isNamePreserving())
Daniel Dunbar259e9cc2009-10-19 01:21:05 +000055 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
Devang Pateld35e2e02009-10-12 22:29:02 +000056 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
Reid Spencer5f016e22007-07-11 17:01:13 +000057}
58
John McCallac418162010-04-22 01:10:34 +000059void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
60 llvm::Value *Init) {
61 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
62 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
63 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
64}
65
Chris Lattner121b3fa2010-07-05 20:21:00 +000066llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +000067 const Twine &Name) {
Daniel Dunbar9bd4da22010-02-16 19:44:13 +000068 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
69 // FIXME: Should we prefer the preferred type alignment here?
70 CharUnits Align = getContext().getTypeAlignInChars(Ty);
71 Alloc->setAlignment(Align.getQuantity());
72 return Alloc;
73}
74
Chris Lattner121b3fa2010-07-05 20:21:00 +000075llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 const Twine &Name) {
Daniel Dunbar195337d2010-02-09 02:48:28 +000077 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
78 // FIXME: Should we prefer the preferred type alignment here?
79 CharUnits Align = getContext().getTypeAlignInChars(Ty);
80 Alloc->setAlignment(Align.getQuantity());
81 return Alloc;
82}
83
Reid Spencer5f016e22007-07-11 17:01:13 +000084/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
85/// expression and compare the result against zero, returning an Int1Ty value.
86llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
John McCall0bab0cd2010-08-23 01:21:21 +000087 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalld608cdb2010-08-22 10:59:02 +000088 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCalld16c2cf2011-02-08 08:22:06 +000089 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman3a173702009-12-11 09:26:29 +000090 }
John McCall0bab0cd2010-08-23 01:21:21 +000091
92 QualType BoolTy = getContext().BoolTy;
Chris Lattner9b2dc282008-04-04 16:54:41 +000093 if (!E->getType()->isAnyComplexType())
Chris Lattner9069fa22007-08-26 16:46:58 +000094 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Reid Spencer5f016e22007-07-11 17:01:13 +000095
Chris Lattner9069fa22007-08-26 16:46:58 +000096 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Reid Spencer5f016e22007-07-11 17:01:13 +000097}
98
John McCall2a416372010-12-05 02:00:02 +000099/// EmitIgnoredExpr - Emit code to compute the specified expression,
100/// ignoring the result.
101void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
102 if (E->isRValue())
103 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
104
105 // Just emit it as an l-value and drop the result.
106 EmitLValue(E);
107}
108
John McCall558d2ab2010-09-15 10:14:12 +0000109/// EmitAnyExpr - Emit code to compute the specified expression which
110/// can have any type. The result is returned as an RValue struct.
111/// If this is an aggregate expression, AggSlot indicates where the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000112/// result should be returned.
John McCalle0c11682012-07-02 23:58:38 +0000113RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
114 AggValueSlot aggSlot,
115 bool ignoreResult) {
Chris Lattner9b655512007-08-31 22:49:20 +0000116 if (!hasAggregateLLVMType(E->getType()))
John McCalle0c11682012-07-02 23:58:38 +0000117 return RValue::get(EmitScalarExpr(E, ignoreResult));
Chris Lattner9b2dc282008-04-04 16:54:41 +0000118 else if (E->getType()->isAnyComplexType())
John McCalle0c11682012-07-02 23:58:38 +0000119 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000120
John McCalle0c11682012-07-02 23:58:38 +0000121 if (!ignoreResult && aggSlot.isIgnored())
122 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
123 EmitAggExpr(E, aggSlot);
124 return aggSlot.asRValue();
Chris Lattner9b655512007-08-31 22:49:20 +0000125}
126
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000127/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
128/// always be accessible even if no aggregate location is provided.
John McCall558d2ab2010-09-15 10:14:12 +0000129RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
130 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000131
132 if (hasAggregateLLVMType(E->getType()) &&
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000133 !E->getType()->isAnyComplexType())
John McCall558d2ab2010-09-15 10:14:12 +0000134 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
135 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000136}
137
John McCall3d3ec1c2010-04-21 10:05:39 +0000138/// EmitAnyExprToMem - Evaluate an expression into a given memory
139/// location.
140void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
141 llvm::Value *Location,
Chad Rosier649b4a12012-03-29 17:37:10 +0000142 Qualifiers Quals,
143 bool IsInit) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000144 // FIXME: This function should take an LValue as an argument.
145 if (E->getType()->isAnyComplexType()) {
John McCallf85e1932011-06-15 23:02:42 +0000146 EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
Eli Friedmanf3940782011-12-03 00:54:26 +0000147 } else if (hasAggregateLLVMType(E->getType())) {
Eli Friedmand7722d92011-12-03 02:13:40 +0000148 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
Eli Friedmanf3940782011-12-03 00:54:26 +0000149 EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
Chad Rosier649b4a12012-03-29 17:37:10 +0000150 AggValueSlot::IsDestructed_t(IsInit),
John McCall90b2bdf2011-08-26 05:38:08 +0000151 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000152 AggValueSlot::IsAliased_t(!IsInit)));
Eli Friedmanf3940782011-12-03 00:54:26 +0000153 } else {
John McCall3d3ec1c2010-04-21 10:05:39 +0000154 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000155 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall545d9962011-06-25 02:11:03 +0000156 EmitStoreThroughLValue(RV, LV);
John McCall3d3ec1c2010-04-21 10:05:39 +0000157 }
158}
159
Benjamin Kramer54353f42010-11-25 18:29:30 +0000160namespace {
Douglas Gregor60dcb842010-05-20 08:36:28 +0000161/// \brief An adjustment to be made to the temporary created when emitting a
162/// reference binding, which accesses a particular subobject of that temporary.
Benjamin Kramer54353f42010-11-25 18:29:30 +0000163 struct SubobjectAdjustment {
Eli Friedman32f498a2012-06-15 23:51:06 +0000164 enum {
165 DerivedToBaseAdjustment,
166 FieldAdjustment,
167 MemberPointerAdjustment
168 } Kind;
Benjamin Kramer54353f42010-11-25 18:29:30 +0000169
170 union {
171 struct {
172 const CastExpr *BasePath;
173 const CXXRecordDecl *DerivedClass;
174 } DerivedToBase;
175
176 FieldDecl *Field;
Eli Friedman32f498a2012-06-15 23:51:06 +0000177
178 struct {
179 const MemberPointerType *MPT;
Rafael Espindolaecccc1e2012-10-27 00:36:38 +0000180 Expr *RHS;
Eli Friedman32f498a2012-06-15 23:51:06 +0000181 } Ptr;
Benjamin Kramer54353f42010-11-25 18:29:30 +0000182 };
183
184 SubobjectAdjustment(const CastExpr *BasePath,
185 const CXXRecordDecl *DerivedClass)
186 : Kind(DerivedToBaseAdjustment) {
187 DerivedToBase.BasePath = BasePath;
188 DerivedToBase.DerivedClass = DerivedClass;
189 }
190
191 SubobjectAdjustment(FieldDecl *Field)
192 : Kind(FieldAdjustment) {
193 this->Field = Field;
194 }
Eli Friedman32f498a2012-06-15 23:51:06 +0000195
Rafael Espindolaecccc1e2012-10-27 00:36:38 +0000196 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
Eli Friedman32f498a2012-06-15 23:51:06 +0000197 : Kind(MemberPointerAdjustment) {
198 this->Ptr.MPT = MPT;
Rafael Espindolaecccc1e2012-10-27 00:36:38 +0000199 this->Ptr.RHS = RHS;
Eli Friedman32f498a2012-06-15 23:51:06 +0000200 }
Douglas Gregor60dcb842010-05-20 08:36:28 +0000201 };
Benjamin Kramer54353f42010-11-25 18:29:30 +0000202}
Douglas Gregor60dcb842010-05-20 08:36:28 +0000203
Anders Carlssondca7ab22010-06-27 16:56:04 +0000204static llvm::Value *
Chris Lattnercb8095f2011-07-20 04:59:57 +0000205CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type,
Anders Carlsson656746c2010-06-27 17:23:46 +0000206 const NamedDecl *InitializedDecl) {
207 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
208 if (VD->hasGlobalStorage()) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000209 SmallString<256> Name;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000210 llvm::raw_svector_ostream Out(Name);
211 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
212 Out.flush();
213
Chris Lattner2acc6e32011-07-18 04:24:23 +0000214 llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
Anders Carlsson656746c2010-06-27 17:23:46 +0000215
216 // Create the reference temporary.
217 llvm::GlobalValue *RefTemp =
218 new llvm::GlobalVariable(CGF.CGM.getModule(),
219 RefTempTy, /*isConstant=*/false,
220 llvm::GlobalValue::InternalLinkage,
221 llvm::Constant::getNullValue(RefTempTy),
222 Name.str());
223 return RefTemp;
224 }
225 }
226
227 return CGF.CreateMemTemp(Type, "ref.tmp");
228}
229
Rafael Espindola582e1852012-10-27 00:40:06 +0000230static const Expr *
Rafael Espindola034653c2012-10-27 00:43:14 +0000231findMaterializedTemporary(const Expr *E, const MaterializeTemporaryExpr *&MTE) {
232 // 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
239 // Look through expressions for materialized temporaries (for now).
240 if (const MaterializeTemporaryExpr *M
241 = dyn_cast<MaterializeTemporaryExpr>(E)) {
242 MTE = M;
243 E = M->GetTemporaryExpr();
244 }
245
246 if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
247 E = DAE->getExpr();
248 return E;
249}
250
251static const Expr *
Rafael Espindola582e1852012-10-27 00:40:06 +0000252skipRValueSubobjectAdjustments(const Expr *E,
253 SmallVectorImpl<SubobjectAdjustment> &Adjustments) {
254 while (true) {
255 E = E->IgnoreParens();
256
257 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
258 if ((CE->getCastKind() == CK_DerivedToBase ||
259 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
260 E->getType()->isRecordType()) {
261 E = CE->getSubExpr();
262 CXXRecordDecl *Derived
263 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
264 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
265 continue;
266 }
267
268 if (CE->getCastKind() == CK_NoOp) {
269 E = CE->getSubExpr();
270 continue;
271 }
272 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
273 if (!ME->isArrow() && ME->getBase()->isRValue()) {
274 assert(ME->getBase()->getType()->isRecordType());
275 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
276 E = ME->getBase();
277 Adjustments.push_back(SubobjectAdjustment(Field));
278 continue;
279 }
280 }
281 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
282 if (BO->isPtrMemOp()) {
283 assert(BO->getLHS()->isRValue());
284 E = BO->getLHS();
285 const MemberPointerType *MPT =
286 BO->getRHS()->getType()->getAs<MemberPointerType>();
287 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
288 }
289 }
290
291 // Nothing changed.
292 break;
293 }
294 return E;
295}
296
Anders Carlsson656746c2010-06-27 17:23:46 +0000297static llvm::Value *
Chris Lattnerd0db03a2010-09-06 00:11:41 +0000298EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
Anders Carlssondca7ab22010-06-27 16:56:04 +0000299 llvm::Value *&ReferenceTemporary,
300 const CXXDestructorDecl *&ReferenceTemporaryDtor,
John McCallf85e1932011-06-15 23:02:42 +0000301 QualType &ObjCARCReferenceLifetimeType,
Anders Carlsson656746c2010-06-27 17:23:46 +0000302 const NamedDecl *InitializedDecl) {
Rafael Espindola034653c2012-10-27 00:43:14 +0000303 const MaterializeTemporaryExpr *M = NULL;
304 E = findMaterializedTemporary(E, M);
305 // Objective-C++ ARC:
306 // If we are binding a reference to a temporary that has ownership, we
307 // need to perform retain/release operations on the temporary.
308 if (M && CGF.getContext().getLangOpts().ObjCAutoRefCount &&
309 M->getType()->isObjCLifetimeType() &&
310 (M->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
311 M->getType().getObjCLifetime() == Qualifiers::OCL_Weak ||
312 M->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing))
313 ObjCARCReferenceLifetimeType = M->getType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +0000314
John McCall1a343eb2011-11-10 08:15:53 +0000315 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) {
316 CGF.enterFullExpression(EWC);
John McCallf1549f62010-07-06 01:34:17 +0000317 CodeGenFunction::RunCleanupsScope Scope(CGF);
Anders Carlssondca7ab22010-06-27 16:56:04 +0000318
John McCall1a343eb2011-11-10 08:15:53 +0000319 return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),
Anders Carlssondca7ab22010-06-27 16:56:04 +0000320 ReferenceTemporary,
321 ReferenceTemporaryDtor,
John McCallf85e1932011-06-15 23:02:42 +0000322 ObjCARCReferenceLifetimeType,
Anders Carlsson656746c2010-06-27 17:23:46 +0000323 InitializedDecl);
Anders Carlssondca7ab22010-06-27 16:56:04 +0000324 }
325
326 RValue RV;
Douglas Gregorda29e092011-01-22 02:44:21 +0000327 if (E->isGLValue()) {
Anders Carlssondca7ab22010-06-27 16:56:04 +0000328 // Emit the expression as an lvalue.
329 LValue LV = CGF.EmitLValue(E);
Chris Lattner74339df2011-07-10 05:34:54 +0000330
Anders Carlssondca7ab22010-06-27 16:56:04 +0000331 if (LV.isSimple())
332 return LV.getAddress();
Anders Carlsson0dc73662010-02-04 17:32:58 +0000333
Anders Carlssondca7ab22010-06-27 16:56:04 +0000334 // We have to load the lvalue.
John McCall545d9962011-06-25 02:11:03 +0000335 RV = CGF.EmitLoadOfLValue(LV);
Eli Friedman5df0d422009-05-20 02:31:19 +0000336 } else {
Douglas Gregord7b23162011-06-22 16:12:01 +0000337 if (!ObjCARCReferenceLifetimeType.isNull()) {
338 ReferenceTemporary = CreateReferenceTemporary(CGF,
339 ObjCARCReferenceLifetimeType,
340 InitializedDecl);
341
342
343 LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
344 ObjCARCReferenceLifetimeType);
345
346 CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
347 RefTempDst, false);
348
349 bool ExtendsLifeOfTemporary = false;
350 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
351 if (Var->extendsLifetimeOfTemporary())
352 ExtendsLifeOfTemporary = true;
353 } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
354 ExtendsLifeOfTemporary = true;
355 }
356
357 if (!ExtendsLifeOfTemporary) {
358 // Since the lifetime of this temporary isn't going to be extended,
359 // we need to clean it up ourselves at the end of the full expression.
360 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
361 case Qualifiers::OCL_None:
362 case Qualifiers::OCL_ExplicitNone:
363 case Qualifiers::OCL_Autoreleasing:
364 break;
365
John McCall9928c482011-07-12 16:41:08 +0000366 case Qualifiers::OCL_Strong: {
367 assert(!ObjCARCReferenceLifetimeType->isArrayType());
368 CleanupKind cleanupKind = CGF.getARCCleanupKind();
369 CGF.pushDestroy(cleanupKind,
370 ReferenceTemporary,
371 ObjCARCReferenceLifetimeType,
372 CodeGenFunction::destroyARCStrongImprecise,
373 cleanupKind & EHCleanup);
Douglas Gregord7b23162011-06-22 16:12:01 +0000374 break;
John McCall9928c482011-07-12 16:41:08 +0000375 }
Douglas Gregord7b23162011-06-22 16:12:01 +0000376
377 case Qualifiers::OCL_Weak:
John McCall9928c482011-07-12 16:41:08 +0000378 assert(!ObjCARCReferenceLifetimeType->isArrayType());
379 CGF.pushDestroy(NormalAndEHCleanup,
380 ReferenceTemporary,
381 ObjCARCReferenceLifetimeType,
382 CodeGenFunction::destroyARCWeak,
383 /*useEHCleanupForArray*/ true);
Douglas Gregord7b23162011-06-22 16:12:01 +0000384 break;
385 }
386
387 ObjCARCReferenceLifetimeType = QualType();
388 }
389
390 return ReferenceTemporary;
391 }
Rafael Espindola582e1852012-10-27 00:40:06 +0000392
Chris Lattner5f9e2722011-07-23 10:55:15 +0000393 SmallVector<SubobjectAdjustment, 2> Adjustments;
Rafael Espindola582e1852012-10-27 00:40:06 +0000394 E = skipRValueSubobjectAdjustments(E, Adjustments);
395 if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
396 if (opaque->getType()->isRecordType())
397 return CGF.EmitOpaqueValueLValue(opaque).getAddress();
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000398
Anders Carlssondca7ab22010-06-27 16:56:04 +0000399 // Create a reference temporary if necessary.
John McCall558d2ab2010-09-15 10:14:12 +0000400 AggValueSlot AggSlot = AggValueSlot::ignored();
Anders Carlssondca7ab22010-06-27 16:56:04 +0000401 if (CGF.hasAggregateLLVMType(E->getType()) &&
John McCall558d2ab2010-09-15 10:14:12 +0000402 !E->getType()->isAnyComplexType()) {
Anders Carlsson656746c2010-06-27 17:23:46 +0000403 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
404 InitializedDecl);
Eli Friedmand7722d92011-12-03 02:13:40 +0000405 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
John McCall7c2349b2011-08-25 20:40:09 +0000406 AggValueSlot::IsDestructed_t isDestructed
407 = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
Eli Friedmanf3940782011-12-03 00:54:26 +0000408 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
409 Qualifiers(), isDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000410 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000411 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000412 }
John McCallf85e1932011-06-15 23:02:42 +0000413
Anders Carlsson656746c2010-06-27 17:23:46 +0000414 if (InitializedDecl) {
Anders Carlssondca7ab22010-06-27 16:56:04 +0000415 // Get the destructor for the reference temporary.
416 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
417 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
418 if (!ClassDecl->hasTrivialDestructor())
Douglas Gregor1d110e02010-07-01 14:13:13 +0000419 ReferenceTemporaryDtor = ClassDecl->getDestructor();
Anders Carlssondca7ab22010-06-27 16:56:04 +0000420 }
421 }
422
John McCallf85e1932011-06-15 23:02:42 +0000423 RV = CGF.EmitAnyExpr(E, AggSlot);
424
Douglas Gregor60dcb842010-05-20 08:36:28 +0000425 // Check if need to perform derived-to-base casts and/or field accesses, to
426 // get from the temporary object we created (and, potentially, for which we
427 // extended the lifetime) to the subobject we're binding the reference to.
428 if (!Adjustments.empty()) {
Anders Carlssondca7ab22010-06-27 16:56:04 +0000429 llvm::Value *Object = RV.getAggregateAddr();
Douglas Gregor60dcb842010-05-20 08:36:28 +0000430 for (unsigned I = Adjustments.size(); I != 0; --I) {
431 SubobjectAdjustment &Adjustment = Adjustments[I-1];
432 switch (Adjustment.Kind) {
433 case SubobjectAdjustment::DerivedToBaseAdjustment:
Anders Carlssondca7ab22010-06-27 16:56:04 +0000434 Object =
435 CGF.GetAddressOfBaseClass(Object,
436 Adjustment.DerivedToBase.DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +0000437 Adjustment.DerivedToBase.BasePath->path_begin(),
438 Adjustment.DerivedToBase.BasePath->path_end(),
Anders Carlssondca7ab22010-06-27 16:56:04 +0000439 /*NullCheckValue=*/false);
Douglas Gregor60dcb842010-05-20 08:36:28 +0000440 break;
441
442 case SubobjectAdjustment::FieldAdjustment: {
Eli Friedman377ecc72012-04-16 03:54:45 +0000443 LValue LV = CGF.MakeAddrLValue(Object, E->getType());
444 LV = CGF.EmitLValueForField(LV, Adjustment.Field);
Douglas Gregor60dcb842010-05-20 08:36:28 +0000445 if (LV.isSimple()) {
446 Object = LV.getAddress();
447 break;
448 }
449
450 // For non-simple lvalues, we actually have to create a copy of
451 // the object we're binding to.
Daniel Dunbar333d42d2010-08-21 03:37:02 +0000452 QualType T = Adjustment.Field->getType().getNonReferenceType()
453 .getUnqualifiedType();
Anders Carlsson045a6d82010-06-27 17:52:15 +0000454 Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
Daniel Dunbar333d42d2010-08-21 03:37:02 +0000455 LValue TempLV = CGF.MakeAddrLValue(Object,
456 Adjustment.Field->getType());
John McCall545d9962011-06-25 02:11:03 +0000457 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
Douglas Gregor60dcb842010-05-20 08:36:28 +0000458 break;
459 }
Anders Carlssondca7ab22010-06-27 16:56:04 +0000460
Eli Friedman32f498a2012-06-15 23:51:06 +0000461 case SubobjectAdjustment::MemberPointerAdjustment: {
Rafael Espindolaecccc1e2012-10-27 00:36:38 +0000462 llvm::Value *Ptr = CGF.EmitScalarExpr(Adjustment.Ptr.RHS);
Eli Friedman32f498a2012-06-15 23:51:06 +0000463 Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress(
Rafael Espindolaecccc1e2012-10-27 00:36:38 +0000464 CGF, Object, Ptr, Adjustment.Ptr.MPT);
Eli Friedman32f498a2012-06-15 23:51:06 +0000465 break;
466 }
Douglas Gregor60dcb842010-05-20 08:36:28 +0000467 }
468 }
Eli Friedman545aa7a2011-03-16 22:34:09 +0000469
470 return Object;
Anders Carlssonb3f74422009-10-15 00:51:46 +0000471 }
Anders Carlsson4bbab922009-05-20 00:36:58 +0000472 }
Eli Friedman5df0d422009-05-20 02:31:19 +0000473
Anders Carlssondca7ab22010-06-27 16:56:04 +0000474 if (RV.isAggregate())
475 return RV.getAggregateAddr();
Eli Friedman5df0d422009-05-20 02:31:19 +0000476
Anders Carlssondca7ab22010-06-27 16:56:04 +0000477 // Create a temporary variable that we can bind the reference to.
Anders Carlsson656746c2010-06-27 17:23:46 +0000478 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
479 InitializedDecl);
480
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000481
482 unsigned Alignment =
483 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
Anders Carlssondca7ab22010-06-27 16:56:04 +0000484 if (RV.isScalar())
485 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000486 /*Volatile=*/false, Alignment, E->getType());
Anders Carlssondca7ab22010-06-27 16:56:04 +0000487 else
488 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
489 /*Volatile=*/false);
490 return ReferenceTemporary;
491}
492
493RValue
Chris Lattnerd0db03a2010-09-06 00:11:41 +0000494CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
Anders Carlssondca7ab22010-06-27 16:56:04 +0000495 const NamedDecl *InitializedDecl) {
496 llvm::Value *ReferenceTemporary = 0;
497 const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
John McCallf85e1932011-06-15 23:02:42 +0000498 QualType ObjCARCReferenceLifetimeType;
Anders Carlssondca7ab22010-06-27 16:56:04 +0000499 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
500 ReferenceTemporaryDtor,
John McCallf85e1932011-06-15 23:02:42 +0000501 ObjCARCReferenceLifetimeType,
Anders Carlssondca7ab22010-06-27 16:56:04 +0000502 InitializedDecl);
Richard Smith2c9f87c2012-08-24 00:54:33 +0000503 if (CatchUndefined && !E->getType()->isFunctionType()) {
504 // C++11 [dcl.ref]p5 (as amended by core issue 453):
505 // If a glvalue to which a reference is directly bound designates neither
506 // an existing object or function of an appropriate type nor a region of
507 // storage of suitable size and alignment to contain an object of the
508 // reference's type, the behavior is undefined.
509 QualType Ty = E->getType();
Richard Smith4def70d2012-10-09 19:52:38 +0000510 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith2c9f87c2012-08-24 00:54:33 +0000511 }
John McCallf85e1932011-06-15 23:02:42 +0000512 if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
Anders Carlsson045a6d82010-06-27 17:52:15 +0000513 return RValue::get(Value);
514
Anders Carlssondca7ab22010-06-27 16:56:04 +0000515 // Make sure to call the destructor for the reference temporary.
John McCallf85e1932011-06-15 23:02:42 +0000516 const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl);
517 if (VD && VD->hasGlobalStorage()) {
518 if (ReferenceTemporaryDtor) {
Anders Carlsson045a6d82010-06-27 17:52:15 +0000519 llvm::Constant *DtorFn =
520 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
John McCall20bb1752012-05-01 06:13:13 +0000521 CGM.getCXXABI().registerGlobalDtor(*this, DtorFn,
John McCalld16c2cf2011-02-08 08:22:06 +0000522 cast<llvm::Constant>(ReferenceTemporary));
John McCallf85e1932011-06-15 23:02:42 +0000523 } else {
524 assert(!ObjCARCReferenceLifetimeType.isNull());
525 // Note: We intentionally do not register a global "destructor" to
526 // release the object.
Anders Carlsson045a6d82010-06-27 17:52:15 +0000527 }
John McCallf85e1932011-06-15 23:02:42 +0000528
529 return RValue::get(Value);
Anders Carlsson045a6d82010-06-27 17:52:15 +0000530 }
John McCall81407d42010-07-21 06:29:51 +0000531
John McCallf85e1932011-06-15 23:02:42 +0000532 if (ReferenceTemporaryDtor)
533 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
534 else {
535 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
536 case Qualifiers::OCL_None:
David Blaikieb219cfc2011-09-23 05:06:16 +0000537 llvm_unreachable(
538 "Not a reference temporary that needs to be deallocated");
John McCallf85e1932011-06-15 23:02:42 +0000539 case Qualifiers::OCL_ExplicitNone:
540 case Qualifiers::OCL_Autoreleasing:
541 // Nothing to do.
542 break;
543
John McCall9928c482011-07-12 16:41:08 +0000544 case Qualifiers::OCL_Strong: {
545 bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>();
546 CleanupKind cleanupKind = getARCCleanupKind();
Benjamin Kramer0d516762011-07-12 18:37:23 +0000547 pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000548 precise ? destroyARCStrongPrecise : destroyARCStrongImprecise,
549 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000550 break;
John McCall9928c482011-07-12 16:41:08 +0000551 }
John McCallf85e1932011-06-15 23:02:42 +0000552
Benjamin Kramer0d516762011-07-12 18:37:23 +0000553 case Qualifiers::OCL_Weak: {
John McCallf85e1932011-06-15 23:02:42 +0000554 // __weak objects always get EH cleanups; otherwise, exceptions
555 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000556 pushDestroy(NormalAndEHCleanup, ReferenceTemporary,
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000557 ObjCARCReferenceLifetimeType, destroyARCWeak, true);
John McCallf85e1932011-06-15 23:02:42 +0000558 break;
559 }
Benjamin Kramer0d516762011-07-12 18:37:23 +0000560 }
John McCallf85e1932011-06-15 23:02:42 +0000561 }
562
Anders Carlssondca7ab22010-06-27 16:56:04 +0000563 return RValue::get(Value);
Anders Carlsson4029ca72009-05-20 00:24:07 +0000564}
565
566
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000567/// getAccessedFieldNo - Given an encoded value and a result number, return the
568/// input field number being accessed.
569unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman4f8d1232008-05-22 00:50:06 +0000570 const llvm::Constant *Elts) {
Chris Lattner89f42832012-01-30 06:20:36 +0000571 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
572 ->getZExtValue();
Dan Gohman4f8d1232008-05-22 00:50:06 +0000573}
574
Richard Smith8e1cee62012-10-25 02:14:12 +0000575/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
576static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
577 llvm::Value *High) {
578 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
579 llvm::Value *K47 = Builder.getInt64(47);
580 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
581 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
582 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
583 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
584 return Builder.CreateMul(B1, KMul);
585}
586
Richard Smith4def70d2012-10-09 19:52:38 +0000587void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
588 llvm::Value *Address,
Richard Smith7ac9ef12012-09-08 02:08:36 +0000589 QualType Ty, CharUnits Alignment) {
Nuno Lopesdef18492012-05-22 17:19:45 +0000590 if (!CatchUndefined)
Mike Stumpb14e62d2009-12-16 02:57:00 +0000591 return;
592
Richard Smith2c9f87c2012-08-24 00:54:33 +0000593 llvm::Value *Cond = 0;
Mike Stumpb14e62d2009-12-16 02:57:00 +0000594
Richard Smith7ac9ef12012-09-08 02:08:36 +0000595 if (TCK != TCK_Load && TCK != TCK_Store) {
Richard Smith2c9f87c2012-08-24 00:54:33 +0000596 // The glvalue must not be an empty glvalue. Don't bother checking this for
597 // loads and stores, because we will get a segfault anyway (if the operation
598 // isn't optimized out).
599 Cond = Builder.CreateICmpNE(
600 Address, llvm::Constant::getNullValue(Address->getType()));
601 }
Chris Lattnerc24b9c42010-04-10 18:34:14 +0000602
Richard Smith4def70d2012-10-09 19:52:38 +0000603 uint64_t AlignVal = Alignment.getQuantity();
604
Richard Smith2c9f87c2012-08-24 00:54:33 +0000605 if (!Ty->isIncompleteType()) {
606 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith2c9f87c2012-08-24 00:54:33 +0000607 if (!AlignVal)
608 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
609
610 // This needs to be to the standard address space.
611 Address = Builder.CreateBitCast(Address, Int8PtrTy);
612
613 // The glvalue must refer to a large enough storage region.
614 // FIXME: If -faddress-sanitizer is enabled, insert dynamic instrumentation
615 // to check this.
616 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy);
617 llvm::Value *Min = Builder.getFalse();
618 llvm::Value *LargeEnough =
619 Builder.CreateICmpUGE(Builder.CreateCall2(F, Address, Min),
620 llvm::ConstantInt::get(IntPtrTy, Size));
621 Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough;
Richard Smith4def70d2012-10-09 19:52:38 +0000622 }
Richard Smith2c9f87c2012-08-24 00:54:33 +0000623
Richard Smith4def70d2012-10-09 19:52:38 +0000624 if (AlignVal) {
Richard Smith2c9f87c2012-08-24 00:54:33 +0000625 // The glvalue must be suitably aligned.
626 llvm::Value *Align =
627 Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
628 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
629 Cond = Builder.CreateAnd(Cond,
630 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0)));
631 }
632
Richard Smith4def70d2012-10-09 19:52:38 +0000633 if (Cond) {
634 llvm::Constant *StaticData[] = {
635 EmitCheckSourceLocation(Loc),
636 EmitCheckTypeDescriptor(Ty),
637 llvm::ConstantInt::get(SizeTy, AlignVal),
638 llvm::ConstantInt::get(Int8Ty, TCK)
639 };
640 EmitCheck(Cond, "type_mismatch", StaticData, Address);
641 }
Richard Smith8e1cee62012-10-25 02:14:12 +0000642
643 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
644 if (TCK != TCK_ConstructorCall &&
645 RD && RD->hasDefinition() && RD->isDynamicClass()) {
646 // Check that the vptr indicates that there is a subobject of type Ty at
647 // offset zero within this object.
648 // FIXME: Produce a diagnostic if the user tries to combine this check with
649 // -fno-rtti.
650
651 // Compute a hash of the mangled name of the type.
652 //
653 // FIXME: This is not guaranteed to be deterministic! Move to a
654 // fingerprinting mechanism once LLVM provides one. For the time
655 // being the implementation happens to be deterministic.
656 llvm::SmallString<64> MangledName;
657 llvm::raw_svector_ostream Out(MangledName);
658 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
659 Out);
660 llvm::hash_code TypeHash = hash_value(Out.str());
661
662 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
663 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
664 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
665 llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
666 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
667 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
668
669 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
670 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
671
672 // Look the hash up in our cache.
673 const int CacheSize = 128;
674 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
675 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
676 "__ubsan_vptr_type_cache");
677 llvm::Value *Slot = Builder.CreateAnd(Hash,
678 llvm::ConstantInt::get(IntPtrTy,
679 CacheSize-1));
680 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
681 llvm::Value *CacheVal =
682 Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
683
684 // If the hash isn't in the cache, call a runtime handler to perform the
685 // hard work of checking whether the vptr is for an object of the right
686 // type. This will either fill in the cache and return, or produce a
687 // diagnostic.
688 llvm::Constant *StaticData[] = {
689 EmitCheckSourceLocation(Loc),
690 EmitCheckTypeDescriptor(Ty),
691 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
692 llvm::ConstantInt::get(Int8Ty, TCK)
693 };
694 llvm::Value *DynamicData[] = { Address, Hash };
695 EmitCheck(Builder.CreateICmpEQ(CacheVal, Hash),
696 "dynamic_type_cache_miss", StaticData, DynamicData, true);
697 }
Mike Stumpb14e62d2009-12-16 02:57:00 +0000698}
Chris Lattner9b655512007-08-31 22:49:20 +0000699
Chris Lattnerdd36d322010-01-09 21:40:03 +0000700
Chris Lattnerdd36d322010-01-09 21:40:03 +0000701CodeGenFunction::ComplexPairTy CodeGenFunction::
702EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
703 bool isInc, bool isPre) {
704 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
705 LV.isVolatileQualified());
706
707 llvm::Value *NextVal;
708 if (isa<llvm::IntegerType>(InVal.first->getType())) {
709 uint64_t AmountVal = isInc ? 1 : -1;
710 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
711
712 // Add the inc/dec to the real part.
713 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
714 } else {
715 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
716 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
717 if (!isInc)
718 FVal.changeSign();
719 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
720
721 // Add the inc/dec to the real part.
722 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
723 }
724
725 ComplexPairTy IncVal(NextVal, InVal.second);
726
727 // Store the updated result through the lvalue.
728 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
729
730 // If this is a postinc, return the value read from memory, otherwise use the
731 // updated value.
732 return isPre ? IncVal : InVal;
733}
734
735
Reid Spencer5f016e22007-07-11 17:01:13 +0000736//===----------------------------------------------------------------------===//
737// LValue Expression Emission
738//===----------------------------------------------------------------------===//
739
Daniel Dunbar13e81732009-02-05 07:09:07 +0000740RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnereb99b012009-10-28 17:39:19 +0000741 if (Ty->isVoidType())
Daniel Dunbar13e81732009-02-05 07:09:07 +0000742 return RValue::get(0);
Chris Lattnereb99b012009-10-28 17:39:19 +0000743
744 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000745 llvm::Type *EltTy = ConvertType(CTy->getElementType());
Owen Anderson03e20502009-07-30 23:11:26 +0000746 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8fa73ed2009-01-09 20:09:28 +0000747 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnereb99b012009-10-28 17:39:19 +0000748 }
749
Chris Lattnerb6c504b2010-08-23 05:26:13 +0000750 // If this is a use of an undefined aggregate type, the aggregate must have an
751 // identifiable address. Just because the contents of the value are undefined
752 // doesn't mean that the address can't be taken and compared.
Chris Lattnereb99b012009-10-28 17:39:19 +0000753 if (hasAggregateLLVMType(Ty)) {
Chris Lattnerb6c504b2010-08-23 05:26:13 +0000754 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
755 return RValue::getAggregate(DestPtr);
Daniel Dunbar8fa73ed2009-01-09 20:09:28 +0000756 }
Chris Lattnereb99b012009-10-28 17:39:19 +0000757
758 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
Daniel Dunbarce1d38b2009-01-09 16:50:52 +0000759}
760
Daniel Dunbar13e81732009-02-05 07:09:07 +0000761RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
762 const char *Name) {
763 ErrorUnsupported(E, Name);
764 return GetUndefRValue(E->getType());
765}
766
Daniel Dunbar6ba82a42008-08-25 20:45:57 +0000767LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
768 const char *Name) {
769 ErrorUnsupported(E, Name);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000770 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000771 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
Daniel Dunbar6ba82a42008-08-25 20:45:57 +0000772}
773
Richard Smith7ac9ef12012-09-08 02:08:36 +0000774LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Mike Stumpb14e62d2009-12-16 02:57:00 +0000775 LValue LV = EmitLValue(E);
Daniel Dunbarf0fe5bc2010-04-05 21:36:35 +0000776 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
Richard Smith4def70d2012-10-09 19:52:38 +0000777 EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
778 E->getType(), LV.getAlignment());
Mike Stumpb14e62d2009-12-16 02:57:00 +0000779 return LV;
780}
781
Reid Spencer5f016e22007-07-11 17:01:13 +0000782/// EmitLValue - Emit code to compute a designator that specifies the location
783/// of the expression.
784///
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000785/// This can return one of two things: a simple address or a bitfield reference.
786/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
787/// an LLVM pointer type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000788///
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000789/// If this returns a bitfield reference, nothing about the pointee type of the
790/// LLVM value is known: For example, it may not be a pointer to an integer.
Reid Spencer5f016e22007-07-11 17:01:13 +0000791///
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000792/// If this returns a normal address, and if the lvalue's C type is fixed size,
793/// this method guarantees that the returned pointer type will point to an LLVM
794/// type of the same size of the lvalue's type. If the lvalue has a variable
795/// length type, this is not possible.
Reid Spencer5f016e22007-07-11 17:01:13 +0000796///
797LValue CodeGenFunction::EmitLValue(const Expr *E) {
798 switch (E->getStmtClass()) {
Daniel Dunbar6ba82a42008-08-25 20:45:57 +0000799 default: return EmitUnsupportedLValue(E, "l-value expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000800
John McCalldb458062011-11-07 03:59:57 +0000801 case Expr::ObjCPropertyRefExprClass:
802 llvm_unreachable("cannot emit a property reference directly");
803
Fariborz Jahanian03b29602010-06-17 19:56:20 +0000804 case Expr::ObjCSelectorExprClass:
Nico Weberc5f80462012-10-11 10:13:44 +0000805 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000806 case Expr::ObjCIsaExprClass:
807 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000808 case Expr::BinaryOperatorClass:
Daniel Dunbar80e62c22008-09-04 03:20:13 +0000809 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
Douglas Gregor6a03e342010-04-23 04:16:32 +0000810 case Expr::CompoundAssignOperatorClass:
John McCall2a416372010-12-05 02:00:02 +0000811 if (!E->getType()->isAnyComplexType())
812 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
813 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000814 case Expr::CallExprClass:
Anders Carlssonfaf86642009-09-01 21:18:52 +0000815 case Expr::CXXMemberCallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +0000816 case Expr::CXXOperatorCallExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +0000817 case Expr::UserDefinedLiteralClass:
Douglas Gregorb4609802008-11-14 16:09:21 +0000818 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar5b5c9ef2009-02-11 20:59:32 +0000819 case Expr::VAArgExprClass:
820 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000821 case Expr::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +0000822 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopher6aff47d2011-09-08 17:15:04 +0000823 case Expr::ParenExprClass:
824 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbournef111d932011-04-15 00:35:48 +0000825 case Expr::GenericSelectionExprClass:
826 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattnerd9f69102008-08-10 01:53:14 +0000827 case Expr::PredefinedExprClass:
828 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 case Expr::StringLiteralClass:
830 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000831 case Expr::ObjCEncodeExprClass:
832 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCall4b9c2d22011-11-06 09:01:30 +0000833 case Expr::PseudoObjectExprClass:
834 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl13dc8f92011-11-27 16:50:07 +0000835 case Expr::InitListExprClass:
Richard Smith13ec9102012-05-14 21:57:21 +0000836 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlssonb58d0172009-05-30 23:23:33 +0000837 case Expr::CXXTemporaryObjectExprClass:
838 case Expr::CXXConstructExprClass:
Anders Carlssone61c9e82009-05-30 23:30:54 +0000839 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
840 case Expr::CXXBindTemporaryExprClass:
841 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Weberc5f80462012-10-11 10:13:44 +0000842 case Expr::CXXUuidofExprClass:
843 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman31a37022012-02-08 05:34:55 +0000844 case Expr::LambdaExprClass:
845 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall1a343eb2011-11-10 08:15:53 +0000846
847 case Expr::ExprWithCleanupsClass: {
848 const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E);
849 enterFullExpression(cleanups);
850 RunCleanupsScope Scope(*this);
851 return EmitLValue(cleanups->getSubExpr());
852 }
853
Douglas Gregored8abf12010-07-08 06:14:04 +0000854 case Expr::CXXScalarValueInitExprClass:
855 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
Anders Carlsson370e5382009-11-14 01:51:50 +0000856 case Expr::CXXDefaultArgExprClass:
857 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Mike Stumpc2e84ae2009-11-15 08:09:41 +0000858 case Expr::CXXTypeidExprClass:
859 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssone61c9e82009-05-30 23:30:54 +0000860
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000861 case Expr::ObjCMessageExprClass:
862 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000863 case Expr::ObjCIvarRefExprClass:
Chris Lattner391d77a2008-03-30 23:03:07 +0000864 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattner65459942009-04-25 19:35:26 +0000865 case Expr::StmtExprClass:
866 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000867 case Expr::UnaryOperatorClass:
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
869 case Expr::ArraySubscriptExprClass:
870 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Nate Begeman213541a2008-04-18 23:10:10 +0000871 case Expr::ExtVectorElementExprClass:
872 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000873 case Expr::MemberExprClass:
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000874 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman06e863f2008-05-13 23:18:27 +0000875 case Expr::CompoundLiteralExprClass:
876 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbar90345582009-03-24 02:38:23 +0000877 case Expr::ConditionalOperatorClass:
Anders Carlsson6fcec8b2009-09-15 16:35:24 +0000878 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCall56ca35d2011-02-17 10:25:35 +0000879 case Expr::BinaryConditionalOperatorClass:
880 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner670a62c2008-12-12 05:35:08 +0000881 case Expr::ChooseExprClass:
Eli Friedman79769322009-03-04 05:52:32 +0000882 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
John McCalle996ffd2011-02-16 08:02:54 +0000883 case Expr::OpaqueValueExprClass:
884 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall91a57552011-07-15 05:09:51 +0000885 case Expr::SubstNonTypeTemplateParmExprClass:
886 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattnerc3953a62009-03-18 04:02:57 +0000887 case Expr::ImplicitCastExprClass:
888 case Expr::CStyleCastExprClass:
889 case Expr::CXXFunctionalCastExprClass:
890 case Expr::CXXStaticCastExprClass:
891 case Expr::CXXDynamicCastExprClass:
892 case Expr::CXXReinterpretCastExprClass:
893 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +0000894 case Expr::ObjCBridgedCastExprClass:
Chris Lattner75dfeda2009-03-18 18:28:57 +0000895 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl13dc8f92011-11-27 16:50:07 +0000896
Douglas Gregor03e80032011-06-21 17:03:29 +0000897 case Expr::MaterializeTemporaryExprClass:
898 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 }
900}
901
John McCalldd2ecee2012-03-10 03:05:10 +0000902/// Given an object of the given canonical type, can we safely copy a
903/// value out of it based on its initializer?
904static bool isConstantEmittableObjectType(QualType type) {
905 assert(type.isCanonical());
906 assert(!type->isReferenceType());
907
908 // Must be const-qualified but non-volatile.
909 Qualifiers qs = type.getLocalQualifiers();
910 if (!qs.hasConst() || qs.hasVolatile()) return false;
911
912 // Otherwise, all object types satisfy this except C++ classes with
913 // mutable subobjects or non-trivial copy/destroy behavior.
914 if (const RecordType *RT = dyn_cast<RecordType>(type))
915 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
916 if (RD->hasMutableFields() || !RD->isTrivial())
917 return false;
918
919 return true;
920}
921
922/// Can we constant-emit a load of a reference to a variable of the
923/// given type? This is different from predicates like
924/// Decl::isUsableInConstantExpressions because we do want it to apply
925/// in situations that don't necessarily satisfy the language's rules
926/// for this (e.g. C++'s ODR-use rules). For example, we want to able
927/// to do this with const float variables even if those variables
928/// aren't marked 'constexpr'.
929enum ConstantEmissionKind {
930 CEK_None,
931 CEK_AsReferenceOnly,
932 CEK_AsValueOrReference,
933 CEK_AsValueOnly
934};
935static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
936 type = type.getCanonicalType();
937 if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) {
938 if (isConstantEmittableObjectType(ref->getPointeeType()))
939 return CEK_AsValueOrReference;
940 return CEK_AsReferenceOnly;
941 }
942 if (isConstantEmittableObjectType(type))
943 return CEK_AsValueOnly;
944 return CEK_None;
945}
946
947/// Try to emit a reference to the given value without producing it as
948/// an l-value. This is actually more than an optimization: we can't
949/// produce an l-value for variables that we never actually captured
950/// in a block or lambda, which means const int variables or constexpr
951/// literals or similar.
952CodeGenFunction::ConstantEmission
John McCallf4b88a42012-03-10 09:33:50 +0000953CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
954 ValueDecl *value = refExpr->getDecl();
955
John McCalldd2ecee2012-03-10 03:05:10 +0000956 // The value needs to be an enum constant or a constant variable.
957 ConstantEmissionKind CEK;
958 if (isa<ParmVarDecl>(value)) {
959 CEK = CEK_None;
960 } else if (VarDecl *var = dyn_cast<VarDecl>(value)) {
961 CEK = checkVarTypeForConstantEmission(var->getType());
962 } else if (isa<EnumConstantDecl>(value)) {
963 CEK = CEK_AsValueOnly;
964 } else {
965 CEK = CEK_None;
966 }
967 if (CEK == CEK_None) return ConstantEmission();
968
John McCalldd2ecee2012-03-10 03:05:10 +0000969 Expr::EvalResult result;
970 bool resultIsReference;
971 QualType resultType;
972
973 // It's best to evaluate all the way as an r-value if that's permitted.
974 if (CEK != CEK_AsReferenceOnly &&
John McCallf4b88a42012-03-10 09:33:50 +0000975 refExpr->EvaluateAsRValue(result, getContext())) {
John McCalldd2ecee2012-03-10 03:05:10 +0000976 resultIsReference = false;
977 resultType = refExpr->getType();
978
979 // Otherwise, try to evaluate as an l-value.
980 } else if (CEK != CEK_AsValueOnly &&
John McCallf4b88a42012-03-10 09:33:50 +0000981 refExpr->EvaluateAsLValue(result, getContext())) {
John McCalldd2ecee2012-03-10 03:05:10 +0000982 resultIsReference = true;
983 resultType = value->getType();
984
985 // Failure.
986 } else {
987 return ConstantEmission();
988 }
989
990 // In any case, if the initializer has side-effects, abandon ship.
991 if (result.HasSideEffects)
992 return ConstantEmission();
993
994 // Emit as a constant.
995 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
996
997 // Make sure we emit a debug reference to the global variable.
998 // This should probably fire even for
999 if (isa<VarDecl>(value)) {
1000 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
John McCallf4b88a42012-03-10 09:33:50 +00001001 EmitDeclRefExprDbgValue(refExpr, C);
John McCalldd2ecee2012-03-10 03:05:10 +00001002 } else {
1003 assert(isa<EnumConstantDecl>(value));
John McCallf4b88a42012-03-10 09:33:50 +00001004 EmitDeclRefExprDbgValue(refExpr, C);
John McCalldd2ecee2012-03-10 03:05:10 +00001005 }
1006
1007 // If we emitted a reference constant, we need to dereference that.
1008 if (resultIsReference)
1009 return ConstantEmission::forReference(C);
1010
1011 return ConstantEmission::forValue(C);
1012}
1013
John McCalla07398e2011-06-16 04:16:24 +00001014llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
1015 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedman6da2c712011-12-03 04:14:32 +00001016 lvalue.getAlignment().getQuantity(),
1017 lvalue.getType(), lvalue.getTBAAInfo());
John McCalla07398e2011-06-16 04:16:24 +00001018}
1019
Rafael Espindolac3f89552012-03-24 16:50:34 +00001020static bool hasBooleanRepresentation(QualType Ty) {
1021 if (Ty->isBooleanType())
1022 return true;
1023
1024 if (const EnumType *ET = Ty->getAs<EnumType>())
1025 return ET->getDecl()->getIntegerType()->isBooleanType();
1026
Douglas Gregor47bfcca2012-04-12 20:42:30 +00001027 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1028 return hasBooleanRepresentation(AT->getValueType());
1029
Rafael Espindolac3f89552012-03-24 16:50:34 +00001030 return false;
1031}
1032
1033llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1034 const EnumType *ET = Ty->getAs<EnumType>();
Chandler Carruth82fe6ae2012-03-27 23:58:37 +00001035 bool IsRegularCPlusPlusEnum = (getLangOpts().CPlusPlus && ET &&
1036 CGM.getCodeGenOpts().StrictEnums &&
1037 !ET->getDecl()->isFixed());
Rafael Espindolac3f89552012-03-24 16:50:34 +00001038 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindolac3f89552012-03-24 16:50:34 +00001039 if (!IsBool && !IsRegularCPlusPlusEnum)
1040 return NULL;
1041
1042 llvm::APInt Min;
1043 llvm::APInt End;
1044 if (IsBool) {
1045 Min = llvm::APInt(8, 0);
1046 End = llvm::APInt(8, 2);
Rafael Espindolac3f89552012-03-24 16:50:34 +00001047 } else {
1048 const EnumDecl *ED = ET->getDecl();
Ted Kremenekcf18ae52012-05-01 17:56:53 +00001049 llvm::Type *LTy = ConvertTypeForMem(ED->getIntegerType());
Rafael Espindolac3f89552012-03-24 16:50:34 +00001050 unsigned Bitwidth = LTy->getScalarSizeInBits();
1051 unsigned NumNegativeBits = ED->getNumNegativeBits();
1052 unsigned NumPositiveBits = ED->getNumPositiveBits();
1053
1054 if (NumNegativeBits) {
1055 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1056 assert(NumBits <= Bitwidth);
1057 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1058 Min = -End;
1059 } else {
1060 assert(NumPositiveBits <= Bitwidth);
1061 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1062 Min = llvm::APInt(Bitwidth, 0);
1063 }
1064 }
1065
Duncan Sands2d7cb062012-04-15 18:04:54 +00001066 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands60c77072012-04-16 16:29:47 +00001067 return MDHelper.createRange(Min, End);
Rafael Espindolac3f89552012-03-24 16:50:34 +00001068}
1069
Daniel Dunbar9d9cc872009-02-10 00:57:50 +00001070llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
Dan Gohman3d5aff52010-10-14 23:06:10 +00001071 unsigned Alignment, QualType Ty,
1072 llvm::MDNode *TBAAInfo) {
Tanya Lattnerc58dcdc2012-08-16 00:10:13 +00001073
1074 // For better performance, handle vector loads differently.
1075 if (Ty->isVectorType()) {
1076 llvm::Value *V;
1077 const llvm::Type *EltTy =
1078 cast<llvm::PointerType>(Addr->getType())->getElementType();
1079
1080 const llvm::VectorType *VTy = cast<llvm::VectorType>(EltTy);
1081
1082 // Handle vectors of size 3, like size 4 for better performance.
1083 if (VTy->getNumElements() == 3) {
1084
1085 // Bitcast to vec4 type.
1086 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1087 4);
1088 llvm::PointerType *ptVec4Ty =
1089 llvm::PointerType::get(vec4Ty,
1090 (cast<llvm::PointerType>(
1091 Addr->getType()))->getAddressSpace());
1092 llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
1093 "castToVec4");
1094 // Now load value.
1095 llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1096
1097 // Shuffle vector to get vec3.
1098 llvm::SmallVector<llvm::Constant*, 3> Mask;
1099 Mask.push_back(llvm::ConstantInt::get(
1100 llvm::Type::getInt32Ty(getLLVMContext()),
1101 0));
1102 Mask.push_back(llvm::ConstantInt::get(
1103 llvm::Type::getInt32Ty(getLLVMContext()),
1104 1));
1105 Mask.push_back(llvm::ConstantInt::get(
1106 llvm::Type::getInt32Ty(getLLVMContext()),
1107 2));
1108
1109 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1110 V = Builder.CreateShuffleVector(LoadVal,
1111 llvm::UndefValue::get(vec4Ty),
1112 MaskV, "extractVec");
1113 return EmitFromMemory(V, Ty);
1114 }
1115 }
1116
Benjamin Kramer578faa82011-09-27 21:06:10 +00001117 llvm::LoadInst *Load = Builder.CreateLoad(Addr);
Daniel Dunbar2da84ff2009-11-29 21:23:36 +00001118 if (Volatile)
1119 Load->setVolatile(true);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001120 if (Alignment)
1121 Load->setAlignment(Alignment);
Dan Gohman3d5aff52010-10-14 23:06:10 +00001122 if (TBAAInfo)
1123 CGM.DecorateInstruction(Load, TBAAInfo);
David Chisnall7a7ee302012-01-16 17:27:18 +00001124 // If this is an atomic type, all normal reads must be atomic
1125 if (Ty->isAtomicType())
1126 Load->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar9d9cc872009-02-10 00:57:50 +00001127
Rafael Espindolac3f89552012-03-24 16:50:34 +00001128 if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1129 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1130 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001131
Rafael Espindolac3f89552012-03-24 16:50:34 +00001132 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi88a569a2012-03-24 14:43:42 +00001133}
1134
John McCall26815d92010-10-27 20:58:56 +00001135llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1136 // Bool has a different representation in memory than in registers.
Rafael Espindolac3f89552012-03-24 16:50:34 +00001137 if (hasBooleanRepresentation(Ty)) {
John McCall26815d92010-10-27 20:58:56 +00001138 // This should really always be an i1, but sometimes it's already
1139 // an i8, and it's awkward to track those cases down.
1140 if (Value->getType()->isIntegerTy(1))
1141 return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool");
1142 assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8");
1143 }
1144
1145 return Value;
1146}
1147
1148llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1149 // Bool has a different representation in memory than in registers.
Rafael Espindolac3f89552012-03-24 16:50:34 +00001150 if (hasBooleanRepresentation(Ty)) {
John McCall26815d92010-10-27 20:58:56 +00001151 assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8");
1152 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1153 }
1154
1155 return Value;
1156}
1157
Daniel Dunbar9d9cc872009-02-10 00:57:50 +00001158void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001159 bool Volatile, unsigned Alignment,
Dan Gohman3d5aff52010-10-14 23:06:10 +00001160 QualType Ty,
David Chisnall7a7ee302012-01-16 17:27:18 +00001161 llvm::MDNode *TBAAInfo,
1162 bool isInit) {
Tanya Lattnerc58dcdc2012-08-16 00:10:13 +00001163
1164 // Handle vectors differently to get better performance.
1165 if (Ty->isVectorType()) {
1166 llvm::Type *SrcTy = Value->getType();
1167 llvm::VectorType *VecTy = cast<llvm::VectorType>(SrcTy);
1168 // Handle vec3 special.
1169 if (VecTy->getNumElements() == 3) {
1170 llvm::LLVMContext &VMContext = getLLVMContext();
1171
1172 // Our source is a vec3, do a shuffle vector to make it a vec4.
1173 llvm::SmallVector<llvm::Constant*, 4> Mask;
1174 Mask.push_back(llvm::ConstantInt::get(
1175 llvm::Type::getInt32Ty(VMContext),
1176 0));
1177 Mask.push_back(llvm::ConstantInt::get(
1178 llvm::Type::getInt32Ty(VMContext),
1179 1));
1180 Mask.push_back(llvm::ConstantInt::get(
1181 llvm::Type::getInt32Ty(VMContext),
1182 2));
1183 Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
1184
1185 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1186 Value = Builder.CreateShuffleVector(Value,
1187 llvm::UndefValue::get(VecTy),
1188 MaskV, "extractVec");
1189 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1190 }
1191 llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
1192 if (DstPtr->getElementType() != SrcTy) {
1193 llvm::Type *MemTy =
1194 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
1195 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
1196 }
1197 }
1198
John McCall26815d92010-10-27 20:58:56 +00001199 Value = EmitToMemory(Value, Ty);
Chris Lattner12569fb2011-07-10 03:38:35 +00001200
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001201 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1202 if (Alignment)
1203 Store->setAlignment(Alignment);
Dan Gohman3d5aff52010-10-14 23:06:10 +00001204 if (TBAAInfo)
1205 CGM.DecorateInstruction(Store, TBAAInfo);
David Chisnall7a7ee302012-01-16 17:27:18 +00001206 if (!isInit && Ty->isAtomicType())
1207 Store->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar9d9cc872009-02-10 00:57:50 +00001208}
1209
David Chisnall7a7ee302012-01-16 17:27:18 +00001210void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1211 bool isInit) {
John McCalla07398e2011-06-16 04:16:24 +00001212 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedman6da2c712011-12-03 04:14:32 +00001213 lvalue.getAlignment().getQuantity(), lvalue.getType(),
David Chisnall7a7ee302012-01-16 17:27:18 +00001214 lvalue.getTBAAInfo(), isInit);
John McCalla07398e2011-06-16 04:16:24 +00001215}
1216
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001217/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1218/// method emits the address of the lvalue, then loads the result as an rvalue,
1219/// returning the rvalue.
John McCall545d9962011-06-25 02:11:03 +00001220RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) {
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001221 if (LV.isObjCWeak()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001222 // load of a __weak object.
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001223 llvm::Value *AddrWeakObj = LV.getAddress();
Chris Lattnereb99b012009-10-28 17:39:19 +00001224 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1225 AddrWeakObj));
Fariborz Jahanian6dc23172008-11-18 21:45:40 +00001226 }
John McCallf85e1932011-06-15 23:02:42 +00001227 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak)
1228 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001229
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 if (LV.isSimple()) {
John McCalle6d134b2011-06-27 21:24:11 +00001231 assert(!LV.getType()->isFunctionType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001232
John McCalld608cdb2010-08-22 10:59:02 +00001233 // Everything needs a load.
John McCall545d9962011-06-25 02:11:03 +00001234 return RValue::get(EmitLoadOfScalar(LV));
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001236
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 if (LV.isVectorElt()) {
Eli Friedmane5a8aeb2012-03-22 22:36:39 +00001238 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1239 LV.isVolatileQualified());
1240 Load->setAlignment(LV.getAlignment().getQuantity());
1241 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 "vecext"));
1243 }
Chris Lattner46ea8eb2007-08-03 00:16:29 +00001244
1245 // If this is a reference to a subset of the elements of a vector, either
1246 // shuffle the input or extract/insert them as appropriate.
Nate Begeman213541a2008-04-18 23:10:10 +00001247 if (LV.isExtVectorElt())
John McCall545d9962011-06-25 02:11:03 +00001248 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio3b8c22d2008-01-22 20:17:04 +00001249
John McCalldb458062011-11-07 03:59:57 +00001250 assert(LV.isBitField() && "Unknown LValue type!");
1251 return EmitLoadOfBitfieldLValue(LV);
Reid Spencer5f016e22007-07-11 17:01:13 +00001252}
1253
John McCall545d9962011-06-25 02:11:03 +00001254RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbarefbf4872010-04-06 01:07:44 +00001255 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbar10e3ded2008-08-06 05:08:45 +00001256
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001257 // Get the output type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001258 llvm::Type *ResLTy = ConvertType(LV.getType());
Micah Villmow25a6a842012-10-08 16:25:52 +00001259 unsigned ResSizeInBits = CGM.getDataLayout().getTypeSizeInBits(ResLTy);
Lauro Ramos Venancio3b8c22d2008-01-22 20:17:04 +00001260
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001261 // Compute the result as an OR of all of the individual component accesses.
1262 llvm::Value *Res = 0;
1263 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
1264 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
Eli Friedmanf4bcfa12012-06-27 21:19:48 +00001265 CharUnits AccessAlignment = AI.AccessAlignment;
1266 if (!LV.getAlignment().isZero())
1267 AccessAlignment = std::min(AccessAlignment, LV.getAlignment());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001268
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001269 // Get the field pointer.
1270 llvm::Value *Ptr = LV.getBitFieldBaseAddr();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001271
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001272 // Only offset by the field index if used, so that incoming values are not
1273 // required to be structures.
1274 if (AI.FieldIndex)
1275 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001276
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001277 // Offset by the byte offset, if used.
Ken Dyck28ebde52011-04-24 10:04:59 +00001278 if (!AI.FieldByteOffset.isZero()) {
John McCalld16c2cf2011-02-08 08:22:06 +00001279 Ptr = EmitCastToVoidPtr(Ptr);
Ken Dyck28ebde52011-04-24 10:04:59 +00001280 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1281 "bf.field.offs");
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001282 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001283
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001284 // Cast to the access type.
Chris Lattner8b418682012-02-07 00:39:47 +00001285 llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(), AI.AccessWidth,
John McCall545d9962011-06-25 02:11:03 +00001286 CGM.getContext().getTargetAddressSpace(LV.getType()));
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001287 Ptr = Builder.CreateBitCast(Ptr, PTy);
Lauro Ramos Venancio3b8c22d2008-01-22 20:17:04 +00001288
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001289 // Perform the load.
1290 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
Eli Friedmanf4bcfa12012-06-27 21:19:48 +00001291 Load->setAlignment(AccessAlignment.getQuantity());
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001292
1293 // Shift out unused low bits and mask out unused high bits.
1294 llvm::Value *Val = Load;
1295 if (AI.FieldBitStart)
Daniel Dunbar26772612010-04-15 03:47:33 +00001296 Val = Builder.CreateLShr(Load, AI.FieldBitStart);
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001297 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
1298 AI.TargetBitWidth),
1299 "bf.clear");
1300
1301 // Extend or truncate to the target size.
1302 if (AI.AccessWidth < ResSizeInBits)
1303 Val = Builder.CreateZExt(Val, ResLTy);
1304 else if (AI.AccessWidth > ResSizeInBits)
1305 Val = Builder.CreateTrunc(Val, ResLTy);
1306
1307 // Shift into place, and OR into the result.
1308 if (AI.TargetBitOffset)
1309 Val = Builder.CreateShl(Val, AI.TargetBitOffset);
1310 Res = Res ? Builder.CreateOr(Res, Val) : Val;
Daniel Dunbar10e3ded2008-08-06 05:08:45 +00001311 }
Lauro Ramos Venancio3b8c22d2008-01-22 20:17:04 +00001312
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001313 // If the bit-field is signed, perform the sign-extension.
1314 //
1315 // FIXME: This can easily be folded into the load of the high bits, which
1316 // could also eliminate the mask of high bits in some situations.
1317 if (Info.isSigned()) {
Daniel Dunbar26772612010-04-15 03:47:33 +00001318 unsigned ExtraBits = ResSizeInBits - Info.getSize();
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001319 if (ExtraBits)
1320 Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
1321 ExtraBits, "bf.val.sext");
Daniel Dunbar10e3ded2008-08-06 05:08:45 +00001322 }
Eli Friedman316bb1b2008-05-17 20:03:47 +00001323
Daniel Dunbarecdb41e2010-04-13 23:34:15 +00001324 return RValue::get(Res);
Lauro Ramos Venancio3b8c22d2008-01-22 20:17:04 +00001325}
1326
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001327// If this is a reference to a subset of the elements of a vector, create an
1328// appropriate shufflevector.
John McCall545d9962011-06-25 02:11:03 +00001329RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
Eli Friedmane5a8aeb2012-03-22 22:36:39 +00001330 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1331 LV.isVolatileQualified());
1332 Load->setAlignment(LV.getAlignment().getQuantity());
1333 llvm::Value *Vec = Load;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001334
Nate Begeman8a997642008-05-09 06:41:27 +00001335 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001336
1337 // If the result of the expression is a non-vector type, we must be extracting
1338 // a single element. Just codegen as an extractelement.
John McCall545d9962011-06-25 02:11:03 +00001339 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattnercf60cd22007-08-10 17:10:08 +00001340 if (!ExprVT) {
Dan Gohman4f8d1232008-05-22 00:50:06 +00001341 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattner77b89b82010-06-27 07:15:29 +00001342 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001343 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner34cdc862007-08-03 16:18:34 +00001344 }
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001345
1346 // Always use shuffle vector to try to retain the original program structure
Chris Lattnercf60cd22007-08-10 17:10:08 +00001347 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001348
Chris Lattner5f9e2722011-07-23 10:55:15 +00001349 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2ce88422012-01-25 05:34:41 +00001350 for (unsigned i = 0; i != NumResultElts; ++i)
1351 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001352
Chris Lattnerfb018d12011-02-15 00:14:06 +00001353 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1354 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer578faa82011-09-27 21:06:10 +00001355 MaskV);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001356 return RValue::get(Vec);
Chris Lattner34cdc862007-08-03 16:18:34 +00001357}
1358
1359
Reid Spencer5f016e22007-07-11 17:01:13 +00001360
1361/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1362/// lvalue, where both are guaranteed to the have the same type, and that type
1363/// is 'Ty'.
David Chisnall7a7ee302012-01-16 17:27:18 +00001364void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) {
Chris Lattner017d6aa2007-08-03 16:28:33 +00001365 if (!Dst.isSimple()) {
1366 if (Dst.isVectorElt()) {
1367 // Read/modify/write the vector, inserting the new element.
Eli Friedmane5a8aeb2012-03-22 22:36:39 +00001368 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1369 Dst.isVolatileQualified());
1370 Load->setAlignment(Dst.getAlignment().getQuantity());
1371 llvm::Value *Vec = Load;
Chris Lattner9b655512007-08-31 22:49:20 +00001372 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner017d6aa2007-08-03 16:28:33 +00001373 Dst.getVectorIdx(), "vecins");
Eli Friedmane5a8aeb2012-03-22 22:36:39 +00001374 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1375 Dst.isVolatileQualified());
1376 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner017d6aa2007-08-03 16:28:33 +00001377 return;
1378 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001379
Nate Begeman213541a2008-04-18 23:10:10 +00001380 // If this is an update of extended vector elements, insert them as
1381 // appropriate.
1382 if (Dst.isExtVectorElt())
John McCall545d9962011-06-25 02:11:03 +00001383 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancioa0c5d0e2008-01-22 22:36:45 +00001384
John McCalldb458062011-11-07 03:59:57 +00001385 assert(Dst.isBitField() && "Unknown LValue type");
1386 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner017d6aa2007-08-03 16:28:33 +00001387 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001388
John McCallf85e1932011-06-15 23:02:42 +00001389 // There's special magic for assigning into an ARC-qualified l-value.
1390 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1391 switch (Lifetime) {
1392 case Qualifiers::OCL_None:
1393 llvm_unreachable("present but none");
1394
1395 case Qualifiers::OCL_ExplicitNone:
1396 // nothing special
1397 break;
1398
1399 case Qualifiers::OCL_Strong:
John McCall545d9962011-06-25 02:11:03 +00001400 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001401 return;
1402
1403 case Qualifiers::OCL_Weak:
1404 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1405 return;
1406
1407 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00001408 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1409 Src.getScalarVal()));
John McCallf85e1932011-06-15 23:02:42 +00001410 // fall into the normal path
1411 break;
1412 }
1413 }
1414
Fariborz Jahanian4f676ed2009-02-21 00:30:43 +00001415 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001416 // load of a __weak object.
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001417 llvm::Value *LvalueDst = Dst.getAddress();
1418 llvm::Value *src = Src.getScalarVal();
Mike Stumpf33651c2009-04-14 00:57:29 +00001419 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001420 return;
1421 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001422
Fariborz Jahanian4f676ed2009-02-21 00:30:43 +00001423 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001424 // load of a __strong object.
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001425 llvm::Value *LvalueDst = Dst.getAddress();
1426 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00001427 if (Dst.isObjCIvar()) {
1428 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001429 llvm::Type *ResultType = ConvertType(getContext().LongTy);
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00001430 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
Fariborz Jahanian76368e82009-09-25 00:00:20 +00001431 llvm::Value *dst = RHS;
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00001432 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1433 llvm::Value *LHS =
1434 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1435 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian76368e82009-09-25 00:00:20 +00001436 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00001437 BytesBetween);
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00001438 } else if (Dst.isGlobalObjCRef()) {
1439 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1440 Dst.isThreadLocalRef());
1441 }
Fariborz Jahanianbf63b872009-05-04 23:27:20 +00001442 else
1443 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahaniandbd32c22008-11-19 17:34:06 +00001444 return;
1445 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001446
Chris Lattner883f6a72007-08-11 00:04:45 +00001447 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnall7a7ee302012-01-16 17:27:18 +00001448 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Reid Spencer5f016e22007-07-11 17:01:13 +00001449}
1450
Lauro Ramos Venancioa0c5d0e2008-01-22 22:36:45 +00001451void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbared3849b2008-11-19 09:36:46 +00001452 llvm::Value **Result) {
Daniel Dunbarefbf4872010-04-06 01:07:44 +00001453 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Lauro Ramos Venancioa0c5d0e2008-01-22 22:36:45 +00001454
Daniel Dunbar26772612010-04-15 03:47:33 +00001455 // Get the output type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001456 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
Micah Villmow25a6a842012-10-08 16:25:52 +00001457 unsigned ResSizeInBits = CGM.getDataLayout().getTypeSizeInBits(ResLTy);
Daniel Dunbar10e3ded2008-08-06 05:08:45 +00001458
Daniel Dunbar26772612010-04-15 03:47:33 +00001459 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbared3849b2008-11-19 09:36:46 +00001460 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson48035352010-04-17 21:52:22 +00001461
Douglas Gregor47bfcca2012-04-12 20:42:30 +00001462 if (hasBooleanRepresentation(Dst.getType()))
Anders Carlsson48035352010-04-17 21:52:22 +00001463 SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
1464
Daniel Dunbar26772612010-04-15 03:47:33 +00001465 SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
1466 Info.getSize()),
1467 "bf.value");
Lauro Ramos Venancioa0c5d0e2008-01-22 22:36:45 +00001468
Daniel Dunbared3849b2008-11-19 09:36:46 +00001469 // Return the new value of the bit-field, if requested.
1470 if (Result) {
1471 // Cast back to the proper type for result.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001472 llvm::Type *SrcTy = Src.getScalarVal()->getType();
Daniel Dunbar26772612010-04-15 03:47:33 +00001473 llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
1474 "bf.reload.val");
Daniel Dunbared3849b2008-11-19 09:36:46 +00001475
1476 // Sign extend if necessary.
Daniel Dunbar26772612010-04-15 03:47:33 +00001477 if (Info.isSigned()) {
1478 unsigned ExtraBits = ResSizeInBits - Info.getSize();
1479 if (ExtraBits)
1480 ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
1481 ExtraBits, "bf.reload.sext");
Daniel Dunbared3849b2008-11-19 09:36:46 +00001482 }
1483
Daniel Dunbar26772612010-04-15 03:47:33 +00001484 *Result = ReloadVal;
Daniel Dunbared3849b2008-11-19 09:36:46 +00001485 }
1486
Daniel Dunbar26772612010-04-15 03:47:33 +00001487 // Iterate over the components, writing each piece to memory.
1488 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
1489 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
Eli Friedmanf4bcfa12012-06-27 21:19:48 +00001490 CharUnits AccessAlignment = AI.AccessAlignment;
1491 if (!Dst.getAlignment().isZero())
1492 AccessAlignment = std::min(AccessAlignment, Dst.getAlignment());
Eli Friedman316bb1b2008-05-17 20:03:47 +00001493
Daniel Dunbar26772612010-04-15 03:47:33 +00001494 // Get the field pointer.
1495 llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
John McCalld16c2cf2011-02-08 08:22:06 +00001496 unsigned addressSpace =
1497 cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001498
Daniel Dunbar26772612010-04-15 03:47:33 +00001499 // Only offset by the field index if used, so that incoming values are not
1500 // required to be structures.
1501 if (AI.FieldIndex)
1502 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001503
Daniel Dunbar26772612010-04-15 03:47:33 +00001504 // Offset by the byte offset, if used.
Ken Dyck28ebde52011-04-24 10:04:59 +00001505 if (!AI.FieldByteOffset.isZero()) {
John McCalld16c2cf2011-02-08 08:22:06 +00001506 Ptr = EmitCastToVoidPtr(Ptr);
Ken Dyck28ebde52011-04-24 10:04:59 +00001507 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1508 "bf.field.offs");
Daniel Dunbar26772612010-04-15 03:47:33 +00001509 }
Eli Friedman316bb1b2008-05-17 20:03:47 +00001510
Daniel Dunbar26772612010-04-15 03:47:33 +00001511 // Cast to the access type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001512 llvm::Type *AccessLTy =
John McCalld16c2cf2011-02-08 08:22:06 +00001513 llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth);
1514
Chris Lattner2acc6e32011-07-18 04:24:23 +00001515 llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace);
Daniel Dunbar26772612010-04-15 03:47:33 +00001516 Ptr = Builder.CreateBitCast(Ptr, PTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001517
Daniel Dunbar26772612010-04-15 03:47:33 +00001518 // Extract the piece of the bit-field value to write in this access, limited
1519 // to the values that are part of this access.
1520 llvm::Value *Val = SrcVal;
1521 if (AI.TargetBitOffset)
1522 Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
1523 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
1524 AI.TargetBitWidth));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001525
Daniel Dunbar26772612010-04-15 03:47:33 +00001526 // Extend or truncate to the access size.
Daniel Dunbar26772612010-04-15 03:47:33 +00001527 if (ResSizeInBits < AI.AccessWidth)
1528 Val = Builder.CreateZExt(Val, AccessLTy);
1529 else if (ResSizeInBits > AI.AccessWidth)
1530 Val = Builder.CreateTrunc(Val, AccessLTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001531
Daniel Dunbar26772612010-04-15 03:47:33 +00001532 // Shift into the position in memory.
1533 if (AI.FieldBitStart)
1534 Val = Builder.CreateShl(Val, AI.FieldBitStart);
1535
1536 // If necessary, load and OR in bits that are outside of the bit-field.
1537 if (AI.TargetBitWidth != AI.AccessWidth) {
1538 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
Eli Friedmanf4bcfa12012-06-27 21:19:48 +00001539 Load->setAlignment(AccessAlignment.getQuantity());
Daniel Dunbar26772612010-04-15 03:47:33 +00001540
1541 // Compute the mask for zeroing the bits that are part of the bit-field.
1542 llvm::APInt InvMask =
1543 ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
1544 AI.FieldBitStart + AI.TargetBitWidth);
1545
1546 // Apply the mask and OR in to the value to write.
1547 Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
1548 }
1549
1550 // Write the value.
1551 llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
1552 Dst.isVolatileQualified());
Eli Friedmanf4bcfa12012-06-27 21:19:48 +00001553 Store->setAlignment(AccessAlignment.getQuantity());
Daniel Dunbar10e3ded2008-08-06 05:08:45 +00001554 }
Lauro Ramos Venancioa0c5d0e2008-01-22 22:36:45 +00001555}
1556
Nate Begeman213541a2008-04-18 23:10:10 +00001557void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall545d9962011-06-25 02:11:03 +00001558 LValue Dst) {
Chris Lattner017d6aa2007-08-03 16:28:33 +00001559 // This access turns into a read/modify/write of the vector. Load the input
1560 // value now.
Eli Friedmane5a8aeb2012-03-22 22:36:39 +00001561 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1562 Dst.isVolatileQualified());
1563 Load->setAlignment(Dst.getAlignment().getQuantity());
1564 llvm::Value *Vec = Load;
Nate Begeman8a997642008-05-09 06:41:27 +00001565 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001566
Chris Lattner9b655512007-08-31 22:49:20 +00001567 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001568
John McCall545d9962011-06-25 02:11:03 +00001569 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner7e6b51b2007-08-03 16:37:04 +00001570 unsigned NumSrcElts = VTy->getNumElements();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001571 unsigned NumDstElts =
1572 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1573 if (NumDstElts == NumSrcElts) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001574 // Use shuffle vector is the src and destination are the same number of
1575 // elements and restore the vector mask since it is on the side it will be
1576 // stored.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001577 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2ce88422012-01-25 05:34:41 +00001578 for (unsigned i = 0; i != NumSrcElts; ++i)
1579 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001580
Chris Lattnerfb018d12011-02-15 00:14:06 +00001581 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001582 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson03e20502009-07-30 23:11:26 +00001583 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer578faa82011-09-27 21:06:10 +00001584 MaskV);
Mike Stumpb3589f42009-07-30 22:28:39 +00001585 } else if (NumDstElts > NumSrcElts) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001586 // Extended the source vector to the same length and then shuffle it
1587 // into the destination.
1588 // FIXME: since we're shuffling with undef, can we just use the indices
1589 // into that? This could be simpler.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001590 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer14c59822012-02-14 12:06:21 +00001591 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2ce88422012-01-25 05:34:41 +00001592 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001593 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +00001594 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001595 llvm::Value *ExtSrcVal =
Daniel Dunbarbb767732009-02-17 18:31:04 +00001596 Builder.CreateShuffleVector(SrcVal,
Owen Anderson03e20502009-07-30 23:11:26 +00001597 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer578faa82011-09-27 21:06:10 +00001598 ExtMaskV);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001599 // build identity
Chris Lattner5f9e2722011-07-23 10:55:15 +00001600 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnereb99b012009-10-28 17:39:19 +00001601 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2ce88422012-01-25 05:34:41 +00001602 Mask.push_back(Builder.getInt32(i));
Chris Lattnereb99b012009-10-28 17:39:19 +00001603
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001604 // modify when what gets shuffled in
Chris Lattner2ce88422012-01-25 05:34:41 +00001605 for (unsigned i = 0; i != NumSrcElts; ++i)
1606 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattnerfb018d12011-02-15 00:14:06 +00001607 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001608 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stumpb3589f42009-07-30 22:28:39 +00001609 } else {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001610 // We should never shorten the vector
David Blaikieb219cfc2011-09-23 05:06:16 +00001611 llvm_unreachable("unexpected shorten vector length");
Chris Lattner7e6b51b2007-08-03 16:37:04 +00001612 }
1613 } else {
1614 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman4f8d1232008-05-22 00:50:06 +00001615 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattnereb99b012009-10-28 17:39:19 +00001616 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001617 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner017d6aa2007-08-03 16:28:33 +00001618 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001619
Eli Friedmane5a8aeb2012-03-22 22:36:39 +00001620 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1621 Dst.isVolatileQualified());
1622 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner017d6aa2007-08-03 16:28:33 +00001623}
1624
Fariborz Jahanianb123ea32009-09-16 21:37:16 +00001625// setObjCGCLValueClass - sets class of he lvalue for the purpose of
1626// generating write-barries API. It is currently a global, ivar,
1627// or neither.
Chris Lattnereb99b012009-10-28 17:39:19 +00001628static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanianccae76c2011-09-30 18:23:36 +00001629 LValue &LV,
1630 bool IsMemberAccess=false) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001631 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanianb123ea32009-09-16 21:37:16 +00001632 return;
1633
Fariborz Jahaniandbf3cfd2009-09-16 23:11:23 +00001634 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanianccae76c2011-09-30 18:23:36 +00001635 QualType ExpTy = E->getType();
1636 if (IsMemberAccess && ExpTy->isPointerType()) {
1637 // If ivar is a structure pointer, assigning to field of
1638 // this struct follows gcc's behavior and makes it a non-ivar
1639 // writer-barrier conservatively.
1640 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1641 if (ExpTy->isRecordType()) {
1642 LV.setObjCIvar(false);
1643 return;
1644 }
1645 }
Daniel Dunbar3491b3d2010-08-21 03:51:29 +00001646 LV.setObjCIvar(true);
Fariborz Jahanian6c7a1f32009-09-24 22:25:38 +00001647 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1648 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar3491b3d2010-08-21 03:51:29 +00001649 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniandbf3cfd2009-09-16 23:11:23 +00001650 return;
1651 }
Chris Lattnereb99b012009-10-28 17:39:19 +00001652
Fariborz Jahanianb123ea32009-09-16 21:37:16 +00001653 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1654 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCallb6bbcc92010-10-15 04:57:14 +00001655 if (VD->hasGlobalStorage()) {
Daniel Dunbar3491b3d2010-08-21 03:51:29 +00001656 LV.setGlobalObjCRef(true);
1657 LV.setThreadLocalRef(VD->isThreadSpecified());
Fariborz Jahanian021a7a62010-07-20 20:30:03 +00001658 }
Fariborz Jahanianb123ea32009-09-16 21:37:16 +00001659 }
Daniel Dunbar3491b3d2010-08-21 03:51:29 +00001660 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnereb99b012009-10-28 17:39:19 +00001661 return;
Fariborz Jahanianb123ea32009-09-16 21:37:16 +00001662 }
Chris Lattnereb99b012009-10-28 17:39:19 +00001663
1664 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanianccae76c2011-09-30 18:23:36 +00001665 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnereb99b012009-10-28 17:39:19 +00001666 return;
1667 }
1668
1669 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanianccae76c2011-09-30 18:23:36 +00001670 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahanian75b08f12009-09-30 17:10:29 +00001671 if (LV.isObjCIvar()) {
1672 // If cast is to a structure pointer, follow gcc's behavior and make it
1673 // a non-ivar write-barrier.
1674 QualType ExpTy = E->getType();
1675 if (ExpTy->isPointerType())
1676 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1677 if (ExpTy->isRecordType())
Daniel Dunbar3491b3d2010-08-21 03:51:29 +00001678 LV.setObjCIvar(false);
Chris Lattnereb99b012009-10-28 17:39:19 +00001679 }
1680 return;
Fariborz Jahanian75b08f12009-09-30 17:10:29 +00001681 }
Peter Collingbournef111d932011-04-15 00:35:48 +00001682
1683 if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1684 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1685 return;
1686 }
1687
Chris Lattnereb99b012009-10-28 17:39:19 +00001688 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanianccae76c2011-09-30 18:23:36 +00001689 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnereb99b012009-10-28 17:39:19 +00001690 return;
1691 }
1692
1693 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanianccae76c2011-09-30 18:23:36 +00001694 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnereb99b012009-10-28 17:39:19 +00001695 return;
1696 }
John McCallf85e1932011-06-15 23:02:42 +00001697
1698 if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanianccae76c2011-09-30 18:23:36 +00001699 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCallf85e1932011-06-15 23:02:42 +00001700 return;
1701 }
1702
Chris Lattnereb99b012009-10-28 17:39:19 +00001703 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahanianb123ea32009-09-16 21:37:16 +00001704 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Fariborz Jahanianfd02ed72009-09-21 18:54:29 +00001705 if (LV.isObjCIvar() && !LV.isObjCArray())
Fariborz Jahanian1c1afc42009-09-18 00:04:00 +00001706 // Using array syntax to assigning to what an ivar points to is not
1707 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Daniel Dunbar3491b3d2010-08-21 03:51:29 +00001708 LV.setObjCIvar(false);
Fariborz Jahanianfd02ed72009-09-21 18:54:29 +00001709 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1710 // Using array syntax to assigning to what global points to is not
1711 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar3491b3d2010-08-21 03:51:29 +00001712 LV.setGlobalObjCRef(false);
Chris Lattnereb99b012009-10-28 17:39:19 +00001713 return;
Fariborz Jahanian1c1afc42009-09-18 00:04:00 +00001714 }
Fariborz Jahanianccae76c2011-09-30 18:23:36 +00001715
Chris Lattnereb99b012009-10-28 17:39:19 +00001716 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanianccae76c2011-09-30 18:23:36 +00001717 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian1c1afc42009-09-18 00:04:00 +00001718 // We don't know if member is an 'ivar', but this flag is looked at
1719 // only in the context of LV.isObjCIvar().
Daniel Dunbar3491b3d2010-08-21 03:51:29 +00001720 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnereb99b012009-10-28 17:39:19 +00001721 return;
Fariborz Jahanianb123ea32009-09-16 21:37:16 +00001722 }
1723}
1724
Chris Lattner3a2b6572011-07-12 06:52:18 +00001725static llvm::Value *
Chandler Carrutha98742c2011-07-12 08:58:26 +00001726EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3a2b6572011-07-12 06:52:18 +00001727 llvm::Value *V, llvm::Type *IRType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001728 StringRef Name = StringRef()) {
Chris Lattner3a2b6572011-07-12 06:52:18 +00001729 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carrutha98742c2011-07-12 08:58:26 +00001730 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3a2b6572011-07-12 06:52:18 +00001731}
1732
Anders Carlssonce53f7d2009-11-07 23:06:58 +00001733static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1734 const Expr *E, const VarDecl *VD) {
Daniel Dunbard2113f22009-11-08 09:46:46 +00001735 assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
Anders Carlssonce53f7d2009-11-07 23:06:58 +00001736 "Var decl must have external storage or be a file var decl!");
1737
1738 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedman2f77b3d2011-11-16 00:42:57 +00001739 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1740 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedman6da2c712011-12-03 04:14:32 +00001741 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
Eli Friedman2f77b3d2011-11-16 00:42:57 +00001742 QualType T = E->getType();
1743 LValue LV;
1744 if (VD->getType()->isReferenceType()) {
1745 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
Eli Friedman6da2c712011-12-03 04:14:32 +00001746 LI->setAlignment(Alignment.getQuantity());
Eli Friedman2f77b3d2011-11-16 00:42:57 +00001747 V = LI;
1748 LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1749 } else {
1750 LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1751 }
Anders Carlssonce53f7d2009-11-07 23:06:58 +00001752 setObjCGCLValueClass(CGF.getContext(), E, LV);
1753 return LV;
1754}
1755
Eli Friedman9a146302009-11-26 06:08:14 +00001756static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner74339df2011-07-10 05:34:54 +00001757 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerd0db03a2010-09-06 00:11:41 +00001758 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedman9a146302009-11-26 06:08:14 +00001759 if (!FD->hasPrototype()) {
1760 if (const FunctionProtoType *Proto =
1761 FD->getType()->getAs<FunctionProtoType>()) {
1762 // Ugly case: for a K&R-style definition, the type of the definition
1763 // isn't the same as the type of a use. Correct for this with a
1764 // bitcast.
1765 QualType NoProtoType =
1766 CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1767 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer578faa82011-09-27 21:06:10 +00001768 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedman9a146302009-11-26 06:08:14 +00001769 }
1770 }
Eli Friedman6da2c712011-12-03 04:14:32 +00001771 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Daniel Dunbar983e3d72010-08-21 04:20:22 +00001772 return CGF.MakeAddrLValue(V, E->getType(), Alignment);
Eli Friedman9a146302009-11-26 06:08:14 +00001773}
1774
Reid Spencer5f016e22007-07-11 17:01:13 +00001775LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson1e74c4f2009-11-07 22:53:10 +00001776 const NamedDecl *ND = E->getDecl();
Eli Friedman6da2c712011-12-03 04:14:32 +00001777 CharUnits Alignment = getContext().getDeclAlign(ND);
Eli Friedman2f77b3d2011-11-16 00:42:57 +00001778 QualType T = E->getType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001779
Richard Smith5016a702012-10-20 01:38:33 +00001780 // A DeclRefExpr for a reference initialized by a constant expression can
1781 // appear without being odr-used. Directly emit the constant initializer.
1782 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1783 const Expr *Init = VD->getAnyInitializer(VD);
1784 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
1785 VD->isUsableInConstantExpressions(getContext()) &&
1786 VD->checkInitIsICE()) {
1787 llvm::Constant *Val =
1788 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
1789 assert(Val && "failed to emit reference constant expression");
1790 // FIXME: Eventually we will want to emit vector element references.
1791 return MakeAddrLValue(Val, T, Alignment);
1792 }
1793 }
1794
Eli Friedman416de512012-01-21 04:52:58 +00001795 // FIXME: We should be able to assert this for FunctionDecls as well!
1796 // FIXME: We should be able to assert this for all DeclRefExprs, not just
1797 // those with a valid source location.
1798 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1799 !E->getLocation().isValid()) &&
1800 "Should not use decl without marking it used!");
1801
Rafael Espindola6a836702010-03-04 18:17:24 +00001802 if (ND->hasAttr<WeakRefAttr>()) {
Chris Lattnerd0db03a2010-09-06 00:11:41 +00001803 const ValueDecl *VD = cast<ValueDecl>(ND);
Rafael Espindola6a836702010-03-04 18:17:24 +00001804 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
Richard Smith5016a702012-10-20 01:38:33 +00001805 return MakeAddrLValue(Aliasee, T, Alignment);
Rafael Espindola6a836702010-03-04 18:17:24 +00001806 }
1807
Anders Carlsson1e74c4f2009-11-07 22:53:10 +00001808 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson1e74c4f2009-11-07 22:53:10 +00001809 // Check if this is a global variable.
Anders Carlssonce53f7d2009-11-07 23:06:58 +00001810 if (VD->hasExternalStorage() || VD->isFileVarDecl())
1811 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson0bc70492009-11-07 22:46:42 +00001812
John McCallf4b88a42012-03-10 09:33:50 +00001813 bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1814
Fariborz Jahanian75f91d62010-11-19 18:17:09 +00001815 bool NonGCable = VD->hasLocalStorage() &&
1816 !VD->getType()->isReferenceType() &&
John McCallf4b88a42012-03-10 09:33:50 +00001817 !isBlockVariable;
Anders Carlsson0bc70492009-11-07 22:46:42 +00001818
1819 llvm::Value *V = LocalDeclMap[VD];
Fariborz Jahanian09349142010-09-07 23:26:17 +00001820 if (!V && VD->isStaticLocal())
Fariborz Jahanian63326a52010-04-19 18:15:02 +00001821 V = CGM.getStaticLocalDeclAddress(VD);
Eli Friedmancec5ebd2012-02-11 02:57:39 +00001822
1823 // Use special handling for lambdas.
John McCallf4b88a42012-03-10 09:33:50 +00001824 if (!V) {
Eli Friedman377ecc72012-04-16 03:54:45 +00001825 if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1826 QualType LambdaTagType = getContext().getTagDeclType(FD->getParent());
1827 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
1828 LambdaTagType);
1829 return EmitLValueForField(LambdaLV, FD);
1830 }
Eli Friedmancec5ebd2012-02-11 02:57:39 +00001831
John McCallf4b88a42012-03-10 09:33:50 +00001832 assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
John McCallf4b88a42012-03-10 09:33:50 +00001833 return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
Richard Smith5016a702012-10-20 01:38:33 +00001834 T, Alignment);
John McCallf4b88a42012-03-10 09:33:50 +00001835 }
1836
Anders Carlsson0bc70492009-11-07 22:46:42 +00001837 assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1838
John McCallf4b88a42012-03-10 09:33:50 +00001839 if (isBlockVariable)
Fariborz Jahanian52a80e12011-01-26 23:08:27 +00001840 V = BuildBlockByrefAddress(V, VD);
Daniel Dunbar6d5eb762010-08-21 03:44:13 +00001841
Eli Friedman2f77b3d2011-11-16 00:42:57 +00001842 LValue LV;
1843 if (VD->getType()->isReferenceType()) {
1844 llvm::LoadInst *LI = Builder.CreateLoad(V);
Eli Friedman6da2c712011-12-03 04:14:32 +00001845 LI->setAlignment(Alignment.getQuantity());
Eli Friedman2f77b3d2011-11-16 00:42:57 +00001846 V = LI;
1847 LV = MakeNaturalAlignAddrLValue(V, T);
1848 } else {
1849 LV = MakeAddrLValue(V, T, Alignment);
1850 }
Chris Lattner3a2b6572011-07-12 06:52:18 +00001851
Fariborz Jahanian75f91d62010-11-19 18:17:09 +00001852 if (NonGCable) {
Daniel Dunbar6d5eb762010-08-21 03:44:13 +00001853 LV.getQuals().removeObjCGCAttr();
Daniel Dunbarea619172010-08-21 03:22:38 +00001854 LV.setNonGC(true);
1855 }
Fariborz Jahanianb123ea32009-09-16 21:37:16 +00001856 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian2682d8b2008-11-20 00:15:42 +00001857 return LV;
Chris Lattnereb99b012009-10-28 17:39:19 +00001858 }
John McCall5808ce42011-02-03 08:15:49 +00001859
1860 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1861 return EmitFunctionDeclLValue(*this, E, fn);
1862
David Blaikieb219cfc2011-09-23 05:06:16 +00001863 llvm_unreachable("Unhandled DeclRefExpr");
Reid Spencer5f016e22007-07-11 17:01:13 +00001864}
1865
1866LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1867 // __extension__ doesn't affect lvalue-ness.
John McCall2de56d12010-08-25 11:45:40 +00001868 if (E->getOpcode() == UO_Extension)
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 return EmitLValue(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001870
Chris Lattner96196622008-07-26 22:37:01 +00001871 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner7da36f62007-10-30 22:53:42 +00001872 switch (E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001873 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCall2de56d12010-08-25 11:45:40 +00001874 case UO_Deref: {
Chris Lattnereb99b012009-10-28 17:39:19 +00001875 QualType T = E->getSubExpr()->getType()->getPointeeType();
1876 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001877
Chris Lattner4cac9e12011-12-19 21:16:08 +00001878 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
Daniel Dunbar6d5eb762010-08-21 03:44:13 +00001879 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall0953e762009-09-24 19:53:00 +00001880
Chris Lattnereb99b012009-10-28 17:39:19 +00001881 // We should not generate __weak write barrier on indirect reference
1882 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1883 // But, we continue to generate __strong write barrier on indirect write
1884 // into a pointer to object.
David Blaikie4e4d0842012-03-11 07:00:24 +00001885 if (getContext().getLangOpts().ObjC1 &&
1886 getContext().getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnereb99b012009-10-28 17:39:19 +00001887 LV.isObjCWeak())
Daniel Dunbarea619172010-08-21 03:22:38 +00001888 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnereb99b012009-10-28 17:39:19 +00001889 return LV;
1890 }
John McCall2de56d12010-08-25 11:45:40 +00001891 case UO_Real:
1892 case UO_Imag: {
Chris Lattner7da36f62007-10-30 22:53:42 +00001893 LValue LV = EmitLValue(E->getSubExpr());
John McCall2a416372010-12-05 02:00:02 +00001894 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1895 llvm::Value *Addr = LV.getAddress();
1896
Richard Smithdfb80de2012-02-18 20:53:32 +00001897 // __real is valid on scalars. This is a faster way of testing that.
1898 // __imag can only produce an rvalue on scalars.
1899 if (E->getOpcode() == UO_Real &&
1900 !cast<llvm::PointerType>(Addr->getType())
John McCall2a416372010-12-05 02:00:02 +00001901 ->getElementType()->isStructTy()) {
1902 assert(E->getSubExpr()->getType()->isArithmeticType());
1903 return LV;
1904 }
1905
1906 assert(E->getSubExpr()->getType()->isAnyComplexType());
1907
John McCall2de56d12010-08-25 11:45:40 +00001908 unsigned Idx = E->getOpcode() == UO_Imag;
Daniel Dunbar9f553f52010-08-21 03:08:16 +00001909 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
John McCall2a416372010-12-05 02:00:02 +00001910 Idx, "idx"),
Daniel Dunbar9f553f52010-08-21 03:08:16 +00001911 ExprTy);
Chris Lattner7da36f62007-10-30 22:53:42 +00001912 }
John McCall2de56d12010-08-25 11:45:40 +00001913 case UO_PreInc:
1914 case UO_PreDec: {
Chris Lattner197a3382010-01-09 21:44:40 +00001915 LValue LV = EmitLValue(E->getSubExpr());
John McCall2de56d12010-08-25 11:45:40 +00001916 bool isInc = E->getOpcode() == UO_PreInc;
Chris Lattner197a3382010-01-09 21:44:40 +00001917
1918 if (E->getType()->isAnyComplexType())
1919 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1920 else
1921 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1922 return LV;
1923 }
Eli Friedmane401cd52009-11-09 04:20:47 +00001924 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001925}
1926
1927LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar79c39282010-08-21 03:15:20 +00001928 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1929 E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001930}
1931
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001932LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar79c39282010-08-21 03:15:20 +00001933 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1934 E->getType());
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001935}
1936
Nico Weber28ad0632012-06-23 02:07:59 +00001937static llvm::Constant*
1938GetAddrOfConstantWideString(StringRef Str,
1939 const char *GlobalName,
1940 ASTContext &Context,
1941 QualType Ty, SourceLocation Loc,
1942 CodeGenModule &CGM) {
1943
1944 StringLiteral *SL = StringLiteral::Create(Context,
1945 Str,
1946 StringLiteral::Wide,
1947 /*Pascal = */false,
1948 Ty, Loc);
1949 llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL);
1950 llvm::GlobalVariable *GV =
1951 new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1952 !CGM.getLangOpts().WritableStrings,
1953 llvm::GlobalValue::PrivateLinkage,
1954 C, GlobalName);
1955 const unsigned WideAlignment =
1956 Context.getTypeAlignInChars(Ty).getQuantity();
1957 GV->setAlignment(WideAlignment);
1958 return GV;
1959}
1960
Nico Weber28ad0632012-06-23 02:07:59 +00001961static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
1962 SmallString<32>& Target) {
1963 Target.resize(CharByteWidth * (Source.size() + 1));
Richard Smithe5f05882012-09-08 07:16:20 +00001964 char *ResultPtr = &Target[0];
1965 const UTF8 *ErrorPtr;
1966 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
Matt Beaumont-Gay402a6d52012-07-03 03:55:58 +00001967 (void)success;
Nico Weber941e47c2012-07-03 02:24:52 +00001968 assert(success);
Nico Weber28ad0632012-06-23 02:07:59 +00001969 Target.resize(ResultPtr - &Target[0]);
1970}
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001971
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001972LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Daniel Dunbar662b71e2008-10-17 21:58:32 +00001973 switch (E->getIdentType()) {
1974 default:
1975 return EmitUnsupportedLValue(E, "predefined expression");
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +00001976
Daniel Dunbar662b71e2008-10-17 21:58:32 +00001977 case PredefinedExpr::Func:
1978 case PredefinedExpr::Function:
Nico Weber28ad0632012-06-23 02:07:59 +00001979 case PredefinedExpr::LFunction:
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +00001980 case PredefinedExpr::PrettyFunction: {
Nico Weber28ad0632012-06-23 02:07:59 +00001981 unsigned IdentType = E->getIdentType();
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +00001982 std::string GlobalVarName;
1983
Nico Weber28ad0632012-06-23 02:07:59 +00001984 switch (IdentType) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001985 default: llvm_unreachable("Invalid type");
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +00001986 case PredefinedExpr::Func:
1987 GlobalVarName = "__func__.";
1988 break;
1989 case PredefinedExpr::Function:
1990 GlobalVarName = "__FUNCTION__.";
1991 break;
Nico Weber28ad0632012-06-23 02:07:59 +00001992 case PredefinedExpr::LFunction:
1993 GlobalVarName = "L__FUNCTION__.";
1994 break;
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +00001995 case PredefinedExpr::PrettyFunction:
1996 GlobalVarName = "__PRETTY_FUNCTION__.";
1997 break;
1998 }
1999
Chris Lattner5f9e2722011-07-23 10:55:15 +00002000 StringRef FnName = CurFn->getName();
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +00002001 if (FnName.startswith("\01"))
2002 FnName = FnName.substr(1);
2003 GlobalVarName += FnName;
2004
2005 const Decl *CurDecl = CurCodeDecl;
2006 if (CurDecl == 0)
2007 CurDecl = getContext().getTranslationUnitDecl();
2008
2009 std::string FunctionName =
John McCall6b5a61b2011-02-07 10:33:21 +00002010 (isa<BlockDecl>(CurDecl)
2011 ? FnName.str()
Nico Weber28ad0632012-06-23 02:07:59 +00002012 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType,
2013 CurDecl));
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +00002014
Nico Weber28ad0632012-06-23 02:07:59 +00002015 const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual();
2016 llvm::Constant *C;
2017 if (ElemType->isWideCharType()) {
2018 SmallString<32> RawChars;
2019 ConvertUTF8ToWideString(
2020 getContext().getTypeSizeInChars(ElemType).getQuantity(),
2021 FunctionName, RawChars);
2022 C = GetAddrOfConstantWideString(RawChars,
2023 GlobalVarName.c_str(),
2024 getContext(),
2025 E->getType(),
2026 E->getLocation(),
2027 CGM);
2028 } else {
2029 C = CGM.GetAddrOfConstantCString(FunctionName,
2030 GlobalVarName.c_str(),
2031 1);
2032 }
Daniel Dunbar79c39282010-08-21 03:15:20 +00002033 return MakeAddrLValue(C, E->getType());
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +00002034 }
Daniel Dunbar662b71e2008-10-17 21:58:32 +00002035 }
Anders Carlsson22742662007-07-21 05:21:51 +00002036}
2037
Richard Smith4def70d2012-10-09 19:52:38 +00002038/// Emit a type description suitable for use by a runtime sanitizer library. The
2039/// format of a type descriptor is
2040///
2041/// \code
Richard Smithdc47bdc2012-10-09 23:55:19 +00002042/// { i16 TypeKind, i16 TypeInfo }
Richard Smith4def70d2012-10-09 19:52:38 +00002043/// \endcode
2044///
Richard Smithdc47bdc2012-10-09 23:55:19 +00002045/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2046/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smith4def70d2012-10-09 19:52:38 +00002047llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2048 // FIXME: Only emit each type's descriptor once.
2049 uint16_t TypeKind = -1;
2050 uint16_t TypeInfo = 0;
Mike Stump41513442009-12-15 00:59:40 +00002051
Richard Smith4def70d2012-10-09 19:52:38 +00002052 if (T->isIntegerType()) {
2053 TypeKind = 0;
2054 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2055 T->isSignedIntegerType();
2056 } else if (T->isFloatingType()) {
2057 TypeKind = 1;
2058 TypeInfo = getContext().getTypeSize(T);
2059 }
2060
2061 // Format the type name as if for a diagnostic, including quotes and
2062 // optionally an 'aka'.
2063 llvm::SmallString<32> Buffer;
2064 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2065 (intptr_t)T.getAsOpaquePtr(),
2066 0, 0, 0, 0, 0, 0, Buffer,
2067 ArrayRef<intptr_t>());
2068
2069 llvm::Constant *Components[] = {
Richard Smithdc47bdc2012-10-09 23:55:19 +00002070 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2071 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smith4def70d2012-10-09 19:52:38 +00002072 };
2073 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2074
2075 llvm::GlobalVariable *GV =
2076 new llvm::GlobalVariable(CGM.getModule(), Descriptor->getType(),
2077 /*isConstant=*/true,
2078 llvm::GlobalVariable::PrivateLinkage,
2079 Descriptor);
2080 GV->setUnnamedAddr(true);
2081 return GV;
2082}
2083
2084llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2085 llvm::Type *TargetTy = IntPtrTy;
2086
2087 // Integers which fit in intptr_t are zero-extended and passed directly.
2088 if (V->getType()->isIntegerTy() &&
2089 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2090 return Builder.CreateZExt(V, TargetTy);
2091
2092 // Pointers are passed directly, everything else is passed by address.
2093 if (!V->getType()->isPointerTy()) {
2094 llvm::Value *Ptr = Builder.CreateAlloca(V->getType());
2095 Builder.CreateStore(V, Ptr);
2096 V = Ptr;
2097 }
2098 return Builder.CreatePtrToInt(V, TargetTy);
2099}
2100
2101/// \brief Emit a representation of a SourceLocation for passing to a handler
2102/// in a sanitizer runtime library. The format for this data is:
2103/// \code
2104/// struct SourceLocation {
2105/// const char *Filename;
2106/// int32_t Line, Column;
2107/// };
2108/// \endcode
2109/// For an invalid SourceLocation, the Filename pointer is null.
2110llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2111 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2112
2113 llvm::Constant *Data[] = {
2114 // FIXME: Only emit each file name once.
2115 PLoc.isValid() ? cast<llvm::Constant>(
2116 Builder.CreateGlobalStringPtr(PLoc.getFilename()))
2117 : llvm::Constant::getNullValue(Int8PtrTy),
2118 Builder.getInt32(PLoc.getLine()),
2119 Builder.getInt32(PLoc.getColumn())
2120 };
2121
2122 return llvm::ConstantStruct::getAnon(Data);
2123}
2124
2125void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName,
2126 llvm::ArrayRef<llvm::Constant *> StaticArgs,
Richard Smith8e1cee62012-10-25 02:14:12 +00002127 llvm::ArrayRef<llvm::Value *> DynamicArgs,
2128 bool Recoverable) {
Richard Smith7ac9ef12012-09-08 02:08:36 +00002129 llvm::BasicBlock *Cont = createBasicBlock("cont");
2130
Richard Smith4def70d2012-10-09 19:52:38 +00002131 // If -fcatch-undefined-behavior is not enabled, just emit a trap. This
2132 // happens when using -ftrapv.
2133 // FIXME: Should -ftrapv require the ubsan runtime library?
2134 if (!CatchUndefined) {
2135 // If we're optimizing, collapse all calls to trap down to just one per
2136 // function to save on code size.
2137 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2138 TrapBB = createBasicBlock("trap");
2139 Builder.CreateCondBr(Checked, Cont, TrapBB);
2140 EmitBlock(TrapBB);
2141 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
2142 llvm::CallInst *TrapCall = Builder.CreateCall(F);
2143 TrapCall->setDoesNotReturn();
2144 TrapCall->setDoesNotThrow();
2145 Builder.CreateUnreachable();
2146 } else {
2147 Builder.CreateCondBr(Checked, Cont, TrapBB);
2148 }
Mike Stump9c276ae2009-12-12 01:27:46 +00002149
Richard Smith4def70d2012-10-09 19:52:38 +00002150 EmitBlock(Cont);
2151 return;
Mike Stump9c276ae2009-12-12 01:27:46 +00002152 }
Mike Stump15037ca2009-12-15 00:35:12 +00002153
Richard Smith4def70d2012-10-09 19:52:38 +00002154 llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
2155 Builder.CreateCondBr(Checked, Cont, Handler);
2156 EmitBlock(Handler);
2157
2158 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2159 llvm::GlobalValue *InfoPtr =
2160 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), true,
2161 llvm::GlobalVariable::PrivateLinkage, Info);
2162 InfoPtr->setUnnamedAddr(true);
2163
2164 llvm::SmallVector<llvm::Value *, 4> Args;
2165 llvm::SmallVector<llvm::Type *, 4> ArgTypes;
2166 Args.reserve(DynamicArgs.size() + 1);
2167 ArgTypes.reserve(DynamicArgs.size() + 1);
2168
2169 // Handler functions take an i8* pointing to the (handler-specific) static
2170 // information block, followed by a sequence of intptr_t arguments
2171 // representing operand values.
2172 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2173 ArgTypes.push_back(Int8PtrTy);
2174 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2175 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2176 ArgTypes.push_back(IntPtrTy);
2177 }
2178
2179 llvm::FunctionType *FnType =
2180 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Bill Wendling0d583392012-10-15 20:36:26 +00002181 llvm::AttrBuilder B;
Richard Smith8e1cee62012-10-25 02:14:12 +00002182 if (!Recoverable) {
2183 B.addAttribute(llvm::Attributes::NoReturn)
2184 .addAttribute(llvm::Attributes::NoUnwind);
2185 }
2186 B.addAttribute(llvm::Attributes::UWTable);
Richard Smith4def70d2012-10-09 19:52:38 +00002187 llvm::Value *Fn = CGM.CreateRuntimeFunction(FnType,
2188 ("__ubsan_handle_" + CheckName).str(),
Bill Wendling50e6b182012-10-15 04:47:45 +00002189 llvm::Attributes::get(getLLVMContext(),
2190 B));
Richard Smith4def70d2012-10-09 19:52:38 +00002191 llvm::CallInst *HandlerCall = Builder.CreateCall(Fn, Args);
Richard Smith8e1cee62012-10-25 02:14:12 +00002192 if (Recoverable) {
2193 Builder.CreateBr(Cont);
2194 } else {
2195 HandlerCall->setDoesNotReturn();
2196 HandlerCall->setDoesNotThrow();
2197 Builder.CreateUnreachable();
2198 }
Richard Smith4def70d2012-10-09 19:52:38 +00002199
Richard Smith7ac9ef12012-09-08 02:08:36 +00002200 EmitBlock(Cont);
Mike Stump9c276ae2009-12-12 01:27:46 +00002201}
2202
Chris Lattner9269d5c2010-06-26 23:03:20 +00002203/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2204/// array to pointer, return the array subexpression.
2205static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2206 // If this isn't just an array->pointer decay, bail out.
2207 const CastExpr *CE = dyn_cast<CastExpr>(E);
John McCall2de56d12010-08-25 11:45:40 +00002208 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
Chris Lattner9269d5c2010-06-26 23:03:20 +00002209 return 0;
2210
2211 // If this is a decay from variable width array, bail out.
2212 const Expr *SubExpr = CE->getSubExpr();
2213 if (SubExpr->getType()->isVariableArrayType())
2214 return 0;
2215
2216 return SubExpr;
2217}
2218
Reid Spencer5f016e22007-07-11 17:01:13 +00002219LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenek23245122007-08-20 16:18:38 +00002220 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner7f02f722007-08-24 05:35:26 +00002221 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman61d004a2009-06-06 19:09:26 +00002222 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor575a1c92011-05-20 16:38:50 +00002223 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman61d004a2009-06-06 19:09:26 +00002224
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 // If the base is a vector type, then we are forming a vector element lvalue
2226 // with this subscript.
Eli Friedman1e692ac2008-06-13 23:01:12 +00002227 if (E->getBase()->getType()->isVectorType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002228 // Emit the vector as an lvalue to get its address.
Eli Friedman1e692ac2008-06-13 23:01:12 +00002229 LValue LHS = EmitLValue(E->getBase());
Ted Kremenek23245122007-08-20 16:18:38 +00002230 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
John McCalld16c2cf2011-02-08 08:22:06 +00002231 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
Eli Friedman1e692ac2008-06-13 23:01:12 +00002232 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
Eli Friedmane5a8aeb2012-03-22 22:36:39 +00002233 E->getBase()->getType(), LHS.getAlignment());
Reid Spencer5f016e22007-07-11 17:01:13 +00002234 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002235
Ted Kremenek23245122007-08-20 16:18:38 +00002236 // Extend or truncate the index type to 32 or 64-bits.
John McCall5936e332011-02-15 09:22:45 +00002237 if (Idx->getType() != IntPtrTy)
2238 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stump9c276ae2009-12-12 01:27:46 +00002239
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002240 // We know that the pointer points to a type of the correct size, unless the
2241 // size is a VLA or Objective-C interface.
Daniel Dunbar2a866252009-04-25 05:08:32 +00002242 llvm::Value *Address = 0;
Eli Friedman6da2c712011-12-03 04:14:32 +00002243 CharUnits ArrayAlignment;
John McCallbc8d40d2011-06-24 21:55:10 +00002244 if (const VariableArrayType *vla =
Anders Carlsson8b33c082008-12-21 00:11:23 +00002245 getContext().getAsVariableArrayType(E->getType())) {
John McCallbc8d40d2011-06-24 21:55:10 +00002246 // The base must be a pointer, which is not an aggregate. Emit
2247 // it. It needs to be emitted first in case it's what captures
2248 // the VLA bounds.
2249 Address = EmitScalarExpr(E->getBase());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002250
John McCallbc8d40d2011-06-24 21:55:10 +00002251 // The element count here is the total number of non-VLA elements.
2252 llvm::Value *numElements = getVLASize(vla).first;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002253
John McCall913dab22011-06-25 01:32:37 +00002254 // Effectively, the multiply by the VLA size is part of the GEP.
2255 // GEP indexes are signed, and scaling an index isn't permitted to
2256 // signed-overflow, so we use the same semantics for our explicit
2257 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +00002258 if (getLangOpts().isSignedOverflowDefined()) {
John McCall913dab22011-06-25 01:32:37 +00002259 Idx = Builder.CreateMul(Idx, numElements);
Chris Lattner2cb42222011-03-01 00:03:48 +00002260 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
John McCall913dab22011-06-25 01:32:37 +00002261 } else {
2262 Idx = Builder.CreateNSWMul(Idx, numElements);
Chris Lattner2cb42222011-03-01 00:03:48 +00002263 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
John McCall913dab22011-06-25 01:32:37 +00002264 }
Chris Lattner9269d5c2010-06-26 23:03:20 +00002265 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2266 // Indexing over an interface, as in "NSString *P; P[4];"
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002267 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00002268 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00002269 getContext().getTypeSizeInChars(OIT).getQuantity());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002270
Daniel Dunbar2a866252009-04-25 05:08:32 +00002271 Idx = Builder.CreateMul(Idx, InterfaceSize);
2272
Chris Lattner9269d5c2010-06-26 23:03:20 +00002273 // The base must be a pointer, which is not an aggregate. Emit it.
2274 llvm::Value *Base = EmitScalarExpr(E->getBase());
John McCalld16c2cf2011-02-08 08:22:06 +00002275 Address = EmitCastToVoidPtr(Base);
2276 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002277 Address = Builder.CreateBitCast(Address, Base->getType());
Chris Lattner9269d5c2010-06-26 23:03:20 +00002278 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2279 // If this is A[i] where A is an array, the frontend will have decayed the
2280 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2281 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2282 // "gep x, i" here. Emit one "gep A, 0, i".
2283 assert(Array->getType()->isArrayType() &&
2284 "Array to pointer decay must have array source type!");
Daniel Dunbard5534082011-04-01 00:49:43 +00002285 LValue ArrayLV = EmitLValue(Array);
2286 llvm::Value *ArrayPtr = ArrayLV.getAddress();
Chris Lattner9269d5c2010-06-26 23:03:20 +00002287 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2288 llvm::Value *Args[] = { Zero, Idx };
2289
Daniel Dunbard5534082011-04-01 00:49:43 +00002290 // Propagate the alignment from the array itself to the result.
2291 ArrayAlignment = ArrayLV.getAlignment();
2292
David Blaikie4e4d0842012-03-11 07:00:24 +00002293 if (getContext().getLangOpts().isSignedOverflowDefined())
Jay Foad0f6ac7c2011-07-22 08:16:57 +00002294 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Chris Lattner2cb42222011-03-01 00:03:48 +00002295 else
Jay Foad0f6ac7c2011-07-22 08:16:57 +00002296 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002297 } else {
Chris Lattner9269d5c2010-06-26 23:03:20 +00002298 // The base must be a pointer, which is not an aggregate. Emit it.
2299 llvm::Value *Base = EmitScalarExpr(E->getBase());
David Blaikie4e4d0842012-03-11 07:00:24 +00002300 if (getContext().getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00002301 Address = Builder.CreateGEP(Base, Idx, "arrayidx");
2302 else
2303 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
Anders Carlsson8b33c082008-12-21 00:11:23 +00002304 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002305
Steve Naroff14108da2009-07-10 23:34:53 +00002306 QualType T = E->getBase()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002307 assert(!T.isNull() &&
Steve Naroff14108da2009-07-10 23:34:53 +00002308 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002309
Chris Lattner44a23992012-01-04 22:35:55 +00002310
Daniel Dunbard5534082011-04-01 00:49:43 +00002311 // Limit the alignment to that of the result type.
Chris Lattner44a23992012-01-04 22:35:55 +00002312 LValue LV;
Eli Friedman6da2c712011-12-03 04:14:32 +00002313 if (!ArrayAlignment.isZero()) {
2314 CharUnits Align = getContext().getTypeAlignInChars(T);
Daniel Dunbard5534082011-04-01 00:49:43 +00002315 ArrayAlignment = std::min(Align, ArrayAlignment);
Chris Lattner44a23992012-01-04 22:35:55 +00002316 LV = MakeAddrLValue(Address, T, ArrayAlignment);
2317 } else {
2318 LV = MakeNaturalAlignAddrLValue(Address, T);
Daniel Dunbard5534082011-04-01 00:49:43 +00002319 }
2320
Daniel Dunbar6d5eb762010-08-21 03:44:13 +00002321 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
John McCall0953e762009-09-24 19:53:00 +00002322
David Blaikie4e4d0842012-03-11 07:00:24 +00002323 if (getContext().getLangOpts().ObjC1 &&
2324 getContext().getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbarea619172010-08-21 03:22:38 +00002325 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahanianb123ea32009-09-16 21:37:16 +00002326 setObjCGCLValueClass(getContext(), E, LV);
2327 }
Fariborz Jahanian643887a2009-02-21 23:37:19 +00002328 return LV;
Reid Spencer5f016e22007-07-11 17:01:13 +00002329}
2330
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002331static
NAKAMURA Takumiedf5a7b2012-01-25 08:58:21 +00002332llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002333 SmallVector<unsigned, 4> &Elts) {
2334 SmallVector<llvm::Constant*, 4> CElts;
Nate Begeman3b8d1162008-05-13 21:03:02 +00002335 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
Chris Lattner2ce88422012-01-25 05:34:41 +00002336 CElts.push_back(Builder.getInt32(Elts[i]));
Nate Begeman3b8d1162008-05-13 21:03:02 +00002337
Chris Lattnerfb018d12011-02-15 00:14:06 +00002338 return llvm::ConstantVector::get(CElts);
Nate Begeman3b8d1162008-05-13 21:03:02 +00002339}
2340
Chris Lattner349aaec2007-08-02 23:37:31 +00002341LValue CodeGenFunction::
Nate Begeman213541a2008-04-18 23:10:10 +00002342EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner349aaec2007-08-02 23:37:31 +00002343 // Emit the base vector as an l-value.
Chris Lattner73525de2009-02-16 21:11:58 +00002344 LValue Base;
2345
2346 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner998eab12009-12-23 21:31:11 +00002347 if (E->isArrow()) {
2348 // If it is a pointer to a vector, emit the address and form an lvalue with
2349 // it.
Chris Lattner2140e902009-02-16 22:14:05 +00002350 llvm::Value *Ptr = EmitScalarExpr(E->getBase());
Chris Lattner998eab12009-12-23 21:31:11 +00002351 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Daniel Dunbar6d5eb762010-08-21 03:44:13 +00002352 Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2353 Base.getQuals().removeObjCGCAttr();
John McCall7eb0a9e2010-11-24 05:12:34 +00002354 } else if (E->getBase()->isGLValue()) {
Chris Lattner998eab12009-12-23 21:31:11 +00002355 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2356 // emit the base as an lvalue.
2357 assert(E->getBase()->getType()->isVectorType());
2358 Base = EmitLValue(E->getBase());
2359 } else {
2360 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCalla07398e2011-06-16 04:16:24 +00002361 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar302c3c22010-01-04 18:02:28 +00002362 "Result must be a vector");
Chris Lattner998eab12009-12-23 21:31:11 +00002363 llvm::Value *Vec = EmitScalarExpr(E->getBase());
2364
Chris Lattner0ad57fb2009-12-23 21:33:41 +00002365 // Store the vector to memory (because LValue wants an address).
Daniel Dunbar195337d2010-02-09 02:48:28 +00002366 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner998eab12009-12-23 21:31:11 +00002367 Builder.CreateStore(Vec, VecMem);
Daniel Dunbar6d5eb762010-08-21 03:44:13 +00002368 Base = MakeAddrLValue(VecMem, E->getBase()->getType());
Chris Lattner998eab12009-12-23 21:31:11 +00002369 }
John McCalla07398e2011-06-16 04:16:24 +00002370
2371 QualType type =
2372 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Chris Lattner998eab12009-12-23 21:31:11 +00002373
Nate Begeman3b8d1162008-05-13 21:03:02 +00002374 // Encode the element access list into a vector of unsigned indices.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002375 SmallVector<unsigned, 4> Indices;
Nate Begeman3b8d1162008-05-13 21:03:02 +00002376 E->getEncodedElementAccess(Indices);
2377
2378 if (Base.isSimple()) {
Chris Lattner2ce88422012-01-25 05:34:41 +00002379 llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
Eli Friedmane5a8aeb2012-03-22 22:36:39 +00002380 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2381 Base.getAlignment());
Nate Begeman3b8d1162008-05-13 21:03:02 +00002382 }
2383 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2384
2385 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002386 SmallVector<llvm::Constant *, 4> CElts;
Nate Begeman3b8d1162008-05-13 21:03:02 +00002387
Chris Lattner89f42832012-01-30 06:20:36 +00002388 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2389 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattnerfb018d12011-02-15 00:14:06 +00002390 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
Eli Friedmane5a8aeb2012-03-22 22:36:39 +00002391 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2392 Base.getAlignment());
Chris Lattner349aaec2007-08-02 23:37:31 +00002393}
2394
Devang Patelb9b00ad2007-10-23 20:28:39 +00002395LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Patel126a8562007-10-24 22:26:28 +00002396 Expr *BaseExpr = E->getBase();
Eli Friedman1e692ac2008-06-13 23:01:12 +00002397
Chris Lattner12f65f62007-12-02 18:52:07 +00002398 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
Eli Friedman377ecc72012-04-16 03:54:45 +00002399 LValue BaseLV;
Richard Smith2c9f87c2012-08-24 00:54:33 +00002400 if (E->isArrow()) {
2401 llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
2402 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Richard Smith4def70d2012-10-09 19:52:38 +00002403 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
Richard Smith2c9f87c2012-08-24 00:54:33 +00002404 BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
2405 } else
Richard Smith7ac9ef12012-09-08 02:08:36 +00002406 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patelb9b00ad2007-10-23 20:28:39 +00002407
Anders Carlssonce53f7d2009-11-07 23:06:58 +00002408 NamedDecl *ND = E->getMemberDecl();
2409 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman377ecc72012-04-16 03:54:45 +00002410 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonce53f7d2009-11-07 23:06:58 +00002411 setObjCGCLValueClass(getContext(), E, LV);
2412 return LV;
2413 }
2414
Anders Carlsson589f9e32009-11-07 23:16:50 +00002415 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
2416 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedman9a146302009-11-26 06:08:14 +00002417
2418 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
2419 return EmitFunctionDeclLValue(*this, E, FD);
2420
David Blaikieb219cfc2011-09-23 05:06:16 +00002421 llvm_unreachable("Unhandled member declaration!");
Eli Friedman472778e2008-02-09 08:50:58 +00002422}
Devang Patelb9b00ad2007-10-23 20:28:39 +00002423
Eli Friedman377ecc72012-04-16 03:54:45 +00002424LValue CodeGenFunction::EmitLValueForField(LValue base,
2425 const FieldDecl *field) {
Eli Friedmanf4bcfa12012-06-27 21:19:48 +00002426 if (field->isBitField()) {
2427 const CGRecordLayout &RL =
2428 CGM.getTypes().getCGRecordLayout(field->getParent());
2429 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
2430 QualType fieldType =
2431 field->getType().withCVRQualifiers(base.getVRQualifiers());
2432 return LValue::MakeBitfield(base.getAddress(), Info, fieldType,
2433 base.getAlignment());
2434 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002435
John McCallbc7fbf02011-02-26 08:07:02 +00002436 const RecordDecl *rec = field->getParent();
2437 QualType type = field->getType();
Eli Friedman6da2c712011-12-03 04:14:32 +00002438 CharUnits alignment = getContext().getDeclAlign(field);
Eli Friedman1e86b342008-05-29 11:33:25 +00002439
Eli Friedman377ecc72012-04-16 03:54:45 +00002440 // FIXME: It should be impossible to have an LValue without alignment for a
2441 // complete type.
2442 if (!base.getAlignment().isZero())
2443 alignment = std::min(alignment, base.getAlignment());
2444
John McCallbc7fbf02011-02-26 08:07:02 +00002445 bool mayAlias = rec->hasAttr<MayAliasAttr>();
2446
Eli Friedman377ecc72012-04-16 03:54:45 +00002447 llvm::Value *addr = base.getAddress();
2448 unsigned cvr = base.getVRQualifiers();
John McCallbc7fbf02011-02-26 08:07:02 +00002449 if (rec->isUnion()) {
Chris Lattner74339df2011-07-10 05:34:54 +00002450 // For unions, there is no pointer adjustment.
John McCallbc7fbf02011-02-26 08:07:02 +00002451 assert(!type->isReferenceType() && "union has reference member");
John McCallbc7fbf02011-02-26 08:07:02 +00002452 } else {
2453 // For structs, we GEP to the field that the record layout suggests.
2454 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
Chris Lattner74339df2011-07-10 05:34:54 +00002455 addr = Builder.CreateStructGEP(addr, idx, field->getName());
John McCallbc7fbf02011-02-26 08:07:02 +00002456
2457 // If this is a reference field, load the reference right now.
2458 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2459 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2460 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
Eli Friedman6da2c712011-12-03 04:14:32 +00002461 load->setAlignment(alignment.getQuantity());
John McCallbc7fbf02011-02-26 08:07:02 +00002462
2463 if (CGM.shouldUseTBAA()) {
2464 llvm::MDNode *tbaa;
2465 if (mayAlias)
2466 tbaa = CGM.getTBAAInfo(getContext().CharTy);
2467 else
2468 tbaa = CGM.getTBAAInfo(type);
2469 CGM.DecorateInstruction(load, tbaa);
2470 }
2471
2472 addr = load;
2473 mayAlias = false;
2474 type = refType->getPointeeType();
Eli Friedman2f77b3d2011-11-16 00:42:57 +00002475 if (type->isIncompleteType())
Eli Friedman6da2c712011-12-03 04:14:32 +00002476 alignment = CharUnits();
Eli Friedman2f77b3d2011-11-16 00:42:57 +00002477 else
Eli Friedman6da2c712011-12-03 04:14:32 +00002478 alignment = getContext().getTypeAlignInChars(type);
John McCallbc7fbf02011-02-26 08:07:02 +00002479 cvr = 0; // qualifiers don't recursively apply to referencee
2480 }
Devang Patelabad06c2007-10-26 19:42:18 +00002481 }
Chris Lattner74339df2011-07-10 05:34:54 +00002482
2483 // Make sure that the address is pointing to the right type. This is critical
2484 // for both unions and structs. A union needs a bitcast, a struct element
2485 // will need a bitcast if the LLVM type laid out doesn't match the desired
2486 // type.
Chandler Carrutha98742c2011-07-12 08:58:26 +00002487 addr = EmitBitCastOfLValueToProperType(*this, addr,
Chris Lattner3a2b6572011-07-12 06:52:18 +00002488 CGM.getTypes().ConvertTypeForMem(type),
2489 field->getName());
John McCall0953e762009-09-24 19:53:00 +00002490
Julien Lerouge77f68bb2011-09-09 22:41:49 +00002491 if (field->hasAttr<AnnotateAttr>())
2492 addr = EmitFieldAnnotations(field, addr);
2493
John McCallbc7fbf02011-02-26 08:07:02 +00002494 LValue LV = MakeAddrLValue(addr, type, alignment);
2495 LV.getQuals().addCVRQualifiers(cvr);
Daniel Dunbar6d5eb762010-08-21 03:44:13 +00002496
Fariborz Jahanianfd02ed72009-09-21 18:54:29 +00002497 // __weak attribute on a field is ignored.
Daniel Dunbar6d5eb762010-08-21 03:44:13 +00002498 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2499 LV.getQuals().removeObjCGCAttr();
John McCallbc7fbf02011-02-26 08:07:02 +00002500
2501 // Fields of may_alias structs act like 'char' for TBAA purposes.
2502 // FIXME: this should get propagated down through anonymous structs
2503 // and unions.
2504 if (mayAlias && LV.getTBAAInfo())
2505 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2506
Daniel Dunbar6d5eb762010-08-21 03:44:13 +00002507 return LV;
Devang Patelb9b00ad2007-10-23 20:28:39 +00002508}
2509
Anders Carlsson06a29702010-01-29 05:24:29 +00002510LValue
Eli Friedman377ecc72012-04-16 03:54:45 +00002511CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2512 const FieldDecl *Field) {
Anders Carlsson06a29702010-01-29 05:24:29 +00002513 QualType FieldType = Field->getType();
2514
2515 if (!FieldType->isReferenceType())
Eli Friedman377ecc72012-04-16 03:54:45 +00002516 return EmitLValueForField(Base, Field);
Anders Carlsson06a29702010-01-29 05:24:29 +00002517
Daniel Dunbar198bcb42010-03-31 01:09:11 +00002518 const CGRecordLayout &RL =
2519 CGM.getTypes().getCGRecordLayout(Field->getParent());
2520 unsigned idx = RL.getLLVMFieldNo(Field);
Eli Friedman377ecc72012-04-16 03:54:45 +00002521 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
Anders Carlsson06a29702010-01-29 05:24:29 +00002522 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2523
Chris Lattner1b5ba852011-07-10 05:53:24 +00002524 // Make sure that the address is pointing to the right type. This is critical
2525 // for both unions and structs. A union needs a bitcast, a struct element
2526 // will need a bitcast if the LLVM type laid out doesn't match the desired
2527 // type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002528 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
Eli Friedman377ecc72012-04-16 03:54:45 +00002529 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2530
Eli Friedman6da2c712011-12-03 04:14:32 +00002531 CharUnits Alignment = getContext().getDeclAlign(Field);
Eli Friedman377ecc72012-04-16 03:54:45 +00002532
2533 // FIXME: It should be impossible to have an LValue without alignment for a
2534 // complete type.
2535 if (!Base.getAlignment().isZero())
2536 Alignment = std::min(Alignment, Base.getAlignment());
2537
Daniel Dunbar983e3d72010-08-21 04:20:22 +00002538 return MakeAddrLValue(V, FieldType, Alignment);
Anders Carlsson06a29702010-01-29 05:24:29 +00002539}
2540
Chris Lattnerd0db03a2010-09-06 00:11:41 +00002541LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith7401cf52011-11-22 22:48:32 +00002542 if (E->isFileScope()) {
2543 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2544 return MakeAddrLValue(GlobalPtr, E->getType());
2545 }
Fariborz Jahanianec22f562012-06-07 18:15:55 +00002546 if (E->getType()->isVariablyModifiedType())
2547 // make sure to emit the VLA size.
2548 EmitVariablyModifiedType(E->getType());
Fariborz Jahanian2ccc0f92012-06-07 17:07:15 +00002549
Daniel Dunbar15006572010-02-16 19:43:39 +00002550 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerd0db03a2010-09-06 00:11:41 +00002551 const Expr *InitExpr = E->getInitializer();
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002552 LValue Result = MakeAddrLValue(DeclPtr, E->getType());
Eli Friedman06e863f2008-05-13 23:18:27 +00002553
Chad Rosier649b4a12012-03-29 17:37:10 +00002554 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2555 /*Init*/ true);
Eli Friedman06e863f2008-05-13 23:18:27 +00002556
2557 return Result;
2558}
2559
Richard Smith13ec9102012-05-14 21:57:21 +00002560LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2561 if (!E->isGLValue())
2562 // Initializing an aggregate temporary in C++11: T{...}.
2563 return EmitAggExprToLValue(E);
2564
2565 // An lvalue initializer list must be initializing a reference.
2566 assert(E->getNumInits() == 1 && "reference init with multiple values");
2567 return EmitLValue(E->getInit(0));
2568}
2569
John McCall56ca35d2011-02-17 10:25:35 +00002570LValue CodeGenFunction::
2571EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2572 if (!expr->isGLValue()) {
John McCallf99a3912011-01-26 19:21:13 +00002573 // ?: here should be an aggregate.
John McCall56ca35d2011-02-17 10:25:35 +00002574 assert((hasAggregateLLVMType(expr->getType()) &&
2575 !expr->getType()->isAnyComplexType()) &&
John McCallf99a3912011-01-26 19:21:13 +00002576 "Unexpected conditional operator!");
John McCall56ca35d2011-02-17 10:25:35 +00002577 return EmitAggExprToLValue(expr);
Anders Carlsson6fcec8b2009-09-15 16:35:24 +00002578 }
Daniel Dunbar90345582009-03-24 02:38:23 +00002579
Eli Friedman2c0c7452012-01-25 05:04:17 +00002580 OpaqueValueMapping binding(*this, expr);
2581
John McCall56ca35d2011-02-17 10:25:35 +00002582 const Expr *condExpr = expr->getCond();
Chris Lattnerc2c90012011-02-27 23:02:32 +00002583 bool CondExprBool;
2584 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002585 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattnerc2c90012011-02-27 23:02:32 +00002586 if (!CondExprBool) std::swap(live, dead);
John McCall56ca35d2011-02-17 10:25:35 +00002587
2588 if (!ContainsLabel(dead))
2589 return EmitLValue(live);
John McCallf99a3912011-01-26 19:21:13 +00002590 }
2591
John McCall56ca35d2011-02-17 10:25:35 +00002592 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2593 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2594 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCallf99a3912011-01-26 19:21:13 +00002595
2596 ConditionalEvaluation eval(*this);
John McCall56ca35d2011-02-17 10:25:35 +00002597 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
John McCallf99a3912011-01-26 19:21:13 +00002598
2599 // Any temporaries created here are conditional.
John McCall56ca35d2011-02-17 10:25:35 +00002600 EmitBlock(lhsBlock);
John McCallf99a3912011-01-26 19:21:13 +00002601 eval.begin(*this);
John McCall56ca35d2011-02-17 10:25:35 +00002602 LValue lhs = EmitLValue(expr->getTrueExpr());
John McCallf99a3912011-01-26 19:21:13 +00002603 eval.end(*this);
2604
John McCall56ca35d2011-02-17 10:25:35 +00002605 if (!lhs.isSimple())
2606 return EmitUnsupportedLValue(expr, "conditional operator");
John McCallf99a3912011-01-26 19:21:13 +00002607
John McCall56ca35d2011-02-17 10:25:35 +00002608 lhsBlock = Builder.GetInsertBlock();
2609 Builder.CreateBr(contBlock);
John McCallf99a3912011-01-26 19:21:13 +00002610
2611 // Any temporaries created here are conditional.
John McCall56ca35d2011-02-17 10:25:35 +00002612 EmitBlock(rhsBlock);
John McCallf99a3912011-01-26 19:21:13 +00002613 eval.begin(*this);
John McCall56ca35d2011-02-17 10:25:35 +00002614 LValue rhs = EmitLValue(expr->getFalseExpr());
John McCallf99a3912011-01-26 19:21:13 +00002615 eval.end(*this);
John McCall56ca35d2011-02-17 10:25:35 +00002616 if (!rhs.isSimple())
2617 return EmitUnsupportedLValue(expr, "conditional operator");
2618 rhsBlock = Builder.GetInsertBlock();
John McCallf99a3912011-01-26 19:21:13 +00002619
John McCall56ca35d2011-02-17 10:25:35 +00002620 EmitBlock(contBlock);
John McCallf99a3912011-01-26 19:21:13 +00002621
Jay Foadbbf3bac2011-03-30 11:28:58 +00002622 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
John McCallf99a3912011-01-26 19:21:13 +00002623 "cond-lvalue");
John McCall56ca35d2011-02-17 10:25:35 +00002624 phi->addIncoming(lhs.getAddress(), lhsBlock);
2625 phi->addIncoming(rhs.getAddress(), rhsBlock);
2626 return MakeAddrLValue(phi, expr->getType());
Daniel Dunbar90345582009-03-24 02:38:23 +00002627}
2628
Richard Smith13ec9102012-05-14 21:57:21 +00002629/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2630/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stumpc849c052009-11-16 06:50:58 +00002631/// otherwise if a cast is needed by the code generator in an lvalue context,
2632/// then it must mean that we need the address of an aggregate in order to
Richard Smith13ec9102012-05-14 21:57:21 +00002633/// access one of its members. This can happen for all the reasons that casts
Mike Stumpc849c052009-11-16 06:50:58 +00002634/// are permitted with aggregate result, including noop aggregate casts, and
2635/// cast from scalar to union.
Chris Lattner75dfeda2009-03-18 18:28:57 +00002636LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlsson0ee33cf2009-09-12 16:16:49 +00002637 switch (E->getCastKind()) {
John McCall2de56d12010-08-25 11:45:40 +00002638 case CK_ToVoid:
Eli Friedmaneaae78a2009-11-16 05:48:01 +00002639 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
John McCalldaa8e4e2010-11-15 09:13:47 +00002640
2641 case CK_Dependent:
2642 llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002643
2644 case CK_BuiltinFnToFnPtr:
2645 llvm_unreachable("builtin functions are handled elsewhere");
2646
David Chisnall7a7ee302012-01-16 17:27:18 +00002647 // These two casts are currently treated as no-ops, although they could
2648 // potentially be real operations depending on the target's ABI.
2649 case CK_NonAtomicToAtomic:
2650 case CK_AtomicToNonAtomic:
John McCalldaa8e4e2010-11-15 09:13:47 +00002651
John McCall2de56d12010-08-25 11:45:40 +00002652 case CK_NoOp:
Douglas Gregorb3d5e2f2011-01-27 23:22:05 +00002653 case CK_LValueToRValue:
2654 if (!E->getSubExpr()->Classify(getContext()).isPRValue()
2655 || E->getType()->isRecordType())
John McCall0e800c92010-12-04 08:14:53 +00002656 return EmitLValue(E->getSubExpr());
Douglas Gregor7c7a7932010-07-15 18:58:16 +00002657 // Fall through to synthesize a temporary.
John McCalldaa8e4e2010-11-15 09:13:47 +00002658
John McCall2de56d12010-08-25 11:45:40 +00002659 case CK_BitCast:
2660 case CK_ArrayToPointerDecay:
2661 case CK_FunctionToPointerDecay:
2662 case CK_NullToMemberPointer:
John McCall404cd162010-11-13 01:35:44 +00002663 case CK_NullToPointer:
John McCall2de56d12010-08-25 11:45:40 +00002664 case CK_IntegralToPointer:
2665 case CK_PointerToIntegral:
John McCalldaa8e4e2010-11-15 09:13:47 +00002666 case CK_PointerToBoolean:
John McCall2de56d12010-08-25 11:45:40 +00002667 case CK_VectorSplat:
2668 case CK_IntegralCast:
John McCalldaa8e4e2010-11-15 09:13:47 +00002669 case CK_IntegralToBoolean:
John McCall2de56d12010-08-25 11:45:40 +00002670 case CK_IntegralToFloating:
2671 case CK_FloatingToIntegral:
John McCalldaa8e4e2010-11-15 09:13:47 +00002672 case CK_FloatingToBoolean:
John McCall2de56d12010-08-25 11:45:40 +00002673 case CK_FloatingCast:
John McCall2bb5d002010-11-13 09:02:35 +00002674 case CK_FloatingRealToComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00002675 case CK_FloatingComplexToReal:
2676 case CK_FloatingComplexToBoolean:
John McCall2bb5d002010-11-13 09:02:35 +00002677 case CK_FloatingComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00002678 case CK_FloatingComplexToIntegralComplex:
John McCall2bb5d002010-11-13 09:02:35 +00002679 case CK_IntegralRealToComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00002680 case CK_IntegralComplexToReal:
2681 case CK_IntegralComplexToBoolean:
John McCall2bb5d002010-11-13 09:02:35 +00002682 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00002683 case CK_IntegralComplexToFloatingComplex:
John McCall2de56d12010-08-25 11:45:40 +00002684 case CK_DerivedToBaseMemberPointer:
2685 case CK_BaseToDerivedMemberPointer:
2686 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00002687 case CK_ReinterpretMemberPointer:
John McCallf85e1932011-06-15 23:02:42 +00002688 case CK_AnyPointerToBlockPointerCast:
John McCall33e56f32011-09-10 06:18:15 +00002689 case CK_ARCProduceObject:
2690 case CK_ARCConsumeObject:
2691 case CK_ARCReclaimReturnedObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00002692 case CK_ARCExtendBlockObject:
2693 case CK_CopyAndAutoreleaseBlockObject: {
Douglas Gregor7c7a7932010-07-15 18:58:16 +00002694 // These casts only produce lvalues when we're binding a reference to a
2695 // temporary realized from a (converted) pure rvalue. Emit the expression
2696 // as a value, copy it into a temporary, and return an lvalue referring to
2697 // that temporary.
2698 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
Chad Rosier649b4a12012-03-29 17:37:10 +00002699 EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002700 return MakeAddrLValue(V, E->getType());
Douglas Gregor7c7a7932010-07-15 18:58:16 +00002701 }
Eli Friedmaneaae78a2009-11-16 05:48:01 +00002702
Anders Carlsson575b3742011-04-11 02:03:26 +00002703 case CK_Dynamic: {
Mike Stumpc849c052009-11-16 06:50:58 +00002704 LValue LV = EmitLValue(E->getSubExpr());
2705 llvm::Value *V = LV.getAddress();
2706 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002707 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stumpc849c052009-11-16 06:50:58 +00002708 }
2709
John McCall2de56d12010-08-25 11:45:40 +00002710 case CK_ConstructorConversion:
2711 case CK_UserDefinedConversion:
John McCall1d9b3b22011-09-09 05:25:32 +00002712 case CK_CPointerToObjCPointerCast:
2713 case CK_BlockPointerToObjCPointerCast:
Chris Lattner75dfeda2009-03-18 18:28:57 +00002714 return EmitLValue(E->getSubExpr());
Anders Carlsson0ee33cf2009-09-12 16:16:49 +00002715
John McCall2de56d12010-08-25 11:45:40 +00002716 case CK_UncheckedDerivedToBase:
2717 case CK_DerivedToBase: {
Anders Carlsson0ee33cf2009-09-12 16:16:49 +00002718 const RecordType *DerivedClassTy =
2719 E->getSubExpr()->getType()->getAs<RecordType>();
2720 CXXRecordDecl *DerivedClassDecl =
2721 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Anders Carlsson0ee33cf2009-09-12 16:16:49 +00002722
2723 LValue LV = EmitLValue(E->getSubExpr());
John McCall0e800c92010-12-04 08:14:53 +00002724 llvm::Value *This = LV.getAddress();
Anders Carlsson0ee33cf2009-09-12 16:16:49 +00002725
2726 // Perform the derived-to-base conversion
2727 llvm::Value *Base =
Fariborz Jahanian353b33b2010-06-17 23:00:29 +00002728 GetAddressOfBaseClass(This, DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00002729 E->path_begin(), E->path_end(),
2730 /*NullCheckValue=*/false);
Anders Carlsson0ee33cf2009-09-12 16:16:49 +00002731
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002732 return MakeAddrLValue(Base, E->getType());
Anders Carlsson0ee33cf2009-09-12 16:16:49 +00002733 }
John McCall2de56d12010-08-25 11:45:40 +00002734 case CK_ToUnion:
Daniel Dunbarb2cd7772010-02-05 20:02:42 +00002735 return EmitAggExprToLValue(E);
John McCall2de56d12010-08-25 11:45:40 +00002736 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00002737 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2738 CXXRecordDecl *DerivedClassDecl =
2739 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2740
2741 LValue LV = EmitLValue(E->getSubExpr());
2742
2743 // Perform the base-to-derived conversion
2744 llvm::Value *Derived =
Anders Carlssona04efdf2010-04-24 21:23:59 +00002745 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00002746 E->path_begin(), E->path_end(),
2747 /*NullCheckValue=*/false);
Anders Carlssona3697c92009-11-23 17:57:54 +00002748
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002749 return MakeAddrLValue(Derived, E->getType());
Eli Friedmaneaae78a2009-11-16 05:48:01 +00002750 }
John McCall2de56d12010-08-25 11:45:40 +00002751 case CK_LValueBitCast: {
Eli Friedmaneaae78a2009-11-16 05:48:01 +00002752 // This must be a reinterpret_cast (or c-style equivalent).
2753 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
Anders Carlsson658e8122009-11-14 21:21:42 +00002754
2755 LValue LV = EmitLValue(E->getSubExpr());
2756 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2757 ConvertType(CE->getTypeAsWritten()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002758 return MakeAddrLValue(V, E->getType());
Anders Carlsson658e8122009-11-14 21:21:42 +00002759 }
John McCall2de56d12010-08-25 11:45:40 +00002760 case CK_ObjCObjectLValueCast: {
Douglas Gregor569c3162010-08-07 11:51:51 +00002761 LValue LV = EmitLValue(E->getSubExpr());
2762 QualType ToType = getContext().getLValueReferenceType(E->getType());
2763 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2764 ConvertType(ToType));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002765 return MakeAddrLValue(V, E->getType());
Douglas Gregor569c3162010-08-07 11:51:51 +00002766 }
Anders Carlsson0ee33cf2009-09-12 16:16:49 +00002767 }
Douglas Gregor7c7a7932010-07-15 18:58:16 +00002768
2769 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner75dfeda2009-03-18 18:28:57 +00002770}
2771
Fariborz Jahanian48620ba2009-10-20 23:29:04 +00002772LValue CodeGenFunction::EmitNullInitializationLValue(
Douglas Gregored8abf12010-07-08 06:14:04 +00002773 const CXXScalarValueInitExpr *E) {
Fariborz Jahanian48620ba2009-10-20 23:29:04 +00002774 QualType Ty = E->getType();
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002775 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
Anders Carlsson1884eb02010-05-22 17:35:42 +00002776 EmitNullInitialization(LV.getAddress(), Ty);
Daniel Dunbar195337d2010-02-09 02:48:28 +00002777 return LV;
Fariborz Jahanian48620ba2009-10-20 23:29:04 +00002778}
2779
John McCalle996ffd2011-02-16 08:02:54 +00002780LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCalla5493f82011-11-08 22:54:08 +00002781 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCall56ca35d2011-02-17 10:25:35 +00002782 return getOpaqueLValueMapping(e);
John McCalle996ffd2011-02-16 08:02:54 +00002783}
2784
Douglas Gregor03e80032011-06-21 17:03:29 +00002785LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2786 const MaterializeTemporaryExpr *E) {
John McCallcec52f02011-08-26 21:08:13 +00002787 RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
Douglas Gregor0b581082011-06-21 18:20:46 +00002788 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Douglas Gregor03e80032011-06-21 17:03:29 +00002789}
2790
Eli Friedman377ecc72012-04-16 03:54:45 +00002791RValue CodeGenFunction::EmitRValueForField(LValue LV,
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002792 const FieldDecl *FD) {
2793 QualType FT = FD->getType();
Eli Friedman377ecc72012-04-16 03:54:45 +00002794 LValue FieldLV = EmitLValueForField(LV, FD);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002795 if (FT->isAnyComplexType())
Eli Friedman377ecc72012-04-16 03:54:45 +00002796 return RValue::getComplex(
2797 LoadComplexFromAddr(FieldLV.getAddress(),
2798 FieldLV.isVolatileQualified()));
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002799 else if (CodeGenFunction::hasAggregateLLVMType(FT))
Eli Friedman377ecc72012-04-16 03:54:45 +00002800 return FieldLV.asAggregateRValue();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002801
Eli Friedman377ecc72012-04-16 03:54:45 +00002802 return EmitLoadOfLValue(FieldLV);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002803}
Douglas Gregor03e80032011-06-21 17:03:29 +00002804
Reid Spencer5f016e22007-07-11 17:01:13 +00002805//===--------------------------------------------------------------------===//
2806// Expression Emission
2807//===--------------------------------------------------------------------===//
2808
Anders Carlssond2490a92009-12-24 20:40:36 +00002809RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2810 ReturnValueSlot ReturnValue) {
Eric Christopher73fb3502011-10-13 21:45:18 +00002811 if (CGDebugInfo *DI = getDebugInfo())
2812 DI->EmitLocation(Builder, E->getLocStart());
Devang Patel79bfb4b2011-03-04 18:54:42 +00002813
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00002814 // Builtins never have block type.
Daniel Dunbarce1d38b2009-01-09 16:50:52 +00002815 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssona1736c02009-12-24 21:13:40 +00002816 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarce1d38b2009-01-09 16:50:52 +00002817
Anders Carlsson774e7c62009-04-03 22:50:24 +00002818 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssona1736c02009-12-24 21:13:40 +00002819 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002820
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +00002821 if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E))
2822 return EmitCUDAKernelCallExpr(CE, ReturnValue);
2823
Douglas Gregor1ddc9c42011-09-06 21:41:04 +00002824 const Decl *TargetDecl = E->getCalleeDecl();
2825 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2826 if (unsigned builtinID = FD->getBuiltinID())
2827 return EmitBuiltinExpr(FD, builtinID, E);
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00002828 }
2829
Chris Lattner5db7ae52009-06-13 00:26:38 +00002830 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson0f294632009-05-27 04:18:27 +00002831 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssona1736c02009-12-24 21:13:40 +00002832 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002833
John McCallf85e1932011-06-15 23:02:42 +00002834 if (const CXXPseudoDestructorExpr *PseudoDtor
2835 = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2836 QualType DestroyedType = PseudoDtor->getDestroyedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002837 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002838 DestroyedType->isObjCLifetimeType() &&
2839 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2840 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerd510fd22011-06-18 10:34:00 +00002841 // Automatic Reference Counting:
2842 // If the pseudo-expression names a retainable object with weak or
2843 // strong lifetime, the object shall be released.
John McCallf85e1932011-06-15 23:02:42 +00002844 Expr *BaseExpr = PseudoDtor->getBase();
2845 llvm::Value *BaseValue = NULL;
2846 Qualifiers BaseQuals;
2847
Benjamin Kramerd510fd22011-06-18 10:34:00 +00002848 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
John McCallf85e1932011-06-15 23:02:42 +00002849 if (PseudoDtor->isArrow()) {
2850 BaseValue = EmitScalarExpr(BaseExpr);
2851 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2852 BaseQuals = PTy->getPointeeType().getQualifiers();
2853 } else {
2854 LValue BaseLV = EmitLValue(BaseExpr);
John McCallf85e1932011-06-15 23:02:42 +00002855 BaseValue = BaseLV.getAddress();
2856 QualType BaseTy = BaseExpr->getType();
2857 BaseQuals = BaseTy.getQualifiers();
2858 }
2859
2860 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2861 case Qualifiers::OCL_None:
2862 case Qualifiers::OCL_ExplicitNone:
2863 case Qualifiers::OCL_Autoreleasing:
2864 break;
2865
2866 case Qualifiers::OCL_Strong:
2867 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerd510fd22011-06-18 10:34:00 +00002868 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallf85e1932011-06-15 23:02:42 +00002869 /*precise*/ true);
2870 break;
2871
2872 case Qualifiers::OCL_Weak:
2873 EmitARCDestroyWeak(BaseValue);
2874 break;
2875 }
2876 } else {
2877 // C++ [expr.pseudo]p1:
2878 // The result shall only be used as the operand for the function call
2879 // operator (), and the result of such a call has type void. The only
2880 // effect is the evaluation of the postfix-expression before the dot or
2881 // arrow.
2882 EmitScalarExpr(E->getCallee());
2883 }
2884
Douglas Gregora71d8192009-09-04 17:36:40 +00002885 return RValue::get(0);
2886 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002887
Chris Lattner7f02f722007-08-24 05:35:26 +00002888 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Anders Carlssond2490a92009-12-24 20:40:36 +00002889 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
Anders Carlsson98647712009-05-27 01:22:39 +00002890 E->arg_begin(), E->arg_end(), TargetDecl);
Chris Lattnerc5e940f2007-08-31 04:44:06 +00002891}
2892
Daniel Dunbar80e62c22008-09-04 03:20:13 +00002893LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattner7a574cc2009-05-12 21:28:12 +00002894 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCall2de56d12010-08-25 11:45:40 +00002895 if (E->getOpcode() == BO_Comma) {
John McCall2a416372010-12-05 02:00:02 +00002896 EmitIgnoredExpr(E->getLHS());
Eli Friedman130c69e2009-12-07 20:18:11 +00002897 EnsureInsertPoint();
Chris Lattner7a574cc2009-05-12 21:28:12 +00002898 return EmitLValue(E->getRHS());
2899 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002900
John McCall2de56d12010-08-25 11:45:40 +00002901 if (E->getOpcode() == BO_PtrMemD ||
2902 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +00002903 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar80e62c22008-09-04 03:20:13 +00002904
John McCall2a416372010-12-05 02:00:02 +00002905 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCallf85e1932011-06-15 23:02:42 +00002906
2907 // Note that in all of these cases, __block variables need the RHS
2908 // evaluated first just in case the variable gets moved by the RHS.
John McCall83ce9d42010-11-16 23:07:28 +00002909
Anders Carlsson86aa0cd2009-10-19 18:28:22 +00002910 if (!hasAggregateLLVMType(E->getType())) {
John McCallf85e1932011-06-15 23:02:42 +00002911 switch (E->getLHS()->getType().getObjCLifetime()) {
2912 case Qualifiers::OCL_Strong:
2913 return EmitARCStoreStrong(E, /*ignored*/ false).first;
2914
2915 case Qualifiers::OCL_Autoreleasing:
2916 return EmitARCStoreAutoreleasing(E).first;
2917
2918 // No reason to do any of these differently.
2919 case Qualifiers::OCL_None:
2920 case Qualifiers::OCL_ExplicitNone:
2921 case Qualifiers::OCL_Weak:
2922 break;
2923 }
2924
John McCallcd940a12010-12-06 06:10:02 +00002925 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smith4def70d2012-10-09 19:52:38 +00002926 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall545d9962011-06-25 02:11:03 +00002927 EmitStoreThroughLValue(RV, LV);
Anders Carlsson86aa0cd2009-10-19 18:28:22 +00002928 return LV;
2929 }
John McCall83ce9d42010-11-16 23:07:28 +00002930
2931 if (E->getType()->isAnyComplexType())
2932 return EmitComplexAssignmentLValue(E);
2933
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00002934 return EmitAggExprToLValue(E);
Daniel Dunbar80e62c22008-09-04 03:20:13 +00002935}
2936
Christopher Lamb22c940e2007-12-29 05:02:41 +00002937LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lamb22c940e2007-12-29 05:02:41 +00002938 RValue RV = EmitCallExpr(E);
Anders Carlsson48265682009-05-27 01:45:47 +00002939
Chris Lattnereb99b012009-10-28 17:39:19 +00002940 if (!RV.isScalar())
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002941 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnereb99b012009-10-28 17:39:19 +00002942
2943 assert(E->getCallReturnType()->isReferenceType() &&
2944 "Can't have a scalar return unless the return type is a "
2945 "reference type!");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002946
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002947 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lamb22c940e2007-12-29 05:02:41 +00002948}
2949
Daniel Dunbar5b5c9ef2009-02-11 20:59:32 +00002950LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2951 // FIXME: This shouldn't require another copy.
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00002952 return EmitAggExprToLValue(E);
Daniel Dunbar5b5c9ef2009-02-11 20:59:32 +00002953}
2954
Anders Carlssonb58d0172009-05-30 23:23:33 +00002955LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCallfc1e6c72010-09-18 00:58:34 +00002956 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2957 && "binding l-value to type which needs a temporary");
Benjamin Kramer578faa82011-09-27 21:06:10 +00002958 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall558d2ab2010-09-15 10:14:12 +00002959 EmitCXXConstructExpr(E, Slot);
2960 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlssonb58d0172009-05-30 23:23:33 +00002961}
2962
Anders Carlssone61c9e82009-05-30 23:30:54 +00002963LValue
Mike Stumpc2e84ae2009-11-15 08:09:41 +00002964CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002965 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc2e84ae2009-11-15 08:09:41 +00002966}
2967
Nico Weberc5f80462012-10-11 10:13:44 +00002968llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
2969 return CGM.GetAddrOfUuidDescriptor(E);
2970}
2971
2972LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
2973 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
2974}
2975
Mike Stumpc2e84ae2009-11-15 08:09:41 +00002976LValue
Anders Carlssone61c9e82009-05-30 23:30:54 +00002977CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCallfc1e6c72010-09-18 00:58:34 +00002978 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallfd71fb82011-08-26 08:02:37 +00002979 Slot.setExternallyDestructed();
John McCallfc1e6c72010-09-18 00:58:34 +00002980 EmitAggExpr(E->getSubExpr(), Slot);
Peter Collingbourne86811602011-11-27 22:09:22 +00002981 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
John McCallfc1e6c72010-09-18 00:58:34 +00002982 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlssone61c9e82009-05-30 23:30:54 +00002983}
2984
Eli Friedman31a37022012-02-08 05:34:55 +00002985LValue
2986CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman31a37022012-02-08 05:34:55 +00002987 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedman4c5d8af2012-02-09 03:32:31 +00002988 EmitLambdaExpr(E, Slot);
Eli Friedman31a37022012-02-08 05:34:55 +00002989 return MakeAddrLValue(Slot.getAddr(), E->getType());
2990}
2991
Daniel Dunbar0a04d772008-08-23 10:51:21 +00002992LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbar0a04d772008-08-23 10:51:21 +00002993 RValue RV = EmitObjCMessageExpr(E);
Anders Carlsson7e70fb22010-06-21 20:59:55 +00002994
2995 if (!RV.isScalar())
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002996 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Anders Carlsson7e70fb22010-06-21 20:59:55 +00002997
2998 assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2999 "Can't have a scalar return unless the return type is a "
3000 "reference type!");
3001
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003002 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbar0a04d772008-08-23 10:51:21 +00003003}
3004
Fariborz Jahanian03b29602010-06-17 19:56:20 +00003005LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
3006 llvm::Value *V =
3007 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003008 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian03b29602010-06-17 19:56:20 +00003009}
3010
Daniel Dunbar2a031922009-04-22 05:08:15 +00003011llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +00003012 const ObjCIvarDecl *Ivar) {
Fariborz Jahanianf63aa3f2009-02-10 19:02:04 +00003013 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +00003014}
3015
Fariborz Jahanian45012a72009-02-03 00:09:52 +00003016LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3017 llvm::Value *BaseValue,
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +00003018 const ObjCIvarDecl *Ivar,
3019 unsigned CVRQualifiers) {
Chris Lattner26f074b2009-04-17 17:44:48 +00003020 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar525c9b72009-04-21 01:19:28 +00003021 Ivar, CVRQualifiers);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +00003022}
3023
3024LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlsson29b7e502008-08-25 01:53:23 +00003025 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
3026 llvm::Value *BaseValue = 0;
3027 const Expr *BaseExpr = E->getBase();
John McCall0953e762009-09-24 19:53:00 +00003028 Qualifiers BaseQuals;
Fariborz Jahanian45012a72009-02-03 00:09:52 +00003029 QualType ObjectTy;
Anders Carlsson29b7e502008-08-25 01:53:23 +00003030 if (E->isArrow()) {
3031 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff14108da2009-07-10 23:34:53 +00003032 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003033 BaseQuals = ObjectTy.getQualifiers();
Anders Carlsson29b7e502008-08-25 01:53:23 +00003034 } else {
3035 LValue BaseLV = EmitLValue(BaseExpr);
3036 // FIXME: this isn't right for bitfields.
3037 BaseValue = BaseLV.getAddress();
Fariborz Jahanian45012a72009-02-03 00:09:52 +00003038 ObjectTy = BaseExpr->getType();
John McCall0953e762009-09-24 19:53:00 +00003039 BaseQuals = ObjectTy.getQualifiers();
Anders Carlsson29b7e502008-08-25 01:53:23 +00003040 }
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +00003041
Fariborz Jahaniandbf3cfd2009-09-16 23:11:23 +00003042 LValue LV =
John McCall0953e762009-09-24 19:53:00 +00003043 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3044 BaseQuals.getCVRQualifiers());
Fariborz Jahaniandbf3cfd2009-09-16 23:11:23 +00003045 setObjCGCLValueClass(getContext(), E, LV);
3046 return LV;
Chris Lattner391d77a2008-03-30 23:03:07 +00003047}
3048
Chris Lattner65459942009-04-25 19:35:26 +00003049LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattner65459942009-04-25 19:35:26 +00003050 // Can only get l-value for message expression returning aggregate type
3051 RValue RV = EmitAnyExprToTemp(E);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003052 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattner65459942009-04-25 19:35:26 +00003053}
3054
Anders Carlsson31777a22009-12-24 19:08:58 +00003055RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Anders Carlssond2490a92009-12-24 20:40:36 +00003056 ReturnValueSlot ReturnValue,
Anders Carlsson98647712009-05-27 01:22:39 +00003057 CallExpr::const_arg_iterator ArgBeg,
3058 CallExpr::const_arg_iterator ArgEnd,
3059 const Decl *TargetDecl) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003060 // Get the actual function type. The callee type will always be a pointer to
3061 // function type or a block pointer type.
3062 assert(CalleeType->isFunctionPointerType() &&
Anders Carlsson8ac67a72009-04-07 18:53:02 +00003063 "Call must have function pointer type!");
3064
John McCall00a1ad92009-10-23 08:22:42 +00003065 CalleeType = getContext().getCanonicalType(CalleeType);
3066
John McCall04a67a62010-02-05 21:31:56 +00003067 const FunctionType *FnType
3068 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00003069
3070 CallArgList Args;
John McCall00a1ad92009-10-23 08:22:42 +00003071 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
Daniel Dunbar19cd87e2008-08-30 03:02:31 +00003072
John McCallde5d3c72012-02-17 03:33:10 +00003073 const CGFunctionInfo &FnInfo =
John McCall0f3d0972012-07-07 06:41:13 +00003074 CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
John McCall01f151e2011-09-21 08:08:30 +00003075
3076 // C99 6.5.2.2p6:
3077 // If the expression that denotes the called function has a type
3078 // that does not include a prototype, [the default argument
3079 // promotions are performed]. If the number of arguments does not
3080 // equal the number of parameters, the behavior is undefined. If
3081 // the function is defined with a type that includes a prototype,
3082 // and either the prototype ends with an ellipsis (, ...) or the
3083 // types of the arguments after promotion are not compatible with
3084 // the types of the parameters, the behavior is undefined. If the
3085 // function is defined with a type that does not include a
3086 // prototype, and the types of the arguments after promotion are
3087 // not compatible with those of the parameters after promotion,
3088 // the behavior is undefined [except in some trivial cases].
3089 // That is, in the general case, we should assume that a call
3090 // through an unprototyped function type works like a *non-variadic*
3091 // call. The way we make this work is to cast to the exact type
3092 // of the promoted arguments.
John McCallde5d3c72012-02-17 03:33:10 +00003093 if (isa<FunctionNoProtoType>(FnType) && !FnInfo.isVariadic()) {
3094 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCall01f151e2011-09-21 08:08:30 +00003095 CalleeTy = CalleeTy->getPointerTo();
3096 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3097 }
3098
3099 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar8f2926b2008-08-23 03:46:30 +00003100}
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +00003101
Chris Lattnereb99b012009-10-28 17:39:19 +00003102LValue CodeGenFunction::
3103EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
Eli Friedman1c5c1a02009-11-18 05:01:17 +00003104 llvm::Value *BaseV;
John McCall2de56d12010-08-25 11:45:40 +00003105 if (E->getOpcode() == BO_PtrMemI)
Eli Friedman1c5c1a02009-11-18 05:01:17 +00003106 BaseV = EmitScalarExpr(E->getLHS());
3107 else
3108 BaseV = EmitLValue(E->getLHS()).getAddress();
Chris Lattnereb99b012009-10-28 17:39:19 +00003109
John McCall6c2ab1d2010-08-31 21:07:20 +00003110 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3111
3112 const MemberPointerType *MPT
3113 = E->getRHS()->getType()->getAs<MemberPointerType>();
3114
3115 llvm::Value *AddV =
3116 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
3117
3118 return MakeAddrLValue(AddV, MPT->getPointeeType());
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +00003119}
Eli Friedman276b0612011-10-11 02:20:01 +00003120
3121static void
3122EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
3123 llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
3124 uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
Richard Smithff34d402012-04-12 05:08:17 +00003125 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
3126 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
3127
3128 switch (E->getOp()) {
3129 case AtomicExpr::AO__c11_atomic_init:
3130 llvm_unreachable("Already handled!");
3131
3132 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3133 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3134 case AtomicExpr::AO__atomic_compare_exchange:
3135 case AtomicExpr::AO__atomic_compare_exchange_n: {
Eli Friedman276b0612011-10-11 02:20:01 +00003136 // Note that cmpxchg only supports specifying one ordering and
3137 // doesn't support weak cmpxchg, at least at the moment.
3138 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3139 LoadVal1->setAlignment(Align);
3140 llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2);
3141 LoadVal2->setAlignment(Align);
3142 llvm::AtomicCmpXchgInst *CXI =
3143 CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order);
3144 CXI->setVolatile(E->isVolatile());
3145 llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1);
3146 StoreVal1->setAlignment(Align);
3147 llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1);
3148 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
3149 return;
3150 }
3151
Richard Smithff34d402012-04-12 05:08:17 +00003152 case AtomicExpr::AO__c11_atomic_load:
3153 case AtomicExpr::AO__atomic_load_n:
3154 case AtomicExpr::AO__atomic_load: {
Eli Friedman276b0612011-10-11 02:20:01 +00003155 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
3156 Load->setAtomic(Order);
3157 Load->setAlignment(Size);
3158 Load->setVolatile(E->isVolatile());
3159 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
3160 StoreDest->setAlignment(Align);
3161 return;
3162 }
3163
Richard Smithff34d402012-04-12 05:08:17 +00003164 case AtomicExpr::AO__c11_atomic_store:
3165 case AtomicExpr::AO__atomic_store:
3166 case AtomicExpr::AO__atomic_store_n: {
Eli Friedman276b0612011-10-11 02:20:01 +00003167 assert(!Dest && "Store does not return a value");
3168 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3169 LoadVal1->setAlignment(Align);
3170 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
3171 Store->setAtomic(Order);
3172 Store->setAlignment(Size);
3173 Store->setVolatile(E->isVolatile());
3174 return;
3175 }
3176
Richard Smithff34d402012-04-12 05:08:17 +00003177 case AtomicExpr::AO__c11_atomic_exchange:
3178 case AtomicExpr::AO__atomic_exchange_n:
3179 case AtomicExpr::AO__atomic_exchange:
3180 Op = llvm::AtomicRMWInst::Xchg;
3181 break;
3182
3183 case AtomicExpr::AO__atomic_add_fetch:
3184 PostOp = llvm::Instruction::Add;
3185 // Fall through.
3186 case AtomicExpr::AO__c11_atomic_fetch_add:
3187 case AtomicExpr::AO__atomic_fetch_add:
3188 Op = llvm::AtomicRMWInst::Add;
3189 break;
3190
3191 case AtomicExpr::AO__atomic_sub_fetch:
3192 PostOp = llvm::Instruction::Sub;
3193 // Fall through.
3194 case AtomicExpr::AO__c11_atomic_fetch_sub:
3195 case AtomicExpr::AO__atomic_fetch_sub:
3196 Op = llvm::AtomicRMWInst::Sub;
3197 break;
3198
3199 case AtomicExpr::AO__atomic_and_fetch:
3200 PostOp = llvm::Instruction::And;
3201 // Fall through.
3202 case AtomicExpr::AO__c11_atomic_fetch_and:
3203 case AtomicExpr::AO__atomic_fetch_and:
3204 Op = llvm::AtomicRMWInst::And;
3205 break;
3206
3207 case AtomicExpr::AO__atomic_or_fetch:
3208 PostOp = llvm::Instruction::Or;
3209 // Fall through.
3210 case AtomicExpr::AO__c11_atomic_fetch_or:
3211 case AtomicExpr::AO__atomic_fetch_or:
3212 Op = llvm::AtomicRMWInst::Or;
3213 break;
3214
3215 case AtomicExpr::AO__atomic_xor_fetch:
3216 PostOp = llvm::Instruction::Xor;
3217 // Fall through.
3218 case AtomicExpr::AO__c11_atomic_fetch_xor:
3219 case AtomicExpr::AO__atomic_fetch_xor:
3220 Op = llvm::AtomicRMWInst::Xor;
3221 break;
Richard Smith51b92402012-04-13 06:31:38 +00003222
3223 case AtomicExpr::AO__atomic_nand_fetch:
3224 PostOp = llvm::Instruction::And;
3225 // Fall through.
3226 case AtomicExpr::AO__atomic_fetch_nand:
3227 Op = llvm::AtomicRMWInst::Nand;
3228 break;
Eli Friedman276b0612011-10-11 02:20:01 +00003229 }
Richard Smithff34d402012-04-12 05:08:17 +00003230
Eli Friedman276b0612011-10-11 02:20:01 +00003231 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3232 LoadVal1->setAlignment(Align);
3233 llvm::AtomicRMWInst *RMWI =
3234 CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
3235 RMWI->setVolatile(E->isVolatile());
Richard Smithff34d402012-04-12 05:08:17 +00003236
3237 // For __atomic_*_fetch operations, perform the operation again to
3238 // determine the value which was written.
3239 llvm::Value *Result = RMWI;
3240 if (PostOp)
3241 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
Richard Smith51b92402012-04-13 06:31:38 +00003242 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
3243 Result = CGF.Builder.CreateNot(Result);
Richard Smithff34d402012-04-12 05:08:17 +00003244 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
Eli Friedman276b0612011-10-11 02:20:01 +00003245 StoreDest->setAlignment(Align);
3246}
3247
3248// This function emits any expression (scalar, complex, or aggregate)
3249// into a temporary alloca.
3250static llvm::Value *
3251EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
3252 llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
Chad Rosier649b4a12012-03-29 17:37:10 +00003253 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
3254 /*Init*/ true);
Eli Friedman276b0612011-10-11 02:20:01 +00003255 return DeclPtr;
3256}
3257
3258static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty,
3259 llvm::Value *Dest) {
3260 if (Ty->isAnyComplexType())
3261 return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false));
3262 if (CGF.hasAggregateLLVMType(Ty))
3263 return RValue::getAggregate(Dest);
3264 return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty)));
3265}
3266
3267RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
3268 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
Richard Smithff34d402012-04-12 05:08:17 +00003269 QualType MemTy = AtomicTy;
3270 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
3271 MemTy = AT->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00003272 CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
3273 uint64_t Size = sizeChars.getQuantity();
3274 CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
3275 unsigned Align = alignChars.getQuantity();
Eli Friedman2be46072011-10-14 20:59:01 +00003276 unsigned MaxInlineWidth =
3277 getContext().getTargetInfo().getMaxAtomicInlineWidth();
3278 bool UseLibcall = (Size != Align || Size > MaxInlineWidth);
Eli Friedman276b0612011-10-11 02:20:01 +00003279
David Chisnall7a7ee302012-01-16 17:27:18 +00003280
3281
Eli Friedman276b0612011-10-11 02:20:01 +00003282 llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
3283 Ptr = EmitScalarExpr(E->getPtr());
David Chisnall7a7ee302012-01-16 17:27:18 +00003284
Richard Smithff34d402012-04-12 05:08:17 +00003285 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
David Chisnall7a7ee302012-01-16 17:27:18 +00003286 assert(!Dest && "Init does not return a value");
David Chisnall5d70cfd2012-04-11 17:24:05 +00003287 if (!hasAggregateLLVMType(E->getVal1()->getType())) {
Douglas Gregor47bfcca2012-04-12 20:42:30 +00003288 QualType PointeeType
3289 = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
3290 EmitScalarInit(EmitScalarExpr(E->getVal1()),
3291 LValue::MakeAddr(Ptr, PointeeType, alignChars,
3292 getContext()));
David Chisnall5d70cfd2012-04-11 17:24:05 +00003293 } else if (E->getType()->isAnyComplexType()) {
3294 EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
3295 } else {
3296 AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars,
3297 AtomicTy.getQualifiers(),
3298 AggValueSlot::IsNotDestructed,
3299 AggValueSlot::DoesNotNeedGCBarriers,
3300 AggValueSlot::IsNotAliased);
3301 EmitAggExpr(E->getVal1(), Slot);
3302 }
David Chisnall7a7ee302012-01-16 17:27:18 +00003303 return RValue::get(0);
3304 }
3305
Eli Friedman276b0612011-10-11 02:20:01 +00003306 Order = EmitScalarExpr(E->getOrder());
Richard Smithff34d402012-04-12 05:08:17 +00003307
3308 switch (E->getOp()) {
3309 case AtomicExpr::AO__c11_atomic_init:
3310 llvm_unreachable("Already handled!");
3311
3312 case AtomicExpr::AO__c11_atomic_load:
3313 case AtomicExpr::AO__atomic_load_n:
3314 break;
3315
3316 case AtomicExpr::AO__atomic_load:
3317 Dest = EmitScalarExpr(E->getVal1());
3318 break;
3319
3320 case AtomicExpr::AO__atomic_store:
Eli Friedman276b0612011-10-11 02:20:01 +00003321 Val1 = EmitScalarExpr(E->getVal1());
Richard Smithff34d402012-04-12 05:08:17 +00003322 break;
3323
3324 case AtomicExpr::AO__atomic_exchange:
3325 Val1 = EmitScalarExpr(E->getVal1());
3326 Dest = EmitScalarExpr(E->getVal2());
3327 break;
3328
3329 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3330 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3331 case AtomicExpr::AO__atomic_compare_exchange_n:
3332 case AtomicExpr::AO__atomic_compare_exchange:
3333 Val1 = EmitScalarExpr(E->getVal1());
3334 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
3335 Val2 = EmitScalarExpr(E->getVal2());
3336 else
3337 Val2 = EmitValToTemp(*this, E->getVal2());
Eli Friedman276b0612011-10-11 02:20:01 +00003338 OrderFail = EmitScalarExpr(E->getOrderFail());
Richard Smithff34d402012-04-12 05:08:17 +00003339 // Evaluate and discard the 'weak' argument.
3340 if (E->getNumSubExprs() == 6)
3341 EmitScalarExpr(E->getWeak());
3342 break;
3343
3344 case AtomicExpr::AO__c11_atomic_fetch_add:
3345 case AtomicExpr::AO__c11_atomic_fetch_sub:
Richard Smithff34d402012-04-12 05:08:17 +00003346 if (MemTy->isPointerType()) {
3347 // For pointer arithmetic, we're required to do a bit of math:
3348 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
Richard Smith2c39d712012-04-13 00:45:38 +00003349 // ... but only for the C11 builtins. The GNU builtins expect the
3350 // user to multiply by sizeof(T).
Richard Smithff34d402012-04-12 05:08:17 +00003351 QualType Val1Ty = E->getVal1()->getType();
3352 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
3353 CharUnits PointeeIncAmt =
3354 getContext().getTypeSizeInChars(MemTy->getPointeeType());
3355 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
3356 Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
3357 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
3358 break;
3359 }
3360 // Fall through.
Richard Smith2c39d712012-04-13 00:45:38 +00003361 case AtomicExpr::AO__atomic_fetch_add:
3362 case AtomicExpr::AO__atomic_fetch_sub:
3363 case AtomicExpr::AO__atomic_add_fetch:
3364 case AtomicExpr::AO__atomic_sub_fetch:
Richard Smithff34d402012-04-12 05:08:17 +00003365 case AtomicExpr::AO__c11_atomic_store:
3366 case AtomicExpr::AO__c11_atomic_exchange:
3367 case AtomicExpr::AO__atomic_store_n:
3368 case AtomicExpr::AO__atomic_exchange_n:
3369 case AtomicExpr::AO__c11_atomic_fetch_and:
3370 case AtomicExpr::AO__c11_atomic_fetch_or:
3371 case AtomicExpr::AO__c11_atomic_fetch_xor:
3372 case AtomicExpr::AO__atomic_fetch_and:
3373 case AtomicExpr::AO__atomic_fetch_or:
3374 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +00003375 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +00003376 case AtomicExpr::AO__atomic_and_fetch:
3377 case AtomicExpr::AO__atomic_or_fetch:
3378 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +00003379 case AtomicExpr::AO__atomic_nand_fetch:
Eli Friedman276b0612011-10-11 02:20:01 +00003380 Val1 = EmitValToTemp(*this, E->getVal1());
Richard Smithff34d402012-04-12 05:08:17 +00003381 break;
Eli Friedman276b0612011-10-11 02:20:01 +00003382 }
3383
Richard Smithff34d402012-04-12 05:08:17 +00003384 if (!E->getType()->isVoidType() && !Dest)
Eli Friedman276b0612011-10-11 02:20:01 +00003385 Dest = CreateMemTemp(E->getType(), ".atomicdst");
3386
David Chisnall3a7d69b2012-03-29 18:01:11 +00003387 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
Eli Friedman276b0612011-10-11 02:20:01 +00003388 if (UseLibcall) {
David Chisnall3a7d69b2012-03-29 18:01:11 +00003389
3390 llvm::SmallVector<QualType, 5> Params;
3391 CallArgList Args;
3392 // Size is always the first parameter
3393 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
3394 getContext().getSizeType());
3395 // Atomic address is always the second parameter
3396 Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
3397 getContext().VoidPtrTy);
3398
Eli Friedman276b0612011-10-11 02:20:01 +00003399 const char* LibCallName;
David Chisnall3a7d69b2012-03-29 18:01:11 +00003400 QualType RetTy = getContext().VoidTy;
Eli Friedman276b0612011-10-11 02:20:01 +00003401 switch (E->getOp()) {
David Chisnall3a7d69b2012-03-29 18:01:11 +00003402 // There is only one libcall for compare an exchange, because there is no
3403 // optimisation benefit possible from a libcall version of a weak compare
3404 // and exchange.
3405 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
Richard Smithff34d402012-04-12 05:08:17 +00003406 // void *desired, int success, int failure)
3407 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3408 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3409 case AtomicExpr::AO__atomic_compare_exchange:
3410 case AtomicExpr::AO__atomic_compare_exchange_n:
David Chisnall3a7d69b2012-03-29 18:01:11 +00003411 LibCallName = "__atomic_compare_exchange";
3412 RetTy = getContext().BoolTy;
3413 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3414 getContext().VoidPtrTy);
3415 Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
3416 getContext().VoidPtrTy);
3417 Args.add(RValue::get(Order),
3418 getContext().IntTy);
3419 Order = OrderFail;
3420 break;
3421 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
3422 // int order)
Richard Smithff34d402012-04-12 05:08:17 +00003423 case AtomicExpr::AO__c11_atomic_exchange:
3424 case AtomicExpr::AO__atomic_exchange_n:
3425 case AtomicExpr::AO__atomic_exchange:
David Chisnall3a7d69b2012-03-29 18:01:11 +00003426 LibCallName = "__atomic_exchange";
3427 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3428 getContext().VoidPtrTy);
3429 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3430 getContext().VoidPtrTy);
3431 break;
3432 // void __atomic_store(size_t size, void *mem, void *val, int order)
Richard Smithff34d402012-04-12 05:08:17 +00003433 case AtomicExpr::AO__c11_atomic_store:
3434 case AtomicExpr::AO__atomic_store:
3435 case AtomicExpr::AO__atomic_store_n:
David Chisnall3a7d69b2012-03-29 18:01:11 +00003436 LibCallName = "__atomic_store";
3437 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3438 getContext().VoidPtrTy);
3439 break;
3440 // void __atomic_load(size_t size, void *mem, void *return, int order)
Richard Smithff34d402012-04-12 05:08:17 +00003441 case AtomicExpr::AO__c11_atomic_load:
3442 case AtomicExpr::AO__atomic_load:
3443 case AtomicExpr::AO__atomic_load_n:
David Chisnall3a7d69b2012-03-29 18:01:11 +00003444 LibCallName = "__atomic_load";
3445 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3446 getContext().VoidPtrTy);
3447 break;
3448#if 0
3449 // These are only defined for 1-16 byte integers. It is not clear what
3450 // their semantics would be on anything else...
Eli Friedman276b0612011-10-11 02:20:01 +00003451 case AtomicExpr::Add: LibCallName = "__atomic_fetch_add_generic"; break;
3452 case AtomicExpr::Sub: LibCallName = "__atomic_fetch_sub_generic"; break;
3453 case AtomicExpr::And: LibCallName = "__atomic_fetch_and_generic"; break;
3454 case AtomicExpr::Or: LibCallName = "__atomic_fetch_or_generic"; break;
3455 case AtomicExpr::Xor: LibCallName = "__atomic_fetch_xor_generic"; break;
David Chisnall3a7d69b2012-03-29 18:01:11 +00003456#endif
3457 default: return EmitUnsupportedRValue(E, "atomic library call");
Eli Friedman276b0612011-10-11 02:20:01 +00003458 }
David Chisnall3a7d69b2012-03-29 18:01:11 +00003459 // order is always the last parameter
3460 Args.add(RValue::get(Order),
3461 getContext().IntTy);
3462
Eli Friedman276b0612011-10-11 02:20:01 +00003463 const CGFunctionInfo &FuncInfo =
John McCall0f3d0972012-07-07 06:41:13 +00003464 CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args,
David Chisnall3a7d69b2012-03-29 18:01:11 +00003465 FunctionType::ExtInfo(), RequiredArgs::All);
3466 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
Eli Friedman276b0612011-10-11 02:20:01 +00003467 llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
3468 RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
3469 if (E->isCmpXChg())
3470 return Res;
Richard Smithff34d402012-04-12 05:08:17 +00003471 if (E->getType()->isVoidType())
Eli Friedman276b0612011-10-11 02:20:01 +00003472 return RValue::get(0);
3473 return ConvertTempToRValue(*this, E->getType(), Dest);
3474 }
David Chisnall3a7d69b2012-03-29 18:01:11 +00003475
Eli Friedman276b0612011-10-11 02:20:01 +00003476 llvm::Type *IPtrTy =
3477 llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
3478 llvm::Value *OrigDest = Dest;
3479 Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
3480 if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
3481 if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
3482 if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
3483
3484 if (isa<llvm::ConstantInt>(Order)) {
3485 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
3486 switch (ord) {
3487 case 0: // memory_order_relaxed
3488 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3489 llvm::Monotonic);
3490 break;
3491 case 1: // memory_order_consume
3492 case 2: // memory_order_acquire
3493 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3494 llvm::Acquire);
3495 break;
3496 case 3: // memory_order_release
3497 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3498 llvm::Release);
3499 break;
3500 case 4: // memory_order_acq_rel
3501 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3502 llvm::AcquireRelease);
3503 break;
3504 case 5: // memory_order_seq_cst
3505 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3506 llvm::SequentiallyConsistent);
3507 break;
3508 default: // invalid order
3509 // We should not ever get here normally, but it's hard to
3510 // enforce that in general.
Richard Smithff34d402012-04-12 05:08:17 +00003511 break;
Eli Friedman276b0612011-10-11 02:20:01 +00003512 }
Richard Smithff34d402012-04-12 05:08:17 +00003513 if (E->getType()->isVoidType())
Eli Friedman276b0612011-10-11 02:20:01 +00003514 return RValue::get(0);
3515 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3516 }
3517
3518 // Long case, when Order isn't obviously constant.
3519
Richard Smithff34d402012-04-12 05:08:17 +00003520 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
3521 E->getOp() == AtomicExpr::AO__atomic_store ||
3522 E->getOp() == AtomicExpr::AO__atomic_store_n;
3523 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
3524 E->getOp() == AtomicExpr::AO__atomic_load ||
3525 E->getOp() == AtomicExpr::AO__atomic_load_n;
3526
Eli Friedman276b0612011-10-11 02:20:01 +00003527 // Create all the relevant BB's
Eli Friedman9e3c20b2011-10-11 20:00:47 +00003528 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
3529 *AcqRelBB = 0, *SeqCstBB = 0;
Eli Friedman276b0612011-10-11 02:20:01 +00003530 MonotonicBB = createBasicBlock("monotonic", CurFn);
Richard Smithff34d402012-04-12 05:08:17 +00003531 if (!IsStore)
Eli Friedman276b0612011-10-11 02:20:01 +00003532 AcquireBB = createBasicBlock("acquire", CurFn);
Richard Smithff34d402012-04-12 05:08:17 +00003533 if (!IsLoad)
Eli Friedman276b0612011-10-11 02:20:01 +00003534 ReleaseBB = createBasicBlock("release", CurFn);
Richard Smithff34d402012-04-12 05:08:17 +00003535 if (!IsLoad && !IsStore)
Eli Friedman276b0612011-10-11 02:20:01 +00003536 AcqRelBB = createBasicBlock("acqrel", CurFn);
3537 SeqCstBB = createBasicBlock("seqcst", CurFn);
3538 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
3539
3540 // Create the switch for the split
3541 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
3542 // doesn't matter unless someone is crazy enough to use something that
3543 // doesn't fold to a constant for the ordering.
3544 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
3545 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
3546
3547 // Emit all the different atomics
3548 Builder.SetInsertPoint(MonotonicBB);
3549 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3550 llvm::Monotonic);
3551 Builder.CreateBr(ContBB);
Richard Smithff34d402012-04-12 05:08:17 +00003552 if (!IsStore) {
Eli Friedman276b0612011-10-11 02:20:01 +00003553 Builder.SetInsertPoint(AcquireBB);
3554 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3555 llvm::Acquire);
3556 Builder.CreateBr(ContBB);
3557 SI->addCase(Builder.getInt32(1), AcquireBB);
3558 SI->addCase(Builder.getInt32(2), AcquireBB);
3559 }
Richard Smithff34d402012-04-12 05:08:17 +00003560 if (!IsLoad) {
Eli Friedman276b0612011-10-11 02:20:01 +00003561 Builder.SetInsertPoint(ReleaseBB);
3562 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3563 llvm::Release);
3564 Builder.CreateBr(ContBB);
3565 SI->addCase(Builder.getInt32(3), ReleaseBB);
3566 }
Richard Smithff34d402012-04-12 05:08:17 +00003567 if (!IsLoad && !IsStore) {
Eli Friedman276b0612011-10-11 02:20:01 +00003568 Builder.SetInsertPoint(AcqRelBB);
3569 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3570 llvm::AcquireRelease);
3571 Builder.CreateBr(ContBB);
3572 SI->addCase(Builder.getInt32(4), AcqRelBB);
3573 }
3574 Builder.SetInsertPoint(SeqCstBB);
3575 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3576 llvm::SequentiallyConsistent);
3577 Builder.CreateBr(ContBB);
3578 SI->addCase(Builder.getInt32(5), SeqCstBB);
3579
3580 // Cleanup and return
3581 Builder.SetInsertPoint(ContBB);
Richard Smithff34d402012-04-12 05:08:17 +00003582 if (E->getType()->isVoidType())
Eli Friedman276b0612011-10-11 02:20:01 +00003583 return RValue::get(0);
3584 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3585}
Peter Collingbournec5096cb2011-10-27 19:19:51 +00003586
Duncan Sands82500162012-04-10 08:23:07 +00003587void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbournec5096cb2011-10-27 19:19:51 +00003588 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sands82500162012-04-10 08:23:07 +00003589 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbournec5096cb2011-10-27 19:19:51 +00003590 return;
3591
Duncan Sands60c77072012-04-16 16:29:47 +00003592 llvm::MDBuilder MDHelper(getLLVMContext());
3593 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbournec5096cb2011-10-27 19:19:51 +00003594
Duncan Sands9bb1d342012-04-14 12:37:26 +00003595 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbournec5096cb2011-10-27 19:19:51 +00003596}
John McCall4b9c2d22011-11-06 09:01:30 +00003597
3598namespace {
3599 struct LValueOrRValue {
3600 LValue LV;
3601 RValue RV;
3602 };
3603}
3604
3605static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3606 const PseudoObjectExpr *E,
3607 bool forLValue,
3608 AggValueSlot slot) {
3609 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3610
3611 // Find the result expression, if any.
3612 const Expr *resultExpr = E->getResultExpr();
3613 LValueOrRValue result;
3614
3615 for (PseudoObjectExpr::const_semantics_iterator
3616 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3617 const Expr *semantic = *i;
3618
3619 // If this semantic expression is an opaque value, bind it
3620 // to the result of its source expression.
3621 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3622
3623 // If this is the result expression, we may need to evaluate
3624 // directly into the slot.
3625 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3626 OVMA opaqueData;
3627 if (ov == resultExpr && ov->isRValue() && !forLValue &&
3628 CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
3629 !ov->getType()->isAnyComplexType()) {
3630 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3631
3632 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3633 opaqueData = OVMA::bind(CGF, ov, LV);
3634 result.RV = slot.asRValue();
3635
3636 // Otherwise, emit as normal.
3637 } else {
3638 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3639
3640 // If this is the result, also evaluate the result now.
3641 if (ov == resultExpr) {
3642 if (forLValue)
3643 result.LV = CGF.EmitLValue(ov);
3644 else
3645 result.RV = CGF.EmitAnyExpr(ov, slot);
3646 }
3647 }
3648
3649 opaques.push_back(opaqueData);
3650
3651 // Otherwise, if the expression is the result, evaluate it
3652 // and remember the result.
3653 } else if (semantic == resultExpr) {
3654 if (forLValue)
3655 result.LV = CGF.EmitLValue(semantic);
3656 else
3657 result.RV = CGF.EmitAnyExpr(semantic, slot);
3658
3659 // Otherwise, evaluate the expression in an ignored context.
3660 } else {
3661 CGF.EmitIgnoredExpr(semantic);
3662 }
3663 }
3664
3665 // Unbind all the opaques now.
3666 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3667 opaques[i].unbind(CGF);
3668
3669 return result;
3670}
3671
3672RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3673 AggValueSlot slot) {
3674 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3675}
3676
3677LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3678 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3679}