blob: 7d1c77a14f9dfe4446906f81fade0eefbec709c2 [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"
Alexey Bataev97720002014-11-11 04:05:39 +000019#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CGRecordLayout.h"
21#include "CodeGenModule.h"
John McCallcbc038a2011-09-21 08:08:30 +000022#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/ASTContext.h"
Renato Golin230c5eb2014-05-19 18:15:42 +000024#include "clang/AST/Attr.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000025#include "clang/AST/DeclObjC.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000028#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000033#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000034#include "llvm/Support/MathExtras.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000035#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000036
Chris Lattnere47e4402007-06-01 18:02:12 +000037using namespace clang;
38using namespace CodeGen;
39
Chris Lattnerd7f58862007-06-02 05:24:33 +000040//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000041// Miscellaneous Helper Methods
42//===--------------------------------------------------------------------===//
43
John McCallad7c5c12011-02-08 08:22:06 +000044llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
45 unsigned addressSpace =
46 cast<llvm::PointerType>(value->getType())->getAddressSpace();
47
Chris Lattner2192fe52011-07-18 04:24:23 +000048 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000049 if (addressSpace)
50 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
51
52 if (value->getType() == destType) return value;
53 return Builder.CreateBitCast(value, destType);
54}
55
Chris Lattnere9a64532007-06-22 21:44:33 +000056/// CreateTempAlloca - This creates a alloca and inserts it into the entry
57/// block.
John McCall7f416cc2015-09-08 08:05:57 +000058Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
59 const Twine &Name) {
60 auto Alloca = CreateTempAlloca(Ty, Name);
61 Alloca->setAlignment(Align.getQuantity());
62 return Address(Alloca, Align);
63}
64
65/// CreateTempAlloca - This creates a alloca and inserts it into the entry
66/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000067llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 const Twine &Name) {
Chris Lattner47640222009-03-22 00:24:14 +000069 if (!Builder.isNamePreserving())
Craig Topper8a13c412014-05-21 05:09:00 +000070 return new llvm::AllocaInst(Ty, nullptr, "", AllocaInsertPt);
71 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000072}
Chris Lattner8394d792007-06-05 20:53:16 +000073
John McCall7f416cc2015-09-08 08:05:57 +000074/// CreateDefaultAlignTempAlloca - This creates an alloca with the
75/// default alignment of the corresponding LLVM type, which is *not*
76/// guaranteed to be related in any way to the expected alignment of
77/// an AST type that might have been lowered to Ty.
78Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
79 const Twine &Name) {
80 CharUnits Align =
81 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
82 return CreateTempAlloca(Ty, Align, Name);
83}
84
85void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
86 assert(isa<llvm::AllocaInst>(Var.getPointer()));
87 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
88 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000089 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +000090 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +000091}
92
John McCall7f416cc2015-09-08 08:05:57 +000093Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000094 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000095 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +000096}
97
John McCall7f416cc2015-09-08 08:05:57 +000098Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000099 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +0000100 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
101}
102
103Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
104 const Twine &Name) {
105 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000106}
107
Chris Lattner8394d792007-06-05 20:53:16 +0000108/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
109/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000110llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000111 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000112 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000113 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000114 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000115 }
John McCall7a9aac22010-08-23 01:21:21 +0000116
117 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000118 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000119 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000120 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000121
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000122 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
123 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000124}
125
John McCalla2342eb2010-12-05 02:00:02 +0000126/// EmitIgnoredExpr - Emit code to compute the specified expression,
127/// ignoring the result.
128void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
129 if (E->isRValue())
130 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
131
132 // Just emit it as an l-value and drop the result.
133 EmitLValue(E);
134}
135
John McCall7a626f62010-09-15 10:14:12 +0000136/// EmitAnyExpr - Emit code to compute the specified expression which
137/// can have any type. The result is returned as an RValue struct.
138/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000139/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000140RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
141 AggValueSlot aggSlot,
142 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000143 switch (getEvaluationKind(E->getType())) {
144 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000145 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000146 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000147 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000148 case TEK_Aggregate:
149 if (!ignoreResult && aggSlot.isIgnored())
150 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
151 EmitAggExpr(E, aggSlot);
152 return aggSlot.asRValue();
153 }
154 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000155}
156
Mike Stump4a3999f2009-09-09 13:00:44 +0000157/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
158/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000159RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
160 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000161
John McCall47fb9502013-03-07 21:37:08 +0000162 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000163 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
164 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000165}
166
John McCall21886962010-04-21 10:05:39 +0000167/// EmitAnyExprToMem - Evaluate an expression into a given memory
168/// location.
169void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000170 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000171 Qualifiers Quals,
172 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000173 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000174 switch (getEvaluationKind(E->getType())) {
175 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000176 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000177 /*isInit*/ false);
178 return;
179
180 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000181 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000182 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000183 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000184 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000185 return;
186 }
187
188 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000189 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000190 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000191 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000192 return;
John McCall21886962010-04-21 10:05:39 +0000193 }
John McCall47fb9502013-03-07 21:37:08 +0000194 }
195 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000196}
197
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000198static void
199pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000200 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000201 // Objective-C++ ARC:
202 // If we are binding a reference to a temporary that has ownership, we
203 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000204 //
205 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000206 if (auto Lifetime = M->getType().getObjCLifetime()) {
207 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000208 case Qualifiers::OCL_None:
209 case Qualifiers::OCL_ExplicitNone:
210 // Carry on to normal cleanup handling.
211 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000212
Richard Smith736a9472013-06-12 20:42:33 +0000213 case Qualifiers::OCL_Autoreleasing:
214 // Nothing to do; cleaned up by an autorelease pool.
215 return;
216
217 case Qualifiers::OCL_Strong:
218 case Qualifiers::OCL_Weak:
219 switch (StorageDuration Duration = M->getStorageDuration()) {
220 case SD_Static:
221 // Note: we intentionally do not register a cleanup to release
222 // the object on program termination.
223 return;
224
225 case SD_Thread:
226 // FIXME: We should probably register a cleanup in this case.
227 return;
228
229 case SD_Automatic:
230 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000231 CodeGenFunction::Destroyer *Destroy;
232 CleanupKind CleanupKind;
233 if (Lifetime == Qualifiers::OCL_Strong) {
234 const ValueDecl *VD = M->getExtendingDecl();
235 bool Precise =
236 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
237 CleanupKind = CGF.getARCCleanupKind();
238 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
239 : &CodeGenFunction::destroyARCStrongImprecise;
240 } else {
241 // __weak objects always get EH cleanups; otherwise, exceptions
242 // could cause really nasty crashes instead of mere leaks.
243 CleanupKind = NormalAndEHCleanup;
244 Destroy = &CodeGenFunction::destroyARCWeak;
245 }
246 if (Duration == SD_FullExpression)
247 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000248 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000249 CleanupKind & EHCleanup);
250 else
251 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000252 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000253 *Destroy, CleanupKind & EHCleanup);
254 return;
255
256 case SD_Dynamic:
257 llvm_unreachable("temporary cannot have dynamic storage duration");
258 }
259 llvm_unreachable("unknown storage duration");
260 }
261 }
262
Craig Topper8a13c412014-05-21 05:09:00 +0000263 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000264 if (const RecordType *RT =
265 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
266 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000267 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000268 if (!ClassDecl->hasTrivialDestructor())
269 ReferenceTemporaryDtor = ClassDecl->getDestructor();
270 }
271
272 if (!ReferenceTemporaryDtor)
273 return;
274
275 // Call the destructor for the temporary.
276 switch (M->getStorageDuration()) {
277 case SD_Static:
278 case SD_Thread: {
279 llvm::Constant *CleanupFn;
280 llvm::Constant *CleanupArg;
281 if (E->getType()->isArrayType()) {
282 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000283 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000284 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
285 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000286 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
287 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000288 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
289 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000290 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000291 }
292 CGF.CGM.getCXXABI().registerGlobalDtor(
293 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
294 break;
295 }
296
297 case SD_FullExpression:
298 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
299 CodeGenFunction::destroyCXXObject,
300 CGF.getLangOpts().Exceptions);
301 break;
302
303 case SD_Automatic:
304 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
305 ReferenceTemporary, E->getType(),
306 CodeGenFunction::destroyCXXObject,
307 CGF.getLangOpts().Exceptions);
308 break;
309
310 case SD_Dynamic:
311 llvm_unreachable("temporary cannot have dynamic storage duration");
312 }
313}
314
John McCall7f416cc2015-09-08 08:05:57 +0000315static Address
Richard Smith736a9472013-06-12 20:42:33 +0000316createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000317 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000318 switch (M->getStorageDuration()) {
319 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000320 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000321 // If we have a constant temporary array or record try to promote it into a
322 // constant global under the same rules a normal constant would've been
323 // promoted. This is easier on the optimizer and generally emits fewer
324 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000325 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000326 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000327 (Ty->isArrayType() || Ty->isRecordType()) &&
328 CGF.CGM.isTypeConstant(Ty, true))
329 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000330 auto *GV = new llvm::GlobalVariable(
331 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
332 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000333 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
334 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000335 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000336 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000337 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000338 return CGF.CreateMemTemp(Ty, "ref.tmp");
339 }
Richard Smith736a9472013-06-12 20:42:33 +0000340 case SD_Thread:
341 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000342 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000343
344 case SD_Dynamic:
345 llvm_unreachable("temporary can't have dynamic storage duration");
346 }
347 llvm_unreachable("unknown storage duration");
348}
349
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000350LValue CodeGenFunction::
351EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000352 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000353
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000354 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
355 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000356 auto ownership = M->getType().getObjCLifetime();
357 if (ownership != Qualifiers::OCL_None &&
358 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000359 Address Object = createReferenceTemporary(*this, M, E);
360 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
361 Object = Address(llvm::ConstantExpr::getBitCast(Var,
362 ConvertTypeForMem(E->getType())
363 ->getPointerTo(Object.getAddressSpace())),
364 Object.getAlignment());
Richard Smitha509f2f2013-06-14 03:07:01 +0000365 // We should not have emitted the initializer for this temporary as a
366 // constant.
367 assert(!Var->hasInitializer());
368 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
369 }
John McCall7f416cc2015-09-08 08:05:57 +0000370 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
371 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000372
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000373 switch (getEvaluationKind(E->getType())) {
374 default: llvm_unreachable("expected scalar or aggregate expression");
375 case TEK_Scalar:
376 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
377 break;
378 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000379 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000380 E->getType().getQualifiers(),
381 AggValueSlot::IsDestructed,
382 AggValueSlot::DoesNotNeedGCBarriers,
383 AggValueSlot::IsNotAliased));
384 break;
385 }
386 }
Richard Smith736a9472013-06-12 20:42:33 +0000387
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000388 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000389 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000390 }
391
Richard Smithf3fabd22013-06-03 00:17:11 +0000392 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000393 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000394 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
395
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000396 for (const auto &Ignored : CommaLHSs)
397 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000398
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000399 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000400 if (opaque->getType()->isRecordType()) {
401 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000402 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000403 }
404 }
405
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000406 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000407 Address Object = createReferenceTemporary(*this, M, E);
408 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
409 Object = Address(llvm::ConstantExpr::getBitCast(
410 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
411 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000412 // If the temporary is a global and has a constant initializer or is a
413 // constant temporary that we promoted to a global, we may have already
414 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000415 if (!Var->hasInitializer()) {
416 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
417 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
418 }
419 } else {
420 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
421 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000422 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000423
Richard Smith736a9472013-06-12 20:42:33 +0000424 // Perform derived-to-base casts and/or field accesses, to get from the
425 // temporary object we created (and, potentially, for which we extended
426 // the lifetime) to the subobject we're binding the reference to.
427 for (unsigned I = Adjustments.size(); I != 0; --I) {
428 SubobjectAdjustment &Adjustment = Adjustments[I-1];
429 switch (Adjustment.Kind) {
430 case SubobjectAdjustment::DerivedToBaseAdjustment:
431 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000432 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
433 Adjustment.DerivedToBase.BasePath->path_begin(),
434 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000435 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000436 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000437
Richard Smith736a9472013-06-12 20:42:33 +0000438 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000439 LValue LV = MakeAddrLValue(Object, E->getType(),
440 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000441 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000442 assert(LV.isSimple() &&
443 "materialized temporary field is not a simple lvalue");
444 Object = LV.getAddress();
445 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000446 }
447
Richard Smith736a9472013-06-12 20:42:33 +0000448 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000449 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000450 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
451 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000452 break;
453 }
454 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000455 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000456
John McCall7f416cc2015-09-08 08:05:57 +0000457 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000458}
459
460RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000461CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
462 // Emit the expression as an lvalue.
463 LValue LV = EmitLValue(E);
464 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000465 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000466
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000467 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000468 // C++11 [dcl.ref]p5 (as amended by core issue 453):
469 // If a glvalue to which a reference is directly bound designates neither
470 // an existing object or function of an appropriate type nor a region of
471 // storage of suitable size and alignment to contain an object of the
472 // reference's type, the behavior is undefined.
473 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000474 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000475 }
John McCall8680f872010-07-21 06:29:51 +0000476
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000477 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000478}
479
480
Mike Stump4a3999f2009-09-09 13:00:44 +0000481/// getAccessedFieldNo - Given an encoded value and a result number, return the
482/// input field number being accessed.
483unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000484 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000485 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
486 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000487}
488
Richard Smith4d3110a2012-10-25 02:14:12 +0000489/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
490static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
491 llvm::Value *High) {
492 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
493 llvm::Value *K47 = Builder.getInt64(47);
494 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
495 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
496 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
497 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
498 return Builder.CreateMul(B1, KMul);
499}
500
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000501bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000502 return SanOpts.has(SanitizerKind::Null) |
503 SanOpts.has(SanitizerKind::Alignment) |
504 SanOpts.has(SanitizerKind::ObjectSize) |
505 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000506}
507
Richard Smithe30752c2012-10-09 19:52:38 +0000508void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000509 llvm::Value *Ptr, QualType Ty,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000510 CharUnits Alignment, bool SkipNullCheck) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000511 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000512 return;
513
Richard Smith2d8b2942012-11-01 07:22:08 +0000514 // Don't check pointers outside the default address space. The null check
515 // isn't correct, the object-size check isn't supported by LLVM, and we can't
516 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000517 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000518 return;
519
Alexey Samsonov24cad992014-07-17 18:46:27 +0000520 SanitizerScope SanScope(this);
521
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000522 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000523 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000524
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000525 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
526 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000527 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
528 !SkipNullCheck) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000529 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000530 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000531
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000532 if (AllowNullPointers) {
533 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000534 // Skip the remaining checks in that case.
535 Done = createBasicBlock("null");
536 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000537 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000538 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000539 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000540 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000541 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000542 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000543
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000544 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000545 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000546
Richard Smith69d0d262012-08-24 00:54:33 +0000547 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000548 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000549 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000550 // FIXME: Get object address space
551 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
552 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000553 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000554 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000555 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000556 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000557 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000558 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000559 }
Richard Smith69d0d262012-08-24 00:54:33 +0000560
Richard Smithb1b0ab42012-11-05 22:21:05 +0000561 uint64_t AlignVal = 0;
562
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000563 if (SanOpts.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000564 AlignVal = Alignment.getQuantity();
565 if (!Ty->isIncompleteType() && !AlignVal)
566 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
567
Richard Smith69d0d262012-08-24 00:54:33 +0000568 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000569 if (AlignVal) {
570 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000571 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000572 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
573 llvm::Value *Aligned =
574 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000575 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000576 }
Richard Smith69d0d262012-08-24 00:54:33 +0000577 }
578
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000579 if (Checks.size() > 0) {
Richard Smithe30752c2012-10-09 19:52:38 +0000580 llvm::Constant *StaticData[] = {
581 EmitCheckSourceLocation(Loc),
582 EmitCheckTypeDescriptor(Ty),
583 llvm::ConstantInt::get(SizeTy, AlignVal),
584 llvm::ConstantInt::get(Int8Ty, TCK)
585 };
John McCall7f416cc2015-09-08 08:05:57 +0000586 EmitCheck(Checks, "type_mismatch", StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000587 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000588
Richard Smithb1b0ab42012-11-05 22:21:05 +0000589 // If possible, check that the vptr indicates that there is a subobject of
590 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000591 //
592 // C++11 [basic.life]p5,6:
593 // [For storage which does not refer to an object within its lifetime]
594 // The program has undefined behavior if:
595 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000596 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000597 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000598 if (SanOpts.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000599 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000600 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
601 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000602 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000603 // Compute a hash of the mangled name of the type.
604 //
605 // FIXME: This is not guaranteed to be deterministic! Move to a
606 // fingerprinting mechanism once LLVM provides one. For the time
607 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000608 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000609 llvm::raw_svector_ostream Out(MangledName);
610 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
611 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000612
Alexey Samsonov84856012014-07-10 22:34:19 +0000613 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000614 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
615 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000616 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000617
Alexey Samsonov84856012014-07-10 22:34:19 +0000618 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
619 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
620 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000621 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000622 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
623 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000624
Alexey Samsonov84856012014-07-10 22:34:19 +0000625 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
626 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000627
Alexey Samsonov84856012014-07-10 22:34:19 +0000628 // Look the hash up in our cache.
629 const int CacheSize = 128;
630 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
631 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
632 "__ubsan_vptr_type_cache");
633 llvm::Value *Slot = Builder.CreateAnd(Hash,
634 llvm::ConstantInt::get(IntPtrTy,
635 CacheSize-1));
636 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
637 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000638 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
639 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000640
641 // If the hash isn't in the cache, call a runtime handler to perform the
642 // hard work of checking whether the vptr is for an object of the right
643 // type. This will either fill in the cache and return, or produce a
644 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000645 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000646 llvm::Constant *StaticData[] = {
647 EmitCheckSourceLocation(Loc),
648 EmitCheckTypeDescriptor(Ty),
649 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
650 llvm::ConstantInt::get(Int8Ty, TCK)
651 };
John McCall7f416cc2015-09-08 08:05:57 +0000652 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000653 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
654 "dynamic_type_cache_miss", StaticData, DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000655 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000656 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000657
658 if (Done) {
659 Builder.CreateBr(Done);
660 EmitBlock(Done);
661 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000662}
Chris Lattner4647a212007-08-31 22:49:20 +0000663
Richard Smith539e4a72013-02-23 02:53:19 +0000664/// Determine whether this expression refers to a flexible array member in a
665/// struct. We disable array bounds checks for such members.
666static bool isFlexibleArrayMemberExpr(const Expr *E) {
667 // For compatibility with existing code, we treat arrays of length 0 or
668 // 1 as flexible array members.
669 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000670 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000671 if (CAT->getSize().ugt(1))
672 return false;
673 } else if (!isa<IncompleteArrayType>(AT))
674 return false;
675
676 E = E->IgnoreParens();
677
678 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000679 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000680 // FIXME: If the base type of the member expr is not FD->getParent(),
681 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000682 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000683 RecordDecl::field_iterator FI(
684 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
685 return ++FI == FD->getParent()->field_end();
686 }
687 }
688
689 return false;
690}
691
692/// If Base is known to point to the start of an array, return the length of
693/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000694static llvm::Value *getArrayIndexingBound(
695 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000696 // For the vector indexing extension, the bound is the number of elements.
697 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
698 IndexedType = Base->getType();
699 return CGF.Builder.getInt32(VT->getNumElements());
700 }
701
702 Base = Base->IgnoreParens();
703
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000704 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000705 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
706 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
707 IndexedType = CE->getSubExpr()->getType();
708 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000709 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000710 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000711 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000712 return CGF.getVLASize(VAT).first;
713 }
714 }
715
Craig Topper8a13c412014-05-21 05:09:00 +0000716 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000717}
718
719void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
720 llvm::Value *Index, QualType IndexType,
721 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000722 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000723 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000724 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000725
Richard Smith539e4a72013-02-23 02:53:19 +0000726 QualType IndexedType;
727 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
728 if (!Bound)
729 return;
730
731 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
732 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
733 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
734
735 llvm::Constant *StaticData[] = {
736 EmitCheckSourceLocation(E->getExprLoc()),
737 EmitCheckTypeDescriptor(IndexedType),
738 EmitCheckTypeDescriptor(IndexType)
739 };
740 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
741 : Builder.CreateICmpULE(IndexVal, BoundVal);
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000742 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
743 StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000744}
745
Chris Lattner116ce8f2010-01-09 21:40:03 +0000746
Chris Lattner116ce8f2010-01-09 21:40:03 +0000747CodeGenFunction::ComplexPairTy CodeGenFunction::
748EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
749 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000750 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000751
Chris Lattner116ce8f2010-01-09 21:40:03 +0000752 llvm::Value *NextVal;
753 if (isa<llvm::IntegerType>(InVal.first->getType())) {
754 uint64_t AmountVal = isInc ? 1 : -1;
755 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000756
Chris Lattner116ce8f2010-01-09 21:40:03 +0000757 // Add the inc/dec to the real part.
758 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
759 } else {
760 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
761 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
762 if (!isInc)
763 FVal.changeSign();
764 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000765
Chris Lattner116ce8f2010-01-09 21:40:03 +0000766 // Add the inc/dec to the real part.
767 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
768 }
Craig Topper99e79272013-07-26 05:59:26 +0000769
Chris Lattner116ce8f2010-01-09 21:40:03 +0000770 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000771
Chris Lattner116ce8f2010-01-09 21:40:03 +0000772 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000773 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000774
Chris Lattner116ce8f2010-01-09 21:40:03 +0000775 // If this is a postinc, return the value read from memory, otherwise use the
776 // updated value.
777 return isPre ? IncVal : InVal;
778}
779
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000780void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
781 CodeGenFunction *CGF) {
782 // Bind VLAs in the cast type.
783 if (CGF && E->getType()->isVariablyModifiedType())
784 CGF->EmitVariablyModifiedType(E->getType());
785
786 if (CGDebugInfo *DI = getModuleDebugInfo())
787 DI->EmitExplicitCastType(E->getType());
788}
789
Chris Lattnera45c5af2007-06-02 19:47:04 +0000790//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000791// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000792//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000793
John McCall7f416cc2015-09-08 08:05:57 +0000794/// EmitPointerWithAlignment - Given an expression of pointer type, try to
795/// derive a more accurate bound on the alignment of the pointer.
796Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
797 AlignmentSource *Source) {
798 // We allow this with ObjC object pointers because of fragile ABIs.
799 assert(E->getType()->isPointerType() ||
800 E->getType()->isObjCObjectPointerType());
801 E = E->IgnoreParens();
802
803 // Casts:
804 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000805 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
806 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000807
808 switch (CE->getCastKind()) {
809 // Non-converting casts (but not C's implicit conversion from void*).
810 case CK_BitCast:
811 case CK_NoOp:
812 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
813 if (PtrTy->getPointeeType()->isVoidType())
814 break;
815
816 AlignmentSource InnerSource;
817 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
818 if (Source) *Source = InnerSource;
819
820 // If this is an explicit bitcast, and the source l-value is
821 // opaque, honor the alignment of the casted-to type.
822 if (isa<ExplicitCastExpr>(CE) &&
John McCall7f416cc2015-09-08 08:05:57 +0000823 InnerSource != AlignmentSource::Decl) {
824 Addr = Address(Addr.getPointer(),
825 getNaturalPointeeTypeAlignment(E->getType(), Source));
826 }
827
Peter Collingbourne574975e2016-01-14 02:49:48 +0000828 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
829 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000830 if (auto PT = E->getType()->getAs<PointerType>())
831 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
832 /*MayBeNull=*/true,
833 CodeGenFunction::CFITCK_UnrelatedCast,
834 CE->getLocStart());
835 }
836
John McCall7f416cc2015-09-08 08:05:57 +0000837 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
838 }
839 break;
840
841 // Array-to-pointer decay.
842 case CK_ArrayToPointerDecay:
843 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
844
845 // Derived-to-base conversions.
846 case CK_UncheckedDerivedToBase:
847 case CK_DerivedToBase: {
848 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
849 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
850 return GetAddressOfBaseClass(Addr, Derived,
851 CE->path_begin(), CE->path_end(),
852 ShouldNullCheckClassCastValue(CE),
853 CE->getExprLoc());
854 }
855
856 // TODO: Is there any reason to treat base-to-derived conversions
857 // specially?
858 default:
859 break;
860 }
861 }
862
863 // Unary &.
864 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
865 if (UO->getOpcode() == UO_AddrOf) {
866 LValue LV = EmitLValue(UO->getSubExpr());
867 if (Source) *Source = LV.getAlignmentSource();
868 return LV.getAddress();
869 }
870 }
871
872 // TODO: conditional operators, comma.
873
874 // Otherwise, use the alignment of the type.
875 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
876 return Address(EmitScalarExpr(E), Align);
877}
878
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000879RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000880 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000881 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000882
883 switch (getEvaluationKind(Ty)) {
884 case TEK_Complex: {
885 llvm::Type *EltTy =
886 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000887 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000888 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000889 }
Craig Topper99e79272013-07-26 05:59:26 +0000890
Chris Lattner65526f02010-08-23 05:26:13 +0000891 // If this is a use of an undefined aggregate type, the aggregate must have an
892 // identifiable address. Just because the contents of the value are undefined
893 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000894 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000895 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000896 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000897 }
John McCall47fb9502013-03-07 21:37:08 +0000898
899 case TEK_Scalar:
900 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
901 }
902 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000903}
904
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000905RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
906 const char *Name) {
907 ErrorUnsupported(E, Name);
908 return GetUndefRValue(E->getType());
909}
910
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000911LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
912 const char *Name) {
913 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000914 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000915 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
916 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000917}
918
Richard Smith4d1458e2012-09-08 02:08:36 +0000919LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000920 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000921 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000922 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
923 else
924 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000925 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000926 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000927 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000928 return LV;
929}
930
Chris Lattner8394d792007-06-05 20:53:16 +0000931/// EmitLValue - Emit code to compute a designator that specifies the location
932/// of the expression.
933///
Mike Stump4a3999f2009-09-09 13:00:44 +0000934/// This can return one of two things: a simple address or a bitfield reference.
935/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
936/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000937///
Mike Stump4a3999f2009-09-09 13:00:44 +0000938/// If this returns a bitfield reference, nothing about the pointee type of the
939/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000940///
Mike Stump4a3999f2009-09-09 13:00:44 +0000941/// If this returns a normal address, and if the lvalue's C type is fixed size,
942/// this method guarantees that the returned pointer type will point to an LLVM
943/// type of the same size of the lvalue's type. If the lvalue has a variable
944/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000945///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000946LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000947 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000948 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000949 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000950
John McCallc109a252011-11-07 03:59:57 +0000951 case Expr::ObjCPropertyRefExprClass:
952 llvm_unreachable("cannot emit a property reference directly");
953
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000954 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000955 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000956 case Expr::ObjCIsaExprClass:
957 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000958 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000959 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000960 case Expr::CompoundAssignOperatorClass: {
961 QualType Ty = E->getType();
962 if (const AtomicType *AT = Ty->getAs<AtomicType>())
963 Ty = AT->getValueType();
964 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000965 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
966 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000967 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000968 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000969 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000970 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000971 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000972 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000973 case Expr::VAArgExprClass:
974 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000975 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000976 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000977 case Expr::ParenExprClass:
978 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000979 case Expr::GenericSelectionExprClass:
980 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000981 case Expr::PredefinedExprClass:
982 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000983 case Expr::StringLiteralClass:
984 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000985 case Expr::ObjCEncodeExprClass:
986 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000987 case Expr::PseudoObjectExprClass:
988 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000989 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000990 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000991 case Expr::CXXTemporaryObjectExprClass:
992 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000993 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
994 case Expr::CXXBindTemporaryExprClass:
995 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000996 case Expr::CXXUuidofExprClass:
997 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000998 case Expr::LambdaExprClass:
999 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001000
1001 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001002 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001003 enterFullExpression(cleanups);
1004 RunCleanupsScope Scope(*this);
1005 return EmitLValue(cleanups->getSubExpr());
1006 }
1007
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001008 case Expr::CXXDefaultArgExprClass:
1009 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001010 case Expr::CXXDefaultInitExprClass: {
1011 CXXDefaultInitExprScope Scope(*this);
1012 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1013 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001014 case Expr::CXXTypeidExprClass:
1015 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001016
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001017 case Expr::ObjCMessageExprClass:
1018 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001019 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001020 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001021 case Expr::StmtExprClass:
1022 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001023 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001024 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001025 case Expr::ArraySubscriptExprClass:
1026 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001027 case Expr::OMPArraySectionExprClass:
1028 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001029 case Expr::ExtVectorElementExprClass:
1030 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001031 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001032 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001033 case Expr::CompoundLiteralExprClass:
1034 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001035 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001036 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001037 case Expr::BinaryConditionalOperatorClass:
1038 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001039 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001040 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001041 case Expr::OpaqueValueExprClass:
1042 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001043 case Expr::SubstNonTypeTemplateParmExprClass:
1044 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001045 case Expr::ImplicitCastExprClass:
1046 case Expr::CStyleCastExprClass:
1047 case Expr::CXXFunctionalCastExprClass:
1048 case Expr::CXXStaticCastExprClass:
1049 case Expr::CXXDynamicCastExprClass:
1050 case Expr::CXXReinterpretCastExprClass:
1051 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001052 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001053 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001054
Douglas Gregorfe314812011-06-21 17:03:29 +00001055 case Expr::MaterializeTemporaryExprClass:
1056 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001057 }
1058}
1059
John McCall71335052012-03-10 03:05:10 +00001060/// Given an object of the given canonical type, can we safely copy a
1061/// value out of it based on its initializer?
1062static bool isConstantEmittableObjectType(QualType type) {
1063 assert(type.isCanonical());
1064 assert(!type->isReferenceType());
1065
1066 // Must be const-qualified but non-volatile.
1067 Qualifiers qs = type.getLocalQualifiers();
1068 if (!qs.hasConst() || qs.hasVolatile()) return false;
1069
1070 // Otherwise, all object types satisfy this except C++ classes with
1071 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001072 if (const auto *RT = dyn_cast<RecordType>(type))
1073 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001074 if (RD->hasMutableFields() || !RD->isTrivial())
1075 return false;
1076
1077 return true;
1078}
1079
1080/// Can we constant-emit a load of a reference to a variable of the
1081/// given type? This is different from predicates like
1082/// Decl::isUsableInConstantExpressions because we do want it to apply
1083/// in situations that don't necessarily satisfy the language's rules
1084/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1085/// to do this with const float variables even if those variables
1086/// aren't marked 'constexpr'.
1087enum ConstantEmissionKind {
1088 CEK_None,
1089 CEK_AsReferenceOnly,
1090 CEK_AsValueOrReference,
1091 CEK_AsValueOnly
1092};
1093static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1094 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001095 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001096 if (isConstantEmittableObjectType(ref->getPointeeType()))
1097 return CEK_AsValueOrReference;
1098 return CEK_AsReferenceOnly;
1099 }
1100 if (isConstantEmittableObjectType(type))
1101 return CEK_AsValueOnly;
1102 return CEK_None;
1103}
1104
1105/// Try to emit a reference to the given value without producing it as
1106/// an l-value. This is actually more than an optimization: we can't
1107/// produce an l-value for variables that we never actually captured
1108/// in a block or lambda, which means const int variables or constexpr
1109/// literals or similar.
1110CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001111CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1112 ValueDecl *value = refExpr->getDecl();
1113
John McCall71335052012-03-10 03:05:10 +00001114 // The value needs to be an enum constant or a constant variable.
1115 ConstantEmissionKind CEK;
1116 if (isa<ParmVarDecl>(value)) {
1117 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001118 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001119 CEK = checkVarTypeForConstantEmission(var->getType());
1120 } else if (isa<EnumConstantDecl>(value)) {
1121 CEK = CEK_AsValueOnly;
1122 } else {
1123 CEK = CEK_None;
1124 }
1125 if (CEK == CEK_None) return ConstantEmission();
1126
John McCall71335052012-03-10 03:05:10 +00001127 Expr::EvalResult result;
1128 bool resultIsReference;
1129 QualType resultType;
1130
1131 // It's best to evaluate all the way as an r-value if that's permitted.
1132 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001133 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001134 resultIsReference = false;
1135 resultType = refExpr->getType();
1136
1137 // Otherwise, try to evaluate as an l-value.
1138 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001139 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001140 resultIsReference = true;
1141 resultType = value->getType();
1142
1143 // Failure.
1144 } else {
1145 return ConstantEmission();
1146 }
1147
1148 // In any case, if the initializer has side-effects, abandon ship.
1149 if (result.HasSideEffects)
1150 return ConstantEmission();
1151
1152 // Emit as a constant.
1153 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1154
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001155 // Make sure we emit a debug reference to the global variable.
1156 // This should probably fire even for
1157 if (isa<VarDecl>(value)) {
1158 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1159 EmitDeclRefExprDbgValue(refExpr, C);
1160 } else {
1161 assert(isa<EnumConstantDecl>(value));
1162 EmitDeclRefExprDbgValue(refExpr, C);
1163 }
John McCall71335052012-03-10 03:05:10 +00001164
1165 // If we emitted a reference constant, we need to dereference that.
1166 if (resultIsReference)
1167 return ConstantEmission::forReference(C);
1168
1169 return ConstantEmission::forValue(C);
1170}
1171
Nick Lewycky2d84e842013-10-02 02:29:49 +00001172llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1173 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001174 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001175 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1176 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001177 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1178 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001179}
1180
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001181static bool hasBooleanRepresentation(QualType Ty) {
1182 if (Ty->isBooleanType())
1183 return true;
1184
1185 if (const EnumType *ET = Ty->getAs<EnumType>())
1186 return ET->getDecl()->getIntegerType()->isBooleanType();
1187
Douglas Gregor298f43d2012-04-12 20:42:30 +00001188 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1189 return hasBooleanRepresentation(AT->getValueType());
1190
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001191 return false;
1192}
1193
Richard Smith1629da92012-12-13 07:11:50 +00001194static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1195 llvm::APInt &Min, llvm::APInt &End,
1196 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001197 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001198 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1199 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001200 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001201 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001202 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001203
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001204 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001205 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1206 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001207 } else {
1208 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001209 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001210 unsigned Bitwidth = LTy->getScalarSizeInBits();
1211 unsigned NumNegativeBits = ED->getNumNegativeBits();
1212 unsigned NumPositiveBits = ED->getNumPositiveBits();
1213
1214 if (NumNegativeBits) {
1215 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1216 assert(NumBits <= Bitwidth);
1217 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1218 Min = -End;
1219 } else {
1220 assert(NumPositiveBits <= Bitwidth);
1221 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1222 Min = llvm::APInt(Bitwidth, 0);
1223 }
1224 }
Richard Smith1629da92012-12-13 07:11:50 +00001225 return true;
1226}
1227
1228llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1229 llvm::APInt Min, End;
1230 if (!getRangeForType(*this, Ty, Min, End,
1231 CGM.getCodeGenOpts().StrictEnums))
Craig Topper8a13c412014-05-21 05:09:00 +00001232 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001233
Duncan Sandsc720e782012-04-15 18:04:54 +00001234 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001235 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001236}
1237
John McCall7f416cc2015-09-08 08:05:57 +00001238llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1239 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001240 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001241 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001242 llvm::MDNode *TBAAInfo,
1243 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001244 uint64_t TBAAOffset,
1245 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001246 // For better performance, handle vector loads differently.
1247 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001248 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001249
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001250 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001251
John McCall7f416cc2015-09-08 08:05:57 +00001252 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001253 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001254
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001255 // Bitcast to vec4 type.
1256 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1257 4);
John McCall7f416cc2015-09-08 08:05:57 +00001258 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001259 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001260 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001261
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001262 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001263 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001264 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001265 return EmitFromMemory(V, Ty);
1266 }
1267 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001268
1269 // Atomic operations have to be done on integral types.
David Majnemera5b195a2015-02-14 01:35:12 +00001270 if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
John McCall7f416cc2015-09-08 08:05:57 +00001271 LValue lvalue =
1272 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemereeaec262015-02-14 02:18:14 +00001273 return EmitAtomicLoad(lvalue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001274 }
Craig Topper99e79272013-07-26 05:59:26 +00001275
John McCall7f416cc2015-09-08 08:05:57 +00001276 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001277 if (isNontemporal) {
1278 llvm::MDNode *Node = llvm::MDNode::get(
1279 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1280 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1281 }
Manman Renc451e572013-04-04 21:53:22 +00001282 if (TBAAInfo) {
1283 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1284 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001285 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001286 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1287 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001288 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001289
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001290 bool NeedsBoolCheck =
1291 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1292 bool NeedsEnumCheck =
1293 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1294 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001295 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001296 llvm::APInt Min, End;
1297 if (getRangeForType(*this, Ty, Min, End, true)) {
1298 --End;
1299 llvm::Value *Check;
1300 if (!Min)
1301 Check = Builder.CreateICmpULE(
1302 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1303 else {
1304 llvm::Value *Upper = Builder.CreateICmpSLE(
1305 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1306 llvm::Value *Lower = Builder.CreateICmpSGE(
1307 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1308 Check = Builder.CreateAnd(Upper, Lower);
1309 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001310 llvm::Constant *StaticArgs[] = {
1311 EmitCheckSourceLocation(Loc),
1312 EmitCheckTypeDescriptor(Ty)
1313 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001314 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001315 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1316 EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001317 }
1318 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001319 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1320 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001321
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001322 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001323}
1324
John McCall3a7f6922010-10-27 20:58:56 +00001325llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1326 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001327 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001328 // This should really always be an i1, but sometimes it's already
1329 // an i8, and it's awkward to track those cases down.
1330 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001331 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1332 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1333 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001334 }
1335
1336 return Value;
1337}
1338
1339llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1340 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001341 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001342 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1343 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001344 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1345 }
1346
1347 return Value;
1348}
1349
John McCall7f416cc2015-09-08 08:05:57 +00001350void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1351 bool Volatile, QualType Ty,
1352 AlignmentSource AlignSource,
1353 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001354 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001355 uint64_t TBAAOffset,
1356 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001357
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001358 // Handle vectors differently to get better performance.
1359 if (Ty->isVectorType()) {
1360 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001361 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001362 // Handle vec3 special.
1363 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001364 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001365 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1366 Builder.getInt32(2),
1367 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001368 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1369 Value = Builder.CreateShuffleVector(Value,
1370 llvm::UndefValue::get(VecTy),
1371 MaskV, "extractVec");
1372 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1373 }
John McCall7f416cc2015-09-08 08:05:57 +00001374 if (Addr.getElementType() != SrcTy) {
1375 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001376 }
1377 }
Craig Topper99e79272013-07-26 05:59:26 +00001378
John McCall3a7f6922010-10-27 20:58:56 +00001379 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001380
David Majnemera5b195a2015-02-14 01:35:12 +00001381 if (Ty->isAtomicType() ||
1382 (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001383 EmitAtomicStore(RValue::get(Value),
John McCall7f416cc2015-09-08 08:05:57 +00001384 LValue::MakeAddr(Addr, Ty, getContext(),
1385 AlignSource, TBAAInfo),
John McCalla8ec7eb2013-03-07 21:37:17 +00001386 isInit);
1387 return;
1388 }
1389
Daniel Dunbar03816342010-08-21 02:24:36 +00001390 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001391 if (isNontemporal) {
1392 llvm::MDNode *Node =
1393 llvm::MDNode::get(Store->getContext(),
1394 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1395 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1396 }
Manman Renc451e572013-04-04 21:53:22 +00001397 if (TBAAInfo) {
1398 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1399 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001400 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001401 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1402 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001403 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001404}
1405
David Chisnallfa35df62012-01-16 17:27:18 +00001406void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001407 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001408 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001409 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001410 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001411 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001412}
1413
Mike Stump4a3999f2009-09-09 13:00:44 +00001414/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1415/// method emits the address of the lvalue, then loads the result as an rvalue,
1416/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001417RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001418 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001419 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001420 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001421 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1422 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001423 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001424 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001425 // In MRC mode, we do a load+autorelease.
1426 if (!getLangOpts().ObjCAutoRefCount) {
1427 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1428 }
1429
1430 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001431 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1432 Object = EmitObjCConsumeObject(LV.getType(), Object);
1433 return RValue::get(Object);
1434 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001435
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001436 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001437 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001438
John McCalla1dee5302010-08-22 10:59:02 +00001439 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001440 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001441 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001442
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001443 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001444 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001445 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001446 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001447 "vecext"));
1448 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001449
1450 // If this is a reference to a subset of the elements of a vector, either
1451 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001452 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001453 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001454
Renato Golin230c5eb2014-05-19 18:15:42 +00001455 // Global Register variables always invoke intrinsics
1456 if (LV.isGlobalReg())
1457 return EmitLoadOfGlobalRegLValue(LV);
1458
John McCallc109a252011-11-07 03:59:57 +00001459 assert(LV.isBitField() && "Unknown LValue type!");
1460 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001461}
1462
John McCall55e1fbc2011-06-25 02:11:03 +00001463RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001464 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001465
Daniel Dunbar3447a022010-04-13 23:34:15 +00001466 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001467 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001468
John McCall7f416cc2015-09-08 08:05:57 +00001469 Address Ptr = LV.getBitFieldAddress();
1470 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001471
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001472 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001473 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001474 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1475 if (HighBits)
1476 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1477 if (Info.Offset + HighBits)
1478 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1479 } else {
1480 if (Info.Offset)
1481 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001482 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001483 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1484 Info.Size),
1485 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001486 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001487 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001488
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001489 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001490}
1491
Nate Begemanb699c9b2009-01-18 06:42:49 +00001492// If this is a reference to a subset of the elements of a vector, create an
1493// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001494RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001495 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1496 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001497
Nate Begemanf322eab2008-05-09 06:41:27 +00001498 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001499
1500 // If the result of the expression is a non-vector type, we must be extracting
1501 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001502 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001503 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001504 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001505 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001506 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001507 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001508
1509 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001510 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001511
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001512 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001513 for (unsigned i = 0; i != NumResultElts; ++i)
1514 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001515
Chris Lattner91c08ad2011-02-15 00:14:06 +00001516 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1517 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001518 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001519 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001520}
1521
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001522/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001523Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1524 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001525 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1526 QualType EQT = ExprVT->getElementType();
1527 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001528
John McCall7f416cc2015-09-08 08:05:57 +00001529 Address CastToPointerElement =
1530 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1531 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001532
1533 const llvm::Constant *Elts = LV.getExtVectorElts();
1534 unsigned ix = getAccessedFieldNo(0, Elts);
1535
John McCall7f416cc2015-09-08 08:05:57 +00001536 Address VectorBasePtrPlusIx =
1537 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1538 getContext().getTypeSizeInChars(EQT),
1539 "vector.elt");
1540
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001541 return VectorBasePtrPlusIx;
1542}
1543
Renato Golin230c5eb2014-05-19 18:15:42 +00001544/// @brief Load of global gamed gegisters are always calls to intrinsics.
1545RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001546 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1547 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001548 llvm::MDNode *RegName = cast<llvm::MDNode>(
1549 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001550
1551 // We accept integer and pointer types only
1552 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1553 llvm::Type *Ty = OrigTy;
1554 if (OrigTy->isPointerTy())
1555 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1556 llvm::Type *Types[] = { Ty };
1557
Renato Golin230c5eb2014-05-19 18:15:42 +00001558 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001559 llvm::Value *Call = Builder.CreateCall(
1560 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001561 if (OrigTy->isPointerTy())
1562 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001563 return RValue::get(Call);
1564}
Chris Lattner40ff7012007-08-03 16:18:34 +00001565
Chris Lattner9369a562007-06-29 16:31:29 +00001566
Chris Lattner8394d792007-06-05 20:53:16 +00001567/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1568/// lvalue, where both are guaranteed to the have the same type, and that type
1569/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001570void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001571 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001572 if (!Dst.isSimple()) {
1573 if (Dst.isVectorElt()) {
1574 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001575 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1576 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001577 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001578 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001579 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1580 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001581 return;
1582 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001583
Nate Begemance4d7fc2008-04-18 23:10:10 +00001584 // If this is an update of extended vector elements, insert them as
1585 // appropriate.
1586 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001587 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001588
Renato Golin230c5eb2014-05-19 18:15:42 +00001589 if (Dst.isGlobalReg())
1590 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1591
John McCallc109a252011-11-07 03:59:57 +00001592 assert(Dst.isBitField() && "Unknown LValue type");
1593 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001594 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001595
John McCall31168b02011-06-15 23:02:42 +00001596 // There's special magic for assigning into an ARC-qualified l-value.
1597 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1598 switch (Lifetime) {
1599 case Qualifiers::OCL_None:
1600 llvm_unreachable("present but none");
1601
1602 case Qualifiers::OCL_ExplicitNone:
1603 // nothing special
1604 break;
1605
1606 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001607 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001608 return;
1609
1610 case Qualifiers::OCL_Weak:
1611 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1612 return;
1613
1614 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001615 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1616 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001617 // fall into the normal path
1618 break;
1619 }
1620 }
1621
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001622 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001623 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001624 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001625 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001626 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001627 return;
1628 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001629
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001630 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001631 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001632 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001633 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001634 if (Dst.isObjCIvar()) {
1635 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001636 llvm::Type *ResultType = IntPtrTy;
1637 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1638 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001639 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001640 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001641 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1642 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001643 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001644 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001645 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001646 } else if (Dst.isGlobalObjCRef()) {
1647 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1648 Dst.isThreadLocalRef());
1649 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001650 else
1651 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001652 return;
1653 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001654
Chris Lattner6278e6a2007-08-11 00:04:45 +00001655 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001656 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001657}
1658
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001659void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001660 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001661 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001662 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001663 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001664
Daniel Dunbar67aba792010-04-15 03:47:33 +00001665 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001666 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001667
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001668 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001669 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001670 /*IsSigned=*/false);
1671 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001672
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001673 // See if there are other bits in the bitfield's storage we'll need to load
1674 // and mask together with source before storing.
1675 if (Info.StorageSize != Info.Size) {
1676 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001677 llvm::Value *Val =
1678 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001679
1680 // Mask the source value as needed.
1681 if (!hasBooleanRepresentation(Dst.getType()))
1682 SrcVal = Builder.CreateAnd(SrcVal,
1683 llvm::APInt::getLowBitsSet(Info.StorageSize,
1684 Info.Size),
1685 "bf.value");
1686 MaskedVal = SrcVal;
1687 if (Info.Offset)
1688 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1689
1690 // Mask out the original value.
1691 Val = Builder.CreateAnd(Val,
1692 ~llvm::APInt::getBitsSet(Info.StorageSize,
1693 Info.Offset,
1694 Info.Offset + Info.Size),
1695 "bf.clear");
1696
1697 // Or together the unchanged values and the source value.
1698 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1699 } else {
1700 assert(Info.Offset == 0);
1701 }
1702
1703 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001704 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001705
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001706 // Return the new value of the bit-field, if requested.
1707 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001708 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001709
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001710 // Sign extend the value if needed.
1711 if (Info.IsSigned) {
1712 assert(Info.Size <= Info.StorageSize);
1713 unsigned HighBits = Info.StorageSize - Info.Size;
1714 if (HighBits) {
1715 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1716 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1717 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001718 }
1719
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001720 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1721 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001722 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001723 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001724}
1725
Nate Begemance4d7fc2008-04-18 23:10:10 +00001726void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001727 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001728 // This access turns into a read/modify/write of the vector. Load the input
1729 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001730 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1731 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001732 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001733
Chris Lattner4647a212007-08-31 22:49:20 +00001734 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001735
John McCall55e1fbc2011-06-25 02:11:03 +00001736 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001737 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001738 unsigned NumDstElts =
1739 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1740 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001741 // Use shuffle vector is the src and destination are the same number of
1742 // elements and restore the vector mask since it is on the side it will be
1743 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001744 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001745 for (unsigned i = 0; i != NumSrcElts; ++i)
1746 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001747
Chris Lattner91c08ad2011-02-15 00:14:06 +00001748 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001749 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001750 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001751 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001752 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001753 // Extended the source vector to the same length and then shuffle it
1754 // into the destination.
1755 // FIXME: since we're shuffling with undef, can we just use the indices
1756 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001757 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001758 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001759 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001760 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001761 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001762 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001763 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001764 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001765 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001766 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001767 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001768 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001769 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001770
Joey Goulycf4143b2013-11-21 17:09:05 +00001771 // When the vector size is odd and .odd or .hi is used, the last element
1772 // of the Elts constant array will be one past the size of the vector.
1773 // Ignore the last element here, if it is greater than the mask size.
1774 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1775 NumSrcElts--;
1776
Nate Begemanb699c9b2009-01-18 06:42:49 +00001777 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001778 for (unsigned i = 0; i != NumSrcElts; ++i)
1779 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001780 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001781 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001782 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001783 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001784 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001785 }
1786 } else {
1787 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001788 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001789 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001790 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001791 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001792
John McCall7f416cc2015-09-08 08:05:57 +00001793 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1794 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001795}
1796
Renato Golin230c5eb2014-05-19 18:15:42 +00001797/// @brief Store of global named registers are always calls to intrinsics.
1798void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001799 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1800 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001801 llvm::MDNode *RegName = cast<llvm::MDNode>(
1802 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001803 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001804
1805 // We accept integer and pointer types only
1806 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1807 llvm::Type *Ty = OrigTy;
1808 if (OrigTy->isPointerTy())
1809 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1810 llvm::Type *Types[] = { Ty };
1811
Renato Golin230c5eb2014-05-19 18:15:42 +00001812 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1813 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001814 if (OrigTy->isPointerTy())
1815 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001816 Builder.CreateCall(
1817 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001818}
1819
Eric Christopherc9e2a682014-05-20 17:10:39 +00001820// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001821// generating write-barries API. It is currently a global, ivar,
1822// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001823static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001824 LValue &LV,
1825 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001826 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001827 return;
Craig Topper99e79272013-07-26 05:59:26 +00001828
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001829 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001830 QualType ExpTy = E->getType();
1831 if (IsMemberAccess && ExpTy->isPointerType()) {
1832 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001833 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001834 // writer-barrier conservatively.
1835 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1836 if (ExpTy->isRecordType()) {
1837 LV.setObjCIvar(false);
1838 return;
1839 }
1840 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001841 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001842 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001843 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001844 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001845 return;
1846 }
Craig Topper99e79272013-07-26 05:59:26 +00001847
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001848 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1849 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001850 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001851 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001852 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001853 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001854 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001855 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001856 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001857 }
Craig Topper99e79272013-07-26 05:59:26 +00001858
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001859 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001860 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001861 return;
1862 }
Craig Topper99e79272013-07-26 05:59:26 +00001863
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001864 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001865 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001866 if (LV.isObjCIvar()) {
1867 // If cast is to a structure pointer, follow gcc's behavior and make it
1868 // a non-ivar write-barrier.
1869 QualType ExpTy = E->getType();
1870 if (ExpTy->isPointerType())
1871 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1872 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001873 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001874 }
1875 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001876 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001877
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001878 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001879 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1880 return;
1881 }
1882
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001883 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001884 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001885 return;
1886 }
Craig Topper99e79272013-07-26 05:59:26 +00001887
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001888 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001889 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001890 return;
1891 }
John McCall31168b02011-06-15 23:02:42 +00001892
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001893 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001894 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001895 return;
1896 }
1897
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001898 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001899 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001900 if (LV.isObjCIvar() && !LV.isObjCArray())
1901 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001902 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001903 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001904 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001905 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001906 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001907 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001908 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001909 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001910
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001911 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001912 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001913 // We don't know if member is an 'ivar', but this flag is looked at
1914 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001915 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001916 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001917 }
1918}
1919
Chris Lattner3f32d692011-07-12 06:52:18 +00001920static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001921EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001922 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001923 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001924 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001925 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001926}
1927
Alexey Bataev97720002014-11-11 04:05:39 +00001928static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001929 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1930 llvm::Type *RealVarTy, SourceLocation Loc) {
1931 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1932 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1933 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1934}
1935
1936Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1937 const ReferenceType *RefTy,
1938 AlignmentSource *Source) {
1939 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1940 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1941 Source, /*forPointee*/ true));
1942
1943}
1944
1945LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1946 const ReferenceType *RefTy) {
1947 AlignmentSource Source;
1948 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1949 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001950}
1951
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001952static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1953 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001954 QualType T = E->getType();
1955
1956 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00001957 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1958 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00001959 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1960
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001961 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001962 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1963 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001964 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00001965 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001966 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00001967 // Emit reference to the private copy of the variable if it is an OpenMP
1968 // threadprivate variable.
1969 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001970 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001971 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001972 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
1973 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001974 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001975 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001976 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001977 setObjCGCLValueClass(CGF.getContext(), E, LV);
1978 return LV;
1979}
1980
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001981static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001982 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001983 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001984 if (!FD->hasPrototype()) {
1985 if (const FunctionProtoType *Proto =
1986 FD->getType()->getAs<FunctionProtoType>()) {
1987 // Ugly case: for a K&R-style definition, the type of the definition
1988 // isn't the same as the type of a use. Correct for this with a
1989 // bitcast.
1990 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00001991 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001992 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001993 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001994 }
1995 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001996 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00001997 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001998}
1999
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002000static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2001 llvm::Value *ThisValue) {
2002 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2003 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2004 return CGF.EmitLValueForField(LV, FD);
2005}
2006
Renato Golin230c5eb2014-05-19 18:15:42 +00002007/// Named Registers are named metadata pointing to the register name
2008/// which will be read from/written to as an argument to the intrinsic
2009/// @llvm.read/write_register.
2010/// So far, only the name is being passed down, but other options such as
2011/// register type, allocation type or even optimization options could be
2012/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002013static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002014 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002015 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002016 assert(Asm->getLabel().size() < 64-Name.size() &&
2017 "Register name too big");
2018 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002019 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002020 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002021 if (M->getNumOperands() == 0) {
2022 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2023 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002024 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002025 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2026 }
John McCall7f416cc2015-09-08 08:05:57 +00002027
2028 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2029
2030 llvm::Value *Ptr =
2031 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2032 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002033}
2034
Chris Lattnerd7f58862007-06-02 05:24:33 +00002035LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002036 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002037 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002038
Renato Goline7b3d5d2014-05-27 16:46:27 +00002039 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2040 // Global Named registers access via intrinsics only
2041 if (VD->getStorageClass() == SC_Register &&
2042 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002043 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002044
Renato Goline7b3d5d2014-05-27 16:46:27 +00002045 // A DeclRefExpr for a reference initialized by a constant expression can
2046 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002047 const Expr *Init = VD->getAnyInitializer(VD);
2048 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2049 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002050 VD->checkInitIsICE() &&
2051 // Do not emit if it is private OpenMP variable.
2052 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2053 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002054 llvm::Constant *Val =
2055 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2056 assert(Val && "failed to emit reference constant expression");
2057 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002058
2059 // Should we be using the alignment of the constant pointer we emitted?
2060 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2061 /*pointee*/ true);
2062
2063 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002064 }
David Majnemer602cfe72015-01-01 09:49:44 +00002065
2066 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002067 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002068 if (auto *FD = LambdaCaptureFields.lookup(VD))
2069 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2070 else if (CapturedStmtInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002071 auto it = LocalDeclMap.find(VD);
2072 if (it != LocalDeclMap.end()) {
2073 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2074 return EmitLoadOfReferenceLValue(it->second, RefTy);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002075 }
John McCall7f416cc2015-09-08 08:05:57 +00002076 return MakeAddrLValue(it->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002077 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002078 LValue CapLVal =
2079 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2080 CapturedStmtInfo->getContextValue());
2081 return MakeAddrLValue(
2082 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2083 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002084 }
John McCall7f416cc2015-09-08 08:05:57 +00002085
David Majnemer602cfe72015-01-01 09:49:44 +00002086 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002087 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2088 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002089 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002090 }
2091
Eli Friedman5720e342012-01-21 04:52:58 +00002092 // FIXME: We should be able to assert this for FunctionDecls as well!
2093 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2094 // those with a valid source location.
2095 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2096 !E->getLocation().isValid()) &&
2097 "Should not use decl without marking it used!");
2098
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002099 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002100 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002101 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2102 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002103 }
2104
Renato Goline7b3d5d2014-05-27 16:46:27 +00002105 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002106 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002107 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002108 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002109
John McCall7f416cc2015-09-08 08:05:57 +00002110 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002111
John McCall7f416cc2015-09-08 08:05:57 +00002112 // The variable should generally be present in the local decl map.
2113 auto iter = LocalDeclMap.find(VD);
2114 if (iter != LocalDeclMap.end()) {
2115 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002116
John McCall7f416cc2015-09-08 08:05:57 +00002117 // Otherwise, it might be static local we haven't emitted yet for
2118 // some reason; most likely, because it's in an outer function.
2119 } else if (VD->isStaticLocal()) {
2120 addr = Address(CGM.getOrCreateStaticVarDecl(
2121 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2122 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002123
John McCall7f416cc2015-09-08 08:05:57 +00002124 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002125 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002126 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2127 }
2128
2129
2130 // Check for OpenMP threadprivate variables.
2131 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2132 return EmitThreadPrivateVarDeclLValue(
2133 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2134 E->getExprLoc());
2135 }
2136
2137 // Drill into block byref variables.
2138 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2139 if (isBlockByref) {
2140 addr = emitBlockByrefAddress(addr, VD);
2141 }
2142
2143 // Drill into reference types.
2144 LValue LV;
2145 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2146 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2147 } else {
2148 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002149 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002150
John McCallcdda29c2013-03-13 03:10:54 +00002151 bool isLocalStorage = VD->hasLocalStorage();
2152
2153 bool NonGCable = isLocalStorage &&
2154 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002155 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002156 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002157 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002158 LV.setNonGC(true);
2159 }
John McCallcdda29c2013-03-13 03:10:54 +00002160
2161 bool isImpreciseLifetime =
2162 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2163 if (isImpreciseLifetime)
2164 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002165 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002166 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002167 }
John McCallf3a88602011-02-03 08:15:49 +00002168
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002169 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002170 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002171
David Blaikie83d382b2011-09-23 05:06:16 +00002172 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002173}
Chris Lattnere47e4402007-06-01 18:02:12 +00002174
Chris Lattner8394d792007-06-05 20:53:16 +00002175LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2176 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002177 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002178 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002179
Chris Lattner0f398c42008-07-26 22:37:01 +00002180 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002181 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002182 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002183 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002184 QualType T = E->getSubExpr()->getType()->getPointeeType();
2185 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002186
John McCall7f416cc2015-09-08 08:05:57 +00002187 AlignmentSource AlignSource;
2188 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2189 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002190 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002191
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002192 // We should not generate __weak write barrier on indirect reference
2193 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2194 // But, we continue to generate __strong write barrier on indirect write
2195 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002196 if (getLangOpts().ObjC1 &&
2197 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002198 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002199 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002200 return LV;
2201 }
John McCalle3027922010-08-25 11:45:40 +00002202 case UO_Real:
2203 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002204 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002205 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002206
Richard Smith0b6b8e42012-02-18 20:53:32 +00002207 // __real is valid on scalars. This is a faster way of testing that.
2208 // __imag can only produce an rvalue on scalars.
2209 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002210 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002211 assert(E->getSubExpr()->getType()->isArithmeticType());
2212 return LV;
2213 }
2214
2215 assert(E->getSubExpr()->getType()->isAnyComplexType());
2216
John McCall7f416cc2015-09-08 08:05:57 +00002217 Address Component =
2218 (E->getOpcode() == UO_Real
2219 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2220 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2221 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
Chris Lattner595db862007-10-30 22:53:42 +00002222 }
John McCalle3027922010-08-25 11:45:40 +00002223 case UO_PreInc:
2224 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002225 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002226 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002227
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002228 if (E->getType()->isAnyComplexType())
2229 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2230 else
2231 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2232 return LV;
2233 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002234 }
Chris Lattner8394d792007-06-05 20:53:16 +00002235}
2236
Chris Lattner4347e3692007-06-06 04:54:52 +00002237LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002238 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002239 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002240}
2241
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002242LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002243 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002244 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002245}
2246
Mike Stump4a3999f2009-09-09 13:00:44 +00002247LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002248 auto SL = E->getFunctionName();
2249 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2250 StringRef FnName = CurFn->getName();
2251 if (FnName.startswith("\01"))
2252 FnName = FnName.substr(1);
2253 StringRef NameItems[] = {
2254 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2255 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002256 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
John McCall7f416cc2015-09-08 08:05:57 +00002257 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2258 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002259 }
Alexey Bataevec474782014-10-09 08:45:04 +00002260 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002261 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002262}
2263
Richard Smithe30752c2012-10-09 19:52:38 +00002264/// Emit a type description suitable for use by a runtime sanitizer library. The
2265/// format of a type descriptor is
2266///
2267/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002268/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002269/// \endcode
2270///
Richard Smith683398a2012-10-09 23:55:19 +00002271/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2272/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002273llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002274 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002275 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002276 return C;
2277
Richard Smithe30752c2012-10-09 19:52:38 +00002278 uint16_t TypeKind = -1;
2279 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002280
Richard Smithe30752c2012-10-09 19:52:38 +00002281 if (T->isIntegerType()) {
2282 TypeKind = 0;
2283 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002284 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002285 } else if (T->isFloatingType()) {
2286 TypeKind = 1;
2287 TypeInfo = getContext().getTypeSize(T);
2288 }
2289
2290 // Format the type name as if for a diagnostic, including quotes and
2291 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002292 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002293 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2294 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002295 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002296 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002297
2298 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002299 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2300 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002301 };
2302 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2303
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002304 auto *GV = new llvm::GlobalVariable(
2305 CGM.getModule(), Descriptor->getType(),
2306 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Richard Smithe30752c2012-10-09 19:52:38 +00002307 GV->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002308 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002309
2310 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002311 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002312
Richard Smithe30752c2012-10-09 19:52:38 +00002313 return GV;
2314}
2315
2316llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2317 llvm::Type *TargetTy = IntPtrTy;
2318
Richard Smith48366f72013-03-22 00:47:07 +00002319 // Floating-point types which fit into intptr_t are bitcast to integers
2320 // and then passed directly (after zero-extension, if necessary).
2321 if (V->getType()->isFloatingPointTy()) {
2322 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2323 if (Bits <= TargetTy->getIntegerBitWidth())
2324 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2325 Bits));
2326 }
2327
Richard Smithe30752c2012-10-09 19:52:38 +00002328 // Integers which fit in intptr_t are zero-extended and passed directly.
2329 if (V->getType()->isIntegerTy() &&
2330 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2331 return Builder.CreateZExt(V, TargetTy);
2332
2333 // Pointers are passed directly, everything else is passed by address.
2334 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002335 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002336 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002337 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002338 }
2339 return Builder.CreatePtrToInt(V, TargetTy);
2340}
2341
2342/// \brief Emit a representation of a SourceLocation for passing to a handler
2343/// in a sanitizer runtime library. The format for this data is:
2344/// \code
2345/// struct SourceLocation {
2346/// const char *Filename;
2347/// int32_t Line, Column;
2348/// };
2349/// \endcode
2350/// For an invalid SourceLocation, the Filename pointer is null.
2351llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002352 llvm::Constant *Filename;
2353 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002354
Alexey Samsonov6c124142014-07-18 17:50:06 +00002355 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2356 if (PLoc.isValid()) {
2357 auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002358 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2359 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2360 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002361 Line = PLoc.getLine();
2362 Column = PLoc.getColumn();
2363 } else {
2364 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2365 Line = Column = 0;
2366 }
2367
2368 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2369 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002370
2371 return llvm::ConstantStruct::getAnon(Data);
2372}
2373
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002374namespace {
2375/// \brief Specify under what conditions this check can be recovered
2376enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002377 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002378 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002379 /// Check supports recovering, runtime has both fatal (noreturn) and
2380 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002381 Recoverable,
2382 /// Runtime conditionally aborts, always need to support recovery.
2383 AlwaysRecoverable
2384};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002385}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002386
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002387static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2388 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002389 switch (Kind) {
2390 case SanitizerKind::Vptr:
2391 return CheckRecoverableKind::AlwaysRecoverable;
2392 case SanitizerKind::Return:
2393 case SanitizerKind::Unreachable:
2394 return CheckRecoverableKind::Unrecoverable;
2395 default:
2396 return CheckRecoverableKind::Recoverable;
2397 }
2398}
2399
Alexey Samsonov88459522015-01-12 22:39:12 +00002400static void emitCheckHandlerCall(CodeGenFunction &CGF,
2401 llvm::FunctionType *FnType,
2402 ArrayRef<llvm::Value *> FnArgs,
2403 StringRef CheckName,
2404 CheckRecoverableKind RecoverKind, bool IsFatal,
2405 llvm::BasicBlock *ContBB) {
2406 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2407 bool NeedsAbortSuffix =
2408 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2409 std::string FnName = ("__ubsan_handle_" + CheckName +
2410 (NeedsAbortSuffix ? "_abort" : "")).str();
2411 bool MayReturn =
2412 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2413
2414 llvm::AttrBuilder B;
2415 if (!MayReturn) {
2416 B.addAttribute(llvm::Attribute::NoReturn)
2417 .addAttribute(llvm::Attribute::NoUnwind);
2418 }
2419 B.addAttribute(llvm::Attribute::UWTable);
2420
2421 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2422 FnType, FnName,
2423 llvm::AttributeSet::get(CGF.getLLVMContext(),
2424 llvm::AttributeSet::FunctionIndex, B));
2425 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2426 if (!MayReturn) {
2427 HandlerCall->setDoesNotReturn();
2428 CGF.Builder.CreateUnreachable();
2429 } else {
2430 CGF.Builder.CreateBr(ContBB);
2431 }
2432}
2433
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002434void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002435 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002436 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2437 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002438 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002439 assert(Checked.size() > 0);
Alexey Samsonov88459522015-01-12 22:39:12 +00002440
2441 llvm::Value *FatalCond = nullptr;
2442 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002443 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002444 for (int i = 0, n = Checked.size(); i < n; ++i) {
2445 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002446 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002447 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002448 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2449 ? TrapCond
2450 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2451 ? RecoverableCond
2452 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002453 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2454 }
2455
Peter Collingbourne9881b782015-06-18 23:59:22 +00002456 if (TrapCond)
2457 EmitTrapCheck(TrapCond);
2458 if (!FatalCond && !RecoverableCond)
2459 return;
2460
Alexey Samsonov88459522015-01-12 22:39:12 +00002461 llvm::Value *JointCond;
2462 if (FatalCond && RecoverableCond)
2463 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2464 else
2465 JointCond = FatalCond ? FatalCond : RecoverableCond;
2466 assert(JointCond);
2467
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002468 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2469 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002470#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002471 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002472 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002473 "All recoverable kinds in a single check must be same!");
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002474 assert(SanOpts.has(Checked[i].second));
2475 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002476#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002477
Richard Smith4d1458e2012-09-08 02:08:36 +00002478 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002479 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2480 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002481 // Give hint that we very much don't expect to execute the handler
2482 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2483 llvm::MDBuilder MDHelper(getLLVMContext());
2484 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2485 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002486 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002487
Alexey Samsonov88459522015-01-12 22:39:12 +00002488 // Emit handler arguments and create handler function type.
Richard Smithe30752c2012-10-09 19:52:38 +00002489 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002490 auto *InfoPtr =
Will Dietz450f1a12013-01-09 03:39:41 +00002491 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
Richard Smithe30752c2012-10-09 19:52:38 +00002492 llvm::GlobalVariable::PrivateLinkage, Info);
2493 InfoPtr->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002494 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
Richard Smithe30752c2012-10-09 19:52:38 +00002495
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002496 SmallVector<llvm::Value *, 4> Args;
2497 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002498 Args.reserve(DynamicArgs.size() + 1);
2499 ArgTypes.reserve(DynamicArgs.size() + 1);
2500
2501 // Handler functions take an i8* pointing to the (handler-specific) static
2502 // information block, followed by a sequence of intptr_t arguments
2503 // representing operand values.
2504 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2505 ArgTypes.push_back(Int8PtrTy);
2506 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2507 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2508 ArgTypes.push_back(IntPtrTy);
2509 }
2510
2511 llvm::FunctionType *FnType =
2512 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002513
Alexey Samsonov88459522015-01-12 22:39:12 +00002514 if (!FatalCond || !RecoverableCond) {
2515 // Simple case: we need to generate a single handler call, either
2516 // fatal, or non-fatal.
2517 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2518 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002519 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002520 // Emit two handler calls: first one for set of unrecoverable checks,
2521 // another one for recoverable.
2522 llvm::BasicBlock *NonFatalHandlerBB =
2523 createBasicBlock("non_fatal." + CheckName);
2524 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2525 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2526 EmitBlock(FatalHandlerBB);
2527 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2528 NonFatalHandlerBB);
2529 EmitBlock(NonFatalHandlerBB);
2530 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2531 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002532 }
Richard Smithe30752c2012-10-09 19:52:38 +00002533
Richard Smith4d1458e2012-09-08 02:08:36 +00002534 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002535}
2536
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002537void CodeGenFunction::EmitCfiSlowPathCheck(llvm::Value *Cond,
2538 llvm::ConstantInt *TypeId,
2539 llvm::Value *Ptr) {
2540 auto &Ctx = getLLVMContext();
2541 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2542
2543 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2544 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2545
2546 llvm::MDBuilder MDHelper(getLLVMContext());
2547 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2548 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2549
2550 EmitBlock(CheckBB);
2551
2552 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2553 "__cfi_slowpath",
2554 llvm::FunctionType::get(
2555 llvm::Type::getVoidTy(Ctx),
2556 {llvm::Type::getInt64Ty(Ctx),
2557 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(Ctx))},
2558 false));
2559 llvm::CallInst *CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2560 CheckCall->setDoesNotThrow();
2561
2562 EmitBlock(Cont);
2563}
2564
Chad Rosierae229d52013-01-29 23:31:22 +00002565void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002566 llvm::BasicBlock *Cont = createBasicBlock("cont");
2567
2568 // If we're optimizing, collapse all calls to trap down to just one per
2569 // function to save on code size.
2570 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2571 TrapBB = createBasicBlock("trap");
2572 Builder.CreateCondBr(Checked, Cont, TrapBB);
2573 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002574 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002575 TrapCall->setDoesNotReturn();
2576 TrapCall->setDoesNotThrow();
2577 Builder.CreateUnreachable();
2578 } else {
2579 Builder.CreateCondBr(Checked, Cont, TrapBB);
2580 }
2581
2582 EmitBlock(Cont);
2583}
2584
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002585llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002586 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002587
2588 if (!CGM.getCodeGenOpts().TrapFuncName.empty())
2589 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
2590 "trap-func-name",
2591 CGM.getCodeGenOpts().TrapFuncName);
2592
2593 return TrapCall;
2594}
2595
John McCall7f416cc2015-09-08 08:05:57 +00002596Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2597 AlignmentSource *AlignSource) {
2598 assert(E->getType()->isArrayType() &&
2599 "Array to pointer decay must have array source type!");
2600
2601 // Expressions of array type can't be bitfields or vector elements.
2602 LValue LV = EmitLValue(E);
2603 Address Addr = LV.getAddress();
2604 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2605
2606 // If the array type was an incomplete type, we need to make sure
2607 // the decay ends up being the right type.
2608 llvm::Type *NewTy = ConvertType(E->getType());
2609 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2610
2611 // Note that VLA pointers are always decayed, so we don't need to do
2612 // anything here.
2613 if (!E->getType()->isVariableArrayType()) {
2614 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2615 "Expected pointer to array");
2616 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2617 }
2618
2619 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2620 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2621}
2622
Chris Lattner6c5abe82010-06-26 23:03:20 +00002623/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2624/// array to pointer, return the array subexpression.
2625static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2626 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002627 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002628 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002629 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002630
Chris Lattner6c5abe82010-06-26 23:03:20 +00002631 // If this is a decay from variable width array, bail out.
2632 const Expr *SubExpr = CE->getSubExpr();
2633 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002634 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002635
Chris Lattner6c5abe82010-06-26 23:03:20 +00002636 return SubExpr;
2637}
2638
John McCall7f416cc2015-09-08 08:05:57 +00002639static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2640 llvm::Value *ptr,
2641 ArrayRef<llvm::Value*> indices,
2642 bool inbounds,
2643 const llvm::Twine &name = "arrayidx") {
2644 if (inbounds) {
2645 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2646 } else {
2647 return CGF.Builder.CreateGEP(ptr, indices, name);
2648 }
2649}
2650
2651static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2652 llvm::Value *idx,
2653 CharUnits eltSize) {
2654 // If we have a constant index, we can use the exact offset of the
2655 // element we're accessing.
2656 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2657 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2658 return arrayAlign.alignmentAtOffset(offset);
2659
2660 // Otherwise, use the worst-case alignment for any element.
2661 } else {
2662 return arrayAlign.alignmentOfArrayElement(eltSize);
2663 }
2664}
2665
2666static QualType getFixedSizeElementType(const ASTContext &ctx,
2667 const VariableArrayType *vla) {
2668 QualType eltType;
2669 do {
2670 eltType = vla->getElementType();
2671 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2672 return eltType;
2673}
2674
2675static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2676 ArrayRef<llvm::Value*> indices,
2677 QualType eltType, bool inbounds,
2678 const llvm::Twine &name = "arrayidx") {
2679 // All the indices except that last must be zero.
2680#ifndef NDEBUG
2681 for (auto idx : indices.drop_back())
2682 assert(isa<llvm::ConstantInt>(idx) &&
2683 cast<llvm::ConstantInt>(idx)->isZero());
2684#endif
2685
2686 // Determine the element size of the statically-sized base. This is
2687 // the thing that the indices are expressed in terms of.
2688 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2689 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2690 }
2691
2692 // We can use that to compute the best alignment of the element.
2693 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2694 CharUnits eltAlign =
2695 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2696
2697 llvm::Value *eltPtr =
2698 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2699 return Address(eltPtr, eltAlign);
2700}
2701
Richard Smith539e4a72013-02-23 02:53:19 +00002702LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2703 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002704 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002705 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002706 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002707 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002708
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002709 if (SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002710 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2711
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002712 // If the base is a vector type, then we are forming a vector element lvalue
2713 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002714 if (E->getBase()->getType()->isVectorType() &&
2715 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002716 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002717 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002718 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002719 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002720 E->getBase()->getType(),
2721 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002722 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002723
John McCall7f416cc2015-09-08 08:05:57 +00002724 // All the other cases basically behave like simple offsetting.
2725
Ted Kremenekc81614d2007-08-20 16:18:38 +00002726 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002727 if (Idx->getType() != IntPtrTy)
2728 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002729
John McCall7f416cc2015-09-08 08:05:57 +00002730 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002731 if (isa<ExtVectorElementExpr>(E->getBase())) {
2732 LValue LV = EmitLValue(E->getBase());
John McCall7f416cc2015-09-08 08:05:57 +00002733 Address Addr = EmitExtVectorElementLValue(LV);
2734
2735 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2736 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2737 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002738 }
John McCall7f416cc2015-09-08 08:05:57 +00002739
2740 AlignmentSource AlignSource;
2741 Address Addr = Address::invalid();
2742 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002743 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002744 // The base must be a pointer, which is not an aggregate. Emit
2745 // it. It needs to be emitted first in case it's what captures
2746 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002747 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002748
John McCall23c29fe2011-06-24 21:55:10 +00002749 // The element count here is the total number of non-VLA elements.
2750 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002751
John McCall77527a82011-06-25 01:32:37 +00002752 // Effectively, the multiply by the VLA size is part of the GEP.
2753 // GEP indexes are signed, and scaling an index isn't permitted to
2754 // signed-overflow, so we use the same semantics for our explicit
2755 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002756 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002757 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002758 } else {
2759 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002760 }
John McCall7f416cc2015-09-08 08:05:57 +00002761
2762 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2763 !getLangOpts().isSignedOverflowDefined());
2764
Chris Lattner6c5abe82010-06-26 23:03:20 +00002765 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2766 // Indexing over an interface, as in "NSString *P; P[4];"
John McCall7f416cc2015-09-08 08:05:57 +00002767 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2768 llvm::Value *InterfaceSizeVal =
2769 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());;
Mike Stump4a3999f2009-09-09 13:00:44 +00002770
John McCall7f416cc2015-09-08 08:05:57 +00002771 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002772
John McCall7f416cc2015-09-08 08:05:57 +00002773 // Emit the base pointer.
2774 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2775
2776 // We don't necessarily build correct LLVM struct types for ObjC
2777 // interfaces, so we can't rely on GEP to do this scaling
2778 // correctly, so we need to cast to i8*. FIXME: is this actually
2779 // true? A lot of other things in the fragile ABI would break...
2780 llvm::Type *OrigBaseTy = Addr.getType();
2781 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2782
2783 // Do the GEP.
2784 CharUnits EltAlign =
2785 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2786 llvm::Value *EltPtr =
2787 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2788 Addr = Address(EltPtr, EltAlign);
2789
2790 // Cast back.
2791 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00002792 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2793 // If this is A[i] where A is an array, the frontend will have decayed the
2794 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2795 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2796 // "gep x, i" here. Emit one "gep A, 0, i".
2797 assert(Array->getType()->isArrayType() &&
2798 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002799 LValue ArrayLV;
2800 // For simple multidimensional array indexing, set the 'accessed' flag for
2801 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002802 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002803 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2804 else
2805 ArrayLV = EmitLValue(Array);
Craig Topper99e79272013-07-26 05:59:26 +00002806
Daniel Dunbar82634272011-04-01 00:49:43 +00002807 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00002808 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
2809 {CGM.getSize(CharUnits::Zero()), Idx},
2810 E->getType(),
2811 !getLangOpts().isSignedOverflowDefined());
2812 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002813 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002814 // The base must be a pointer; emit it with an estimate of its alignment.
2815 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2816 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
2817 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00002818 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002819
John McCall7f416cc2015-09-08 08:05:57 +00002820 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002821
John McCall7f416cc2015-09-08 08:05:57 +00002822 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00002823
Richard Smith9c6890a2012-11-01 22:30:59 +00002824 if (getLangOpts().ObjC1 &&
2825 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002826 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002827 setObjCGCLValueClass(getContext(), E, LV);
2828 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002829 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002830}
2831
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002832LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2833 bool IsLowerBound) {
2834 LValue Base;
2835 if (auto *ASE =
2836 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
2837 Base = EmitOMPArraySectionExpr(ASE, IsLowerBound);
2838 else
2839 Base = EmitLValue(E->getBase());
2840 QualType BaseTy = Base.getType();
2841 llvm::Value *Idx = nullptr;
2842 QualType ResultExprTy;
2843 if (auto *AT = getContext().getAsArrayType(BaseTy))
2844 ResultExprTy = AT->getElementType();
2845 else
2846 ResultExprTy = BaseTy->getPointeeType();
2847 if (IsLowerBound || (!IsLowerBound && E->getColonLoc().isInvalid())) {
2848 // Requesting lower bound or upper bound, but without provided length and
2849 // without ':' symbol for the default length -> length = 1.
2850 // Idx = LowerBound ?: 0;
2851 if (auto *LowerBound = E->getLowerBound()) {
2852 Idx = Builder.CreateIntCast(
2853 EmitScalarExpr(LowerBound), IntPtrTy,
2854 LowerBound->getType()->hasSignedIntegerRepresentation());
2855 } else
2856 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
2857 } else {
2858 // Try to emit length or lower bound as constant. If this is possible, 1 is
2859 // subtracted from constant length or lower bound. Otherwise, emit LLVM IR
2860 // (LB + Len) - 1.
2861 auto &C = CGM.getContext();
2862 auto *Length = E->getLength();
2863 llvm::APSInt ConstLength;
2864 if (Length) {
2865 // Idx = LowerBound + Length - 1;
2866 if (Length->isIntegerConstantExpr(ConstLength, C)) {
2867 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2868 Length = nullptr;
2869 }
2870 auto *LowerBound = E->getLowerBound();
2871 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
2872 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
2873 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
2874 LowerBound = nullptr;
2875 }
2876 if (!Length)
2877 --ConstLength;
2878 else if (!LowerBound)
2879 --ConstLowerBound;
2880
2881 if (Length || LowerBound) {
2882 auto *LowerBoundVal =
2883 LowerBound
2884 ? Builder.CreateIntCast(
2885 EmitScalarExpr(LowerBound), IntPtrTy,
2886 LowerBound->getType()->hasSignedIntegerRepresentation())
2887 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
2888 auto *LengthVal =
2889 Length
2890 ? Builder.CreateIntCast(
2891 EmitScalarExpr(Length), IntPtrTy,
2892 Length->getType()->hasSignedIntegerRepresentation())
2893 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
2894 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
2895 /*HasNUW=*/false,
2896 !getLangOpts().isSignedOverflowDefined());
2897 if (Length && LowerBound) {
2898 Idx = Builder.CreateSub(
2899 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
2900 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2901 }
2902 } else
2903 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
2904 } else {
2905 // Idx = ArraySize - 1;
2906 if (auto *VAT = C.getAsVariableArrayType(BaseTy)) {
2907 Length = VAT->getSizeExpr();
2908 if (Length->isIntegerConstantExpr(ConstLength, C))
2909 Length = nullptr;
2910 } else {
2911 auto *CAT = C.getAsConstantArrayType(BaseTy);
2912 ConstLength = CAT->getSize();
2913 }
2914 if (Length) {
2915 auto *LengthVal = Builder.CreateIntCast(
2916 EmitScalarExpr(Length), IntPtrTy,
2917 Length->getType()->hasSignedIntegerRepresentation());
2918 Idx = Builder.CreateSub(
2919 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
2920 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2921 } else {
2922 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2923 --ConstLength;
2924 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
2925 }
2926 }
2927 }
2928 assert(Idx);
2929
John McCall7f416cc2015-09-08 08:05:57 +00002930 llvm::Value *EltPtr;
2931 QualType FixedSizeEltType = ResultExprTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002932 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
2933 // The element count here is the total number of non-VLA elements.
2934 llvm::Value *numElements = getVLASize(VLA).first;
John McCall7f416cc2015-09-08 08:05:57 +00002935 FixedSizeEltType = getFixedSizeElementType(getContext(), VLA);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002936
2937 // Effectively, the multiply by the VLA size is part of the GEP.
2938 // GEP indexes are signed, and scaling an index isn't permitted to
2939 // signed-overflow, so we use the same semantics for our explicit
2940 // multiply. We suppress this if overflow is not undefined behavior.
2941 if (getLangOpts().isSignedOverflowDefined()) {
2942 Idx = Builder.CreateMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002943 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002944 } else {
2945 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002946 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002947 }
2948 } else if (BaseTy->isConstantArrayType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002949 llvm::Value *ArrayPtr = Base.getPointer();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002950 llvm::Value *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
2951 llvm::Value *Args[] = {Zero, Idx};
2952
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002953 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002954 EltPtr = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002955 else
John McCall7f416cc2015-09-08 08:05:57 +00002956 EltPtr = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002957 } else {
2958 // The base must be a pointer, which is not an aggregate. Emit it.
2959 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002960 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002961 else
John McCall7f416cc2015-09-08 08:05:57 +00002962 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002963 }
2964
John McCall7f416cc2015-09-08 08:05:57 +00002965 CharUnits EltAlign =
2966 Base.getAlignment().alignmentOfArrayElement(
2967 getContext().getTypeSizeInChars(FixedSizeEltType));
2968
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002969 // Limit the alignment to that of the result type.
John McCall7f416cc2015-09-08 08:05:57 +00002970 LValue LV = MakeAddrLValue(Address(EltPtr, EltAlign), ResultExprTy,
2971 Base.getAlignmentSource());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002972
2973 LV.getQuals().setAddressSpace(BaseTy.getAddressSpace());
2974
2975 return LV;
2976}
2977
Chris Lattner9e751ca2007-08-02 23:37:31 +00002978LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002979EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002980 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002981 LValue Base;
2982
2983 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002984 if (E->isArrow()) {
2985 // If it is a pointer to a vector, emit the address and form an lvalue with
2986 // it.
John McCall7f416cc2015-09-08 08:05:57 +00002987 AlignmentSource AlignSource;
2988 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00002989 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00002990 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002991 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002992 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002993 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2994 // emit the base as an lvalue.
2995 assert(E->getBase()->getType()->isVectorType());
2996 Base = EmitLValue(E->getBase());
2997 } else {
2998 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002999 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003000 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003001 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003002
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003003 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003004 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003005 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003006 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3007 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003008 }
John McCall1553b192011-06-16 04:16:24 +00003009
3010 QualType type =
3011 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003012
Nate Begemand3862152008-05-13 21:03:02 +00003013 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003014 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003015 E->getEncodedElementAccess(Indices);
3016
3017 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003018 llvm::Constant *CV =
3019 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003020 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00003021 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00003022 }
3023 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3024
3025 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003026 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003027
Chris Lattner595ba3a2012-01-30 06:20:36 +00003028 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3029 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003030 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003031 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3032 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003033}
3034
Devang Patel30efa2e2007-10-23 20:28:39 +00003035LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003036 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003037
Chris Lattner4e4186b2007-12-02 18:52:07 +00003038 // 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 +00003039 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003040 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003041 AlignmentSource AlignSource;
3042 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003043 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003044 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3045 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003046 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003047 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003048
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003049 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003050 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003051 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003052 setObjCGCLValueClass(getContext(), E, LV);
3053 return LV;
3054 }
Craig Topper99e79272013-07-26 05:59:26 +00003055
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003056 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003057 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003058
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003059 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003060 return EmitFunctionDeclLValue(*this, E, FD);
3061
David Blaikie83d382b2011-09-23 05:06:16 +00003062 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003063}
Devang Patel30efa2e2007-10-23 20:28:39 +00003064
John McCalldec348f72013-05-03 07:33:41 +00003065/// Given that we are currently emitting a lambda, emit an l-value for
3066/// one of its members.
3067LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3068 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3069 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3070 QualType LambdaTagType =
3071 getContext().getTagDeclType(Field->getParent());
3072 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3073 return EmitLValueForField(LambdaLV, Field);
3074}
3075
John McCall7f416cc2015-09-08 08:05:57 +00003076/// Drill down to the storage of a field without walking into
3077/// reference types.
3078///
3079/// The resulting address doesn't necessarily have the right type.
3080static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3081 const FieldDecl *field) {
3082 const RecordDecl *rec = field->getParent();
3083
3084 unsigned idx =
3085 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3086
3087 CharUnits offset;
3088 // Adjust the alignment down to the given offset.
3089 // As a special case, if the LLVM field index is 0, we know that this
3090 // is zero.
3091 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3092 .getFieldOffset(field->getFieldIndex()) == 0) &&
3093 "LLVM field at index zero had non-zero offset?");
3094 if (idx != 0) {
3095 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3096 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3097 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3098 }
3099
3100 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3101}
3102
Eli Friedman7f1ff602012-04-16 03:54:45 +00003103LValue CodeGenFunction::EmitLValueForField(LValue base,
3104 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003105 AlignmentSource fieldAlignSource =
3106 getFieldAlignmentSource(base.getAlignmentSource());
3107
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003108 if (field->isBitField()) {
3109 const CGRecordLayout &RL =
3110 CGM.getTypes().getCGRecordLayout(field->getParent());
3111 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003112 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003113 unsigned Idx = RL.getLLVMFieldNo(field);
3114 if (Idx != 0)
3115 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003116 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3117 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003118 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003119 llvm::Type *FieldIntTy =
3120 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3121 if (Addr.getElementType() != FieldIntTy)
3122 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003123
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003124 QualType fieldType =
3125 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003126 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003127 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003128
John McCall53fcbd22011-02-26 08:07:02 +00003129 const RecordDecl *rec = field->getParent();
3130 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003131
John McCall53fcbd22011-02-26 08:07:02 +00003132 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3133
John McCall7f416cc2015-09-08 08:05:57 +00003134 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003135 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003136 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003137 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003138 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003139 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003140 // TODO: handle path-aware TBAA for union.
3141 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003142 } else {
3143 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003144 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003145
3146 // If this is a reference field, load the reference right now.
3147 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3148 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3149 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3150
Manman Renc451e572013-04-04 21:53:22 +00003151 // Loading the reference will disable path-aware TBAA.
3152 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003153 if (CGM.shouldUseTBAA()) {
3154 llvm::MDNode *tbaa;
3155 if (mayAlias)
3156 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3157 else
3158 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003159 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003160 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003161 }
3162
John McCall53fcbd22011-02-26 08:07:02 +00003163 mayAlias = false;
3164 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003165
3166 CharUnits alignment =
3167 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3168 addr = Address(load, alignment);
3169
3170 // Qualifiers on the struct don't apply to the referencee, and
3171 // we'll pick up CVR from the actual type later, so reset these
3172 // additional qualifiers now.
3173 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003174 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003175 }
Craig Topper99e79272013-07-26 05:59:26 +00003176
Chris Lattner13ee4f42011-07-10 05:34:54 +00003177 // Make sure that the address is pointing to the right type. This is critical
3178 // for both unions and structs. A union needs a bitcast, a struct element
3179 // will need a bitcast if the LLVM type laid out doesn't match the desired
3180 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003181 addr = Builder.CreateElementBitCast(addr,
3182 CGM.getTypes().ConvertTypeForMem(type),
3183 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003184
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003185 if (field->hasAttr<AnnotateAttr>())
3186 addr = EmitFieldAnnotations(field, addr);
3187
John McCall7f416cc2015-09-08 08:05:57 +00003188 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003189 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003190 if (TBAAPath) {
3191 const ASTRecordLayout &Layout =
3192 getContext().getASTRecordLayout(field->getParent());
3193 // Set the base type to be the base type of the base LValue and
3194 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003195 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3196 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003197 Layout.getFieldOffset(field->getFieldIndex()) /
3198 getContext().getCharWidth());
3199 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003200
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003201 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003202 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3203 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003204
3205 // Fields of may_alias structs act like 'char' for TBAA purposes.
3206 // FIXME: this should get propagated down through anonymous structs
3207 // and unions.
3208 if (mayAlias && LV.getTBAAInfo())
3209 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3210
Daniel Dunbarf166a522010-08-21 03:44:13 +00003211 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003212}
3213
Craig Topper99e79272013-07-26 05:59:26 +00003214LValue
3215CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003216 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003217 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003218
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003219 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003220 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003221
John McCall7f416cc2015-09-08 08:05:57 +00003222 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003223
John McCall7f416cc2015-09-08 08:05:57 +00003224 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003225 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003226 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003227
John McCall7f416cc2015-09-08 08:05:57 +00003228 // TODO: access-path TBAA?
3229 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3230 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003231}
3232
Chris Lattnerf53c0962010-09-06 00:11:41 +00003233LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003234 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003235 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3236 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003237 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003238 if (E->getType()->isVariablyModifiedType())
3239 // make sure to emit the VLA size.
3240 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003241
John McCall7f416cc2015-09-08 08:05:57 +00003242 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003243 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003244 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003245
Chad Rosier615ed1a2012-03-29 17:37:10 +00003246 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3247 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003248
3249 return Result;
3250}
3251
Richard Smithbb653bd2012-05-14 21:57:21 +00003252LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3253 if (!E->isGLValue())
3254 // Initializing an aggregate temporary in C++11: T{...}.
3255 return EmitAggExprToLValue(E);
3256
3257 // An lvalue initializer list must be initializing a reference.
3258 assert(E->getNumInits() == 1 && "reference init with multiple values");
3259 return EmitLValue(E->getInit(0));
3260}
3261
Richard Smithf3076ff2014-06-20 18:43:47 +00003262/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3263/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3264/// LValue is returned and the current block has been terminated.
3265static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3266 const Expr *Operand) {
3267 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3268 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3269 return None;
3270 }
3271
3272 return CGF.EmitLValue(Operand);
3273}
3274
John McCallc07a0c72011-02-17 10:25:35 +00003275LValue CodeGenFunction::
3276EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3277 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003278 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003279 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003280 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003281 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003282 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003283
Eli Friedman59954892012-01-25 05:04:17 +00003284 OpaqueValueMapping binding(*this, expr);
3285
John McCallc07a0c72011-02-17 10:25:35 +00003286 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003287 bool CondExprBool;
3288 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003289 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003290 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003291
Justin Bogneref512b92014-01-06 22:27:43 +00003292 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003293 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003294 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003295 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003296 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003297 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003298 }
3299
John McCallc07a0c72011-02-17 10:25:35 +00003300 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3301 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3302 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003303
3304 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003305 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003306
John McCall0a6bf2e2011-01-26 19:21:13 +00003307 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003308 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003309 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003310 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003311 Optional<LValue> lhs =
3312 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003313 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003314
Richard Smithf3076ff2014-06-20 18:43:47 +00003315 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003316 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003317
John McCallc07a0c72011-02-17 10:25:35 +00003318 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003319 if (lhs)
3320 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003321
John McCall0a6bf2e2011-01-26 19:21:13 +00003322 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003323 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003324 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003325 Optional<LValue> rhs =
3326 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003327 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003328 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003329 return EmitUnsupportedLValue(expr, "conditional operator");
3330 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003331
John McCallc07a0c72011-02-17 10:25:35 +00003332 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003333
Richard Smithf3076ff2014-06-20 18:43:47 +00003334 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003335 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003336 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003337 phi->addIncoming(lhs->getPointer(), lhsBlock);
3338 phi->addIncoming(rhs->getPointer(), rhsBlock);
3339 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3340 AlignmentSource alignSource =
3341 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3342 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003343 } else {
3344 assert((lhs || rhs) &&
3345 "both operands of glvalue conditional are throw-expressions?");
3346 return lhs ? *lhs : *rhs;
3347 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003348}
3349
Richard Smithbb653bd2012-05-14 21:57:21 +00003350/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3351/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003352/// otherwise if a cast is needed by the code generator in an lvalue context,
3353/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003354/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003355/// are permitted with aggregate result, including noop aggregate casts, and
3356/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003357LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003358 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003359 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003360 case CK_BitCast:
3361 case CK_ArrayToPointerDecay:
3362 case CK_FunctionToPointerDecay:
3363 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003364 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003365 case CK_IntegralToPointer:
3366 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003367 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003368 case CK_VectorSplat:
3369 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003370 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003371 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003372 case CK_IntegralToFloating:
3373 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003374 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003375 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003376 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003377 case CK_FloatingComplexToReal:
3378 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003379 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003380 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003381 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003382 case CK_IntegralComplexToReal:
3383 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003384 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003385 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003386 case CK_DerivedToBaseMemberPointer:
3387 case CK_BaseToDerivedMemberPointer:
3388 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003389 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003390 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003391 case CK_ARCProduceObject:
3392 case CK_ARCConsumeObject:
3393 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003394 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003395 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003396 case CK_AddressSpaceConversion:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003397 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3398
3399 case CK_Dependent:
3400 llvm_unreachable("dependent cast kind in IR gen!");
3401
3402 case CK_BuiltinFnToFnPtr:
3403 llvm_unreachable("builtin functions are handled elsewhere");
3404
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003405 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003406 case CK_NonAtomicToAtomic:
3407 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003408 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003409
Anders Carlsson8a01a752011-04-11 02:03:26 +00003410 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003411 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003412 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003413 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003414 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003415 }
3416
John McCalle3027922010-08-25 11:45:40 +00003417 case CK_ConstructorConversion:
3418 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003419 case CK_CPointerToObjCPointerCast:
3420 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003421 case CK_NoOp:
3422 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003423 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003424
John McCalle3027922010-08-25 11:45:40 +00003425 case CK_UncheckedDerivedToBase:
3426 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003427 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003428 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003429 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003430
Anders Carlssond95f9602009-09-12 16:16:49 +00003431 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003432 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003433
Anders Carlssond95f9602009-09-12 16:16:49 +00003434 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003435 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003436 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3437 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003438
John McCall7f416cc2015-09-08 08:05:57 +00003439 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003440 }
John McCalle3027922010-08-25 11:45:40 +00003441 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003442 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003443 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003444 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003445 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003446
Anders Carlsson8c793172009-11-23 17:57:54 +00003447 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003448
Anders Carlsson8c793172009-11-23 17:57:54 +00003449 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003450 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003451 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003452 E->path_begin(), E->path_end(),
3453 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003454
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003455 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3456 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003457 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003458 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003459 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003460
Peter Collingbourned2926c92015-03-14 02:42:25 +00003461 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003462 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3463 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003464 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003465
John McCall7f416cc2015-09-08 08:05:57 +00003466 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003467 }
John McCalle3027922010-08-25 11:45:40 +00003468 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003469 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003470 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003471
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003472 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003473 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003474 Address V = Builder.CreateBitCast(LV.getAddress(),
3475 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003476
3477 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003478 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3479 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003480 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003481
John McCall7f416cc2015-09-08 08:05:57 +00003482 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003483 }
John McCalle3027922010-08-25 11:45:40 +00003484 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003485 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003486 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3487 ConvertType(E->getType()));
3488 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003489 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003490 case CK_ZeroToOCLEvent:
3491 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003492 }
Craig Topper99e79272013-07-26 05:59:26 +00003493
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003494 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003495}
3496
John McCall1bf58462011-02-16 08:02:54 +00003497LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003498 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003499 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003500}
3501
Eli Friedman7f1ff602012-04-16 03:54:45 +00003502RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003503 const FieldDecl *FD,
3504 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003505 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003506 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003507 switch (getEvaluationKind(FT)) {
3508 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003509 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003510 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003511 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003512 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003513 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003514 }
3515 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003516}
Douglas Gregorfe314812011-06-21 17:03:29 +00003517
Chris Lattnere47e4402007-06-01 18:02:12 +00003518//===--------------------------------------------------------------------===//
3519// Expression Emission
3520//===--------------------------------------------------------------------===//
3521
Craig Topper99e79272013-07-26 05:59:26 +00003522RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003523 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003524 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003525 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003526 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003527
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003528 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003529 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003530
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003531 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003532 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3533
Douglas Gregore0e96302011-09-06 21:41:04 +00003534 const Decl *TargetDecl = E->getCalleeDecl();
3535 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3536 if (unsigned builtinID = FD->getBuiltinID())
Peter Collingbournef7706832014-12-12 23:41:25 +00003537 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003538 }
3539
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003540 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00003541 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003542 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003543
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003544 if (const auto *PseudoDtor =
3545 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00003546 QualType DestroyedType = PseudoDtor->getDestroyedType();
John McCall460ce582015-10-22 18:38:17 +00003547 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003548 // Automatic Reference Counting:
3549 // If the pseudo-expression names a retainable object with weak or
3550 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00003551 Expr *BaseExpr = PseudoDtor->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003552 Address BaseValue = Address::invalid();
John McCall31168b02011-06-15 23:02:42 +00003553 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00003554
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003555 // 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 +00003556 if (PseudoDtor->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003557 BaseValue = EmitPointerWithAlignment(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003558 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3559 BaseQuals = PTy->getPointeeType().getQualifiers();
3560 } else {
3561 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003562 BaseValue = BaseLV.getAddress();
3563 QualType BaseTy = BaseExpr->getType();
3564 BaseQuals = BaseTy.getQualifiers();
3565 }
Craig Topper99e79272013-07-26 05:59:26 +00003566
John McCall460ce582015-10-22 18:38:17 +00003567 switch (DestroyedType.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00003568 case Qualifiers::OCL_None:
3569 case Qualifiers::OCL_ExplicitNone:
3570 case Qualifiers::OCL_Autoreleasing:
3571 break;
Craig Topper99e79272013-07-26 05:59:26 +00003572
John McCall31168b02011-06-15 23:02:42 +00003573 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00003574 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003575 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00003576 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00003577 break;
3578
3579 case Qualifiers::OCL_Weak:
3580 EmitARCDestroyWeak(BaseValue);
3581 break;
3582 }
3583 } else {
3584 // C++ [expr.pseudo]p1:
3585 // The result shall only be used as the operand for the function call
3586 // operator (), and the result of such a call has type void. The only
3587 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00003588 // arrow.
John McCall31168b02011-06-15 23:02:42 +00003589 EmitScalarExpr(E->getCallee());
3590 }
Craig Topper99e79272013-07-26 05:59:26 +00003591
Craig Topper8a13c412014-05-21 05:09:00 +00003592 return RValue::get(nullptr);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003593 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003594
Chris Lattner2da04b32007-08-24 05:35:26 +00003595 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003596 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3597 TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00003598}
3599
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003600LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003601 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003602 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003603 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003604 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003605 return EmitLValue(E->getRHS());
3606 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003607
John McCalle3027922010-08-25 11:45:40 +00003608 if (E->getOpcode() == BO_PtrMemD ||
3609 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003610 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003611
John McCalla2342eb2010-12-05 02:00:02 +00003612 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003613
3614 // Note that in all of these cases, __block variables need the RHS
3615 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003616
3617 switch (getEvaluationKind(E->getType())) {
3618 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003619 switch (E->getLHS()->getType().getObjCLifetime()) {
3620 case Qualifiers::OCL_Strong:
3621 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3622
3623 case Qualifiers::OCL_Autoreleasing:
3624 return EmitARCStoreAutoreleasing(E).first;
3625
3626 // No reason to do any of these differently.
3627 case Qualifiers::OCL_None:
3628 case Qualifiers::OCL_ExplicitNone:
3629 case Qualifiers::OCL_Weak:
3630 break;
3631 }
3632
John McCalld0a30012010-12-06 06:10:02 +00003633 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003634 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003635 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003636 return LV;
3637 }
John McCall4f29b492010-11-16 23:07:28 +00003638
John McCall47fb9502013-03-07 21:37:08 +00003639 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003640 return EmitComplexAssignmentLValue(E);
3641
John McCall47fb9502013-03-07 21:37:08 +00003642 case TEK_Aggregate:
3643 return EmitAggExprToLValue(E);
3644 }
3645 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003646}
3647
Christopher Lambd91c3d42007-12-29 05:02:41 +00003648LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003649 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003650
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003651 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003652 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3653 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003654
David Majnemerced8bdf2015-02-25 17:36:15 +00003655 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003656 "Can't have a scalar return unless the return type is a "
3657 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003658
John McCall7f416cc2015-09-08 08:05:57 +00003659 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003660}
3661
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003662LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3663 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003664 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003665}
3666
Anders Carlsson3be22e22009-05-30 23:23:33 +00003667LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003668 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3669 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003670 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003671 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003672 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3673 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003674}
3675
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003676LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003677CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003678 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003679}
3680
John McCall7f416cc2015-09-08 08:05:57 +00003681Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3682 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3683 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003684}
3685
3686LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003687 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3688 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00003689}
3690
Mike Stumpc9b231c2009-11-15 08:09:41 +00003691LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003692CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003693 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003694 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003695 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003696 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3697 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3698 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003699}
3700
Eli Friedman5bc17122012-02-08 05:34:55 +00003701LValue
3702CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003703 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003704 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003705 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3706 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00003707}
3708
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003709LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003710 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003711
Anders Carlsson280e61f12010-06-21 20:59:55 +00003712 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003713 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3714 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003715
Alp Toker314cc812014-01-25 16:55:45 +00003716 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003717 "Can't have a scalar return unless the return type is a "
3718 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003719
John McCall7f416cc2015-09-08 08:05:57 +00003720 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003721}
3722
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003723LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003724 Address V =
3725 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3726 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003727}
3728
Daniel Dunbar722f4242009-04-22 05:08:15 +00003729llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003730 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003731 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003732}
3733
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003734LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3735 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003736 const ObjCIvarDecl *Ivar,
3737 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003738 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003739 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003740}
3741
3742LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003743 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00003744 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003745 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003746 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003747 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003748 if (E->isArrow()) {
3749 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003750 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003751 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003752 } else {
3753 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00003754 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003755 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003756 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003757 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003758
Craig Topper99e79272013-07-26 05:59:26 +00003759 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003760 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3761 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003762 setObjCGCLValueClass(getContext(), E, LV);
3763 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003764}
3765
Chris Lattnera4185c52009-04-25 19:35:26 +00003766LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003767 // Can only get l-value for message expression returning aggregate type
3768 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00003769 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3770 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00003771}
3772
Anders Carlsson0435ed52009-12-24 19:08:58 +00003773RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003774 const CallExpr *E, ReturnValueSlot ReturnValue,
Samuel Antao798f11c2015-11-23 22:04:44 +00003775 CGCalleeInfo CalleeInfo, llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003776 // Get the actual function type. The callee type will always be a pointer to
3777 // function type or a block pointer type.
3778 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003779 "Call must have function pointer type!");
3780
Samuel Antao798f11c2015-11-23 22:04:44 +00003781 // Preserve the non-canonical function type because things like exception
3782 // specifications disappear in the canonical type. That information is useful
3783 // to drive the generation of more accurate code for this call later on.
3784 const FunctionProtoType *NonCanonicalFTP = CalleeType->getAs<PointerType>()
3785 ->getPointeeType()
3786 ->getAs<FunctionProtoType>();
3787
3788 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
3789
Eric Christopher2b2d56f2015-11-12 00:44:12 +00003790 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00003791 // We can only guarantee that a function is called from the correct
3792 // context/function based on the appropriate target attributes,
3793 // so only check in the case where we have both always_inline and target
3794 // since otherwise we could be making a conditional call after a check for
3795 // the proper cpu features (and it won't cause code generation issues due to
3796 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00003797 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
3798 TargetDecl->hasAttr<TargetAttr>())
3799 checkTargetFeatures(E, FD);
3800
John McCall6fd4c232009-10-23 08:22:42 +00003801 CalleeType = getContext().getCanonicalType(CalleeType);
3802
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003803 const auto *FnType =
3804 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00003805
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003806 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003807 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3808 if (llvm::Constant *PrefixSig =
3809 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003810 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003811 llvm::Constant *FTRTTIConst =
3812 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
3813 llvm::Type *PrefixStructTyElems[] = {
3814 PrefixSig->getType(),
3815 FTRTTIConst->getType()
3816 };
3817 llvm::StructType *PrefixStructTy = llvm::StructType::get(
3818 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
3819
3820 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
3821 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
3822 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003823 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00003824 llvm::Value *CalleeSig =
3825 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003826 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
3827
3828 llvm::BasicBlock *Cont = createBasicBlock("cont");
3829 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
3830 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
3831
3832 EmitBlock(TypeCheck);
3833 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003834 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003835 llvm::Value *CalleeRTTI =
3836 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003837 llvm::Value *CalleeRTTIMatch =
3838 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
3839 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003840 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003841 EmitCheckTypeDescriptor(CalleeType)
3842 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003843 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
3844 "function_type_mismatch", StaticData, Callee);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003845
3846 Builder.CreateBr(Cont);
3847 EmitBlock(Cont);
3848 }
3849 }
3850
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00003851 // If we are checking indirect calls and this call is indirect, check that the
3852 // function pointer is a member of the bit set for the function type.
3853 if (SanOpts.has(SanitizerKind::CFIICall) &&
3854 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3855 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00003856 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00003857
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00003858 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
3859 llvm::Value *BitSetName = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00003860
3861 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy);
3862 llvm::Value *BitSetTest =
3863 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
3864 {CastedCallee, BitSetName});
3865
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00003866 auto TypeId = CGM.CreateCfiIdForTypeMetadata(MD);
3867 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && TypeId) {
3868 EmitCfiSlowPathCheck(BitSetTest, TypeId, CastedCallee);
3869 } else {
3870 llvm::Constant *StaticData[] = {
3871 EmitCheckSourceLocation(E->getLocStart()),
3872 EmitCheckTypeDescriptor(QualType(FnType, 0)),
3873 };
3874 EmitCheck(std::make_pair(BitSetTest, SanitizerKind::CFIICall),
3875 "cfi_bad_icall", StaticData, CastedCallee);
3876 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00003877 }
3878
Daniel Dunbarc722b852008-08-30 03:02:31 +00003879 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00003880 if (Chain)
3881 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
3882 CGM.getContext().VoidPtrTy);
David Blaikief05779e2015-07-21 18:37:18 +00003883 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
3884 E->getDirectCallee(), /*ParamsToSkip*/ 0);
Daniel Dunbarc722b852008-08-30 03:02:31 +00003885
Peter Collingbournef7706832014-12-12 23:41:25 +00003886 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
3887 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00003888
3889 // C99 6.5.2.2p6:
3890 // If the expression that denotes the called function has a type
3891 // that does not include a prototype, [the default argument
3892 // promotions are performed]. If the number of arguments does not
3893 // equal the number of parameters, the behavior is undefined. If
3894 // the function is defined with a type that includes a prototype,
3895 // and either the prototype ends with an ellipsis (, ...) or the
3896 // types of the arguments after promotion are not compatible with
3897 // the types of the parameters, the behavior is undefined. If the
3898 // function is defined with a type that does not include a
3899 // prototype, and the types of the arguments after promotion are
3900 // not compatible with those of the parameters after promotion,
3901 // the behavior is undefined [except in some trivial cases].
3902 // That is, in the general case, we should assume that a call
3903 // through an unprototyped function type works like a *non-variadic*
3904 // call. The way we make this work is to cast to the exact type
3905 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00003906 //
3907 // Chain calls use this same code path to add the invisible chain parameter
3908 // to the function type.
3909 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00003910 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00003911 CalleeTy = CalleeTy->getPointerTo();
3912 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3913 }
3914
Samuel Antao798f11c2015-11-23 22:04:44 +00003915 return EmitCall(FnInfo, Callee, ReturnValue, Args,
3916 CGCalleeInfo(NonCanonicalFTP, TargetDecl));
Daniel Dunbar97db84c2008-08-23 03:46:30 +00003917}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003918
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003919LValue CodeGenFunction::
3920EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003921 Address BaseAddr = Address::invalid();
3922 if (E->getOpcode() == BO_PtrMemI) {
3923 BaseAddr = EmitPointerWithAlignment(E->getLHS());
3924 } else {
3925 BaseAddr = EmitLValue(E->getLHS()).getAddress();
3926 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003927
John McCallc134eb52010-08-31 21:07:20 +00003928 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3929
3930 const MemberPointerType *MPT
3931 = E->getRHS()->getType()->getAs<MemberPointerType>();
3932
John McCall7f416cc2015-09-08 08:05:57 +00003933 AlignmentSource AlignSource;
3934 Address MemberAddr =
3935 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
3936 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00003937
John McCall7f416cc2015-09-08 08:05:57 +00003938 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003939}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003940
John McCall47fb9502013-03-07 21:37:08 +00003941/// Given the address of a temporary variable, produce an r-value of
3942/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00003943RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003944 QualType type,
3945 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00003946 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00003947 switch (getEvaluationKind(type)) {
3948 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003949 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003950 case TEK_Aggregate:
3951 return lvalue.asAggregateRValue();
3952 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003953 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003954 }
3955 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003956}
3957
Duncan Sandse81111c2012-04-10 08:23:07 +00003958void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003959 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003960 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003961 return;
3962
Duncan Sands65229ed2012-04-16 16:29:47 +00003963 llvm::MDBuilder MDHelper(getLLVMContext());
3964 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003965
Duncan Sands6fc46192012-04-14 12:37:26 +00003966 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003967}
John McCallfe96e0b2011-11-06 09:01:30 +00003968
3969namespace {
3970 struct LValueOrRValue {
3971 LValue LV;
3972 RValue RV;
3973 };
3974}
3975
3976static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3977 const PseudoObjectExpr *E,
3978 bool forLValue,
3979 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003980 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00003981
3982 // Find the result expression, if any.
3983 const Expr *resultExpr = E->getResultExpr();
3984 LValueOrRValue result;
3985
3986 for (PseudoObjectExpr::const_semantics_iterator
3987 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3988 const Expr *semantic = *i;
3989
3990 // If this semantic expression is an opaque value, bind it
3991 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003992 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00003993
3994 // If this is the result expression, we may need to evaluate
3995 // directly into the slot.
3996 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3997 OVMA opaqueData;
3998 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00003999 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004000 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4001
John McCall7f416cc2015-09-08 08:05:57 +00004002 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4003 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004004 opaqueData = OVMA::bind(CGF, ov, LV);
4005 result.RV = slot.asRValue();
4006
4007 // Otherwise, emit as normal.
4008 } else {
4009 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4010
4011 // If this is the result, also evaluate the result now.
4012 if (ov == resultExpr) {
4013 if (forLValue)
4014 result.LV = CGF.EmitLValue(ov);
4015 else
4016 result.RV = CGF.EmitAnyExpr(ov, slot);
4017 }
4018 }
4019
4020 opaques.push_back(opaqueData);
4021
4022 // Otherwise, if the expression is the result, evaluate it
4023 // and remember the result.
4024 } else if (semantic == resultExpr) {
4025 if (forLValue)
4026 result.LV = CGF.EmitLValue(semantic);
4027 else
4028 result.RV = CGF.EmitAnyExpr(semantic, slot);
4029
4030 // Otherwise, evaluate the expression in an ignored context.
4031 } else {
4032 CGF.EmitIgnoredExpr(semantic);
4033 }
4034 }
4035
4036 // Unbind all the opaques now.
4037 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4038 opaques[i].unbind(CGF);
4039
4040 return result;
4041}
4042
4043RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4044 AggValueSlot slot) {
4045 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4046}
4047
4048LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4049 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4050}