blob: ad62e10473b66220d1cdead48d6282ce940cb1f5 [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere47e4402007-06-01 18:02:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGCall.h"
Devang Pateld3a6b0f2011-03-04 18:54:42 +000017#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CGRecordLayout.h"
20#include "CodeGenModule.h"
John McCallcbc038a2011-09-21 08:08:30 +000021#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth85098242010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/ADT/Hashing.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000030#include "llvm/Support/ConvertUTF.h"
31
Chris Lattnere47e4402007-06-01 18:02:12 +000032using namespace clang;
33using namespace CodeGen;
34
Chris Lattnerd7f58862007-06-02 05:24:33 +000035//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000036// Miscellaneous Helper Methods
37//===--------------------------------------------------------------------===//
38
John McCallad7c5c12011-02-08 08:22:06 +000039llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
40 unsigned addressSpace =
41 cast<llvm::PointerType>(value->getType())->getAddressSpace();
42
Chris Lattner2192fe52011-07-18 04:24:23 +000043 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000044 if (addressSpace)
45 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
46
47 if (value->getType() == destType) return value;
48 return Builder.CreateBitCast(value, destType);
49}
50
Chris Lattnere9a64532007-06-22 21:44:33 +000051/// CreateTempAlloca - This creates a alloca and inserts it into the entry
52/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000053llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000054 const Twine &Name) {
Chris Lattner47640222009-03-22 00:24:14 +000055 if (!Builder.isNamePreserving())
Daniel Dunbarb5aacc22009-10-19 01:21:05 +000056 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
Devang Pateldac79de2009-10-12 22:29:02 +000057 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000058}
Chris Lattner8394d792007-06-05 20:53:16 +000059
John McCall2e6567a2010-04-22 01:10:34 +000060void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
61 llvm::Value *Init) {
62 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
63 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
64 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
65}
66
Chris Lattnerc401de92010-07-05 20:21:00 +000067llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000069 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
70 // FIXME: Should we prefer the preferred type alignment here?
71 CharUnits Align = getContext().getTypeAlignInChars(Ty);
72 Alloc->setAlignment(Align.getQuantity());
73 return Alloc;
74}
75
Chris Lattnerc401de92010-07-05 20:21:00 +000076llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000078 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
79 // FIXME: Should we prefer the preferred type alignment here?
80 CharUnits Align = getContext().getTypeAlignInChars(Ty);
81 Alloc->setAlignment(Align.getQuantity());
82 return Alloc;
83}
84
Chris Lattner8394d792007-06-05 20:53:16 +000085/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
86/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000087llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
John McCall7a9aac22010-08-23 01:21:21 +000088 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +000089 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +000090 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +000091 }
John McCall7a9aac22010-08-23 01:21:21 +000092
93 QualType BoolTy = getContext().BoolTy;
Chris Lattnerf3bc75a2008-04-04 16:54:41 +000094 if (!E->getType()->isAnyComplexType())
Chris Lattner268fcce2007-08-26 16:46:58 +000095 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Chris Lattner8394d792007-06-05 20:53:16 +000096
Chris Lattner268fcce2007-08-26 16:46:58 +000097 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Chris Lattnerf0106d22007-06-02 19:33:17 +000098}
99
John McCalla2342eb2010-12-05 02:00:02 +0000100/// EmitIgnoredExpr - Emit code to compute the specified expression,
101/// ignoring the result.
102void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
103 if (E->isRValue())
104 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
105
106 // Just emit it as an l-value and drop the result.
107 EmitLValue(E);
108}
109
John McCall7a626f62010-09-15 10:14:12 +0000110/// EmitAnyExpr - Emit code to compute the specified expression which
111/// can have any type. The result is returned as an RValue struct.
112/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000113/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000114RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
115 AggValueSlot aggSlot,
116 bool ignoreResult) {
Chris Lattner4647a212007-08-31 22:49:20 +0000117 if (!hasAggregateLLVMType(E->getType()))
John McCall4e8ca4f2012-07-02 23:58:38 +0000118 return RValue::get(EmitScalarExpr(E, ignoreResult));
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000119 else if (E->getType()->isAnyComplexType())
John McCall4e8ca4f2012-07-02 23:58:38 +0000120 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
Mike Stump4a3999f2009-09-09 13:00:44 +0000121
John McCall4e8ca4f2012-07-02 23:58:38 +0000122 if (!ignoreResult && aggSlot.isIgnored())
123 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
124 EmitAggExpr(E, aggSlot);
125 return aggSlot.asRValue();
Chris Lattner4647a212007-08-31 22:49:20 +0000126}
127
Mike Stump4a3999f2009-09-09 13:00:44 +0000128/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
129/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000130RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
131 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000132
133 if (hasAggregateLLVMType(E->getType()) &&
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000134 !E->getType()->isAnyComplexType())
John McCall7a626f62010-09-15 10:14:12 +0000135 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
136 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000137}
138
John McCall21886962010-04-21 10:05:39 +0000139/// EmitAnyExprToMem - Evaluate an expression into a given memory
140/// location.
141void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
142 llvm::Value *Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000143 Qualifiers Quals,
144 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000145 // FIXME: This function should take an LValue as an argument.
146 if (E->getType()->isAnyComplexType()) {
John McCall31168b02011-06-15 23:02:42 +0000147 EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000148 } else if (hasAggregateLLVMType(E->getType())) {
Eli Friedman38cd36d2011-12-03 02:13:40 +0000149 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000150 EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000151 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000152 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000153 AggValueSlot::IsAliased_t(!IsInit)));
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000154 } else {
John McCall21886962010-04-21 10:05:39 +0000155 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000156 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000157 EmitStoreThroughLValue(RV, LV);
John McCall21886962010-04-21 10:05:39 +0000158 }
159}
160
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000161static llvm::Value *
Chris Lattner24516962011-07-20 04:59:57 +0000162CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000163 const NamedDecl *InitializedDecl) {
164 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
165 if (VD->hasGlobalStorage()) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000166 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000167 llvm::raw_svector_ostream Out(Name);
168 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
169 Out.flush();
170
Chris Lattner2192fe52011-07-18 04:24:23 +0000171 llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
Anders Carlsson18c205e2010-06-27 17:23:46 +0000172
173 // Create the reference temporary.
174 llvm::GlobalValue *RefTemp =
175 new llvm::GlobalVariable(CGF.CGM.getModule(),
176 RefTempTy, /*isConstant=*/false,
177 llvm::GlobalValue::InternalLinkage,
178 llvm::Constant::getNullValue(RefTempTy),
179 Name.str());
180 return RefTemp;
181 }
182 }
183
184 return CGF.CreateMemTemp(Type, "ref.tmp");
185}
186
187static llvm::Value *
Chris Lattnerf53c0962010-09-06 00:11:41 +0000188EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000189 llvm::Value *&ReferenceTemporary,
190 const CXXDestructorDecl *&ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000191 QualType &ObjCARCReferenceLifetimeType,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000192 const NamedDecl *InitializedDecl) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000193 const MaterializeTemporaryExpr *M = NULL;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000194 E = E->findMaterializedTemporary(M);
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000195 // Objective-C++ ARC:
196 // If we are binding a reference to a temporary that has ownership, we
197 // need to perform retain/release operations on the temporary.
Richard Smith9c6890a2012-11-01 22:30:59 +0000198 if (M && CGF.getLangOpts().ObjCAutoRefCount &&
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000199 M->getType()->isObjCLifetimeType() &&
200 (M->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
201 M->getType().getObjCLifetime() == Qualifiers::OCL_Weak ||
202 M->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing))
203 ObjCARCReferenceLifetimeType = M->getType();
Sebastian Redl29526f02011-11-27 16:50:07 +0000204
John McCall08ef4662011-11-10 08:15:53 +0000205 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) {
206 CGF.enterFullExpression(EWC);
John McCallbd309292010-07-06 01:34:17 +0000207 CodeGenFunction::RunCleanupsScope Scope(CGF);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000208
John McCall08ef4662011-11-10 08:15:53 +0000209 return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000210 ReferenceTemporary,
211 ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000212 ObjCARCReferenceLifetimeType,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000213 InitializedDecl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000214 }
215
216 RValue RV;
Douglas Gregor9c399a22011-01-22 02:44:21 +0000217 if (E->isGLValue()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000218 // Emit the expression as an lvalue.
219 LValue LV = CGF.EmitLValue(E);
Chris Lattner13ee4f42011-07-10 05:34:54 +0000220
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000221 if (LV.isSimple())
222 return LV.getAddress();
Anders Carlsson824e0612010-02-04 17:32:58 +0000223
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000224 // We have to load the lvalue.
John McCall55e1fbc2011-06-25 02:11:03 +0000225 RV = CGF.EmitLoadOfLValue(LV);
Eli Friedmanc21cb442009-05-20 02:31:19 +0000226 } else {
Douglas Gregor58df5092011-06-22 16:12:01 +0000227 if (!ObjCARCReferenceLifetimeType.isNull()) {
228 ReferenceTemporary = CreateReferenceTemporary(CGF,
229 ObjCARCReferenceLifetimeType,
230 InitializedDecl);
231
232
233 LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
234 ObjCARCReferenceLifetimeType);
235
236 CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
237 RefTempDst, false);
238
239 bool ExtendsLifeOfTemporary = false;
240 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
241 if (Var->extendsLifetimeOfTemporary())
242 ExtendsLifeOfTemporary = true;
243 } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
244 ExtendsLifeOfTemporary = true;
245 }
246
247 if (!ExtendsLifeOfTemporary) {
248 // Since the lifetime of this temporary isn't going to be extended,
249 // we need to clean it up ourselves at the end of the full expression.
250 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
251 case Qualifiers::OCL_None:
252 case Qualifiers::OCL_ExplicitNone:
253 case Qualifiers::OCL_Autoreleasing:
254 break;
255
John McCall4bd0fb12011-07-12 16:41:08 +0000256 case Qualifiers::OCL_Strong: {
257 assert(!ObjCARCReferenceLifetimeType->isArrayType());
258 CleanupKind cleanupKind = CGF.getARCCleanupKind();
259 CGF.pushDestroy(cleanupKind,
260 ReferenceTemporary,
261 ObjCARCReferenceLifetimeType,
262 CodeGenFunction::destroyARCStrongImprecise,
263 cleanupKind & EHCleanup);
Douglas Gregor58df5092011-06-22 16:12:01 +0000264 break;
John McCall4bd0fb12011-07-12 16:41:08 +0000265 }
Douglas Gregor58df5092011-06-22 16:12:01 +0000266
267 case Qualifiers::OCL_Weak:
John McCall4bd0fb12011-07-12 16:41:08 +0000268 assert(!ObjCARCReferenceLifetimeType->isArrayType());
269 CGF.pushDestroy(NormalAndEHCleanup,
270 ReferenceTemporary,
271 ObjCARCReferenceLifetimeType,
272 CodeGenFunction::destroyARCWeak,
273 /*useEHCleanupForArray*/ true);
Douglas Gregor58df5092011-06-22 16:12:01 +0000274 break;
275 }
276
277 ObjCARCReferenceLifetimeType = QualType();
278 }
279
280 return ReferenceTemporary;
281 }
Rafael Espindolab4136762012-10-27 00:40:06 +0000282
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000283 SmallVector<SubobjectAdjustment, 2> Adjustments;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000284 E = E->skipRValueSubobjectAdjustments(Adjustments);
Rafael Espindolab4136762012-10-27 00:40:06 +0000285 if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
286 if (opaque->getType()->isRecordType())
287 return CGF.EmitOpaqueValueLValue(opaque).getAddress();
Douglas Gregoraae38d62010-05-22 05:17:18 +0000288
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000289 // Create a reference temporary if necessary.
John McCall7a626f62010-09-15 10:14:12 +0000290 AggValueSlot AggSlot = AggValueSlot::ignored();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000291 if (CGF.hasAggregateLLVMType(E->getType()) &&
John McCall7a626f62010-09-15 10:14:12 +0000292 !E->getType()->isAnyComplexType()) {
Anders Carlsson18c205e2010-06-27 17:23:46 +0000293 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
294 InitializedDecl);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000295 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
John McCall8d6fc952011-08-25 20:40:09 +0000296 AggValueSlot::IsDestructed_t isDestructed
297 = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000298 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
299 Qualifiers(), isDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000300 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000301 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000302 }
John McCall31168b02011-06-15 23:02:42 +0000303
Anders Carlsson18c205e2010-06-27 17:23:46 +0000304 if (InitializedDecl) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000305 // Get the destructor for the reference temporary.
306 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
307 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
308 if (!ClassDecl->hasTrivialDestructor())
Douglas Gregorbac74902010-07-01 14:13:13 +0000309 ReferenceTemporaryDtor = ClassDecl->getDestructor();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000310 }
311 }
312
John McCall31168b02011-06-15 23:02:42 +0000313 RV = CGF.EmitAnyExpr(E, AggSlot);
314
Douglas Gregor7c38f152010-05-20 08:36:28 +0000315 // Check if need to perform derived-to-base casts and/or field accesses, to
316 // get from the temporary object we created (and, potentially, for which we
317 // extended the lifetime) to the subobject we're binding the reference to.
318 if (!Adjustments.empty()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000319 llvm::Value *Object = RV.getAggregateAddr();
Douglas Gregor7c38f152010-05-20 08:36:28 +0000320 for (unsigned I = Adjustments.size(); I != 0; --I) {
321 SubobjectAdjustment &Adjustment = Adjustments[I-1];
322 switch (Adjustment.Kind) {
323 case SubobjectAdjustment::DerivedToBaseAdjustment:
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000324 Object =
325 CGF.GetAddressOfBaseClass(Object,
326 Adjustment.DerivedToBase.DerivedClass,
John McCallcf142162010-08-07 06:22:56 +0000327 Adjustment.DerivedToBase.BasePath->path_begin(),
328 Adjustment.DerivedToBase.BasePath->path_end(),
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000329 /*NullCheckValue=*/false);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000330 break;
331
332 case SubobjectAdjustment::FieldAdjustment: {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000333 LValue LV = CGF.MakeAddrLValue(Object, E->getType());
334 LV = CGF.EmitLValueForField(LV, Adjustment.Field);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000335 if (LV.isSimple()) {
336 Object = LV.getAddress();
337 break;
338 }
339
340 // For non-simple lvalues, we actually have to create a copy of
341 // the object we're binding to.
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000342 QualType T = Adjustment.Field->getType().getNonReferenceType()
343 .getUnqualifiedType();
Anders Carlsson3f48c602010-06-27 17:52:15 +0000344 Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000345 LValue TempLV = CGF.MakeAddrLValue(Object,
346 Adjustment.Field->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000347 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000348 break;
349 }
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000350
Eli Friedman13ffdd82012-06-15 23:51:06 +0000351 case SubobjectAdjustment::MemberPointerAdjustment: {
Rafael Espindolae7b11f52012-10-27 00:36:38 +0000352 llvm::Value *Ptr = CGF.EmitScalarExpr(Adjustment.Ptr.RHS);
Eli Friedman13ffdd82012-06-15 23:51:06 +0000353 Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress(
Rafael Espindolae7b11f52012-10-27 00:36:38 +0000354 CGF, Object, Ptr, Adjustment.Ptr.MPT);
Eli Friedman13ffdd82012-06-15 23:51:06 +0000355 break;
356 }
Douglas Gregor7c38f152010-05-20 08:36:28 +0000357 }
358 }
Eli Friedmanb6069252011-03-16 22:34:09 +0000359
360 return Object;
Anders Carlsson66413c22009-10-15 00:51:46 +0000361 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000362 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000363
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000364 if (RV.isAggregate())
365 return RV.getAggregateAddr();
Eli Friedmanc21cb442009-05-20 02:31:19 +0000366
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000367 // Create a temporary variable that we can bind the reference to.
Anders Carlsson18c205e2010-06-27 17:23:46 +0000368 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
369 InitializedDecl);
370
Daniel Dunbar03816342010-08-21 02:24:36 +0000371
372 unsigned Alignment =
373 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000374 if (RV.isScalar())
375 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
Daniel Dunbar03816342010-08-21 02:24:36 +0000376 /*Volatile=*/false, Alignment, E->getType());
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000377 else
378 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
379 /*Volatile=*/false);
380 return ReferenceTemporary;
381}
382
383RValue
Chris Lattnerf53c0962010-09-06 00:11:41 +0000384CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000385 const NamedDecl *InitializedDecl) {
386 llvm::Value *ReferenceTemporary = 0;
387 const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
John McCall31168b02011-06-15 23:02:42 +0000388 QualType ObjCARCReferenceLifetimeType;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000389 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
390 ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000391 ObjCARCReferenceLifetimeType,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000392 InitializedDecl);
Richard Smithb1b0ab42012-11-05 22:21:05 +0000393 if (SanitizePerformTypeCheck && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000394 // C++11 [dcl.ref]p5 (as amended by core issue 453):
395 // If a glvalue to which a reference is directly bound designates neither
396 // an existing object or function of an appropriate type nor a region of
397 // storage of suitable size and alignment to contain an object of the
398 // reference's type, the behavior is undefined.
399 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000400 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000401 }
John McCall31168b02011-06-15 23:02:42 +0000402 if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
Anders Carlsson3f48c602010-06-27 17:52:15 +0000403 return RValue::get(Value);
404
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000405 // Make sure to call the destructor for the reference temporary.
John McCall31168b02011-06-15 23:02:42 +0000406 const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl);
407 if (VD && VD->hasGlobalStorage()) {
408 if (ReferenceTemporaryDtor) {
Anders Carlsson3f48c602010-06-27 17:52:15 +0000409 llvm::Constant *DtorFn =
410 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
John McCallc84ed6a2012-05-01 06:13:13 +0000411 CGM.getCXXABI().registerGlobalDtor(*this, DtorFn,
John McCallad7c5c12011-02-08 08:22:06 +0000412 cast<llvm::Constant>(ReferenceTemporary));
John McCall31168b02011-06-15 23:02:42 +0000413 } else {
414 assert(!ObjCARCReferenceLifetimeType.isNull());
415 // Note: We intentionally do not register a global "destructor" to
416 // release the object.
Anders Carlsson3f48c602010-06-27 17:52:15 +0000417 }
John McCall31168b02011-06-15 23:02:42 +0000418
419 return RValue::get(Value);
Anders Carlsson3f48c602010-06-27 17:52:15 +0000420 }
John McCall8680f872010-07-21 06:29:51 +0000421
John McCall31168b02011-06-15 23:02:42 +0000422 if (ReferenceTemporaryDtor)
423 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
424 else {
425 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
426 case Qualifiers::OCL_None:
David Blaikie83d382b2011-09-23 05:06:16 +0000427 llvm_unreachable(
428 "Not a reference temporary that needs to be deallocated");
John McCall31168b02011-06-15 23:02:42 +0000429 case Qualifiers::OCL_ExplicitNone:
430 case Qualifiers::OCL_Autoreleasing:
431 // Nothing to do.
432 break;
433
John McCall4bd0fb12011-07-12 16:41:08 +0000434 case Qualifiers::OCL_Strong: {
435 bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>();
436 CleanupKind cleanupKind = getARCCleanupKind();
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000437 pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000438 precise ? destroyARCStrongPrecise : destroyARCStrongImprecise,
439 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000440 break;
John McCall4bd0fb12011-07-12 16:41:08 +0000441 }
John McCall31168b02011-06-15 23:02:42 +0000442
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000443 case Qualifiers::OCL_Weak: {
John McCall31168b02011-06-15 23:02:42 +0000444 // __weak objects always get EH cleanups; otherwise, exceptions
445 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000446 pushDestroy(NormalAndEHCleanup, ReferenceTemporary,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000447 ObjCARCReferenceLifetimeType, destroyARCWeak, true);
John McCall31168b02011-06-15 23:02:42 +0000448 break;
449 }
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000450 }
John McCall31168b02011-06-15 23:02:42 +0000451 }
452
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000453 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000454}
455
456
Mike Stump4a3999f2009-09-09 13:00:44 +0000457/// getAccessedFieldNo - Given an encoded value and a result number, return the
458/// input field number being accessed.
459unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000460 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000461 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
462 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000463}
464
Richard Smith4d3110a2012-10-25 02:14:12 +0000465/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
466static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
467 llvm::Value *High) {
468 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
469 llvm::Value *K47 = Builder.getInt64(47);
470 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
471 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
472 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
473 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
474 return Builder.CreateMul(B1, KMul);
475}
476
Richard Smithe30752c2012-10-09 19:52:38 +0000477void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
478 llvm::Value *Address,
Richard Smith4d1458e2012-09-08 02:08:36 +0000479 QualType Ty, CharUnits Alignment) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000480 if (!SanitizePerformTypeCheck)
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000481 return;
482
Richard Smith2d8b2942012-11-01 07:22:08 +0000483 // Don't check pointers outside the default address space. The null check
484 // isn't correct, the object-size check isn't supported by LLVM, and we can't
485 // communicate the addresses to the runtime handler for the vptr check.
486 if (Address->getType()->getPointerAddressSpace())
487 return;
488
Richard Smith69d0d262012-08-24 00:54:33 +0000489 llvm::Value *Cond = 0;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000490
Will Dietzf54319c2013-01-18 11:30:38 +0000491 if (SanOpts->Null) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000492 // The glvalue must not be an empty glvalue.
493 Cond = Builder.CreateICmpNE(
494 Address, llvm::Constant::getNullValue(Address->getType()));
495 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000496
Will Dietzf54319c2013-01-18 11:30:38 +0000497 if (SanOpts->ObjectSize && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000498 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000499
Richard Smith69d0d262012-08-24 00:54:33 +0000500 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000501 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000502 // to check this.
503 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy);
504 llvm::Value *Min = Builder.getFalse();
Richard Smith2d8b2942012-11-01 07:22:08 +0000505 llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000506 llvm::Value *LargeEnough =
Richard Smith2d8b2942012-11-01 07:22:08 +0000507 Builder.CreateICmpUGE(Builder.CreateCall2(F, CastAddr, Min),
Richard Smith69d0d262012-08-24 00:54:33 +0000508 llvm::ConstantInt::get(IntPtrTy, Size));
509 Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough;
Richard Smithe30752c2012-10-09 19:52:38 +0000510 }
Richard Smith69d0d262012-08-24 00:54:33 +0000511
Richard Smithb1b0ab42012-11-05 22:21:05 +0000512 uint64_t AlignVal = 0;
513
Will Dietzf54319c2013-01-18 11:30:38 +0000514 if (SanOpts->Alignment) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000515 AlignVal = Alignment.getQuantity();
516 if (!Ty->isIncompleteType() && !AlignVal)
517 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
518
Richard Smith69d0d262012-08-24 00:54:33 +0000519 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000520 if (AlignVal) {
521 llvm::Value *Align =
522 Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
523 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
524 llvm::Value *Aligned =
525 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
526 Cond = Cond ? Builder.CreateAnd(Cond, Aligned) : Aligned;
527 }
Richard Smith69d0d262012-08-24 00:54:33 +0000528 }
529
Richard Smithe30752c2012-10-09 19:52:38 +0000530 if (Cond) {
531 llvm::Constant *StaticData[] = {
532 EmitCheckSourceLocation(Loc),
533 EmitCheckTypeDescriptor(Ty),
534 llvm::ConstantInt::get(SizeTy, AlignVal),
535 llvm::ConstantInt::get(Int8Ty, TCK)
536 };
Will Dietz88e02332012-12-02 19:50:33 +0000537 EmitCheck(Cond, "type_mismatch", StaticData, Address, CRK_Recoverable);
Richard Smithe30752c2012-10-09 19:52:38 +0000538 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000539
Richard Smithb1b0ab42012-11-05 22:21:05 +0000540 // If possible, check that the vptr indicates that there is a subobject of
541 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000542 //
543 // C++11 [basic.life]p5,6:
544 // [For storage which does not refer to an object within its lifetime]
545 // The program has undefined behavior if:
546 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000547 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000548 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Will Dietzf54319c2013-01-18 11:30:38 +0000549 if (SanOpts->Vptr &&
Richard Smithbe024a82012-12-18 00:22:45 +0000550 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000551 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000552 // Compute a hash of the mangled name of the type.
553 //
554 // FIXME: This is not guaranteed to be deterministic! Move to a
555 // fingerprinting mechanism once LLVM provides one. For the time
556 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000557 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000558 llvm::raw_svector_ostream Out(MangledName);
559 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
560 Out);
561 llvm::hash_code TypeHash = hash_value(Out.str());
562
563 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
564 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
565 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
566 llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
567 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
568 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
569
570 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
571 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
572
573 // Look the hash up in our cache.
574 const int CacheSize = 128;
575 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
576 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
577 "__ubsan_vptr_type_cache");
578 llvm::Value *Slot = Builder.CreateAnd(Hash,
579 llvm::ConstantInt::get(IntPtrTy,
580 CacheSize-1));
581 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
582 llvm::Value *CacheVal =
583 Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
584
585 // If the hash isn't in the cache, call a runtime handler to perform the
586 // hard work of checking whether the vptr is for an object of the right
587 // type. This will either fill in the cache and return, or produce a
588 // diagnostic.
589 llvm::Constant *StaticData[] = {
590 EmitCheckSourceLocation(Loc),
591 EmitCheckTypeDescriptor(Ty),
592 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
593 llvm::ConstantInt::get(Int8Ty, TCK)
594 };
595 llvm::Value *DynamicData[] = { Address, Hash };
596 EmitCheck(Builder.CreateICmpEQ(CacheVal, Hash),
Will Dietz88e02332012-12-02 19:50:33 +0000597 "dynamic_type_cache_miss", StaticData, DynamicData,
598 CRK_AlwaysRecoverable);
Richard Smith4d3110a2012-10-25 02:14:12 +0000599 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000600}
Chris Lattner4647a212007-08-31 22:49:20 +0000601
Chris Lattner116ce8f2010-01-09 21:40:03 +0000602
Chris Lattner116ce8f2010-01-09 21:40:03 +0000603CodeGenFunction::ComplexPairTy CodeGenFunction::
604EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
605 bool isInc, bool isPre) {
606 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
607 LV.isVolatileQualified());
608
609 llvm::Value *NextVal;
610 if (isa<llvm::IntegerType>(InVal.first->getType())) {
611 uint64_t AmountVal = isInc ? 1 : -1;
612 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
613
614 // Add the inc/dec to the real part.
615 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
616 } else {
617 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
618 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
619 if (!isInc)
620 FVal.changeSign();
621 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
622
623 // Add the inc/dec to the real part.
624 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
625 }
626
627 ComplexPairTy IncVal(NextVal, InVal.second);
628
629 // Store the updated result through the lvalue.
630 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
631
632 // If this is a postinc, return the value read from memory, otherwise use the
633 // updated value.
634 return isPre ? IncVal : InVal;
635}
636
637
Chris Lattnera45c5af2007-06-02 19:47:04 +0000638//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000639// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000640//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000641
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000642RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000643 if (Ty->isVoidType())
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000644 return RValue::get(0);
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000645
646 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000647 llvm::Type *EltTy = ConvertType(CTy->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000648 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000649 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000650 }
651
Chris Lattner65526f02010-08-23 05:26:13 +0000652 // If this is a use of an undefined aggregate type, the aggregate must have an
653 // identifiable address. Just because the contents of the value are undefined
654 // doesn't mean that the address can't be taken and compared.
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000655 if (hasAggregateLLVMType(Ty)) {
Chris Lattner65526f02010-08-23 05:26:13 +0000656 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
657 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000658 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000659
660 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000661}
662
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000663RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
664 const char *Name) {
665 ErrorUnsupported(E, Name);
666 return GetUndefRValue(E->getType());
667}
668
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000669LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
670 const char *Name) {
671 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000672 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000673 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000674}
675
Richard Smith4d1458e2012-09-08 02:08:36 +0000676LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000677 LValue LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000678 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
Richard Smithe30752c2012-10-09 19:52:38 +0000679 EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
680 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000681 return LV;
682}
683
Chris Lattner8394d792007-06-05 20:53:16 +0000684/// EmitLValue - Emit code to compute a designator that specifies the location
685/// of the expression.
686///
Mike Stump4a3999f2009-09-09 13:00:44 +0000687/// This can return one of two things: a simple address or a bitfield reference.
688/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
689/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000690///
Mike Stump4a3999f2009-09-09 13:00:44 +0000691/// If this returns a bitfield reference, nothing about the pointee type of the
692/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000693///
Mike Stump4a3999f2009-09-09 13:00:44 +0000694/// If this returns a normal address, and if the lvalue's C type is fixed size,
695/// this method guarantees that the returned pointer type will point to an LLVM
696/// type of the same size of the lvalue's type. If the lvalue has a variable
697/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000698///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000699LValue CodeGenFunction::EmitLValue(const Expr *E) {
700 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000701 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000702
John McCallc109a252011-11-07 03:59:57 +0000703 case Expr::ObjCPropertyRefExprClass:
704 llvm_unreachable("cannot emit a property reference directly");
705
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000706 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000707 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000708 case Expr::ObjCIsaExprClass:
709 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000710 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000711 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
Douglas Gregor914af212010-04-23 04:16:32 +0000712 case Expr::CompoundAssignOperatorClass:
John McCalla2342eb2010-12-05 02:00:02 +0000713 if (!E->getType()->isAnyComplexType())
714 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
715 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000716 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000717 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000718 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000719 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000720 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000721 case Expr::VAArgExprClass:
722 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000723 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000724 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000725 case Expr::ParenExprClass:
726 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000727 case Expr::GenericSelectionExprClass:
728 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000729 case Expr::PredefinedExprClass:
730 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000731 case Expr::StringLiteralClass:
732 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000733 case Expr::ObjCEncodeExprClass:
734 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000735 case Expr::PseudoObjectExprClass:
736 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000737 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000738 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000739 case Expr::CXXTemporaryObjectExprClass:
740 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000741 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
742 case Expr::CXXBindTemporaryExprClass:
743 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000744 case Expr::CXXUuidofExprClass:
745 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000746 case Expr::LambdaExprClass:
747 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000748
749 case Expr::ExprWithCleanupsClass: {
750 const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E);
751 enterFullExpression(cleanups);
752 RunCleanupsScope Scope(*this);
753 return EmitLValue(cleanups->getSubExpr());
754 }
755
Douglas Gregor747eb782010-07-08 06:14:04 +0000756 case Expr::CXXScalarValueInitExprClass:
757 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
Anders Carlsson52ce3bb2009-11-14 01:51:50 +0000758 case Expr::CXXDefaultArgExprClass:
759 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Mike Stumpc9b231c2009-11-15 08:09:41 +0000760 case Expr::CXXTypeidExprClass:
761 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000762
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000763 case Expr::ObjCMessageExprClass:
764 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000765 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +0000766 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +0000767 case Expr::StmtExprClass:
768 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000769 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +0000770 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000771 case Expr::ArraySubscriptExprClass:
772 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +0000773 case Expr::ExtVectorElementExprClass:
774 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000775 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +0000776 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +0000777 case Expr::CompoundLiteralExprClass:
778 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +0000779 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +0000780 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +0000781 case Expr::BinaryConditionalOperatorClass:
782 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +0000783 case Expr::ChooseExprClass:
Eli Friedmane0a5b8b2009-03-04 05:52:32 +0000784 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
John McCall1bf58462011-02-16 08:02:54 +0000785 case Expr::OpaqueValueExprClass:
786 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +0000787 case Expr::SubstNonTypeTemplateParmExprClass:
788 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +0000789 case Expr::ImplicitCastExprClass:
790 case Expr::CStyleCastExprClass:
791 case Expr::CXXFunctionalCastExprClass:
792 case Expr::CXXStaticCastExprClass:
793 case Expr::CXXDynamicCastExprClass:
794 case Expr::CXXReinterpretCastExprClass:
795 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +0000796 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +0000797 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000798
Douglas Gregorfe314812011-06-21 17:03:29 +0000799 case Expr::MaterializeTemporaryExprClass:
800 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000801 }
802}
803
John McCall71335052012-03-10 03:05:10 +0000804/// Given an object of the given canonical type, can we safely copy a
805/// value out of it based on its initializer?
806static bool isConstantEmittableObjectType(QualType type) {
807 assert(type.isCanonical());
808 assert(!type->isReferenceType());
809
810 // Must be const-qualified but non-volatile.
811 Qualifiers qs = type.getLocalQualifiers();
812 if (!qs.hasConst() || qs.hasVolatile()) return false;
813
814 // Otherwise, all object types satisfy this except C++ classes with
815 // mutable subobjects or non-trivial copy/destroy behavior.
816 if (const RecordType *RT = dyn_cast<RecordType>(type))
817 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
818 if (RD->hasMutableFields() || !RD->isTrivial())
819 return false;
820
821 return true;
822}
823
824/// Can we constant-emit a load of a reference to a variable of the
825/// given type? This is different from predicates like
826/// Decl::isUsableInConstantExpressions because we do want it to apply
827/// in situations that don't necessarily satisfy the language's rules
828/// for this (e.g. C++'s ODR-use rules). For example, we want to able
829/// to do this with const float variables even if those variables
830/// aren't marked 'constexpr'.
831enum ConstantEmissionKind {
832 CEK_None,
833 CEK_AsReferenceOnly,
834 CEK_AsValueOrReference,
835 CEK_AsValueOnly
836};
837static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
838 type = type.getCanonicalType();
839 if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) {
840 if (isConstantEmittableObjectType(ref->getPointeeType()))
841 return CEK_AsValueOrReference;
842 return CEK_AsReferenceOnly;
843 }
844 if (isConstantEmittableObjectType(type))
845 return CEK_AsValueOnly;
846 return CEK_None;
847}
848
849/// Try to emit a reference to the given value without producing it as
850/// an l-value. This is actually more than an optimization: we can't
851/// produce an l-value for variables that we never actually captured
852/// in a block or lambda, which means const int variables or constexpr
853/// literals or similar.
854CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +0000855CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
856 ValueDecl *value = refExpr->getDecl();
857
John McCall71335052012-03-10 03:05:10 +0000858 // The value needs to be an enum constant or a constant variable.
859 ConstantEmissionKind CEK;
860 if (isa<ParmVarDecl>(value)) {
861 CEK = CEK_None;
862 } else if (VarDecl *var = dyn_cast<VarDecl>(value)) {
863 CEK = checkVarTypeForConstantEmission(var->getType());
864 } else if (isa<EnumConstantDecl>(value)) {
865 CEK = CEK_AsValueOnly;
866 } else {
867 CEK = CEK_None;
868 }
869 if (CEK == CEK_None) return ConstantEmission();
870
John McCall71335052012-03-10 03:05:10 +0000871 Expr::EvalResult result;
872 bool resultIsReference;
873 QualType resultType;
874
875 // It's best to evaluate all the way as an r-value if that's permitted.
876 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +0000877 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000878 resultIsReference = false;
879 resultType = refExpr->getType();
880
881 // Otherwise, try to evaluate as an l-value.
882 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +0000883 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000884 resultIsReference = true;
885 resultType = value->getType();
886
887 // Failure.
888 } else {
889 return ConstantEmission();
890 }
891
892 // In any case, if the initializer has side-effects, abandon ship.
893 if (result.HasSideEffects)
894 return ConstantEmission();
895
896 // Emit as a constant.
897 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
898
899 // Make sure we emit a debug reference to the global variable.
900 // This should probably fire even for
901 if (isa<VarDecl>(value)) {
902 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
John McCall113bee02012-03-10 09:33:50 +0000903 EmitDeclRefExprDbgValue(refExpr, C);
John McCall71335052012-03-10 03:05:10 +0000904 } else {
905 assert(isa<EnumConstantDecl>(value));
John McCall113bee02012-03-10 09:33:50 +0000906 EmitDeclRefExprDbgValue(refExpr, C);
John McCall71335052012-03-10 03:05:10 +0000907 }
908
909 // If we emitted a reference constant, we need to dereference that.
910 if (resultIsReference)
911 return ConstantEmission::forReference(C);
912
913 return ConstantEmission::forValue(C);
914}
915
John McCall1553b192011-06-16 04:16:24 +0000916llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
917 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +0000918 lvalue.getAlignment().getQuantity(),
919 lvalue.getType(), lvalue.getTBAAInfo());
John McCall1553b192011-06-16 04:16:24 +0000920}
921
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000922static bool hasBooleanRepresentation(QualType Ty) {
923 if (Ty->isBooleanType())
924 return true;
925
926 if (const EnumType *ET = Ty->getAs<EnumType>())
927 return ET->getDecl()->getIntegerType()->isBooleanType();
928
Douglas Gregor298f43d2012-04-12 20:42:30 +0000929 if (const AtomicType *AT = Ty->getAs<AtomicType>())
930 return hasBooleanRepresentation(AT->getValueType());
931
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000932 return false;
933}
934
Richard Smith1629da92012-12-13 07:11:50 +0000935static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
936 llvm::APInt &Min, llvm::APInt &End,
937 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000938 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +0000939 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
940 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000941 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000942 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +0000943 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000944
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000945 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +0000946 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
947 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000948 } else {
949 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +0000950 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000951 unsigned Bitwidth = LTy->getScalarSizeInBits();
952 unsigned NumNegativeBits = ED->getNumNegativeBits();
953 unsigned NumPositiveBits = ED->getNumPositiveBits();
954
955 if (NumNegativeBits) {
956 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
957 assert(NumBits <= Bitwidth);
958 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
959 Min = -End;
960 } else {
961 assert(NumPositiveBits <= Bitwidth);
962 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
963 Min = llvm::APInt(Bitwidth, 0);
964 }
965 }
Richard Smith1629da92012-12-13 07:11:50 +0000966 return true;
967}
968
969llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
970 llvm::APInt Min, End;
971 if (!getRangeForType(*this, Ty, Min, End,
972 CGM.getCodeGenOpts().StrictEnums))
973 return 0;
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000974
Duncan Sandsc720e782012-04-15 18:04:54 +0000975 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +0000976 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000977}
978
Daniel Dunbar1d425462009-02-10 00:57:50 +0000979llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
Dan Gohman947c9af2010-10-14 23:06:10 +0000980 unsigned Alignment, QualType Ty,
981 llvm::MDNode *TBAAInfo) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +0000982
983 // For better performance, handle vector loads differently.
984 if (Ty->isVectorType()) {
985 llvm::Value *V;
986 const llvm::Type *EltTy =
987 cast<llvm::PointerType>(Addr->getType())->getElementType();
988
989 const llvm::VectorType *VTy = cast<llvm::VectorType>(EltTy);
990
991 // Handle vectors of size 3, like size 4 for better performance.
992 if (VTy->getNumElements() == 3) {
993
994 // Bitcast to vec4 type.
995 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
996 4);
997 llvm::PointerType *ptVec4Ty =
998 llvm::PointerType::get(vec4Ty,
999 (cast<llvm::PointerType>(
1000 Addr->getType()))->getAddressSpace());
1001 llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
1002 "castToVec4");
1003 // Now load value.
1004 llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001005
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001006 // Shuffle vector to get vec3.
Richard Smithf0480fc2012-12-13 05:41:48 +00001007 llvm::Constant *Mask[] = {
1008 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
1009 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
1010 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
1011 };
1012
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001013 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1014 V = Builder.CreateShuffleVector(LoadVal,
1015 llvm::UndefValue::get(vec4Ty),
1016 MaskV, "extractVec");
1017 return EmitFromMemory(V, Ty);
1018 }
1019 }
1020
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001021 llvm::LoadInst *Load = Builder.CreateLoad(Addr);
Daniel Dunbarc76493a2009-11-29 21:23:36 +00001022 if (Volatile)
1023 Load->setVolatile(true);
Daniel Dunbar03816342010-08-21 02:24:36 +00001024 if (Alignment)
1025 Load->setAlignment(Alignment);
Dan Gohman947c9af2010-10-14 23:06:10 +00001026 if (TBAAInfo)
1027 CGM.DecorateInstruction(Load, TBAAInfo);
David Chisnallfa35df62012-01-16 17:27:18 +00001028 // If this is an atomic type, all normal reads must be atomic
1029 if (Ty->isAtomicType())
1030 Load->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001031
Will Dietzf54319c2013-01-18 11:30:38 +00001032 if ((SanOpts->Bool && hasBooleanRepresentation(Ty)) ||
1033 (SanOpts->Enum && Ty->getAs<EnumType>())) {
Richard Smith1629da92012-12-13 07:11:50 +00001034 llvm::APInt Min, End;
1035 if (getRangeForType(*this, Ty, Min, End, true)) {
1036 --End;
1037 llvm::Value *Check;
1038 if (!Min)
1039 Check = Builder.CreateICmpULE(
1040 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1041 else {
1042 llvm::Value *Upper = Builder.CreateICmpSLE(
1043 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1044 llvm::Value *Lower = Builder.CreateICmpSGE(
1045 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1046 Check = Builder.CreateAnd(Upper, Lower);
1047 }
1048 // FIXME: Provide a SourceLocation.
1049 EmitCheck(Check, "load_invalid_value", EmitCheckTypeDescriptor(Ty),
1050 EmitCheckValue(Load), CRK_Recoverable);
1051 }
1052 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001053 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1054 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001055
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001056 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001057}
1058
John McCall3a7f6922010-10-27 20:58:56 +00001059llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1060 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001061 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001062 // This should really always be an i1, but sometimes it's already
1063 // an i8, and it's awkward to track those cases down.
1064 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001065 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1066 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1067 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001068 }
1069
1070 return Value;
1071}
1072
1073llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1074 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001075 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001076 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1077 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001078 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1079 }
1080
1081 return Value;
1082}
1083
Daniel Dunbar1d425462009-02-10 00:57:50 +00001084void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
Daniel Dunbar03816342010-08-21 02:24:36 +00001085 bool Volatile, unsigned Alignment,
Dan Gohman947c9af2010-10-14 23:06:10 +00001086 QualType Ty,
David Chisnallfa35df62012-01-16 17:27:18 +00001087 llvm::MDNode *TBAAInfo,
1088 bool isInit) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001089
1090 // Handle vectors differently to get better performance.
1091 if (Ty->isVectorType()) {
1092 llvm::Type *SrcTy = Value->getType();
1093 llvm::VectorType *VecTy = cast<llvm::VectorType>(SrcTy);
1094 // Handle vec3 special.
1095 if (VecTy->getNumElements() == 3) {
1096 llvm::LLVMContext &VMContext = getLLVMContext();
1097
1098 // Our source is a vec3, do a shuffle vector to make it a vec4.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001099 SmallVector<llvm::Constant*, 4> Mask;
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001100 Mask.push_back(llvm::ConstantInt::get(
1101 llvm::Type::getInt32Ty(VMContext),
1102 0));
1103 Mask.push_back(llvm::ConstantInt::get(
1104 llvm::Type::getInt32Ty(VMContext),
1105 1));
1106 Mask.push_back(llvm::ConstantInt::get(
1107 llvm::Type::getInt32Ty(VMContext),
1108 2));
1109 Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
1110
1111 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1112 Value = Builder.CreateShuffleVector(Value,
1113 llvm::UndefValue::get(VecTy),
1114 MaskV, "extractVec");
1115 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1116 }
1117 llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
1118 if (DstPtr->getElementType() != SrcTy) {
1119 llvm::Type *MemTy =
1120 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
1121 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
1122 }
1123 }
1124
John McCall3a7f6922010-10-27 20:58:56 +00001125 Value = EmitToMemory(Value, Ty);
Chris Lattner1a5f8972011-07-10 03:38:35 +00001126
Daniel Dunbar03816342010-08-21 02:24:36 +00001127 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1128 if (Alignment)
1129 Store->setAlignment(Alignment);
Dan Gohman947c9af2010-10-14 23:06:10 +00001130 if (TBAAInfo)
1131 CGM.DecorateInstruction(Store, TBAAInfo);
David Chisnallfa35df62012-01-16 17:27:18 +00001132 if (!isInit && Ty->isAtomicType())
1133 Store->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001134}
1135
David Chisnallfa35df62012-01-16 17:27:18 +00001136void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1137 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001138 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +00001139 lvalue.getAlignment().getQuantity(), lvalue.getType(),
David Chisnallfa35df62012-01-16 17:27:18 +00001140 lvalue.getTBAAInfo(), isInit);
John McCall1553b192011-06-16 04:16:24 +00001141}
1142
Mike Stump4a3999f2009-09-09 13:00:44 +00001143/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1144/// method emits the address of the lvalue, then loads the result as an rvalue,
1145/// returning the rvalue.
John McCall55e1fbc2011-06-25 02:11:03 +00001146RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001147 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001148 // load of a __weak object.
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001149 llvm::Value *AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001150 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1151 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001152 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001153 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1154 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1155 Object = EmitObjCConsumeObject(LV.getType(), Object);
1156 return RValue::get(Object);
1157 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001158
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001159 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001160 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001161
John McCalla1dee5302010-08-22 10:59:02 +00001162 // Everything needs a load.
John McCall55e1fbc2011-06-25 02:11:03 +00001163 return RValue::get(EmitLoadOfScalar(LV));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001164 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001165
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001166 if (LV.isVectorElt()) {
Eli Friedman610bb872012-03-22 22:36:39 +00001167 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1168 LV.isVolatileQualified());
1169 Load->setAlignment(LV.getAlignment().getQuantity());
1170 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001171 "vecext"));
1172 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001173
1174 // If this is a reference to a subset of the elements of a vector, either
1175 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001176 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001177 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001178
John McCallc109a252011-11-07 03:59:57 +00001179 assert(LV.isBitField() && "Unknown LValue type!");
1180 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001181}
1182
John McCall55e1fbc2011-06-25 02:11:03 +00001183RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001184 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001185
Daniel Dunbar3447a022010-04-13 23:34:15 +00001186 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001187 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001188
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001189 llvm::Value *Ptr = LV.getBitFieldAddr();
1190 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),
1191 "bf.load");
1192 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
Mike Stump4a3999f2009-09-09 13:00:44 +00001193
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001194 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001195 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001196 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1197 if (HighBits)
1198 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1199 if (Info.Offset + HighBits)
1200 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1201 } else {
1202 if (Info.Offset)
1203 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001204 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001205 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1206 Info.Size),
1207 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001208 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001209 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001210
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001211 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001212}
1213
Nate Begemanb699c9b2009-01-18 06:42:49 +00001214// If this is a reference to a subset of the elements of a vector, create an
1215// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001216RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
Eli Friedman610bb872012-03-22 22:36:39 +00001217 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1218 LV.isVolatileQualified());
1219 Load->setAlignment(LV.getAlignment().getQuantity());
1220 llvm::Value *Vec = Load;
Mike Stump4a3999f2009-09-09 13:00:44 +00001221
Nate Begemanf322eab2008-05-09 06:41:27 +00001222 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001223
1224 // If the result of the expression is a non-vector type, we must be extracting
1225 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001226 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001227 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001228 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattner5e016ae2010-06-27 07:15:29 +00001229 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001230 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001231 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001232
1233 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001234 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001235
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001236 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001237 for (unsigned i = 0; i != NumResultElts; ++i)
1238 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001239
Chris Lattner91c08ad2011-02-15 00:14:06 +00001240 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1241 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001242 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001243 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001244}
1245
1246
Chris Lattner9369a562007-06-29 16:31:29 +00001247
Chris Lattner8394d792007-06-05 20:53:16 +00001248/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1249/// lvalue, where both are guaranteed to the have the same type, and that type
1250/// is 'Ty'.
David Chisnallfa35df62012-01-16 17:27:18 +00001251void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001252 if (!Dst.isSimple()) {
1253 if (Dst.isVectorElt()) {
1254 // Read/modify/write the vector, inserting the new element.
Eli Friedman610bb872012-03-22 22:36:39 +00001255 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1256 Dst.isVolatileQualified());
1257 Load->setAlignment(Dst.getAlignment().getQuantity());
1258 llvm::Value *Vec = Load;
Chris Lattner4647a212007-08-31 22:49:20 +00001259 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001260 Dst.getVectorIdx(), "vecins");
Eli Friedman610bb872012-03-22 22:36:39 +00001261 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1262 Dst.isVolatileQualified());
1263 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001264 return;
1265 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001266
Nate Begemance4d7fc2008-04-18 23:10:10 +00001267 // If this is an update of extended vector elements, insert them as
1268 // appropriate.
1269 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001270 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001271
John McCallc109a252011-11-07 03:59:57 +00001272 assert(Dst.isBitField() && "Unknown LValue type");
1273 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001274 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001275
John McCall31168b02011-06-15 23:02:42 +00001276 // There's special magic for assigning into an ARC-qualified l-value.
1277 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1278 switch (Lifetime) {
1279 case Qualifiers::OCL_None:
1280 llvm_unreachable("present but none");
1281
1282 case Qualifiers::OCL_ExplicitNone:
1283 // nothing special
1284 break;
1285
1286 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001287 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001288 return;
1289
1290 case Qualifiers::OCL_Weak:
1291 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1292 return;
1293
1294 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001295 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1296 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001297 // fall into the normal path
1298 break;
1299 }
1300 }
1301
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001302 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001303 // load of a __weak object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001304 llvm::Value *LvalueDst = Dst.getAddress();
1305 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001306 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001307 return;
1308 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001309
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001310 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001311 // load of a __strong object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001312 llvm::Value *LvalueDst = Dst.getAddress();
1313 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001314 if (Dst.isObjCIvar()) {
1315 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00001316 llvm::Type *ResultType = ConvertType(getContext().LongTy);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001317 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001318 llvm::Value *dst = RHS;
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001319 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1320 llvm::Value *LHS =
1321 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1322 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001323 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001324 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001325 } else if (Dst.isGlobalObjCRef()) {
1326 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1327 Dst.isThreadLocalRef());
1328 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001329 else
1330 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001331 return;
1332 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001333
Chris Lattner6278e6a2007-08-11 00:04:45 +00001334 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001335 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001336}
1337
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001338void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001339 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001340 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001341 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001342 llvm::Value *Ptr = Dst.getBitFieldAddr();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001343
Daniel Dunbar67aba792010-04-15 03:47:33 +00001344 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001345 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001346
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001347 // Cast the source to the storage type and shift it into place.
1348 SrcVal = Builder.CreateIntCast(SrcVal,
1349 Ptr->getType()->getPointerElementType(),
1350 /*IsSigned=*/false);
1351 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001352
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001353 // See if there are other bits in the bitfield's storage we'll need to load
1354 // and mask together with source before storing.
1355 if (Info.StorageSize != Info.Size) {
1356 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1357 llvm::Value *Val = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
1358 "bf.load");
1359 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1360
1361 // Mask the source value as needed.
1362 if (!hasBooleanRepresentation(Dst.getType()))
1363 SrcVal = Builder.CreateAnd(SrcVal,
1364 llvm::APInt::getLowBitsSet(Info.StorageSize,
1365 Info.Size),
1366 "bf.value");
1367 MaskedVal = SrcVal;
1368 if (Info.Offset)
1369 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1370
1371 // Mask out the original value.
1372 Val = Builder.CreateAnd(Val,
1373 ~llvm::APInt::getBitsSet(Info.StorageSize,
1374 Info.Offset,
1375 Info.Offset + Info.Size),
1376 "bf.clear");
1377
1378 // Or together the unchanged values and the source value.
1379 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1380 } else {
1381 assert(Info.Offset == 0);
1382 }
1383
1384 // Write the new value back out.
1385 llvm::StoreInst *Store = Builder.CreateStore(SrcVal, Ptr,
1386 Dst.isVolatileQualified());
1387 Store->setAlignment(Info.StorageAlignment);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001388
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001389 // Return the new value of the bit-field, if requested.
1390 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001391 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001392
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001393 // Sign extend the value if needed.
1394 if (Info.IsSigned) {
1395 assert(Info.Size <= Info.StorageSize);
1396 unsigned HighBits = Info.StorageSize - Info.Size;
1397 if (HighBits) {
1398 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1399 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1400 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001401 }
1402
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001403 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1404 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001405 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001406 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001407}
1408
Nate Begemance4d7fc2008-04-18 23:10:10 +00001409void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001410 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001411 // This access turns into a read/modify/write of the vector. Load the input
1412 // value now.
Eli Friedman610bb872012-03-22 22:36:39 +00001413 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1414 Dst.isVolatileQualified());
1415 Load->setAlignment(Dst.getAlignment().getQuantity());
1416 llvm::Value *Vec = Load;
Nate Begemanf322eab2008-05-09 06:41:27 +00001417 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001418
Chris Lattner4647a212007-08-31 22:49:20 +00001419 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001420
John McCall55e1fbc2011-06-25 02:11:03 +00001421 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001422 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001423 unsigned NumDstElts =
1424 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1425 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001426 // Use shuffle vector is the src and destination are the same number of
1427 // elements and restore the vector mask since it is on the side it will be
1428 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001429 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001430 for (unsigned i = 0; i != NumSrcElts; ++i)
1431 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001432
Chris Lattner91c08ad2011-02-15 00:14:06 +00001433 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001434 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001435 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001436 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001437 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001438 // Extended the source vector to the same length and then shuffle it
1439 // into the destination.
1440 // FIXME: since we're shuffling with undef, can we just use the indices
1441 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001442 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001443 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001444 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001445 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001446 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001447 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001448 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001449 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001450 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001451 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001452 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001453 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001454 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001455
Nate Begemanb699c9b2009-01-18 06:42:49 +00001456 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001457 for (unsigned i = 0; i != NumSrcElts; ++i)
1458 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001459 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001460 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001461 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001462 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001463 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001464 }
1465 } else {
1466 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001467 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001468 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001469 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001470 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001471
Eli Friedman610bb872012-03-22 22:36:39 +00001472 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1473 Dst.isVolatileQualified());
1474 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001475}
1476
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001477// setObjCGCLValueClass - sets class of he lvalue for the purpose of
1478// generating write-barries API. It is currently a global, ivar,
1479// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001480static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001481 LValue &LV,
1482 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001483 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001484 return;
1485
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001486 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001487 QualType ExpTy = E->getType();
1488 if (IsMemberAccess && ExpTy->isPointerType()) {
1489 // If ivar is a structure pointer, assigning to field of
1490 // this struct follows gcc's behavior and makes it a non-ivar
1491 // writer-barrier conservatively.
1492 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1493 if (ExpTy->isRecordType()) {
1494 LV.setObjCIvar(false);
1495 return;
1496 }
1497 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001498 LV.setObjCIvar(true);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001499 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1500 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001501 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001502 return;
1503 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001504
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001505 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1506 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001507 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001508 LV.setGlobalObjCRef(true);
1509 LV.setThreadLocalRef(VD->isThreadSpecified());
Fariborz Jahanian217af242010-07-20 20:30:03 +00001510 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001511 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001512 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001513 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001514 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001515
1516 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001517 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001518 return;
1519 }
1520
1521 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001522 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001523 if (LV.isObjCIvar()) {
1524 // If cast is to a structure pointer, follow gcc's behavior and make it
1525 // a non-ivar write-barrier.
1526 QualType ExpTy = E->getType();
1527 if (ExpTy->isPointerType())
1528 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1529 if (ExpTy->isRecordType())
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001530 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001531 }
1532 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001533 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001534
1535 if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1536 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1537 return;
1538 }
1539
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001540 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001541 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001542 return;
1543 }
1544
1545 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001546 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001547 return;
1548 }
John McCall31168b02011-06-15 23:02:42 +00001549
1550 if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001551 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001552 return;
1553 }
1554
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001555 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001556 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001557 if (LV.isObjCIvar() && !LV.isObjCArray())
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001558 // Using array syntax to assigning to what an ivar points to is not
1559 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001560 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001561 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1562 // Using array syntax to assigning to what global points to is not
1563 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001564 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001565 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001566 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001567
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001568 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001569 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001570 // We don't know if member is an 'ivar', but this flag is looked at
1571 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001572 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001573 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001574 }
1575}
1576
Chris Lattner3f32d692011-07-12 06:52:18 +00001577static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001578EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001579 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001580 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001581 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001582 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001583}
1584
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001585static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1586 const Expr *E, const VarDecl *VD) {
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001587 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001588 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1589 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001590 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001591 QualType T = E->getType();
1592 LValue LV;
1593 if (VD->getType()->isReferenceType()) {
1594 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001595 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001596 V = LI;
1597 LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1598 } else {
1599 LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1600 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001601 setObjCGCLValueClass(CGF.getContext(), E, LV);
1602 return LV;
1603}
1604
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001605static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001606 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001607 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001608 if (!FD->hasPrototype()) {
1609 if (const FunctionProtoType *Proto =
1610 FD->getType()->getAs<FunctionProtoType>()) {
1611 // Ugly case: for a K&R-style definition, the type of the definition
1612 // isn't the same as the type of a use. Correct for this with a
1613 // bitcast.
1614 QualType NoProtoType =
1615 CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1616 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001617 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001618 }
1619 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001620 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Daniel Dunbar5c816372010-08-21 04:20:22 +00001621 return CGF.MakeAddrLValue(V, E->getType(), Alignment);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001622}
1623
Chris Lattnerd7f58862007-06-02 05:24:33 +00001624LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001625 const NamedDecl *ND = E->getDecl();
Eli Friedmana0544d62011-12-03 04:14:32 +00001626 CharUnits Alignment = getContext().getDeclAlign(ND);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001627 QualType T = E->getType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001628
Richard Smith5a1104b2012-10-20 01:38:33 +00001629 // A DeclRefExpr for a reference initialized by a constant expression can
1630 // appear without being odr-used. Directly emit the constant initializer.
1631 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1632 const Expr *Init = VD->getAnyInitializer(VD);
1633 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
1634 VD->isUsableInConstantExpressions(getContext()) &&
1635 VD->checkInitIsICE()) {
1636 llvm::Constant *Val =
1637 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
1638 assert(Val && "failed to emit reference constant expression");
1639 // FIXME: Eventually we will want to emit vector element references.
1640 return MakeAddrLValue(Val, T, Alignment);
1641 }
1642 }
1643
Eli Friedman5720e342012-01-21 04:52:58 +00001644 // FIXME: We should be able to assert this for FunctionDecls as well!
1645 // FIXME: We should be able to assert this for all DeclRefExprs, not just
1646 // those with a valid source location.
1647 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1648 !E->getLocation().isValid()) &&
1649 "Should not use decl without marking it used!");
1650
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001651 if (ND->hasAttr<WeakRefAttr>()) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001652 const ValueDecl *VD = cast<ValueDecl>(ND);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001653 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
Richard Smith5a1104b2012-10-20 01:38:33 +00001654 return MakeAddrLValue(Aliasee, T, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001655 }
1656
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001657 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001658 // Check if this is a global variable.
Nick Lewycky230203c2013-01-10 01:46:29 +00001659 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001660 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00001661
John McCall113bee02012-03-10 09:33:50 +00001662 bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1663
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001664 bool NonGCable = VD->hasLocalStorage() &&
1665 !VD->getType()->isReferenceType() &&
John McCall113bee02012-03-10 09:33:50 +00001666 !isBlockVariable;
Anders Carlsson6eee9722009-11-07 22:46:42 +00001667
Nick Lewycky230203c2013-01-10 01:46:29 +00001668 llvm::Value *V = LocalDeclMap.lookup(VD);
Fariborz Jahanian366a9482010-09-07 23:26:17 +00001669 if (!V && VD->isStaticLocal())
Fariborz Jahanian4d55b2d2010-04-19 18:15:02 +00001670 V = CGM.getStaticLocalDeclAddress(VD);
Eli Friedman9fbeba02012-02-11 02:57:39 +00001671
1672 // Use special handling for lambdas.
John McCall113bee02012-03-10 09:33:50 +00001673 if (!V) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00001674 if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1675 QualType LambdaTagType = getContext().getTagDeclType(FD->getParent());
1676 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
1677 LambdaTagType);
1678 return EmitLValueForField(LambdaLV, FD);
1679 }
Eli Friedman9fbeba02012-02-11 02:57:39 +00001680
John McCall113bee02012-03-10 09:33:50 +00001681 assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
John McCall113bee02012-03-10 09:33:50 +00001682 return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
Richard Smith5a1104b2012-10-20 01:38:33 +00001683 T, Alignment);
John McCall113bee02012-03-10 09:33:50 +00001684 }
1685
Anders Carlsson6eee9722009-11-07 22:46:42 +00001686 assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1687
John McCall113bee02012-03-10 09:33:50 +00001688 if (isBlockVariable)
Fariborz Jahanian2f2fa722011-01-26 23:08:27 +00001689 V = BuildBlockByrefAddress(V, VD);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001690
Eli Friedmand20adbd2011-11-16 00:42:57 +00001691 LValue LV;
1692 if (VD->getType()->isReferenceType()) {
1693 llvm::LoadInst *LI = Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001694 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001695 V = LI;
1696 LV = MakeNaturalAlignAddrLValue(V, T);
1697 } else {
1698 LV = MakeAddrLValue(V, T, Alignment);
1699 }
Chris Lattner3f32d692011-07-12 06:52:18 +00001700
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001701 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00001702 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00001703 LV.setNonGC(true);
1704 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001705 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00001706 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001707 }
John McCallf3a88602011-02-03 08:15:49 +00001708
1709 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1710 return EmitFunctionDeclLValue(*this, E, fn);
1711
David Blaikie83d382b2011-09-23 05:06:16 +00001712 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001713}
Chris Lattnere47e4402007-06-01 18:02:12 +00001714
Chris Lattner8394d792007-06-05 20:53:16 +00001715LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1716 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00001717 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00001718 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001719
Chris Lattner0f398c42008-07-26 22:37:01 +00001720 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00001721 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001722 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00001723 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001724 QualType T = E->getSubExpr()->getType()->getPointeeType();
1725 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00001726
Chris Lattner2415357a2011-12-19 21:16:08 +00001727 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001728 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00001729
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001730 // We should not generate __weak write barrier on indirect reference
1731 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1732 // But, we continue to generate __strong write barrier on indirect write
1733 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00001734 if (getLangOpts().ObjC1 &&
1735 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001736 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00001737 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001738 return LV;
1739 }
John McCalle3027922010-08-25 11:45:40 +00001740 case UO_Real:
1741 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00001742 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00001743 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1744 llvm::Value *Addr = LV.getAddress();
1745
Richard Smith0b6b8e42012-02-18 20:53:32 +00001746 // __real is valid on scalars. This is a faster way of testing that.
1747 // __imag can only produce an rvalue on scalars.
1748 if (E->getOpcode() == UO_Real &&
1749 !cast<llvm::PointerType>(Addr->getType())
John McCalla2342eb2010-12-05 02:00:02 +00001750 ->getElementType()->isStructTy()) {
1751 assert(E->getSubExpr()->getType()->isArithmeticType());
1752 return LV;
1753 }
1754
1755 assert(E->getSubExpr()->getType()->isAnyComplexType());
1756
John McCalle3027922010-08-25 11:45:40 +00001757 unsigned Idx = E->getOpcode() == UO_Imag;
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001758 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
John McCalla2342eb2010-12-05 02:00:02 +00001759 Idx, "idx"),
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001760 ExprTy);
Chris Lattner595db862007-10-30 22:53:42 +00001761 }
John McCalle3027922010-08-25 11:45:40 +00001762 case UO_PreInc:
1763 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001764 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00001765 bool isInc = E->getOpcode() == UO_PreInc;
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001766
1767 if (E->getType()->isAnyComplexType())
1768 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1769 else
1770 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1771 return LV;
1772 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00001773 }
Chris Lattner8394d792007-06-05 20:53:16 +00001774}
1775
Chris Lattner4347e3692007-06-06 04:54:52 +00001776LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001777 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1778 E->getType());
Chris Lattner4347e3692007-06-06 04:54:52 +00001779}
1780
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001781LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001782 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1783 E->getType());
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001784}
1785
Nico Weber3a691a32012-06-23 02:07:59 +00001786static llvm::Constant*
1787GetAddrOfConstantWideString(StringRef Str,
1788 const char *GlobalName,
1789 ASTContext &Context,
1790 QualType Ty, SourceLocation Loc,
1791 CodeGenModule &CGM) {
1792
1793 StringLiteral *SL = StringLiteral::Create(Context,
1794 Str,
1795 StringLiteral::Wide,
1796 /*Pascal = */false,
1797 Ty, Loc);
1798 llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL);
1799 llvm::GlobalVariable *GV =
1800 new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1801 !CGM.getLangOpts().WritableStrings,
1802 llvm::GlobalValue::PrivateLinkage,
1803 C, GlobalName);
1804 const unsigned WideAlignment =
1805 Context.getTypeAlignInChars(Ty).getQuantity();
1806 GV->setAlignment(WideAlignment);
1807 return GV;
1808}
1809
Nico Weber3a691a32012-06-23 02:07:59 +00001810static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
1811 SmallString<32>& Target) {
1812 Target.resize(CharByteWidth * (Source.size() + 1));
Richard Smith639b8d02012-09-08 07:16:20 +00001813 char *ResultPtr = &Target[0];
1814 const UTF8 *ErrorPtr;
1815 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
Matt Beaumont-Gay36af16af2012-07-03 03:55:58 +00001816 (void)success;
Nico Weber4b18c3f2012-07-03 02:24:52 +00001817 assert(success);
Nico Weber3a691a32012-06-23 02:07:59 +00001818 Target.resize(ResultPtr - &Target[0]);
1819}
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001820
Mike Stump4a3999f2009-09-09 13:00:44 +00001821LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Daniel Dunbarb3517472008-10-17 21:58:32 +00001822 switch (E->getIdentType()) {
1823 default:
1824 return EmitUnsupportedLValue(E, "predefined expression");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001825
Daniel Dunbarb3517472008-10-17 21:58:32 +00001826 case PredefinedExpr::Func:
1827 case PredefinedExpr::Function:
Nico Weber3a691a32012-06-23 02:07:59 +00001828 case PredefinedExpr::LFunction:
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001829 case PredefinedExpr::PrettyFunction: {
Nico Weber3a691a32012-06-23 02:07:59 +00001830 unsigned IdentType = E->getIdentType();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001831 std::string GlobalVarName;
1832
Nico Weber3a691a32012-06-23 02:07:59 +00001833 switch (IdentType) {
David Blaikie83d382b2011-09-23 05:06:16 +00001834 default: llvm_unreachable("Invalid type");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001835 case PredefinedExpr::Func:
1836 GlobalVarName = "__func__.";
1837 break;
1838 case PredefinedExpr::Function:
1839 GlobalVarName = "__FUNCTION__.";
1840 break;
Nico Weber3a691a32012-06-23 02:07:59 +00001841 case PredefinedExpr::LFunction:
1842 GlobalVarName = "L__FUNCTION__.";
1843 break;
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001844 case PredefinedExpr::PrettyFunction:
1845 GlobalVarName = "__PRETTY_FUNCTION__.";
1846 break;
1847 }
1848
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001849 StringRef FnName = CurFn->getName();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001850 if (FnName.startswith("\01"))
1851 FnName = FnName.substr(1);
1852 GlobalVarName += FnName;
1853
1854 const Decl *CurDecl = CurCodeDecl;
1855 if (CurDecl == 0)
1856 CurDecl = getContext().getTranslationUnitDecl();
1857
1858 std::string FunctionName =
John McCall351762c2011-02-07 10:33:21 +00001859 (isa<BlockDecl>(CurDecl)
1860 ? FnName.str()
Nico Weber3a691a32012-06-23 02:07:59 +00001861 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType,
1862 CurDecl));
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001863
Nico Weber3a691a32012-06-23 02:07:59 +00001864 const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual();
1865 llvm::Constant *C;
1866 if (ElemType->isWideCharType()) {
1867 SmallString<32> RawChars;
1868 ConvertUTF8ToWideString(
1869 getContext().getTypeSizeInChars(ElemType).getQuantity(),
1870 FunctionName, RawChars);
1871 C = GetAddrOfConstantWideString(RawChars,
1872 GlobalVarName.c_str(),
1873 getContext(),
1874 E->getType(),
1875 E->getLocation(),
1876 CGM);
1877 } else {
1878 C = CGM.GetAddrOfConstantCString(FunctionName,
1879 GlobalVarName.c_str(),
1880 1);
1881 }
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001882 return MakeAddrLValue(C, E->getType());
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001883 }
Daniel Dunbarb3517472008-10-17 21:58:32 +00001884 }
Anders Carlsson625bfc82007-07-21 05:21:51 +00001885}
1886
Richard Smithe30752c2012-10-09 19:52:38 +00001887/// Emit a type description suitable for use by a runtime sanitizer library. The
1888/// format of a type descriptor is
1889///
1890/// \code
Richard Smith683398a2012-10-09 23:55:19 +00001891/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00001892/// \endcode
1893///
Richard Smith683398a2012-10-09 23:55:19 +00001894/// followed by an array of i8 containing the type name. TypeKind is 0 for an
1895/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00001896llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
1897 // FIXME: Only emit each type's descriptor once.
1898 uint16_t TypeKind = -1;
1899 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00001900
Richard Smithe30752c2012-10-09 19:52:38 +00001901 if (T->isIntegerType()) {
1902 TypeKind = 0;
1903 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00001904 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00001905 } else if (T->isFloatingType()) {
1906 TypeKind = 1;
1907 TypeInfo = getContext().getTypeSize(T);
1908 }
1909
1910 // Format the type name as if for a diagnostic, including quotes and
1911 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001912 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00001913 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
1914 (intptr_t)T.getAsOpaquePtr(),
1915 0, 0, 0, 0, 0, 0, Buffer,
1916 ArrayRef<intptr_t>());
1917
1918 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00001919 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
1920 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00001921 };
1922 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
1923
1924 llvm::GlobalVariable *GV =
1925 new llvm::GlobalVariable(CGM.getModule(), Descriptor->getType(),
1926 /*isConstant=*/true,
1927 llvm::GlobalVariable::PrivateLinkage,
1928 Descriptor);
1929 GV->setUnnamedAddr(true);
1930 return GV;
1931}
1932
1933llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
1934 llvm::Type *TargetTy = IntPtrTy;
1935
1936 // Integers which fit in intptr_t are zero-extended and passed directly.
1937 if (V->getType()->isIntegerTy() &&
1938 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
1939 return Builder.CreateZExt(V, TargetTy);
1940
1941 // Pointers are passed directly, everything else is passed by address.
1942 if (!V->getType()->isPointerTy()) {
1943 llvm::Value *Ptr = Builder.CreateAlloca(V->getType());
1944 Builder.CreateStore(V, Ptr);
1945 V = Ptr;
1946 }
1947 return Builder.CreatePtrToInt(V, TargetTy);
1948}
1949
1950/// \brief Emit a representation of a SourceLocation for passing to a handler
1951/// in a sanitizer runtime library. The format for this data is:
1952/// \code
1953/// struct SourceLocation {
1954/// const char *Filename;
1955/// int32_t Line, Column;
1956/// };
1957/// \endcode
1958/// For an invalid SourceLocation, the Filename pointer is null.
1959llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
1960 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
1961
1962 llvm::Constant *Data[] = {
1963 // FIXME: Only emit each file name once.
1964 PLoc.isValid() ? cast<llvm::Constant>(
1965 Builder.CreateGlobalStringPtr(PLoc.getFilename()))
1966 : llvm::Constant::getNullValue(Int8PtrTy),
1967 Builder.getInt32(PLoc.getLine()),
1968 Builder.getInt32(PLoc.getColumn())
1969 };
1970
1971 return llvm::ConstantStruct::getAnon(Data);
1972}
1973
1974void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001975 ArrayRef<llvm::Constant *> StaticArgs,
1976 ArrayRef<llvm::Value *> DynamicArgs,
Will Dietz88e02332012-12-02 19:50:33 +00001977 CheckRecoverableKind RecoverKind) {
Will Dietzf54319c2013-01-18 11:30:38 +00001978 assert(SanOpts != &SanitizerOptions::Disabled);
Chad Rosierae229d52013-01-29 23:31:22 +00001979
1980 if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) {
1981 assert (RecoverKind != CRK_AlwaysRecoverable &&
1982 "Runtime call required for AlwaysRecoverable kind!");
1983 return EmitTrapCheck(Checked);
1984 }
1985
Richard Smith4d1458e2012-09-08 02:08:36 +00001986 llvm::BasicBlock *Cont = createBasicBlock("cont");
1987
Richard Smithe30752c2012-10-09 19:52:38 +00001988 llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
Will Dietzddd282a2012-12-15 01:39:14 +00001989
1990 llvm::Instruction *Branch = Builder.CreateCondBr(Checked, Cont, Handler);
1991
1992 // Give hint that we very much don't expect to execute the handler
1993 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
1994 llvm::MDBuilder MDHelper(getLLVMContext());
1995 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
1996 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
1997
Richard Smithe30752c2012-10-09 19:52:38 +00001998 EmitBlock(Handler);
1999
2000 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2001 llvm::GlobalValue *InfoPtr =
Will Dietz450f1a12013-01-09 03:39:41 +00002002 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
Richard Smithe30752c2012-10-09 19:52:38 +00002003 llvm::GlobalVariable::PrivateLinkage, Info);
2004 InfoPtr->setUnnamedAddr(true);
2005
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002006 SmallVector<llvm::Value *, 4> Args;
2007 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002008 Args.reserve(DynamicArgs.size() + 1);
2009 ArgTypes.reserve(DynamicArgs.size() + 1);
2010
2011 // Handler functions take an i8* pointing to the (handler-specific) static
2012 // information block, followed by a sequence of intptr_t arguments
2013 // representing operand values.
2014 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2015 ArgTypes.push_back(Int8PtrTy);
2016 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2017 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2018 ArgTypes.push_back(IntPtrTy);
2019 }
2020
Will Dietz88e02332012-12-02 19:50:33 +00002021 bool Recover = (RecoverKind == CRK_AlwaysRecoverable) ||
2022 ((RecoverKind == CRK_Recoverable) &&
2023 CGM.getCodeGenOpts().SanitizeRecover);
2024
Richard Smithe30752c2012-10-09 19:52:38 +00002025 llvm::FunctionType *FnType =
2026 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Bill Wendlinga514ebc2012-10-15 20:36:26 +00002027 llvm::AttrBuilder B;
Will Dietz88e02332012-12-02 19:50:33 +00002028 if (!Recover) {
Bill Wendling207f0532012-12-20 19:27:06 +00002029 B.addAttribute(llvm::Attribute::NoReturn)
2030 .addAttribute(llvm::Attribute::NoUnwind);
Richard Smith4d3110a2012-10-25 02:14:12 +00002031 }
Bill Wendling207f0532012-12-20 19:27:06 +00002032 B.addAttribute(llvm::Attribute::UWTable);
Will Dietz88e02332012-12-02 19:50:33 +00002033
2034 // Checks that have two variants use a suffix to differentiate them
2035 bool NeedsAbortSuffix = (RecoverKind != CRK_Unrecoverable) &&
2036 !CGM.getCodeGenOpts().SanitizeRecover;
Richard Smith78f6b032012-12-03 22:39:14 +00002037 std::string FunctionName = ("__ubsan_handle_" + CheckName +
2038 (NeedsAbortSuffix? "_abort" : "")).str();
2039 llvm::Value *Fn =
2040 CGM.CreateRuntimeFunction(FnType, FunctionName,
Bill Wendling8594fcb2013-01-31 00:30:05 +00002041 llvm::AttributeSet::get(getLLVMContext(),
2042 llvm::AttributeSet::FunctionIndex,
2043 B));
Richard Smithe30752c2012-10-09 19:52:38 +00002044 llvm::CallInst *HandlerCall = Builder.CreateCall(Fn, Args);
Will Dietz88e02332012-12-02 19:50:33 +00002045 if (Recover) {
Richard Smith4d3110a2012-10-25 02:14:12 +00002046 Builder.CreateBr(Cont);
2047 } else {
2048 HandlerCall->setDoesNotReturn();
2049 HandlerCall->setDoesNotThrow();
2050 Builder.CreateUnreachable();
2051 }
Richard Smithe30752c2012-10-09 19:52:38 +00002052
Richard Smith4d1458e2012-09-08 02:08:36 +00002053 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002054}
2055
Chad Rosierae229d52013-01-29 23:31:22 +00002056void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002057 llvm::BasicBlock *Cont = createBasicBlock("cont");
2058
2059 // If we're optimizing, collapse all calls to trap down to just one per
2060 // function to save on code size.
2061 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2062 TrapBB = createBasicBlock("trap");
2063 Builder.CreateCondBr(Checked, Cont, TrapBB);
2064 EmitBlock(TrapBB);
2065 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
2066 llvm::CallInst *TrapCall = Builder.CreateCall(F);
2067 TrapCall->setDoesNotReturn();
2068 TrapCall->setDoesNotThrow();
2069 Builder.CreateUnreachable();
2070 } else {
2071 Builder.CreateCondBr(Checked, Cont, TrapBB);
2072 }
2073
2074 EmitBlock(Cont);
2075}
2076
Chris Lattner6c5abe82010-06-26 23:03:20 +00002077/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2078/// array to pointer, return the array subexpression.
2079static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2080 // If this isn't just an array->pointer decay, bail out.
2081 const CastExpr *CE = dyn_cast<CastExpr>(E);
John McCalle3027922010-08-25 11:45:40 +00002082 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
Chris Lattner6c5abe82010-06-26 23:03:20 +00002083 return 0;
2084
2085 // If this is a decay from variable width array, bail out.
2086 const Expr *SubExpr = CE->getSubExpr();
2087 if (SubExpr->getType()->isVariableArrayType())
2088 return 0;
2089
2090 return SubExpr;
2091}
2092
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002093LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002094 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002095 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002096 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002097 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002098
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002099 // If the base is a vector type, then we are forming a vector element lvalue
2100 // with this subscript.
Eli Friedman327944b2008-06-13 23:01:12 +00002101 if (E->getBase()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002102 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002103 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002104 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
John McCallad7c5c12011-02-08 08:22:06 +00002105 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
Eli Friedman327944b2008-06-13 23:01:12 +00002106 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
Eli Friedman610bb872012-03-22 22:36:39 +00002107 E->getBase()->getType(), LHS.getAlignment());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002108 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002109
Ted Kremenekc81614d2007-08-20 16:18:38 +00002110 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002111 if (Idx->getType() != IntPtrTy)
2112 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002113
Mike Stump4a3999f2009-09-09 13:00:44 +00002114 // We know that the pointer points to a type of the correct size, unless the
2115 // size is a VLA or Objective-C interface.
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002116 llvm::Value *Address = 0;
Eli Friedmana0544d62011-12-03 04:14:32 +00002117 CharUnits ArrayAlignment;
John McCall23c29fe2011-06-24 21:55:10 +00002118 if (const VariableArrayType *vla =
Anders Carlsson3d312f82008-12-21 00:11:23 +00002119 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002120 // The base must be a pointer, which is not an aggregate. Emit
2121 // it. It needs to be emitted first in case it's what captures
2122 // the VLA bounds.
2123 Address = EmitScalarExpr(E->getBase());
Mike Stump4a3999f2009-09-09 13:00:44 +00002124
John McCall23c29fe2011-06-24 21:55:10 +00002125 // The element count here is the total number of non-VLA elements.
2126 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002127
John McCall77527a82011-06-25 01:32:37 +00002128 // Effectively, the multiply by the VLA size is part of the GEP.
2129 // GEP indexes are signed, and scaling an index isn't permitted to
2130 // signed-overflow, so we use the same semantics for our explicit
2131 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002132 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002133 Idx = Builder.CreateMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00002134 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00002135 } else {
2136 Idx = Builder.CreateNSWMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00002137 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00002138 }
Chris Lattner6c5abe82010-06-26 23:03:20 +00002139 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2140 // Indexing over an interface, as in "NSString *P; P[4];"
Mike Stump4a3999f2009-09-09 13:00:44 +00002141 llvm::Value *InterfaceSize =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002142 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck40775002010-01-11 17:06:35 +00002143 getContext().getTypeSizeInChars(OIT).getQuantity());
Mike Stump4a3999f2009-09-09 13:00:44 +00002144
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002145 Idx = Builder.CreateMul(Idx, InterfaceSize);
2146
Chris Lattner6c5abe82010-06-26 23:03:20 +00002147 // The base must be a pointer, which is not an aggregate. Emit it.
2148 llvm::Value *Base = EmitScalarExpr(E->getBase());
John McCallad7c5c12011-02-08 08:22:06 +00002149 Address = EmitCastToVoidPtr(Base);
2150 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002151 Address = Builder.CreateBitCast(Address, Base->getType());
Chris Lattner6c5abe82010-06-26 23:03:20 +00002152 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2153 // If this is A[i] where A is an array, the frontend will have decayed the
2154 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2155 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2156 // "gep x, i" here. Emit one "gep A, 0, i".
2157 assert(Array->getType()->isArrayType() &&
2158 "Array to pointer decay must have array source type!");
Daniel Dunbar82634272011-04-01 00:49:43 +00002159 LValue ArrayLV = EmitLValue(Array);
2160 llvm::Value *ArrayPtr = ArrayLV.getAddress();
Chris Lattner6c5abe82010-06-26 23:03:20 +00002161 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2162 llvm::Value *Args[] = { Zero, Idx };
2163
Daniel Dunbar82634272011-04-01 00:49:43 +00002164 // Propagate the alignment from the array itself to the result.
2165 ArrayAlignment = ArrayLV.getAlignment();
2166
Richard Smith9c6890a2012-11-01 22:30:59 +00002167 if (getLangOpts().isSignedOverflowDefined())
Jay Foad040dd822011-07-22 08:16:57 +00002168 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Chris Lattner2e72da942011-03-01 00:03:48 +00002169 else
Jay Foad040dd822011-07-22 08:16:57 +00002170 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002171 } else {
Chris Lattner6c5abe82010-06-26 23:03:20 +00002172 // The base must be a pointer, which is not an aggregate. Emit it.
2173 llvm::Value *Base = EmitScalarExpr(E->getBase());
Richard Smith9c6890a2012-11-01 22:30:59 +00002174 if (getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002175 Address = Builder.CreateGEP(Base, Idx, "arrayidx");
2176 else
2177 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
Anders Carlsson3d312f82008-12-21 00:11:23 +00002178 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002179
Steve Naroff7cae42b2009-07-10 23:34:53 +00002180 QualType T = E->getBase()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00002181 assert(!T.isNull() &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00002182 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002183
Chris Lattner36bc4f42012-01-04 22:35:55 +00002184
Daniel Dunbar82634272011-04-01 00:49:43 +00002185 // Limit the alignment to that of the result type.
Chris Lattner36bc4f42012-01-04 22:35:55 +00002186 LValue LV;
Eli Friedmana0544d62011-12-03 04:14:32 +00002187 if (!ArrayAlignment.isZero()) {
2188 CharUnits Align = getContext().getTypeAlignInChars(T);
Daniel Dunbar82634272011-04-01 00:49:43 +00002189 ArrayAlignment = std::min(Align, ArrayAlignment);
Chris Lattner36bc4f42012-01-04 22:35:55 +00002190 LV = MakeAddrLValue(Address, T, ArrayAlignment);
2191 } else {
2192 LV = MakeNaturalAlignAddrLValue(Address, T);
Daniel Dunbar82634272011-04-01 00:49:43 +00002193 }
2194
Daniel Dunbarf166a522010-08-21 03:44:13 +00002195 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002196
Richard Smith9c6890a2012-11-01 22:30:59 +00002197 if (getLangOpts().ObjC1 &&
2198 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002199 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002200 setObjCGCLValueClass(getContext(), E, LV);
2201 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002202 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002203}
2204
Mike Stump4a3999f2009-09-09 13:00:44 +00002205static
NAKAMURA Takumiccca11a2012-01-25 08:58:21 +00002206llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002207 SmallVector<unsigned, 4> &Elts) {
2208 SmallVector<llvm::Constant*, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002209 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002210 CElts.push_back(Builder.getInt32(Elts[i]));
Nate Begemand3862152008-05-13 21:03:02 +00002211
Chris Lattner91c08ad2011-02-15 00:14:06 +00002212 return llvm::ConstantVector::get(CElts);
Nate Begemand3862152008-05-13 21:03:02 +00002213}
2214
Chris Lattner9e751ca2007-08-02 23:37:31 +00002215LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002216EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002217 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002218 LValue Base;
2219
2220 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002221 if (E->isArrow()) {
2222 // If it is a pointer to a vector, emit the address and form an lvalue with
2223 // it.
Chris Lattnerb8211f62009-02-16 22:14:05 +00002224 llvm::Value *Ptr = EmitScalarExpr(E->getBase());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002225 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Daniel Dunbarf166a522010-08-21 03:44:13 +00002226 Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2227 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002228 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002229 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2230 // emit the base as an lvalue.
2231 assert(E->getBase()->getType()->isVectorType());
2232 Base = EmitLValue(E->getBase());
2233 } else {
2234 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002235 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002236 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002237 llvm::Value *Vec = EmitScalarExpr(E->getBase());
2238
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002239 // Store the vector to memory (because LValue wants an address).
Daniel Dunbara7566f12010-02-09 02:48:28 +00002240 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002241 Builder.CreateStore(Vec, VecMem);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002242 Base = MakeAddrLValue(VecMem, E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002243 }
John McCall1553b192011-06-16 04:16:24 +00002244
2245 QualType type =
2246 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002247
Nate Begemand3862152008-05-13 21:03:02 +00002248 // Encode the element access list into a vector of unsigned indices.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002249 SmallVector<unsigned, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002250 E->getEncodedElementAccess(Indices);
2251
2252 if (Base.isSimple()) {
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002253 llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002254 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2255 Base.getAlignment());
Nate Begemand3862152008-05-13 21:03:02 +00002256 }
2257 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2258
2259 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002260 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002261
Chris Lattner595ba3a2012-01-30 06:20:36 +00002262 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2263 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002264 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
Eli Friedman610bb872012-03-22 22:36:39 +00002265 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2266 Base.getAlignment());
Chris Lattner9e751ca2007-08-02 23:37:31 +00002267}
2268
Devang Patel30efa2e2007-10-23 20:28:39 +00002269LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00002270 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00002271
Chris Lattner4e4186b2007-12-02 18:52:07 +00002272 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
Eli Friedman7f1ff602012-04-16 03:54:45 +00002273 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00002274 if (E->isArrow()) {
2275 llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
2276 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Richard Smithe30752c2012-10-09 19:52:38 +00002277 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +00002278 BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
2279 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00002280 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00002281
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002282 NamedDecl *ND = E->getMemberDecl();
2283 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002284 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002285 setObjCGCLValueClass(getContext(), E, LV);
2286 return LV;
2287 }
2288
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00002289 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
2290 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002291
2292 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
2293 return EmitFunctionDeclLValue(*this, E, FD);
2294
David Blaikie83d382b2011-09-23 05:06:16 +00002295 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00002296}
Devang Patel30efa2e2007-10-23 20:28:39 +00002297
Eli Friedman7f1ff602012-04-16 03:54:45 +00002298LValue CodeGenFunction::EmitLValueForField(LValue base,
2299 const FieldDecl *field) {
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002300 if (field->isBitField()) {
2301 const CGRecordLayout &RL =
2302 CGM.getTypes().getCGRecordLayout(field->getParent());
2303 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002304 llvm::Value *Addr = base.getAddress();
2305 unsigned Idx = RL.getLLVMFieldNo(field);
2306 if (Idx != 0)
2307 // For structs, we GEP to the field that the record layout suggests.
2308 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
2309 // Get the access type.
2310 llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
2311 getLLVMContext(), Info.StorageSize,
2312 CGM.getContext().getTargetAddressSpace(base.getType()));
2313 if (Addr->getType() != PtrTy)
2314 Addr = Builder.CreateBitCast(Addr, PtrTy);
2315
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002316 QualType fieldType =
2317 field->getType().withCVRQualifiers(base.getVRQualifiers());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002318 return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002319 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002320
John McCall53fcbd22011-02-26 08:07:02 +00002321 const RecordDecl *rec = field->getParent();
2322 QualType type = field->getType();
Eli Friedmana0544d62011-12-03 04:14:32 +00002323 CharUnits alignment = getContext().getDeclAlign(field);
Eli Friedman133e8042008-05-29 11:33:25 +00002324
Eli Friedman7f1ff602012-04-16 03:54:45 +00002325 // FIXME: It should be impossible to have an LValue without alignment for a
2326 // complete type.
2327 if (!base.getAlignment().isZero())
2328 alignment = std::min(alignment, base.getAlignment());
2329
John McCall53fcbd22011-02-26 08:07:02 +00002330 bool mayAlias = rec->hasAttr<MayAliasAttr>();
2331
Eli Friedman7f1ff602012-04-16 03:54:45 +00002332 llvm::Value *addr = base.getAddress();
2333 unsigned cvr = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00002334 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00002335 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00002336 assert(!type->isReferenceType() && "union has reference member");
John McCall53fcbd22011-02-26 08:07:02 +00002337 } else {
2338 // For structs, we GEP to the field that the record layout suggests.
2339 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
Chris Lattner13ee4f42011-07-10 05:34:54 +00002340 addr = Builder.CreateStructGEP(addr, idx, field->getName());
John McCall53fcbd22011-02-26 08:07:02 +00002341
2342 // If this is a reference field, load the reference right now.
2343 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2344 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2345 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
Eli Friedmana0544d62011-12-03 04:14:32 +00002346 load->setAlignment(alignment.getQuantity());
John McCall53fcbd22011-02-26 08:07:02 +00002347
2348 if (CGM.shouldUseTBAA()) {
2349 llvm::MDNode *tbaa;
2350 if (mayAlias)
2351 tbaa = CGM.getTBAAInfo(getContext().CharTy);
2352 else
2353 tbaa = CGM.getTBAAInfo(type);
2354 CGM.DecorateInstruction(load, tbaa);
2355 }
2356
2357 addr = load;
2358 mayAlias = false;
2359 type = refType->getPointeeType();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002360 if (type->isIncompleteType())
Eli Friedmana0544d62011-12-03 04:14:32 +00002361 alignment = CharUnits();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002362 else
Eli Friedmana0544d62011-12-03 04:14:32 +00002363 alignment = getContext().getTypeAlignInChars(type);
John McCall53fcbd22011-02-26 08:07:02 +00002364 cvr = 0; // qualifiers don't recursively apply to referencee
2365 }
Devang Pateled93c3c2007-10-26 19:42:18 +00002366 }
Chris Lattner13ee4f42011-07-10 05:34:54 +00002367
2368 // Make sure that the address is pointing to the right type. This is critical
2369 // for both unions and structs. A union needs a bitcast, a struct element
2370 // will need a bitcast if the LLVM type laid out doesn't match the desired
2371 // type.
Chandler Carruth4678f672011-07-12 08:58:26 +00002372 addr = EmitBitCastOfLValueToProperType(*this, addr,
Chris Lattner3f32d692011-07-12 06:52:18 +00002373 CGM.getTypes().ConvertTypeForMem(type),
2374 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00002375
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002376 if (field->hasAttr<AnnotateAttr>())
2377 addr = EmitFieldAnnotations(field, addr);
2378
John McCall53fcbd22011-02-26 08:07:02 +00002379 LValue LV = MakeAddrLValue(addr, type, alignment);
2380 LV.getQuals().addCVRQualifiers(cvr);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002381
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002382 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00002383 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2384 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00002385
2386 // Fields of may_alias structs act like 'char' for TBAA purposes.
2387 // FIXME: this should get propagated down through anonymous structs
2388 // and unions.
2389 if (mayAlias && LV.getTBAAInfo())
2390 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2391
Daniel Dunbarf166a522010-08-21 03:44:13 +00002392 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00002393}
2394
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002395LValue
Eli Friedman7f1ff602012-04-16 03:54:45 +00002396CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2397 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002398 QualType FieldType = Field->getType();
2399
2400 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002401 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002402
Daniel Dunbar034299e2010-03-31 01:09:11 +00002403 const CGRecordLayout &RL =
2404 CGM.getTypes().getCGRecordLayout(Field->getParent());
2405 unsigned idx = RL.getLLVMFieldNo(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002406 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002407 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2408
Chris Lattnerd7c59352011-07-10 05:53:24 +00002409 // Make sure that the address is pointing to the right type. This is critical
2410 // for both unions and structs. A union needs a bitcast, a struct element
2411 // will need a bitcast if the LLVM type laid out doesn't match the desired
2412 // type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002413 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002414 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2415
Eli Friedmana0544d62011-12-03 04:14:32 +00002416 CharUnits Alignment = getContext().getDeclAlign(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002417
2418 // FIXME: It should be impossible to have an LValue without alignment for a
2419 // complete type.
2420 if (!Base.getAlignment().isZero())
2421 Alignment = std::min(Alignment, Base.getAlignment());
2422
Daniel Dunbar5c816372010-08-21 04:20:22 +00002423 return MakeAddrLValue(V, FieldType, Alignment);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002424}
2425
Chris Lattnerf53c0962010-09-06 00:11:41 +00002426LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00002427 if (E->isFileScope()) {
2428 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2429 return MakeAddrLValue(GlobalPtr, E->getType());
2430 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00002431 if (E->getType()->isVariablyModifiedType())
2432 // make sure to emit the VLA size.
2433 EmitVariablyModifiedType(E->getType());
Fariborz Jahanianbbc5bbf2012-06-07 17:07:15 +00002434
Daniel Dunbar27bacaf2010-02-16 19:43:39 +00002435 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00002436 const Expr *InitExpr = E->getInitializer();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002437 LValue Result = MakeAddrLValue(DeclPtr, E->getType());
Eli Friedman9fd8b682008-05-13 23:18:27 +00002438
Chad Rosier615ed1a2012-03-29 17:37:10 +00002439 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2440 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00002441
2442 return Result;
2443}
2444
Richard Smithbb653bd2012-05-14 21:57:21 +00002445LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2446 if (!E->isGLValue())
2447 // Initializing an aggregate temporary in C++11: T{...}.
2448 return EmitAggExprToLValue(E);
2449
2450 // An lvalue initializer list must be initializing a reference.
2451 assert(E->getNumInits() == 1 && "reference init with multiple values");
2452 return EmitLValue(E->getInit(0));
2453}
2454
John McCallc07a0c72011-02-17 10:25:35 +00002455LValue CodeGenFunction::
2456EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2457 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00002458 // ?: here should be an aggregate.
John McCallc07a0c72011-02-17 10:25:35 +00002459 assert((hasAggregateLLVMType(expr->getType()) &&
2460 !expr->getType()->isAnyComplexType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00002461 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00002462 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00002463 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002464
Eli Friedman59954892012-01-25 05:04:17 +00002465 OpaqueValueMapping binding(*this, expr);
2466
John McCallc07a0c72011-02-17 10:25:35 +00002467 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002468 bool CondExprBool;
2469 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00002470 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002471 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00002472
2473 if (!ContainsLabel(dead))
2474 return EmitLValue(live);
John McCall0a6bf2e2011-01-26 19:21:13 +00002475 }
2476
John McCallc07a0c72011-02-17 10:25:35 +00002477 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2478 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2479 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00002480
2481 ConditionalEvaluation eval(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002482 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002483
2484 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002485 EmitBlock(lhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002486 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002487 LValue lhs = EmitLValue(expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002488 eval.end(*this);
2489
John McCallc07a0c72011-02-17 10:25:35 +00002490 if (!lhs.isSimple())
2491 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00002492
John McCallc07a0c72011-02-17 10:25:35 +00002493 lhsBlock = Builder.GetInsertBlock();
2494 Builder.CreateBr(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002495
2496 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002497 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002498 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002499 LValue rhs = EmitLValue(expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002500 eval.end(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002501 if (!rhs.isSimple())
2502 return EmitUnsupportedLValue(expr, "conditional operator");
2503 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00002504
John McCallc07a0c72011-02-17 10:25:35 +00002505 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002506
Jay Foad20c0f022011-03-30 11:28:58 +00002507 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
John McCall0a6bf2e2011-01-26 19:21:13 +00002508 "cond-lvalue");
John McCallc07a0c72011-02-17 10:25:35 +00002509 phi->addIncoming(lhs.getAddress(), lhsBlock);
2510 phi->addIncoming(rhs.getAddress(), rhsBlock);
2511 return MakeAddrLValue(phi, expr->getType());
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002512}
2513
Richard Smithbb653bd2012-05-14 21:57:21 +00002514/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2515/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00002516/// otherwise if a cast is needed by the code generator in an lvalue context,
2517/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00002518/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00002519/// are permitted with aggregate result, including noop aggregate casts, and
2520/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002521LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00002522 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00002523 case CK_ToVoid:
Eli Friedman8c98dff2009-11-16 05:48:01 +00002524 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
John McCall8cb679e2010-11-15 09:13:47 +00002525
2526 case CK_Dependent:
2527 llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00002528
2529 case CK_BuiltinFnToFnPtr:
2530 llvm_unreachable("builtin functions are handled elsewhere");
2531
David Chisnallfa35df62012-01-16 17:27:18 +00002532 // These two casts are currently treated as no-ops, although they could
2533 // potentially be real operations depending on the target's ABI.
2534 case CK_NonAtomicToAtomic:
2535 case CK_AtomicToNonAtomic:
John McCall8cb679e2010-11-15 09:13:47 +00002536
John McCalle3027922010-08-25 11:45:40 +00002537 case CK_NoOp:
Douglas Gregor21d3fca2011-01-27 23:22:05 +00002538 case CK_LValueToRValue:
2539 if (!E->getSubExpr()->Classify(getContext()).isPRValue()
2540 || E->getType()->isRecordType())
John McCalle26a8722010-12-04 08:14:53 +00002541 return EmitLValue(E->getSubExpr());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002542 // Fall through to synthesize a temporary.
John McCall8cb679e2010-11-15 09:13:47 +00002543
John McCalle3027922010-08-25 11:45:40 +00002544 case CK_BitCast:
2545 case CK_ArrayToPointerDecay:
2546 case CK_FunctionToPointerDecay:
2547 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00002548 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00002549 case CK_IntegralToPointer:
2550 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002551 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002552 case CK_VectorSplat:
2553 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00002554 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002555 case CK_IntegralToFloating:
2556 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002557 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002558 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00002559 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002560 case CK_FloatingComplexToReal:
2561 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002562 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002563 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00002564 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002565 case CK_IntegralComplexToReal:
2566 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002567 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002568 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00002569 case CK_DerivedToBaseMemberPointer:
2570 case CK_BaseToDerivedMemberPointer:
2571 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00002572 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00002573 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00002574 case CK_ARCProduceObject:
2575 case CK_ARCConsumeObject:
2576 case CK_ARCReclaimReturnedObject:
Douglas Gregored90df32012-02-22 05:02:47 +00002577 case CK_ARCExtendBlockObject:
2578 case CK_CopyAndAutoreleaseBlockObject: {
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002579 // These casts only produce lvalues when we're binding a reference to a
2580 // temporary realized from a (converted) pure rvalue. Emit the expression
2581 // as a value, copy it into a temporary, and return an lvalue referring to
2582 // that temporary.
2583 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00002584 EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002585 return MakeAddrLValue(V, E->getType());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002586 }
Eli Friedman8c98dff2009-11-16 05:48:01 +00002587
Anders Carlsson8a01a752011-04-11 02:03:26 +00002588 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00002589 LValue LV = EmitLValue(E->getSubExpr());
2590 llvm::Value *V = LV.getAddress();
2591 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002592 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00002593 }
2594
John McCalle3027922010-08-25 11:45:40 +00002595 case CK_ConstructorConversion:
2596 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00002597 case CK_CPointerToObjCPointerCast:
2598 case CK_BlockPointerToObjCPointerCast:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002599 return EmitLValue(E->getSubExpr());
Anders Carlssond95f9602009-09-12 16:16:49 +00002600
John McCalle3027922010-08-25 11:45:40 +00002601 case CK_UncheckedDerivedToBase:
2602 case CK_DerivedToBase: {
Anders Carlssond95f9602009-09-12 16:16:49 +00002603 const RecordType *DerivedClassTy =
2604 E->getSubExpr()->getType()->getAs<RecordType>();
2605 CXXRecordDecl *DerivedClassDecl =
2606 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Anders Carlssond95f9602009-09-12 16:16:49 +00002607
2608 LValue LV = EmitLValue(E->getSubExpr());
John McCalle26a8722010-12-04 08:14:53 +00002609 llvm::Value *This = LV.getAddress();
Anders Carlssond95f9602009-09-12 16:16:49 +00002610
2611 // Perform the derived-to-base conversion
2612 llvm::Value *Base =
Fariborz Jahanian64cda8b2010-06-17 23:00:29 +00002613 GetAddressOfBaseClass(This, DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002614 E->path_begin(), E->path_end(),
2615 /*NullCheckValue=*/false);
Anders Carlssond95f9602009-09-12 16:16:49 +00002616
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002617 return MakeAddrLValue(Base, E->getType());
Anders Carlssond95f9602009-09-12 16:16:49 +00002618 }
John McCalle3027922010-08-25 11:45:40 +00002619 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00002620 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00002621 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00002622 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2623 CXXRecordDecl *DerivedClassDecl =
2624 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2625
2626 LValue LV = EmitLValue(E->getSubExpr());
2627
2628 // Perform the base-to-derived conversion
2629 llvm::Value *Derived =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +00002630 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002631 E->path_begin(), E->path_end(),
2632 /*NullCheckValue=*/false);
Anders Carlsson8c793172009-11-23 17:57:54 +00002633
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002634 return MakeAddrLValue(Derived, E->getType());
Eli Friedman8c98dff2009-11-16 05:48:01 +00002635 }
John McCalle3027922010-08-25 11:45:40 +00002636 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00002637 // This must be a reinterpret_cast (or c-style equivalent).
2638 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
Anders Carlsson50cb3212009-11-14 21:21:42 +00002639
2640 LValue LV = EmitLValue(E->getSubExpr());
2641 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2642 ConvertType(CE->getTypeAsWritten()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002643 return MakeAddrLValue(V, E->getType());
Anders Carlsson50cb3212009-11-14 21:21:42 +00002644 }
John McCalle3027922010-08-25 11:45:40 +00002645 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002646 LValue LV = EmitLValue(E->getSubExpr());
2647 QualType ToType = getContext().getLValueReferenceType(E->getType());
2648 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2649 ConvertType(ToType));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002650 return MakeAddrLValue(V, E->getType());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002651 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002652 case CK_ZeroToOCLEvent:
2653 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00002654 }
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002655
2656 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002657}
2658
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002659LValue CodeGenFunction::EmitNullInitializationLValue(
Douglas Gregor747eb782010-07-08 06:14:04 +00002660 const CXXScalarValueInitExpr *E) {
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002661 QualType Ty = E->getType();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002662 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
Anders Carlssonc0964b62010-05-22 17:35:42 +00002663 EmitNullInitialization(LV.getAddress(), Ty);
Daniel Dunbara7566f12010-02-09 02:48:28 +00002664 return LV;
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002665}
2666
John McCall1bf58462011-02-16 08:02:54 +00002667LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00002668 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00002669 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00002670}
2671
Douglas Gregorfe314812011-06-21 17:03:29 +00002672LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2673 const MaterializeTemporaryExpr *E) {
John McCall17054bd62011-08-26 21:08:13 +00002674 RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
Douglas Gregord410c082011-06-21 18:20:46 +00002675 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Douglas Gregorfe314812011-06-21 17:03:29 +00002676}
2677
Eli Friedman7f1ff602012-04-16 03:54:45 +00002678RValue CodeGenFunction::EmitRValueForField(LValue LV,
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002679 const FieldDecl *FD) {
2680 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00002681 LValue FieldLV = EmitLValueForField(LV, FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002682 if (FT->isAnyComplexType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002683 return RValue::getComplex(
2684 LoadComplexFromAddr(FieldLV.getAddress(),
2685 FieldLV.isVolatileQualified()));
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002686 else if (CodeGenFunction::hasAggregateLLVMType(FT))
Eli Friedman7f1ff602012-04-16 03:54:45 +00002687 return FieldLV.asAggregateRValue();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002688
Eli Friedman7f1ff602012-04-16 03:54:45 +00002689 return EmitLoadOfLValue(FieldLV);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002690}
Douglas Gregorfe314812011-06-21 17:03:29 +00002691
Chris Lattnere47e4402007-06-01 18:02:12 +00002692//===--------------------------------------------------------------------===//
2693// Expression Emission
2694//===--------------------------------------------------------------------===//
2695
Anders Carlsson17490832009-12-24 20:40:36 +00002696RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2697 ReturnValueSlot ReturnValue) {
Eric Christopher7cdf9482011-10-13 21:45:18 +00002698 if (CGDebugInfo *DI = getDebugInfo())
2699 DI->EmitLocation(Builder, E->getLocStart());
Devang Pateld3a6b0f2011-03-04 18:54:42 +00002700
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002701 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002702 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00002703 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002704
Anders Carlssone5fd6f22009-04-03 22:50:24 +00002705 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002706 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002707
Peter Collingbournefe883422011-10-06 18:29:37 +00002708 if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E))
2709 return EmitCUDAKernelCallExpr(CE, ReturnValue);
2710
Douglas Gregore0e96302011-09-06 21:41:04 +00002711 const Decl *TargetDecl = E->getCalleeDecl();
2712 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2713 if (unsigned builtinID = FD->getBuiltinID())
2714 return EmitBuiltinExpr(FD, builtinID, E);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002715 }
2716
Chris Lattner4ca97c32009-06-13 00:26:38 +00002717 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00002718 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002719 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002720
John McCall31168b02011-06-15 23:02:42 +00002721 if (const CXXPseudoDestructorExpr *PseudoDtor
2722 = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2723 QualType DestroyedType = PseudoDtor->getDestroyedType();
Richard Smith9c6890a2012-11-01 22:30:59 +00002724 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002725 DestroyedType->isObjCLifetimeType() &&
2726 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2727 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002728 // Automatic Reference Counting:
2729 // If the pseudo-expression names a retainable object with weak or
2730 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00002731 Expr *BaseExpr = PseudoDtor->getBase();
2732 llvm::Value *BaseValue = NULL;
2733 Qualifiers BaseQuals;
2734
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002735 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
John McCall31168b02011-06-15 23:02:42 +00002736 if (PseudoDtor->isArrow()) {
2737 BaseValue = EmitScalarExpr(BaseExpr);
2738 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2739 BaseQuals = PTy->getPointeeType().getQualifiers();
2740 } else {
2741 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00002742 BaseValue = BaseLV.getAddress();
2743 QualType BaseTy = BaseExpr->getType();
2744 BaseQuals = BaseTy.getQualifiers();
2745 }
2746
2747 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2748 case Qualifiers::OCL_None:
2749 case Qualifiers::OCL_ExplicitNone:
2750 case Qualifiers::OCL_Autoreleasing:
2751 break;
2752
2753 case Qualifiers::OCL_Strong:
2754 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002755 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCall31168b02011-06-15 23:02:42 +00002756 /*precise*/ true);
2757 break;
2758
2759 case Qualifiers::OCL_Weak:
2760 EmitARCDestroyWeak(BaseValue);
2761 break;
2762 }
2763 } else {
2764 // C++ [expr.pseudo]p1:
2765 // The result shall only be used as the operand for the function call
2766 // operator (), and the result of such a call has type void. The only
2767 // effect is the evaluation of the postfix-expression before the dot or
2768 // arrow.
2769 EmitScalarExpr(E->getCallee());
2770 }
2771
Douglas Gregorad8a3362009-09-04 17:36:40 +00002772 return RValue::get(0);
2773 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002774
Chris Lattner2da04b32007-08-24 05:35:26 +00002775 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Anders Carlsson17490832009-12-24 20:40:36 +00002776 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002777 E->arg_begin(), E->arg_end(), TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00002778}
2779
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002780LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00002781 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00002782 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00002783 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00002784 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00002785 return EmitLValue(E->getRHS());
2786 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002787
John McCalle3027922010-08-25 11:45:40 +00002788 if (E->getOpcode() == BO_PtrMemD ||
2789 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002790 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002791
John McCalla2342eb2010-12-05 02:00:02 +00002792 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00002793
2794 // Note that in all of these cases, __block variables need the RHS
2795 // evaluated first just in case the variable gets moved by the RHS.
John McCall4f29b492010-11-16 23:07:28 +00002796
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002797 if (!hasAggregateLLVMType(E->getType())) {
John McCall31168b02011-06-15 23:02:42 +00002798 switch (E->getLHS()->getType().getObjCLifetime()) {
2799 case Qualifiers::OCL_Strong:
2800 return EmitARCStoreStrong(E, /*ignored*/ false).first;
2801
2802 case Qualifiers::OCL_Autoreleasing:
2803 return EmitARCStoreAutoreleasing(E).first;
2804
2805 // No reason to do any of these differently.
2806 case Qualifiers::OCL_None:
2807 case Qualifiers::OCL_ExplicitNone:
2808 case Qualifiers::OCL_Weak:
2809 break;
2810 }
2811
John McCalld0a30012010-12-06 06:10:02 +00002812 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00002813 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00002814 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002815 return LV;
2816 }
John McCall4f29b492010-11-16 23:07:28 +00002817
2818 if (E->getType()->isAnyComplexType())
2819 return EmitComplexAssignmentLValue(E);
2820
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002821 return EmitAggExprToLValue(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002822}
2823
Christopher Lambd91c3d42007-12-29 05:02:41 +00002824LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00002825 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00002826
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002827 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002828 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002829
2830 assert(E->getCallReturnType()->isReferenceType() &&
2831 "Can't have a scalar return unless the return type is a "
2832 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00002833
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002834 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00002835}
2836
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002837LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2838 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002839 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002840}
2841
Anders Carlsson3be22e22009-05-30 23:23:33 +00002842LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002843 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2844 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002845 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00002846 EmitCXXConstructExpr(E, Slot);
2847 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlsson3be22e22009-05-30 23:23:33 +00002848}
2849
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002850LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00002851CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002852 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00002853}
2854
Nico Webercf4ff5862012-10-11 10:13:44 +00002855llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
2856 return CGM.GetAddrOfUuidDescriptor(E);
2857}
2858
2859LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
2860 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
2861}
2862
Mike Stumpc9b231c2009-11-15 08:09:41 +00002863LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002864CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002865 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00002866 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00002867 EmitAggExpr(E->getSubExpr(), Slot);
Peter Collingbourne702b2842011-11-27 22:09:22 +00002868 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
John McCall8ea46b62010-09-18 00:58:34 +00002869 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002870}
2871
Eli Friedman5bc17122012-02-08 05:34:55 +00002872LValue
2873CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00002874 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002875 EmitLambdaExpr(E, Slot);
Eli Friedman5bc17122012-02-08 05:34:55 +00002876 return MakeAddrLValue(Slot.getAddr(), E->getType());
2877}
2878
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002879LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002880 RValue RV = EmitObjCMessageExpr(E);
Anders Carlsson280e61f12010-06-21 20:59:55 +00002881
2882 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002883 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Anders Carlsson280e61f12010-06-21 20:59:55 +00002884
2885 assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2886 "Can't have a scalar return unless the return type is a "
2887 "reference type!");
2888
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002889 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002890}
2891
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00002892LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2893 llvm::Value *V =
2894 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002895 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00002896}
2897
Daniel Dunbar722f4242009-04-22 05:08:15 +00002898llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002899 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002900 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002901}
2902
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002903LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2904 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002905 const ObjCIvarDecl *Ivar,
2906 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00002907 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00002908 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002909}
2910
2911LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002912 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2913 llvm::Value *BaseValue = 0;
2914 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00002915 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002916 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002917 if (E->isArrow()) {
2918 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002919 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002920 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002921 } else {
2922 LValue BaseLV = EmitLValue(BaseExpr);
2923 // FIXME: this isn't right for bitfields.
2924 BaseValue = BaseLV.getAddress();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002925 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00002926 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002927 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002928
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002929 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00002930 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2931 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002932 setObjCGCLValueClass(getContext(), E, LV);
2933 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00002934}
2935
Chris Lattnera4185c52009-04-25 19:35:26 +00002936LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00002937 // Can only get l-value for message expression returning aggregate type
2938 RValue RV = EmitAnyExprToTemp(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002939 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnera4185c52009-04-25 19:35:26 +00002940}
2941
Anders Carlsson0435ed52009-12-24 19:08:58 +00002942RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Anders Carlsson17490832009-12-24 20:40:36 +00002943 ReturnValueSlot ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002944 CallExpr::const_arg_iterator ArgBeg,
2945 CallExpr::const_arg_iterator ArgEnd,
2946 const Decl *TargetDecl) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002947 // Get the actual function type. The callee type will always be a pointer to
2948 // function type or a block pointer type.
2949 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00002950 "Call must have function pointer type!");
2951
John McCall6fd4c232009-10-23 08:22:42 +00002952 CalleeType = getContext().getCanonicalType(CalleeType);
2953
John McCallab26cfa2010-02-05 21:31:56 +00002954 const FunctionType *FnType
2955 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00002956
2957 CallArgList Args;
John McCall6fd4c232009-10-23 08:22:42 +00002958 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
Daniel Dunbarc722b852008-08-30 03:02:31 +00002959
John McCalla729c622012-02-17 03:33:10 +00002960 const CGFunctionInfo &FnInfo =
John McCall8dda7b22012-07-07 06:41:13 +00002961 CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
John McCallcbc038a2011-09-21 08:08:30 +00002962
2963 // C99 6.5.2.2p6:
2964 // If the expression that denotes the called function has a type
2965 // that does not include a prototype, [the default argument
2966 // promotions are performed]. If the number of arguments does not
2967 // equal the number of parameters, the behavior is undefined. If
2968 // the function is defined with a type that includes a prototype,
2969 // and either the prototype ends with an ellipsis (, ...) or the
2970 // types of the arguments after promotion are not compatible with
2971 // the types of the parameters, the behavior is undefined. If the
2972 // function is defined with a type that does not include a
2973 // prototype, and the types of the arguments after promotion are
2974 // not compatible with those of the parameters after promotion,
2975 // the behavior is undefined [except in some trivial cases].
2976 // That is, in the general case, we should assume that a call
2977 // through an unprototyped function type works like a *non-variadic*
2978 // call. The way we make this work is to cast to the exact type
2979 // of the promoted arguments.
John McCallc818bbb2012-12-07 07:03:17 +00002980 if (isa<FunctionNoProtoType>(FnType)) {
John McCalla729c622012-02-17 03:33:10 +00002981 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00002982 CalleeTy = CalleeTy->getPointerTo();
2983 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
2984 }
2985
2986 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00002987}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002988
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002989LValue CodeGenFunction::
2990EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
Eli Friedman928a5672009-11-18 05:01:17 +00002991 llvm::Value *BaseV;
John McCalle3027922010-08-25 11:45:40 +00002992 if (E->getOpcode() == BO_PtrMemI)
Eli Friedman928a5672009-11-18 05:01:17 +00002993 BaseV = EmitScalarExpr(E->getLHS());
2994 else
2995 BaseV = EmitLValue(E->getLHS()).getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002996
John McCallc134eb52010-08-31 21:07:20 +00002997 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2998
2999 const MemberPointerType *MPT
3000 = E->getRHS()->getType()->getAs<MemberPointerType>();
3001
3002 llvm::Value *AddV =
3003 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
3004
3005 return MakeAddrLValue(AddV, MPT->getPointeeType());
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003006}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003007
3008static void
3009EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
3010 llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
3011 uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
Richard Smithfeea8832012-04-12 05:08:17 +00003012 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
3013 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
3014
3015 switch (E->getOp()) {
3016 case AtomicExpr::AO__c11_atomic_init:
3017 llvm_unreachable("Already handled!");
3018
3019 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3020 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3021 case AtomicExpr::AO__atomic_compare_exchange:
3022 case AtomicExpr::AO__atomic_compare_exchange_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003023 // Note that cmpxchg only supports specifying one ordering and
3024 // doesn't support weak cmpxchg, at least at the moment.
3025 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3026 LoadVal1->setAlignment(Align);
3027 llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2);
3028 LoadVal2->setAlignment(Align);
3029 llvm::AtomicCmpXchgInst *CXI =
3030 CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order);
3031 CXI->setVolatile(E->isVolatile());
3032 llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1);
3033 StoreVal1->setAlignment(Align);
3034 llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1);
3035 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
3036 return;
3037 }
3038
Richard Smithfeea8832012-04-12 05:08:17 +00003039 case AtomicExpr::AO__c11_atomic_load:
3040 case AtomicExpr::AO__atomic_load_n:
3041 case AtomicExpr::AO__atomic_load: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003042 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
3043 Load->setAtomic(Order);
3044 Load->setAlignment(Size);
3045 Load->setVolatile(E->isVolatile());
3046 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
3047 StoreDest->setAlignment(Align);
3048 return;
3049 }
3050
Richard Smithfeea8832012-04-12 05:08:17 +00003051 case AtomicExpr::AO__c11_atomic_store:
3052 case AtomicExpr::AO__atomic_store:
3053 case AtomicExpr::AO__atomic_store_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003054 assert(!Dest && "Store does not return a value");
3055 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3056 LoadVal1->setAlignment(Align);
3057 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
3058 Store->setAtomic(Order);
3059 Store->setAlignment(Size);
3060 Store->setVolatile(E->isVolatile());
3061 return;
3062 }
3063
Richard Smithfeea8832012-04-12 05:08:17 +00003064 case AtomicExpr::AO__c11_atomic_exchange:
3065 case AtomicExpr::AO__atomic_exchange_n:
3066 case AtomicExpr::AO__atomic_exchange:
3067 Op = llvm::AtomicRMWInst::Xchg;
3068 break;
3069
3070 case AtomicExpr::AO__atomic_add_fetch:
3071 PostOp = llvm::Instruction::Add;
3072 // Fall through.
3073 case AtomicExpr::AO__c11_atomic_fetch_add:
3074 case AtomicExpr::AO__atomic_fetch_add:
3075 Op = llvm::AtomicRMWInst::Add;
3076 break;
3077
3078 case AtomicExpr::AO__atomic_sub_fetch:
3079 PostOp = llvm::Instruction::Sub;
3080 // Fall through.
3081 case AtomicExpr::AO__c11_atomic_fetch_sub:
3082 case AtomicExpr::AO__atomic_fetch_sub:
3083 Op = llvm::AtomicRMWInst::Sub;
3084 break;
3085
3086 case AtomicExpr::AO__atomic_and_fetch:
3087 PostOp = llvm::Instruction::And;
3088 // Fall through.
3089 case AtomicExpr::AO__c11_atomic_fetch_and:
3090 case AtomicExpr::AO__atomic_fetch_and:
3091 Op = llvm::AtomicRMWInst::And;
3092 break;
3093
3094 case AtomicExpr::AO__atomic_or_fetch:
3095 PostOp = llvm::Instruction::Or;
3096 // Fall through.
3097 case AtomicExpr::AO__c11_atomic_fetch_or:
3098 case AtomicExpr::AO__atomic_fetch_or:
3099 Op = llvm::AtomicRMWInst::Or;
3100 break;
3101
3102 case AtomicExpr::AO__atomic_xor_fetch:
3103 PostOp = llvm::Instruction::Xor;
3104 // Fall through.
3105 case AtomicExpr::AO__c11_atomic_fetch_xor:
3106 case AtomicExpr::AO__atomic_fetch_xor:
3107 Op = llvm::AtomicRMWInst::Xor;
3108 break;
Richard Smithd65cee92012-04-13 06:31:38 +00003109
3110 case AtomicExpr::AO__atomic_nand_fetch:
3111 PostOp = llvm::Instruction::And;
3112 // Fall through.
3113 case AtomicExpr::AO__atomic_fetch_nand:
3114 Op = llvm::AtomicRMWInst::Nand;
3115 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003116 }
Richard Smithfeea8832012-04-12 05:08:17 +00003117
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003118 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3119 LoadVal1->setAlignment(Align);
3120 llvm::AtomicRMWInst *RMWI =
3121 CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
3122 RMWI->setVolatile(E->isVolatile());
Richard Smithfeea8832012-04-12 05:08:17 +00003123
3124 // For __atomic_*_fetch operations, perform the operation again to
3125 // determine the value which was written.
3126 llvm::Value *Result = RMWI;
3127 if (PostOp)
3128 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
Richard Smithd65cee92012-04-13 06:31:38 +00003129 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
3130 Result = CGF.Builder.CreateNot(Result);
Richard Smithfeea8832012-04-12 05:08:17 +00003131 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003132 StoreDest->setAlignment(Align);
3133}
3134
3135// This function emits any expression (scalar, complex, or aggregate)
3136// into a temporary alloca.
3137static llvm::Value *
3138EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
3139 llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00003140 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
3141 /*Init*/ true);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003142 return DeclPtr;
3143}
3144
3145static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty,
3146 llvm::Value *Dest) {
3147 if (Ty->isAnyComplexType())
3148 return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false));
3149 if (CGF.hasAggregateLLVMType(Ty))
3150 return RValue::getAggregate(Dest);
3151 return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty)));
3152}
3153
3154RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
3155 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
Richard Smithfeea8832012-04-12 05:08:17 +00003156 QualType MemTy = AtomicTy;
3157 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
3158 MemTy = AT->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003159 CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
3160 uint64_t Size = sizeChars.getQuantity();
3161 CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
3162 unsigned Align = alignChars.getQuantity();
Benjamin Kramer37196de2012-11-17 17:30:55 +00003163 unsigned MaxInlineWidthInBits =
3164 getContext().getTargetInfo().getMaxAtomicInlineWidth();
3165 bool UseLibcall = (Size != Align ||
3166 getContext().toBits(sizeChars) > MaxInlineWidthInBits);
David Chisnallfa35df62012-01-16 17:27:18 +00003167
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003168 llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
3169 Ptr = EmitScalarExpr(E->getPtr());
David Chisnallfa35df62012-01-16 17:27:18 +00003170
Richard Smithfeea8832012-04-12 05:08:17 +00003171 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
David Chisnallfa35df62012-01-16 17:27:18 +00003172 assert(!Dest && "Init does not return a value");
David Chisnalleb9496e2012-04-11 17:24:05 +00003173 if (!hasAggregateLLVMType(E->getVal1()->getType())) {
Douglas Gregor298f43d2012-04-12 20:42:30 +00003174 QualType PointeeType
3175 = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
3176 EmitScalarInit(EmitScalarExpr(E->getVal1()),
3177 LValue::MakeAddr(Ptr, PointeeType, alignChars,
3178 getContext()));
David Chisnalleb9496e2012-04-11 17:24:05 +00003179 } else if (E->getType()->isAnyComplexType()) {
3180 EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
3181 } else {
3182 AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars,
3183 AtomicTy.getQualifiers(),
3184 AggValueSlot::IsNotDestructed,
3185 AggValueSlot::DoesNotNeedGCBarriers,
3186 AggValueSlot::IsNotAliased);
3187 EmitAggExpr(E->getVal1(), Slot);
3188 }
David Chisnallfa35df62012-01-16 17:27:18 +00003189 return RValue::get(0);
3190 }
3191
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003192 Order = EmitScalarExpr(E->getOrder());
Richard Smithfeea8832012-04-12 05:08:17 +00003193
3194 switch (E->getOp()) {
3195 case AtomicExpr::AO__c11_atomic_init:
3196 llvm_unreachable("Already handled!");
3197
3198 case AtomicExpr::AO__c11_atomic_load:
3199 case AtomicExpr::AO__atomic_load_n:
3200 break;
3201
3202 case AtomicExpr::AO__atomic_load:
3203 Dest = EmitScalarExpr(E->getVal1());
3204 break;
3205
3206 case AtomicExpr::AO__atomic_store:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003207 Val1 = EmitScalarExpr(E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003208 break;
3209
3210 case AtomicExpr::AO__atomic_exchange:
3211 Val1 = EmitScalarExpr(E->getVal1());
3212 Dest = EmitScalarExpr(E->getVal2());
3213 break;
3214
3215 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3216 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3217 case AtomicExpr::AO__atomic_compare_exchange_n:
3218 case AtomicExpr::AO__atomic_compare_exchange:
3219 Val1 = EmitScalarExpr(E->getVal1());
3220 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
3221 Val2 = EmitScalarExpr(E->getVal2());
3222 else
3223 Val2 = EmitValToTemp(*this, E->getVal2());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003224 OrderFail = EmitScalarExpr(E->getOrderFail());
Richard Smithfeea8832012-04-12 05:08:17 +00003225 // Evaluate and discard the 'weak' argument.
3226 if (E->getNumSubExprs() == 6)
3227 EmitScalarExpr(E->getWeak());
3228 break;
3229
3230 case AtomicExpr::AO__c11_atomic_fetch_add:
3231 case AtomicExpr::AO__c11_atomic_fetch_sub:
Richard Smithfeea8832012-04-12 05:08:17 +00003232 if (MemTy->isPointerType()) {
3233 // For pointer arithmetic, we're required to do a bit of math:
3234 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
Richard Smith01ba47d2012-04-13 00:45:38 +00003235 // ... but only for the C11 builtins. The GNU builtins expect the
3236 // user to multiply by sizeof(T).
Richard Smithfeea8832012-04-12 05:08:17 +00003237 QualType Val1Ty = E->getVal1()->getType();
3238 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
3239 CharUnits PointeeIncAmt =
3240 getContext().getTypeSizeInChars(MemTy->getPointeeType());
3241 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
3242 Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
3243 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
3244 break;
3245 }
3246 // Fall through.
Richard Smith01ba47d2012-04-13 00:45:38 +00003247 case AtomicExpr::AO__atomic_fetch_add:
3248 case AtomicExpr::AO__atomic_fetch_sub:
3249 case AtomicExpr::AO__atomic_add_fetch:
3250 case AtomicExpr::AO__atomic_sub_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003251 case AtomicExpr::AO__c11_atomic_store:
3252 case AtomicExpr::AO__c11_atomic_exchange:
3253 case AtomicExpr::AO__atomic_store_n:
3254 case AtomicExpr::AO__atomic_exchange_n:
3255 case AtomicExpr::AO__c11_atomic_fetch_and:
3256 case AtomicExpr::AO__c11_atomic_fetch_or:
3257 case AtomicExpr::AO__c11_atomic_fetch_xor:
3258 case AtomicExpr::AO__atomic_fetch_and:
3259 case AtomicExpr::AO__atomic_fetch_or:
3260 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003261 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003262 case AtomicExpr::AO__atomic_and_fetch:
3263 case AtomicExpr::AO__atomic_or_fetch:
3264 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003265 case AtomicExpr::AO__atomic_nand_fetch:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003266 Val1 = EmitValToTemp(*this, E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003267 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003268 }
3269
Richard Smithfeea8832012-04-12 05:08:17 +00003270 if (!E->getType()->isVoidType() && !Dest)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003271 Dest = CreateMemTemp(E->getType(), ".atomicdst");
3272
David Chisnalldb365f32012-03-29 18:01:11 +00003273 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003274 if (UseLibcall) {
David Chisnalldb365f32012-03-29 18:01:11 +00003275
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003276 SmallVector<QualType, 5> Params;
David Chisnalldb365f32012-03-29 18:01:11 +00003277 CallArgList Args;
3278 // Size is always the first parameter
3279 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
3280 getContext().getSizeType());
3281 // Atomic address is always the second parameter
3282 Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
3283 getContext().VoidPtrTy);
3284
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003285 const char* LibCallName;
David Chisnalldb365f32012-03-29 18:01:11 +00003286 QualType RetTy = getContext().VoidTy;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003287 switch (E->getOp()) {
David Chisnalldb365f32012-03-29 18:01:11 +00003288 // There is only one libcall for compare an exchange, because there is no
3289 // optimisation benefit possible from a libcall version of a weak compare
3290 // and exchange.
3291 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
Richard Smithfeea8832012-04-12 05:08:17 +00003292 // void *desired, int success, int failure)
3293 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3294 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3295 case AtomicExpr::AO__atomic_compare_exchange:
3296 case AtomicExpr::AO__atomic_compare_exchange_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003297 LibCallName = "__atomic_compare_exchange";
3298 RetTy = getContext().BoolTy;
3299 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3300 getContext().VoidPtrTy);
3301 Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
3302 getContext().VoidPtrTy);
3303 Args.add(RValue::get(Order),
3304 getContext().IntTy);
3305 Order = OrderFail;
3306 break;
3307 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
3308 // int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003309 case AtomicExpr::AO__c11_atomic_exchange:
3310 case AtomicExpr::AO__atomic_exchange_n:
3311 case AtomicExpr::AO__atomic_exchange:
David Chisnalldb365f32012-03-29 18:01:11 +00003312 LibCallName = "__atomic_exchange";
3313 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3314 getContext().VoidPtrTy);
3315 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3316 getContext().VoidPtrTy);
3317 break;
3318 // void __atomic_store(size_t size, void *mem, void *val, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003319 case AtomicExpr::AO__c11_atomic_store:
3320 case AtomicExpr::AO__atomic_store:
3321 case AtomicExpr::AO__atomic_store_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003322 LibCallName = "__atomic_store";
3323 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3324 getContext().VoidPtrTy);
3325 break;
3326 // void __atomic_load(size_t size, void *mem, void *return, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003327 case AtomicExpr::AO__c11_atomic_load:
3328 case AtomicExpr::AO__atomic_load:
3329 case AtomicExpr::AO__atomic_load_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003330 LibCallName = "__atomic_load";
3331 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3332 getContext().VoidPtrTy);
3333 break;
3334#if 0
3335 // These are only defined for 1-16 byte integers. It is not clear what
3336 // their semantics would be on anything else...
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003337 case AtomicExpr::Add: LibCallName = "__atomic_fetch_add_generic"; break;
3338 case AtomicExpr::Sub: LibCallName = "__atomic_fetch_sub_generic"; break;
3339 case AtomicExpr::And: LibCallName = "__atomic_fetch_and_generic"; break;
3340 case AtomicExpr::Or: LibCallName = "__atomic_fetch_or_generic"; break;
3341 case AtomicExpr::Xor: LibCallName = "__atomic_fetch_xor_generic"; break;
David Chisnalldb365f32012-03-29 18:01:11 +00003342#endif
3343 default: return EmitUnsupportedRValue(E, "atomic library call");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003344 }
David Chisnalldb365f32012-03-29 18:01:11 +00003345 // order is always the last parameter
3346 Args.add(RValue::get(Order),
3347 getContext().IntTy);
3348
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003349 const CGFunctionInfo &FuncInfo =
John McCall8dda7b22012-07-07 06:41:13 +00003350 CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args,
David Chisnalldb365f32012-03-29 18:01:11 +00003351 FunctionType::ExtInfo(), RequiredArgs::All);
3352 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003353 llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
3354 RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
3355 if (E->isCmpXChg())
3356 return Res;
Richard Smithfeea8832012-04-12 05:08:17 +00003357 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003358 return RValue::get(0);
3359 return ConvertTempToRValue(*this, E->getType(), Dest);
3360 }
David Chisnalldb365f32012-03-29 18:01:11 +00003361
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003362 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
3363 E->getOp() == AtomicExpr::AO__atomic_store ||
3364 E->getOp() == AtomicExpr::AO__atomic_store_n;
3365 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
3366 E->getOp() == AtomicExpr::AO__atomic_load ||
3367 E->getOp() == AtomicExpr::AO__atomic_load_n;
3368
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003369 llvm::Type *IPtrTy =
3370 llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
3371 llvm::Value *OrigDest = Dest;
3372 Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
3373 if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
3374 if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
3375 if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
3376
3377 if (isa<llvm::ConstantInt>(Order)) {
3378 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
3379 switch (ord) {
3380 case 0: // memory_order_relaxed
3381 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3382 llvm::Monotonic);
3383 break;
3384 case 1: // memory_order_consume
3385 case 2: // memory_order_acquire
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003386 if (IsStore)
3387 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003388 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3389 llvm::Acquire);
3390 break;
3391 case 3: // memory_order_release
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003392 if (IsLoad)
3393 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003394 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3395 llvm::Release);
3396 break;
3397 case 4: // memory_order_acq_rel
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003398 if (IsLoad || IsStore)
3399 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003400 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3401 llvm::AcquireRelease);
3402 break;
3403 case 5: // memory_order_seq_cst
3404 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3405 llvm::SequentiallyConsistent);
3406 break;
3407 default: // invalid order
3408 // We should not ever get here normally, but it's hard to
3409 // enforce that in general.
Richard Smithfeea8832012-04-12 05:08:17 +00003410 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003411 }
Richard Smithfeea8832012-04-12 05:08:17 +00003412 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003413 return RValue::get(0);
3414 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3415 }
3416
3417 // Long case, when Order isn't obviously constant.
3418
3419 // Create all the relevant BB's
Eli Friedmanc2025562011-10-11 20:00:47 +00003420 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
3421 *AcqRelBB = 0, *SeqCstBB = 0;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003422 MonotonicBB = createBasicBlock("monotonic", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003423 if (!IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003424 AcquireBB = createBasicBlock("acquire", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003425 if (!IsLoad)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003426 ReleaseBB = createBasicBlock("release", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003427 if (!IsLoad && !IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003428 AcqRelBB = createBasicBlock("acqrel", CurFn);
3429 SeqCstBB = createBasicBlock("seqcst", CurFn);
3430 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
3431
3432 // Create the switch for the split
3433 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
3434 // doesn't matter unless someone is crazy enough to use something that
3435 // doesn't fold to a constant for the ordering.
3436 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
3437 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
3438
3439 // Emit all the different atomics
3440 Builder.SetInsertPoint(MonotonicBB);
3441 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3442 llvm::Monotonic);
3443 Builder.CreateBr(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003444 if (!IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003445 Builder.SetInsertPoint(AcquireBB);
3446 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3447 llvm::Acquire);
3448 Builder.CreateBr(ContBB);
3449 SI->addCase(Builder.getInt32(1), AcquireBB);
3450 SI->addCase(Builder.getInt32(2), AcquireBB);
3451 }
Richard Smithfeea8832012-04-12 05:08:17 +00003452 if (!IsLoad) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003453 Builder.SetInsertPoint(ReleaseBB);
3454 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3455 llvm::Release);
3456 Builder.CreateBr(ContBB);
3457 SI->addCase(Builder.getInt32(3), ReleaseBB);
3458 }
Richard Smithfeea8832012-04-12 05:08:17 +00003459 if (!IsLoad && !IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003460 Builder.SetInsertPoint(AcqRelBB);
3461 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3462 llvm::AcquireRelease);
3463 Builder.CreateBr(ContBB);
3464 SI->addCase(Builder.getInt32(4), AcqRelBB);
3465 }
3466 Builder.SetInsertPoint(SeqCstBB);
3467 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3468 llvm::SequentiallyConsistent);
3469 Builder.CreateBr(ContBB);
3470 SI->addCase(Builder.getInt32(5), SeqCstBB);
3471
3472 // Cleanup and return
3473 Builder.SetInsertPoint(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003474 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003475 return RValue::get(0);
3476 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3477}
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003478
Duncan Sandse81111c2012-04-10 08:23:07 +00003479void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003480 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003481 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003482 return;
3483
Duncan Sands65229ed2012-04-16 16:29:47 +00003484 llvm::MDBuilder MDHelper(getLLVMContext());
3485 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003486
Duncan Sands6fc46192012-04-14 12:37:26 +00003487 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003488}
John McCallfe96e0b2011-11-06 09:01:30 +00003489
3490namespace {
3491 struct LValueOrRValue {
3492 LValue LV;
3493 RValue RV;
3494 };
3495}
3496
3497static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3498 const PseudoObjectExpr *E,
3499 bool forLValue,
3500 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003501 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00003502
3503 // Find the result expression, if any.
3504 const Expr *resultExpr = E->getResultExpr();
3505 LValueOrRValue result;
3506
3507 for (PseudoObjectExpr::const_semantics_iterator
3508 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3509 const Expr *semantic = *i;
3510
3511 // If this semantic expression is an opaque value, bind it
3512 // to the result of its source expression.
3513 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3514
3515 // If this is the result expression, we may need to evaluate
3516 // directly into the slot.
3517 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3518 OVMA opaqueData;
3519 if (ov == resultExpr && ov->isRValue() && !forLValue &&
3520 CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
3521 !ov->getType()->isAnyComplexType()) {
3522 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3523
3524 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3525 opaqueData = OVMA::bind(CGF, ov, LV);
3526 result.RV = slot.asRValue();
3527
3528 // Otherwise, emit as normal.
3529 } else {
3530 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3531
3532 // If this is the result, also evaluate the result now.
3533 if (ov == resultExpr) {
3534 if (forLValue)
3535 result.LV = CGF.EmitLValue(ov);
3536 else
3537 result.RV = CGF.EmitAnyExpr(ov, slot);
3538 }
3539 }
3540
3541 opaques.push_back(opaqueData);
3542
3543 // Otherwise, if the expression is the result, evaluate it
3544 // and remember the result.
3545 } else if (semantic == resultExpr) {
3546 if (forLValue)
3547 result.LV = CGF.EmitLValue(semantic);
3548 else
3549 result.RV = CGF.EmitAnyExpr(semantic, slot);
3550
3551 // Otherwise, evaluate the expression in an ignored context.
3552 } else {
3553 CGF.EmitIgnoredExpr(semantic);
3554 }
3555 }
3556
3557 // Unbind all the opaques now.
3558 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3559 opaques[i].unbind(CGF);
3560
3561 return result;
3562}
3563
3564RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3565 AggValueSlot slot) {
3566 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3567}
3568
3569LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3570 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3571}