blob: cda7766884942880f9258c1287fabe57c8ca6517 [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"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000035
Chris Lattnere47e4402007-06-01 18:02:12 +000036using namespace clang;
37using namespace CodeGen;
38
Chris Lattnerd7f58862007-06-02 05:24:33 +000039//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000040// Miscellaneous Helper Methods
41//===--------------------------------------------------------------------===//
42
John McCallad7c5c12011-02-08 08:22:06 +000043llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
44 unsigned addressSpace =
45 cast<llvm::PointerType>(value->getType())->getAddressSpace();
46
Chris Lattner2192fe52011-07-18 04:24:23 +000047 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000048 if (addressSpace)
49 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
50
51 if (value->getType() == destType) return value;
52 return Builder.CreateBitCast(value, destType);
53}
54
Chris Lattnere9a64532007-06-22 21:44:33 +000055/// CreateTempAlloca - This creates a alloca and inserts it into the entry
56/// block.
John McCall7f416cc2015-09-08 08:05:57 +000057Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
58 const Twine &Name) {
59 auto Alloca = CreateTempAlloca(Ty, Name);
60 Alloca->setAlignment(Align.getQuantity());
61 return Address(Alloca, Align);
62}
63
64/// CreateTempAlloca - This creates a alloca and inserts it into the entry
65/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000066llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 const Twine &Name) {
Chris Lattner47640222009-03-22 00:24:14 +000068 if (!Builder.isNamePreserving())
Craig Topper8a13c412014-05-21 05:09:00 +000069 return new llvm::AllocaInst(Ty, nullptr, "", AllocaInsertPt);
70 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000071}
Chris Lattner8394d792007-06-05 20:53:16 +000072
John McCall7f416cc2015-09-08 08:05:57 +000073/// CreateDefaultAlignTempAlloca - This creates an alloca with the
74/// default alignment of the corresponding LLVM type, which is *not*
75/// guaranteed to be related in any way to the expected alignment of
76/// an AST type that might have been lowered to Ty.
77Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
78 const Twine &Name) {
79 CharUnits Align =
80 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
81 return CreateTempAlloca(Ty, Align, Name);
82}
83
84void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
85 assert(isa<llvm::AllocaInst>(Var.getPointer()));
86 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
87 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000088 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
89 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
90}
91
John McCall7f416cc2015-09-08 08:05:57 +000092Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000093 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000094 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +000095}
96
John McCall7f416cc2015-09-08 08:05:57 +000097Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000098 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +000099 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
100}
101
102Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
103 const Twine &Name) {
104 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000105}
106
Chris Lattner8394d792007-06-05 20:53:16 +0000107/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
108/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000109llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000110 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000111 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000112 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000113 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000114 }
John McCall7a9aac22010-08-23 01:21:21 +0000115
116 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000117 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000118 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000119 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000120
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000121 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
122 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000123}
124
John McCalla2342eb2010-12-05 02:00:02 +0000125/// EmitIgnoredExpr - Emit code to compute the specified expression,
126/// ignoring the result.
127void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
128 if (E->isRValue())
129 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
130
131 // Just emit it as an l-value and drop the result.
132 EmitLValue(E);
133}
134
John McCall7a626f62010-09-15 10:14:12 +0000135/// EmitAnyExpr - Emit code to compute the specified expression which
136/// can have any type. The result is returned as an RValue struct.
137/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000138/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000139RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
140 AggValueSlot aggSlot,
141 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000142 switch (getEvaluationKind(E->getType())) {
143 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000144 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000145 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000146 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000147 case TEK_Aggregate:
148 if (!ignoreResult && aggSlot.isIgnored())
149 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
150 EmitAggExpr(E, aggSlot);
151 return aggSlot.asRValue();
152 }
153 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000154}
155
Mike Stump4a3999f2009-09-09 13:00:44 +0000156/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
157/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000158RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
159 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000160
John McCall47fb9502013-03-07 21:37:08 +0000161 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000162 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
163 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000164}
165
John McCall21886962010-04-21 10:05:39 +0000166/// EmitAnyExprToMem - Evaluate an expression into a given memory
167/// location.
168void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000169 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000170 Qualifiers Quals,
171 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000172 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000173 switch (getEvaluationKind(E->getType())) {
174 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000175 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000176 /*isInit*/ false);
177 return;
178
179 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000180 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000181 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000182 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000183 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000184 return;
185 }
186
187 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000188 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000189 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000190 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000191 return;
John McCall21886962010-04-21 10:05:39 +0000192 }
John McCall47fb9502013-03-07 21:37:08 +0000193 }
194 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000195}
196
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000197static void
198pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000199 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000200 // Objective-C++ ARC:
201 // If we are binding a reference to a temporary that has ownership, we
202 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000203 //
204 // FIXME: This should be looking at E, not M.
205 if (CGF.getLangOpts().ObjCAutoRefCount &&
206 M->getType()->isObjCLifetimeType()) {
207 QualType ObjCARCReferenceLifetimeType = M->getType();
208 switch (Qualifiers::ObjCLifetime Lifetime =
209 ObjCARCReferenceLifetimeType.getObjCLifetime()) {
210 case Qualifiers::OCL_None:
211 case Qualifiers::OCL_ExplicitNone:
212 // Carry on to normal cleanup handling.
213 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000214
Richard Smith736a9472013-06-12 20:42:33 +0000215 case Qualifiers::OCL_Autoreleasing:
216 // Nothing to do; cleaned up by an autorelease pool.
217 return;
218
219 case Qualifiers::OCL_Strong:
220 case Qualifiers::OCL_Weak:
221 switch (StorageDuration Duration = M->getStorageDuration()) {
222 case SD_Static:
223 // Note: we intentionally do not register a cleanup to release
224 // the object on program termination.
225 return;
226
227 case SD_Thread:
228 // FIXME: We should probably register a cleanup in this case.
229 return;
230
231 case SD_Automatic:
232 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000233 CodeGenFunction::Destroyer *Destroy;
234 CleanupKind CleanupKind;
235 if (Lifetime == Qualifiers::OCL_Strong) {
236 const ValueDecl *VD = M->getExtendingDecl();
237 bool Precise =
238 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
239 CleanupKind = CGF.getARCCleanupKind();
240 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
241 : &CodeGenFunction::destroyARCStrongImprecise;
242 } else {
243 // __weak objects always get EH cleanups; otherwise, exceptions
244 // could cause really nasty crashes instead of mere leaks.
245 CleanupKind = NormalAndEHCleanup;
246 Destroy = &CodeGenFunction::destroyARCWeak;
247 }
248 if (Duration == SD_FullExpression)
249 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
250 ObjCARCReferenceLifetimeType, *Destroy,
251 CleanupKind & EHCleanup);
252 else
253 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
254 ObjCARCReferenceLifetimeType,
255 *Destroy, CleanupKind & EHCleanup);
256 return;
257
258 case SD_Dynamic:
259 llvm_unreachable("temporary cannot have dynamic storage duration");
260 }
261 llvm_unreachable("unknown storage duration");
262 }
263 }
264
Craig Topper8a13c412014-05-21 05:09:00 +0000265 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000266 if (const RecordType *RT =
267 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
268 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000269 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000270 if (!ClassDecl->hasTrivialDestructor())
271 ReferenceTemporaryDtor = ClassDecl->getDestructor();
272 }
273
274 if (!ReferenceTemporaryDtor)
275 return;
276
277 // Call the destructor for the temporary.
278 switch (M->getStorageDuration()) {
279 case SD_Static:
280 case SD_Thread: {
281 llvm::Constant *CleanupFn;
282 llvm::Constant *CleanupArg;
283 if (E->getType()->isArrayType()) {
284 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000285 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000286 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
287 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000288 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
289 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000290 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
291 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000292 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000293 }
294 CGF.CGM.getCXXABI().registerGlobalDtor(
295 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
296 break;
297 }
298
299 case SD_FullExpression:
300 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
301 CodeGenFunction::destroyCXXObject,
302 CGF.getLangOpts().Exceptions);
303 break;
304
305 case SD_Automatic:
306 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
307 ReferenceTemporary, E->getType(),
308 CodeGenFunction::destroyCXXObject,
309 CGF.getLangOpts().Exceptions);
310 break;
311
312 case SD_Dynamic:
313 llvm_unreachable("temporary cannot have dynamic storage duration");
314 }
315}
316
John McCall7f416cc2015-09-08 08:05:57 +0000317static Address
Richard Smith736a9472013-06-12 20:42:33 +0000318createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000319 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000320 switch (M->getStorageDuration()) {
321 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000322 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000323 // If we have a constant temporary array or record try to promote it into a
324 // constant global under the same rules a normal constant would've been
325 // promoted. This is easier on the optimizer and generally emits fewer
326 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000327 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000328 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000329 (Ty->isArrayType() || Ty->isRecordType()) &&
330 CGF.CGM.isTypeConstant(Ty, true))
331 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000332 auto *GV = new llvm::GlobalVariable(
333 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
334 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000335 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
336 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000337 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000338 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000339 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000340 return CGF.CreateMemTemp(Ty, "ref.tmp");
341 }
Richard Smith736a9472013-06-12 20:42:33 +0000342 case SD_Thread:
343 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000344 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000345
346 case SD_Dynamic:
347 llvm_unreachable("temporary can't have dynamic storage duration");
348 }
349 llvm_unreachable("unknown storage duration");
350}
351
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000352LValue CodeGenFunction::
353EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000354 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000355
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000356 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
357 // as that will cause the lifetime adjustment to be lost for ARC
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000358 if (getLangOpts().ObjCAutoRefCount &&
Richard Smith736a9472013-06-12 20:42:33 +0000359 M->getType()->isObjCLifetimeType() &&
360 M->getType().getObjCLifetime() != Qualifiers::OCL_None &&
361 M->getType().getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000362 Address Object = createReferenceTemporary(*this, M, E);
363 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
364 Object = Address(llvm::ConstantExpr::getBitCast(Var,
365 ConvertTypeForMem(E->getType())
366 ->getPointerTo(Object.getAddressSpace())),
367 Object.getAlignment());
Richard Smitha509f2f2013-06-14 03:07:01 +0000368 // We should not have emitted the initializer for this temporary as a
369 // constant.
370 assert(!Var->hasInitializer());
371 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
372 }
John McCall7f416cc2015-09-08 08:05:57 +0000373 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
374 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000375
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000376 switch (getEvaluationKind(E->getType())) {
377 default: llvm_unreachable("expected scalar or aggregate expression");
378 case TEK_Scalar:
379 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
380 break;
381 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000382 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000383 E->getType().getQualifiers(),
384 AggValueSlot::IsDestructed,
385 AggValueSlot::DoesNotNeedGCBarriers,
386 AggValueSlot::IsNotAliased));
387 break;
388 }
389 }
Richard Smith736a9472013-06-12 20:42:33 +0000390
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000391 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000392 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000393 }
394
Richard Smithf3fabd22013-06-03 00:17:11 +0000395 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000396 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000397 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
398
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000399 for (const auto &Ignored : CommaLHSs)
400 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000401
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000402 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000403 if (opaque->getType()->isRecordType()) {
404 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000405 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000406 }
407 }
408
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000409 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000410 Address Object = createReferenceTemporary(*this, M, E);
411 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
412 Object = Address(llvm::ConstantExpr::getBitCast(
413 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
414 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000415 // If the temporary is a global and has a constant initializer or is a
416 // constant temporary that we promoted to a global, we may have already
417 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000418 if (!Var->hasInitializer()) {
419 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
420 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
421 }
422 } else {
423 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
424 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000425 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000426
Richard Smith736a9472013-06-12 20:42:33 +0000427 // Perform derived-to-base casts and/or field accesses, to get from the
428 // temporary object we created (and, potentially, for which we extended
429 // the lifetime) to the subobject we're binding the reference to.
430 for (unsigned I = Adjustments.size(); I != 0; --I) {
431 SubobjectAdjustment &Adjustment = Adjustments[I-1];
432 switch (Adjustment.Kind) {
433 case SubobjectAdjustment::DerivedToBaseAdjustment:
434 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000435 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
436 Adjustment.DerivedToBase.BasePath->path_begin(),
437 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000438 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000439 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000440
Richard Smith736a9472013-06-12 20:42:33 +0000441 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000442 LValue LV = MakeAddrLValue(Object, E->getType(),
443 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000444 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000445 assert(LV.isSimple() &&
446 "materialized temporary field is not a simple lvalue");
447 Object = LV.getAddress();
448 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000449 }
450
Richard Smith736a9472013-06-12 20:42:33 +0000451 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000452 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000453 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
454 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000455 break;
456 }
457 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000458 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000459
John McCall7f416cc2015-09-08 08:05:57 +0000460 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000461}
462
463RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000464CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
465 // Emit the expression as an lvalue.
466 LValue LV = EmitLValue(E);
467 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000468 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000469
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000470 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000471 // C++11 [dcl.ref]p5 (as amended by core issue 453):
472 // If a glvalue to which a reference is directly bound designates neither
473 // an existing object or function of an appropriate type nor a region of
474 // storage of suitable size and alignment to contain an object of the
475 // reference's type, the behavior is undefined.
476 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000477 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000478 }
John McCall8680f872010-07-21 06:29:51 +0000479
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000480 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000481}
482
483
Mike Stump4a3999f2009-09-09 13:00:44 +0000484/// getAccessedFieldNo - Given an encoded value and a result number, return the
485/// input field number being accessed.
486unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000487 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000488 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
489 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000490}
491
Richard Smith4d3110a2012-10-25 02:14:12 +0000492/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
493static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
494 llvm::Value *High) {
495 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
496 llvm::Value *K47 = Builder.getInt64(47);
497 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
498 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
499 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
500 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
501 return Builder.CreateMul(B1, KMul);
502}
503
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000504bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000505 return SanOpts.has(SanitizerKind::Null) |
506 SanOpts.has(SanitizerKind::Alignment) |
507 SanOpts.has(SanitizerKind::ObjectSize) |
508 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000509}
510
Richard Smithe30752c2012-10-09 19:52:38 +0000511void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000512 llvm::Value *Ptr, QualType Ty,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000513 CharUnits Alignment, bool SkipNullCheck) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000514 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000515 return;
516
Richard Smith2d8b2942012-11-01 07:22:08 +0000517 // Don't check pointers outside the default address space. The null check
518 // isn't correct, the object-size check isn't supported by LLVM, and we can't
519 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000520 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000521 return;
522
Alexey Samsonov24cad992014-07-17 18:46:27 +0000523 SanitizerScope SanScope(this);
524
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000525 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000526 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000527
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000528 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
529 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000530 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
531 !SkipNullCheck) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000532 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000533 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000534
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000535 if (AllowNullPointers) {
536 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000537 // Skip the remaining checks in that case.
538 Done = createBasicBlock("null");
539 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000540 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000541 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000542 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000543 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000544 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000545 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000546
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000547 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000548 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000549
Richard Smith69d0d262012-08-24 00:54:33 +0000550 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000551 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000552 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000553 // FIXME: Get object address space
554 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
555 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000556 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000557 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000558 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000559 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000560 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000561 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000562 }
Richard Smith69d0d262012-08-24 00:54:33 +0000563
Richard Smithb1b0ab42012-11-05 22:21:05 +0000564 uint64_t AlignVal = 0;
565
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000566 if (SanOpts.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000567 AlignVal = Alignment.getQuantity();
568 if (!Ty->isIncompleteType() && !AlignVal)
569 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
570
Richard Smith69d0d262012-08-24 00:54:33 +0000571 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000572 if (AlignVal) {
573 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000574 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000575 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
576 llvm::Value *Aligned =
577 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000578 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000579 }
Richard Smith69d0d262012-08-24 00:54:33 +0000580 }
581
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000582 if (Checks.size() > 0) {
Richard Smithe30752c2012-10-09 19:52:38 +0000583 llvm::Constant *StaticData[] = {
584 EmitCheckSourceLocation(Loc),
585 EmitCheckTypeDescriptor(Ty),
586 llvm::ConstantInt::get(SizeTy, AlignVal),
587 llvm::ConstantInt::get(Int8Ty, TCK)
588 };
John McCall7f416cc2015-09-08 08:05:57 +0000589 EmitCheck(Checks, "type_mismatch", StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000590 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000591
Richard Smithb1b0ab42012-11-05 22:21:05 +0000592 // If possible, check that the vptr indicates that there is a subobject of
593 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000594 //
595 // C++11 [basic.life]p5,6:
596 // [For storage which does not refer to an object within its lifetime]
597 // The program has undefined behavior if:
598 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000599 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000600 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000601 if (SanOpts.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000602 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000603 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
604 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000605 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000606 // Compute a hash of the mangled name of the type.
607 //
608 // FIXME: This is not guaranteed to be deterministic! Move to a
609 // fingerprinting mechanism once LLVM provides one. For the time
610 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000611 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000612 llvm::raw_svector_ostream Out(MangledName);
613 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
614 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000615
Alexey Samsonov84856012014-07-10 22:34:19 +0000616 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000617 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
618 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000619 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000620
Alexey Samsonov84856012014-07-10 22:34:19 +0000621 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
622 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
623 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000624 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000625 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
626 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000627
Alexey Samsonov84856012014-07-10 22:34:19 +0000628 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
629 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000630
Alexey Samsonov84856012014-07-10 22:34:19 +0000631 // Look the hash up in our cache.
632 const int CacheSize = 128;
633 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
634 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
635 "__ubsan_vptr_type_cache");
636 llvm::Value *Slot = Builder.CreateAnd(Hash,
637 llvm::ConstantInt::get(IntPtrTy,
638 CacheSize-1));
639 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
640 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000641 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
642 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000643
644 // If the hash isn't in the cache, call a runtime handler to perform the
645 // hard work of checking whether the vptr is for an object of the right
646 // type. This will either fill in the cache and return, or produce a
647 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000648 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000649 llvm::Constant *StaticData[] = {
650 EmitCheckSourceLocation(Loc),
651 EmitCheckTypeDescriptor(Ty),
652 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
653 llvm::ConstantInt::get(Int8Ty, TCK)
654 };
John McCall7f416cc2015-09-08 08:05:57 +0000655 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000656 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
657 "dynamic_type_cache_miss", StaticData, DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000658 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000659 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000660
661 if (Done) {
662 Builder.CreateBr(Done);
663 EmitBlock(Done);
664 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000665}
Chris Lattner4647a212007-08-31 22:49:20 +0000666
Richard Smith539e4a72013-02-23 02:53:19 +0000667/// Determine whether this expression refers to a flexible array member in a
668/// struct. We disable array bounds checks for such members.
669static bool isFlexibleArrayMemberExpr(const Expr *E) {
670 // For compatibility with existing code, we treat arrays of length 0 or
671 // 1 as flexible array members.
672 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000673 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000674 if (CAT->getSize().ugt(1))
675 return false;
676 } else if (!isa<IncompleteArrayType>(AT))
677 return false;
678
679 E = E->IgnoreParens();
680
681 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000682 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000683 // FIXME: If the base type of the member expr is not FD->getParent(),
684 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000685 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000686 RecordDecl::field_iterator FI(
687 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
688 return ++FI == FD->getParent()->field_end();
689 }
690 }
691
692 return false;
693}
694
695/// If Base is known to point to the start of an array, return the length of
696/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000697static llvm::Value *getArrayIndexingBound(
698 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000699 // For the vector indexing extension, the bound is the number of elements.
700 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
701 IndexedType = Base->getType();
702 return CGF.Builder.getInt32(VT->getNumElements());
703 }
704
705 Base = Base->IgnoreParens();
706
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000707 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000708 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
709 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
710 IndexedType = CE->getSubExpr()->getType();
711 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000712 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000713 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000714 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000715 return CGF.getVLASize(VAT).first;
716 }
717 }
718
Craig Topper8a13c412014-05-21 05:09:00 +0000719 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000720}
721
722void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
723 llvm::Value *Index, QualType IndexType,
724 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000725 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000726 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000727 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000728
Richard Smith539e4a72013-02-23 02:53:19 +0000729 QualType IndexedType;
730 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
731 if (!Bound)
732 return;
733
734 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
735 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
736 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
737
738 llvm::Constant *StaticData[] = {
739 EmitCheckSourceLocation(E->getExprLoc()),
740 EmitCheckTypeDescriptor(IndexedType),
741 EmitCheckTypeDescriptor(IndexType)
742 };
743 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
744 : Builder.CreateICmpULE(IndexVal, BoundVal);
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000745 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
746 StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000747}
748
Chris Lattner116ce8f2010-01-09 21:40:03 +0000749
Chris Lattner116ce8f2010-01-09 21:40:03 +0000750CodeGenFunction::ComplexPairTy CodeGenFunction::
751EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
752 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000753 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000754
Chris Lattner116ce8f2010-01-09 21:40:03 +0000755 llvm::Value *NextVal;
756 if (isa<llvm::IntegerType>(InVal.first->getType())) {
757 uint64_t AmountVal = isInc ? 1 : -1;
758 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000759
Chris Lattner116ce8f2010-01-09 21:40:03 +0000760 // Add the inc/dec to the real part.
761 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
762 } else {
763 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
764 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
765 if (!isInc)
766 FVal.changeSign();
767 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000768
Chris Lattner116ce8f2010-01-09 21:40:03 +0000769 // Add the inc/dec to the real part.
770 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
771 }
Craig Topper99e79272013-07-26 05:59:26 +0000772
Chris Lattner116ce8f2010-01-09 21:40:03 +0000773 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000774
Chris Lattner116ce8f2010-01-09 21:40:03 +0000775 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000776 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000777
Chris Lattner116ce8f2010-01-09 21:40:03 +0000778 // If this is a postinc, return the value read from memory, otherwise use the
779 // updated value.
780 return isPre ? IncVal : InVal;
781}
782
Chris Lattnera45c5af2007-06-02 19:47:04 +0000783//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000784// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000785//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000786
John McCall7f416cc2015-09-08 08:05:57 +0000787/// EmitPointerWithAlignment - Given an expression of pointer type, try to
788/// derive a more accurate bound on the alignment of the pointer.
789Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
790 AlignmentSource *Source) {
791 // We allow this with ObjC object pointers because of fragile ABIs.
792 assert(E->getType()->isPointerType() ||
793 E->getType()->isObjCObjectPointerType());
794 E = E->IgnoreParens();
795
796 // Casts:
797 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
798 // Bind VLAs in the cast type.
799 if (E->getType()->isVariablyModifiedType())
800 EmitVariablyModifiedType(E->getType());
801
802 switch (CE->getCastKind()) {
803 // Non-converting casts (but not C's implicit conversion from void*).
804 case CK_BitCast:
805 case CK_NoOp:
806 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
807 if (PtrTy->getPointeeType()->isVoidType())
808 break;
809
810 AlignmentSource InnerSource;
811 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
812 if (Source) *Source = InnerSource;
813
814 // If this is an explicit bitcast, and the source l-value is
815 // opaque, honor the alignment of the casted-to type.
816 if (isa<ExplicitCastExpr>(CE) &&
817 CE->getCastKind() == CK_BitCast &&
818 InnerSource != AlignmentSource::Decl) {
819 Addr = Address(Addr.getPointer(),
820 getNaturalPointeeTypeAlignment(E->getType(), Source));
821 }
822
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000823 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
824 if (auto PT = E->getType()->getAs<PointerType>())
825 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
826 /*MayBeNull=*/true,
827 CodeGenFunction::CFITCK_UnrelatedCast,
828 CE->getLocStart());
829 }
830
John McCall7f416cc2015-09-08 08:05:57 +0000831 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
832 }
833 break;
834
835 // Array-to-pointer decay.
836 case CK_ArrayToPointerDecay:
837 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
838
839 // Derived-to-base conversions.
840 case CK_UncheckedDerivedToBase:
841 case CK_DerivedToBase: {
842 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
843 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
844 return GetAddressOfBaseClass(Addr, Derived,
845 CE->path_begin(), CE->path_end(),
846 ShouldNullCheckClassCastValue(CE),
847 CE->getExprLoc());
848 }
849
850 // TODO: Is there any reason to treat base-to-derived conversions
851 // specially?
852 default:
853 break;
854 }
855 }
856
857 // Unary &.
858 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
859 if (UO->getOpcode() == UO_AddrOf) {
860 LValue LV = EmitLValue(UO->getSubExpr());
861 if (Source) *Source = LV.getAlignmentSource();
862 return LV.getAddress();
863 }
864 }
865
866 // TODO: conditional operators, comma.
867
868 // Otherwise, use the alignment of the type.
869 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
870 return Address(EmitScalarExpr(E), Align);
871}
872
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000873RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000874 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000875 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000876
877 switch (getEvaluationKind(Ty)) {
878 case TEK_Complex: {
879 llvm::Type *EltTy =
880 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000881 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000882 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000883 }
Craig Topper99e79272013-07-26 05:59:26 +0000884
Chris Lattner65526f02010-08-23 05:26:13 +0000885 // If this is a use of an undefined aggregate type, the aggregate must have an
886 // identifiable address. Just because the contents of the value are undefined
887 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000888 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000889 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000890 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000891 }
John McCall47fb9502013-03-07 21:37:08 +0000892
893 case TEK_Scalar:
894 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
895 }
896 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000897}
898
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000899RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
900 const char *Name) {
901 ErrorUnsupported(E, Name);
902 return GetUndefRValue(E->getType());
903}
904
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000905LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
906 const char *Name) {
907 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000908 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000909 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
910 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000911}
912
Richard Smith4d1458e2012-09-08 02:08:36 +0000913LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000914 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000915 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000916 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
917 else
918 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000919 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000920 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000921 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000922 return LV;
923}
924
Chris Lattner8394d792007-06-05 20:53:16 +0000925/// EmitLValue - Emit code to compute a designator that specifies the location
926/// of the expression.
927///
Mike Stump4a3999f2009-09-09 13:00:44 +0000928/// This can return one of two things: a simple address or a bitfield reference.
929/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
930/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000931///
Mike Stump4a3999f2009-09-09 13:00:44 +0000932/// If this returns a bitfield reference, nothing about the pointee type of the
933/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000934///
Mike Stump4a3999f2009-09-09 13:00:44 +0000935/// If this returns a normal address, and if the lvalue's C type is fixed size,
936/// this method guarantees that the returned pointer type will point to an LLVM
937/// type of the same size of the lvalue's type. If the lvalue has a variable
938/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000939///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000940LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000941 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000942 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000943 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000944
John McCallc109a252011-11-07 03:59:57 +0000945 case Expr::ObjCPropertyRefExprClass:
946 llvm_unreachable("cannot emit a property reference directly");
947
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000948 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000949 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000950 case Expr::ObjCIsaExprClass:
951 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000952 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000953 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000954 case Expr::CompoundAssignOperatorClass: {
955 QualType Ty = E->getType();
956 if (const AtomicType *AT = Ty->getAs<AtomicType>())
957 Ty = AT->getValueType();
958 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000959 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
960 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000961 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000962 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000963 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000964 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000965 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000966 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000967 case Expr::VAArgExprClass:
968 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000969 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000970 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000971 case Expr::ParenExprClass:
972 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000973 case Expr::GenericSelectionExprClass:
974 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000975 case Expr::PredefinedExprClass:
976 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000977 case Expr::StringLiteralClass:
978 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000979 case Expr::ObjCEncodeExprClass:
980 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000981 case Expr::PseudoObjectExprClass:
982 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000983 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000984 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000985 case Expr::CXXTemporaryObjectExprClass:
986 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000987 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
988 case Expr::CXXBindTemporaryExprClass:
989 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000990 case Expr::CXXUuidofExprClass:
991 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000992 case Expr::LambdaExprClass:
993 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000994
995 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000996 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +0000997 enterFullExpression(cleanups);
998 RunCleanupsScope Scope(*this);
999 return EmitLValue(cleanups->getSubExpr());
1000 }
1001
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001002 case Expr::CXXDefaultArgExprClass:
1003 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001004 case Expr::CXXDefaultInitExprClass: {
1005 CXXDefaultInitExprScope Scope(*this);
1006 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1007 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001008 case Expr::CXXTypeidExprClass:
1009 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001010
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001011 case Expr::ObjCMessageExprClass:
1012 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001013 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001014 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001015 case Expr::StmtExprClass:
1016 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001017 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001018 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001019 case Expr::ArraySubscriptExprClass:
1020 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001021 case Expr::OMPArraySectionExprClass:
1022 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001023 case Expr::ExtVectorElementExprClass:
1024 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001025 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001026 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001027 case Expr::CompoundLiteralExprClass:
1028 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001029 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001030 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001031 case Expr::BinaryConditionalOperatorClass:
1032 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001033 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001034 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001035 case Expr::OpaqueValueExprClass:
1036 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001037 case Expr::SubstNonTypeTemplateParmExprClass:
1038 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001039 case Expr::ImplicitCastExprClass:
1040 case Expr::CStyleCastExprClass:
1041 case Expr::CXXFunctionalCastExprClass:
1042 case Expr::CXXStaticCastExprClass:
1043 case Expr::CXXDynamicCastExprClass:
1044 case Expr::CXXReinterpretCastExprClass:
1045 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001046 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001047 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001048
Douglas Gregorfe314812011-06-21 17:03:29 +00001049 case Expr::MaterializeTemporaryExprClass:
1050 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001051 }
1052}
1053
John McCall71335052012-03-10 03:05:10 +00001054/// Given an object of the given canonical type, can we safely copy a
1055/// value out of it based on its initializer?
1056static bool isConstantEmittableObjectType(QualType type) {
1057 assert(type.isCanonical());
1058 assert(!type->isReferenceType());
1059
1060 // Must be const-qualified but non-volatile.
1061 Qualifiers qs = type.getLocalQualifiers();
1062 if (!qs.hasConst() || qs.hasVolatile()) return false;
1063
1064 // Otherwise, all object types satisfy this except C++ classes with
1065 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001066 if (const auto *RT = dyn_cast<RecordType>(type))
1067 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001068 if (RD->hasMutableFields() || !RD->isTrivial())
1069 return false;
1070
1071 return true;
1072}
1073
1074/// Can we constant-emit a load of a reference to a variable of the
1075/// given type? This is different from predicates like
1076/// Decl::isUsableInConstantExpressions because we do want it to apply
1077/// in situations that don't necessarily satisfy the language's rules
1078/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1079/// to do this with const float variables even if those variables
1080/// aren't marked 'constexpr'.
1081enum ConstantEmissionKind {
1082 CEK_None,
1083 CEK_AsReferenceOnly,
1084 CEK_AsValueOrReference,
1085 CEK_AsValueOnly
1086};
1087static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1088 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001089 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001090 if (isConstantEmittableObjectType(ref->getPointeeType()))
1091 return CEK_AsValueOrReference;
1092 return CEK_AsReferenceOnly;
1093 }
1094 if (isConstantEmittableObjectType(type))
1095 return CEK_AsValueOnly;
1096 return CEK_None;
1097}
1098
1099/// Try to emit a reference to the given value without producing it as
1100/// an l-value. This is actually more than an optimization: we can't
1101/// produce an l-value for variables that we never actually captured
1102/// in a block or lambda, which means const int variables or constexpr
1103/// literals or similar.
1104CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001105CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1106 ValueDecl *value = refExpr->getDecl();
1107
John McCall71335052012-03-10 03:05:10 +00001108 // The value needs to be an enum constant or a constant variable.
1109 ConstantEmissionKind CEK;
1110 if (isa<ParmVarDecl>(value)) {
1111 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001112 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001113 CEK = checkVarTypeForConstantEmission(var->getType());
1114 } else if (isa<EnumConstantDecl>(value)) {
1115 CEK = CEK_AsValueOnly;
1116 } else {
1117 CEK = CEK_None;
1118 }
1119 if (CEK == CEK_None) return ConstantEmission();
1120
John McCall71335052012-03-10 03:05:10 +00001121 Expr::EvalResult result;
1122 bool resultIsReference;
1123 QualType resultType;
1124
1125 // It's best to evaluate all the way as an r-value if that's permitted.
1126 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001127 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001128 resultIsReference = false;
1129 resultType = refExpr->getType();
1130
1131 // Otherwise, try to evaluate as an l-value.
1132 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001133 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001134 resultIsReference = true;
1135 resultType = value->getType();
1136
1137 // Failure.
1138 } else {
1139 return ConstantEmission();
1140 }
1141
1142 // In any case, if the initializer has side-effects, abandon ship.
1143 if (result.HasSideEffects)
1144 return ConstantEmission();
1145
1146 // Emit as a constant.
1147 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1148
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001149 // Make sure we emit a debug reference to the global variable.
1150 // This should probably fire even for
1151 if (isa<VarDecl>(value)) {
1152 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1153 EmitDeclRefExprDbgValue(refExpr, C);
1154 } else {
1155 assert(isa<EnumConstantDecl>(value));
1156 EmitDeclRefExprDbgValue(refExpr, C);
1157 }
John McCall71335052012-03-10 03:05:10 +00001158
1159 // If we emitted a reference constant, we need to dereference that.
1160 if (resultIsReference)
1161 return ConstantEmission::forReference(C);
1162
1163 return ConstantEmission::forValue(C);
1164}
1165
Nick Lewycky2d84e842013-10-02 02:29:49 +00001166llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1167 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001168 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001169 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1170 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001171 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1172 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001173}
1174
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001175static bool hasBooleanRepresentation(QualType Ty) {
1176 if (Ty->isBooleanType())
1177 return true;
1178
1179 if (const EnumType *ET = Ty->getAs<EnumType>())
1180 return ET->getDecl()->getIntegerType()->isBooleanType();
1181
Douglas Gregor298f43d2012-04-12 20:42:30 +00001182 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1183 return hasBooleanRepresentation(AT->getValueType());
1184
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001185 return false;
1186}
1187
Richard Smith1629da92012-12-13 07:11:50 +00001188static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1189 llvm::APInt &Min, llvm::APInt &End,
1190 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001191 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001192 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1193 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001194 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001195 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001196 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001197
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001198 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001199 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1200 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001201 } else {
1202 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001203 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001204 unsigned Bitwidth = LTy->getScalarSizeInBits();
1205 unsigned NumNegativeBits = ED->getNumNegativeBits();
1206 unsigned NumPositiveBits = ED->getNumPositiveBits();
1207
1208 if (NumNegativeBits) {
1209 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1210 assert(NumBits <= Bitwidth);
1211 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1212 Min = -End;
1213 } else {
1214 assert(NumPositiveBits <= Bitwidth);
1215 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1216 Min = llvm::APInt(Bitwidth, 0);
1217 }
1218 }
Richard Smith1629da92012-12-13 07:11:50 +00001219 return true;
1220}
1221
1222llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1223 llvm::APInt Min, End;
1224 if (!getRangeForType(*this, Ty, Min, End,
1225 CGM.getCodeGenOpts().StrictEnums))
Craig Topper8a13c412014-05-21 05:09:00 +00001226 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001227
Duncan Sandsc720e782012-04-15 18:04:54 +00001228 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001229 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001230}
1231
John McCall7f416cc2015-09-08 08:05:57 +00001232llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1233 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001234 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001235 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001236 llvm::MDNode *TBAAInfo,
1237 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001238 uint64_t TBAAOffset,
1239 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001240 // For better performance, handle vector loads differently.
1241 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001242 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001243
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001244 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001245
John McCall7f416cc2015-09-08 08:05:57 +00001246 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001247 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001248
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001249 // Bitcast to vec4 type.
1250 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1251 4);
John McCall7f416cc2015-09-08 08:05:57 +00001252 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001253 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001254 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001255
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001256 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001257 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001258 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001259 return EmitFromMemory(V, Ty);
1260 }
1261 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001262
1263 // Atomic operations have to be done on integral types.
David Majnemera5b195a2015-02-14 01:35:12 +00001264 if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
John McCall7f416cc2015-09-08 08:05:57 +00001265 LValue lvalue =
1266 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemereeaec262015-02-14 02:18:14 +00001267 return EmitAtomicLoad(lvalue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001268 }
Craig Topper99e79272013-07-26 05:59:26 +00001269
John McCall7f416cc2015-09-08 08:05:57 +00001270 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001271 if (isNontemporal) {
1272 llvm::MDNode *Node = llvm::MDNode::get(
1273 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1274 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1275 }
Manman Renc451e572013-04-04 21:53:22 +00001276 if (TBAAInfo) {
1277 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1278 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001279 if (TBAAPath)
1280 CGM.DecorateInstruction(Load, TBAAPath, false/*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001281 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001282
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001283 bool NeedsBoolCheck =
1284 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1285 bool NeedsEnumCheck =
1286 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1287 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001288 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001289 llvm::APInt Min, End;
1290 if (getRangeForType(*this, Ty, Min, End, true)) {
1291 --End;
1292 llvm::Value *Check;
1293 if (!Min)
1294 Check = Builder.CreateICmpULE(
1295 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1296 else {
1297 llvm::Value *Upper = Builder.CreateICmpSLE(
1298 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1299 llvm::Value *Lower = Builder.CreateICmpSGE(
1300 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1301 Check = Builder.CreateAnd(Upper, Lower);
1302 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001303 llvm::Constant *StaticArgs[] = {
1304 EmitCheckSourceLocation(Loc),
1305 EmitCheckTypeDescriptor(Ty)
1306 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001307 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001308 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1309 EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001310 }
1311 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001312 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1313 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001314
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001315 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001316}
1317
John McCall3a7f6922010-10-27 20:58:56 +00001318llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1319 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001320 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001321 // This should really always be an i1, but sometimes it's already
1322 // an i8, and it's awkward to track those cases down.
1323 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001324 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1325 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1326 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001327 }
1328
1329 return Value;
1330}
1331
1332llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1333 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001334 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001335 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1336 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001337 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1338 }
1339
1340 return Value;
1341}
1342
John McCall7f416cc2015-09-08 08:05:57 +00001343void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1344 bool Volatile, QualType Ty,
1345 AlignmentSource AlignSource,
1346 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001347 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001348 uint64_t TBAAOffset,
1349 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001350
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001351 // Handle vectors differently to get better performance.
1352 if (Ty->isVectorType()) {
1353 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001354 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001355 // Handle vec3 special.
1356 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001357 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001358 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1359 Builder.getInt32(2),
1360 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001361 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1362 Value = Builder.CreateShuffleVector(Value,
1363 llvm::UndefValue::get(VecTy),
1364 MaskV, "extractVec");
1365 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1366 }
John McCall7f416cc2015-09-08 08:05:57 +00001367 if (Addr.getElementType() != SrcTy) {
1368 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001369 }
1370 }
Craig Topper99e79272013-07-26 05:59:26 +00001371
John McCall3a7f6922010-10-27 20:58:56 +00001372 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001373
David Majnemera5b195a2015-02-14 01:35:12 +00001374 if (Ty->isAtomicType() ||
1375 (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001376 EmitAtomicStore(RValue::get(Value),
John McCall7f416cc2015-09-08 08:05:57 +00001377 LValue::MakeAddr(Addr, Ty, getContext(),
1378 AlignSource, TBAAInfo),
John McCalla8ec7eb2013-03-07 21:37:17 +00001379 isInit);
1380 return;
1381 }
1382
Daniel Dunbar03816342010-08-21 02:24:36 +00001383 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001384 if (isNontemporal) {
1385 llvm::MDNode *Node =
1386 llvm::MDNode::get(Store->getContext(),
1387 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1388 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1389 }
Manman Renc451e572013-04-04 21:53:22 +00001390 if (TBAAInfo) {
1391 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1392 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001393 if (TBAAPath)
1394 CGM.DecorateInstruction(Store, TBAAPath, false/*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001395 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001396}
1397
David Chisnallfa35df62012-01-16 17:27:18 +00001398void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001399 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001400 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001401 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001402 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001403 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001404}
1405
Mike Stump4a3999f2009-09-09 13:00:44 +00001406/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1407/// method emits the address of the lvalue, then loads the result as an rvalue,
1408/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001409RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001410 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001411 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001412 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001413 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1414 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001415 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001416 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1417 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1418 Object = EmitObjCConsumeObject(LV.getType(), Object);
1419 return RValue::get(Object);
1420 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001421
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001422 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001423 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001424
John McCalla1dee5302010-08-22 10:59:02 +00001425 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001426 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001427 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001428
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001429 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001430 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001431 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001432 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001433 "vecext"));
1434 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001435
1436 // If this is a reference to a subset of the elements of a vector, either
1437 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001438 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001439 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001440
Renato Golin230c5eb2014-05-19 18:15:42 +00001441 // Global Register variables always invoke intrinsics
1442 if (LV.isGlobalReg())
1443 return EmitLoadOfGlobalRegLValue(LV);
1444
John McCallc109a252011-11-07 03:59:57 +00001445 assert(LV.isBitField() && "Unknown LValue type!");
1446 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001447}
1448
John McCall55e1fbc2011-06-25 02:11:03 +00001449RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001450 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001451
Daniel Dunbar3447a022010-04-13 23:34:15 +00001452 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001453 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001454
John McCall7f416cc2015-09-08 08:05:57 +00001455 Address Ptr = LV.getBitFieldAddress();
1456 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001457
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001458 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001459 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001460 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1461 if (HighBits)
1462 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1463 if (Info.Offset + HighBits)
1464 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1465 } else {
1466 if (Info.Offset)
1467 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001468 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001469 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1470 Info.Size),
1471 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001472 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001473 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001474
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001475 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001476}
1477
Nate Begemanb699c9b2009-01-18 06:42:49 +00001478// If this is a reference to a subset of the elements of a vector, create an
1479// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001480RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001481 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1482 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001483
Nate Begemanf322eab2008-05-09 06:41:27 +00001484 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001485
1486 // If the result of the expression is a non-vector type, we must be extracting
1487 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001488 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001489 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001490 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001491 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001492 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001493 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001494
1495 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001496 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001497
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001498 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001499 for (unsigned i = 0; i != NumResultElts; ++i)
1500 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001501
Chris Lattner91c08ad2011-02-15 00:14:06 +00001502 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1503 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001504 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001505 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001506}
1507
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001508/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001509Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1510 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001511 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1512 QualType EQT = ExprVT->getElementType();
1513 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001514
John McCall7f416cc2015-09-08 08:05:57 +00001515 Address CastToPointerElement =
1516 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1517 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001518
1519 const llvm::Constant *Elts = LV.getExtVectorElts();
1520 unsigned ix = getAccessedFieldNo(0, Elts);
1521
John McCall7f416cc2015-09-08 08:05:57 +00001522 Address VectorBasePtrPlusIx =
1523 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1524 getContext().getTypeSizeInChars(EQT),
1525 "vector.elt");
1526
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001527 return VectorBasePtrPlusIx;
1528}
1529
Renato Golin230c5eb2014-05-19 18:15:42 +00001530/// @brief Load of global gamed gegisters are always calls to intrinsics.
1531RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001532 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1533 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001534 llvm::MDNode *RegName = cast<llvm::MDNode>(
1535 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001536
1537 // We accept integer and pointer types only
1538 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1539 llvm::Type *Ty = OrigTy;
1540 if (OrigTy->isPointerTy())
1541 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1542 llvm::Type *Types[] = { Ty };
1543
Renato Golin230c5eb2014-05-19 18:15:42 +00001544 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001545 llvm::Value *Call = Builder.CreateCall(
1546 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001547 if (OrigTy->isPointerTy())
1548 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001549 return RValue::get(Call);
1550}
Chris Lattner40ff7012007-08-03 16:18:34 +00001551
Chris Lattner9369a562007-06-29 16:31:29 +00001552
Chris Lattner8394d792007-06-05 20:53:16 +00001553/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1554/// lvalue, where both are guaranteed to the have the same type, and that type
1555/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001556void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001557 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001558 if (!Dst.isSimple()) {
1559 if (Dst.isVectorElt()) {
1560 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001561 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1562 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001563 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001564 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001565 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1566 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001567 return;
1568 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001569
Nate Begemance4d7fc2008-04-18 23:10:10 +00001570 // If this is an update of extended vector elements, insert them as
1571 // appropriate.
1572 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001573 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001574
Renato Golin230c5eb2014-05-19 18:15:42 +00001575 if (Dst.isGlobalReg())
1576 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1577
John McCallc109a252011-11-07 03:59:57 +00001578 assert(Dst.isBitField() && "Unknown LValue type");
1579 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001580 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001581
John McCall31168b02011-06-15 23:02:42 +00001582 // There's special magic for assigning into an ARC-qualified l-value.
1583 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1584 switch (Lifetime) {
1585 case Qualifiers::OCL_None:
1586 llvm_unreachable("present but none");
1587
1588 case Qualifiers::OCL_ExplicitNone:
1589 // nothing special
1590 break;
1591
1592 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001593 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001594 return;
1595
1596 case Qualifiers::OCL_Weak:
1597 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1598 return;
1599
1600 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001601 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1602 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001603 // fall into the normal path
1604 break;
1605 }
1606 }
1607
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001608 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001609 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001610 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001611 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001612 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001613 return;
1614 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001615
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001616 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001617 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001618 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001619 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001620 if (Dst.isObjCIvar()) {
1621 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001622 llvm::Type *ResultType = IntPtrTy;
1623 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1624 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001625 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001626 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001627 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1628 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001629 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001630 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001631 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001632 } else if (Dst.isGlobalObjCRef()) {
1633 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1634 Dst.isThreadLocalRef());
1635 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001636 else
1637 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001638 return;
1639 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001640
Chris Lattner6278e6a2007-08-11 00:04:45 +00001641 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001642 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001643}
1644
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001645void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001646 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001647 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001648 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001649 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001650
Daniel Dunbar67aba792010-04-15 03:47:33 +00001651 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001652 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001653
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001654 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001655 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001656 /*IsSigned=*/false);
1657 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001658
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001659 // See if there are other bits in the bitfield's storage we'll need to load
1660 // and mask together with source before storing.
1661 if (Info.StorageSize != Info.Size) {
1662 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001663 llvm::Value *Val =
1664 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001665
1666 // Mask the source value as needed.
1667 if (!hasBooleanRepresentation(Dst.getType()))
1668 SrcVal = Builder.CreateAnd(SrcVal,
1669 llvm::APInt::getLowBitsSet(Info.StorageSize,
1670 Info.Size),
1671 "bf.value");
1672 MaskedVal = SrcVal;
1673 if (Info.Offset)
1674 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1675
1676 // Mask out the original value.
1677 Val = Builder.CreateAnd(Val,
1678 ~llvm::APInt::getBitsSet(Info.StorageSize,
1679 Info.Offset,
1680 Info.Offset + Info.Size),
1681 "bf.clear");
1682
1683 // Or together the unchanged values and the source value.
1684 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1685 } else {
1686 assert(Info.Offset == 0);
1687 }
1688
1689 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001690 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001691
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001692 // Return the new value of the bit-field, if requested.
1693 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001694 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001695
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001696 // Sign extend the value if needed.
1697 if (Info.IsSigned) {
1698 assert(Info.Size <= Info.StorageSize);
1699 unsigned HighBits = Info.StorageSize - Info.Size;
1700 if (HighBits) {
1701 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1702 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1703 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001704 }
1705
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001706 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1707 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001708 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001709 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001710}
1711
Nate Begemance4d7fc2008-04-18 23:10:10 +00001712void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001713 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001714 // This access turns into a read/modify/write of the vector. Load the input
1715 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001716 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1717 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001718 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001719
Chris Lattner4647a212007-08-31 22:49:20 +00001720 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001721
John McCall55e1fbc2011-06-25 02:11:03 +00001722 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001723 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001724 unsigned NumDstElts =
1725 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1726 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001727 // Use shuffle vector is the src and destination are the same number of
1728 // elements and restore the vector mask since it is on the side it will be
1729 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001730 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001731 for (unsigned i = 0; i != NumSrcElts; ++i)
1732 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001733
Chris Lattner91c08ad2011-02-15 00:14:06 +00001734 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001735 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001736 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001737 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001738 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001739 // Extended the source vector to the same length and then shuffle it
1740 // into the destination.
1741 // FIXME: since we're shuffling with undef, can we just use the indices
1742 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001743 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001744 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001745 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001746 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001747 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001748 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001749 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001750 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001751 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001752 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001753 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001754 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001755 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001756
Joey Goulycf4143b2013-11-21 17:09:05 +00001757 // When the vector size is odd and .odd or .hi is used, the last element
1758 // of the Elts constant array will be one past the size of the vector.
1759 // Ignore the last element here, if it is greater than the mask size.
1760 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1761 NumSrcElts--;
1762
Nate Begemanb699c9b2009-01-18 06:42:49 +00001763 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001764 for (unsigned i = 0; i != NumSrcElts; ++i)
1765 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001766 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001767 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001768 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001769 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001770 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001771 }
1772 } else {
1773 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001774 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001775 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001776 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001777 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001778
John McCall7f416cc2015-09-08 08:05:57 +00001779 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1780 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001781}
1782
Renato Golin230c5eb2014-05-19 18:15:42 +00001783/// @brief Store of global named registers are always calls to intrinsics.
1784void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001785 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1786 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001787 llvm::MDNode *RegName = cast<llvm::MDNode>(
1788 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001789 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001790
1791 // We accept integer and pointer types only
1792 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1793 llvm::Type *Ty = OrigTy;
1794 if (OrigTy->isPointerTy())
1795 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1796 llvm::Type *Types[] = { Ty };
1797
Renato Golin230c5eb2014-05-19 18:15:42 +00001798 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1799 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001800 if (OrigTy->isPointerTy())
1801 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001802 Builder.CreateCall(
1803 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001804}
1805
Eric Christopherc9e2a682014-05-20 17:10:39 +00001806// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001807// generating write-barries API. It is currently a global, ivar,
1808// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001809static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001810 LValue &LV,
1811 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001812 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001813 return;
Craig Topper99e79272013-07-26 05:59:26 +00001814
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001815 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001816 QualType ExpTy = E->getType();
1817 if (IsMemberAccess && ExpTy->isPointerType()) {
1818 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001819 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001820 // writer-barrier conservatively.
1821 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1822 if (ExpTy->isRecordType()) {
1823 LV.setObjCIvar(false);
1824 return;
1825 }
1826 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001827 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001828 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001829 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001830 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001831 return;
1832 }
Craig Topper99e79272013-07-26 05:59:26 +00001833
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001834 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1835 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001836 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001837 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001838 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001839 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001840 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001841 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001842 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001843 }
Craig Topper99e79272013-07-26 05:59:26 +00001844
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001845 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001846 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001847 return;
1848 }
Craig Topper99e79272013-07-26 05:59:26 +00001849
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001850 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001851 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001852 if (LV.isObjCIvar()) {
1853 // If cast is to a structure pointer, follow gcc's behavior and make it
1854 // a non-ivar write-barrier.
1855 QualType ExpTy = E->getType();
1856 if (ExpTy->isPointerType())
1857 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1858 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001859 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001860 }
1861 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001862 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001863
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001864 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001865 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1866 return;
1867 }
1868
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001869 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001870 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001871 return;
1872 }
Craig Topper99e79272013-07-26 05:59:26 +00001873
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001874 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001875 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001876 return;
1877 }
John McCall31168b02011-06-15 23:02:42 +00001878
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001879 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001880 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001881 return;
1882 }
1883
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001884 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001885 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001886 if (LV.isObjCIvar() && !LV.isObjCArray())
1887 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001888 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001889 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001890 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001891 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001892 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001893 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001894 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001895 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001896
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001897 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001898 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001899 // We don't know if member is an 'ivar', but this flag is looked at
1900 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001901 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001902 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001903 }
1904}
1905
Chris Lattner3f32d692011-07-12 06:52:18 +00001906static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001907EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001908 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001909 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001910 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001911 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001912}
1913
Alexey Bataev97720002014-11-11 04:05:39 +00001914static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001915 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1916 llvm::Type *RealVarTy, SourceLocation Loc) {
1917 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1918 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1919 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1920}
1921
1922Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1923 const ReferenceType *RefTy,
1924 AlignmentSource *Source) {
1925 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1926 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1927 Source, /*forPointee*/ true));
1928
1929}
1930
1931LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1932 const ReferenceType *RefTy) {
1933 AlignmentSource Source;
1934 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1935 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001936}
1937
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001938static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1939 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001940 QualType T = E->getType();
1941
1942 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00001943 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1944 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00001945 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1946
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001947 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001948 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1949 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001950 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00001951 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001952 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00001953 // Emit reference to the private copy of the variable if it is an OpenMP
1954 // threadprivate variable.
1955 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001956 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001957 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001958 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
1959 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001960 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001961 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001962 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001963 setObjCGCLValueClass(CGF.getContext(), E, LV);
1964 return LV;
1965}
1966
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001967static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001968 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001969 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001970 if (!FD->hasPrototype()) {
1971 if (const FunctionProtoType *Proto =
1972 FD->getType()->getAs<FunctionProtoType>()) {
1973 // Ugly case: for a K&R-style definition, the type of the definition
1974 // isn't the same as the type of a use. Correct for this with a
1975 // bitcast.
1976 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00001977 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001978 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001979 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001980 }
1981 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001982 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00001983 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001984}
1985
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00001986static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
1987 llvm::Value *ThisValue) {
1988 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
1989 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
1990 return CGF.EmitLValueForField(LV, FD);
1991}
1992
Renato Golin230c5eb2014-05-19 18:15:42 +00001993/// Named Registers are named metadata pointing to the register name
1994/// which will be read from/written to as an argument to the intrinsic
1995/// @llvm.read/write_register.
1996/// So far, only the name is being passed down, but other options such as
1997/// register type, allocation type or even optimization options could be
1998/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00001999static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002000 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002001 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002002 assert(Asm->getLabel().size() < 64-Name.size() &&
2003 "Register name too big");
2004 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002005 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002006 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002007 if (M->getNumOperands() == 0) {
2008 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2009 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002010 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002011 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2012 }
John McCall7f416cc2015-09-08 08:05:57 +00002013
2014 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2015
2016 llvm::Value *Ptr =
2017 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2018 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002019}
2020
Chris Lattnerd7f58862007-06-02 05:24:33 +00002021LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002022 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002023 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002024
Renato Goline7b3d5d2014-05-27 16:46:27 +00002025 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2026 // Global Named registers access via intrinsics only
2027 if (VD->getStorageClass() == SC_Register &&
2028 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002029 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002030
Renato Goline7b3d5d2014-05-27 16:46:27 +00002031 // A DeclRefExpr for a reference initialized by a constant expression can
2032 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002033 const Expr *Init = VD->getAnyInitializer(VD);
2034 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2035 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002036 VD->checkInitIsICE() &&
2037 // Do not emit if it is private OpenMP variable.
2038 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2039 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002040 llvm::Constant *Val =
2041 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2042 assert(Val && "failed to emit reference constant expression");
2043 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002044
2045 // Should we be using the alignment of the constant pointer we emitted?
2046 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2047 /*pointee*/ true);
2048
2049 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002050 }
David Majnemer602cfe72015-01-01 09:49:44 +00002051
2052 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002053 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002054 if (auto *FD = LambdaCaptureFields.lookup(VD))
2055 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2056 else if (CapturedStmtInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002057 auto it = LocalDeclMap.find(VD);
2058 if (it != LocalDeclMap.end()) {
2059 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2060 return EmitLoadOfReferenceLValue(it->second, RefTy);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002061 }
John McCall7f416cc2015-09-08 08:05:57 +00002062 return MakeAddrLValue(it->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002063 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002064 LValue CapLVal =
2065 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2066 CapturedStmtInfo->getContextValue());
2067 return MakeAddrLValue(
2068 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2069 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002070 }
John McCall7f416cc2015-09-08 08:05:57 +00002071
David Majnemer602cfe72015-01-01 09:49:44 +00002072 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002073 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2074 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002075 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002076 }
2077
Eli Friedman5720e342012-01-21 04:52:58 +00002078 // FIXME: We should be able to assert this for FunctionDecls as well!
2079 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2080 // those with a valid source location.
2081 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2082 !E->getLocation().isValid()) &&
2083 "Should not use decl without marking it used!");
2084
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002085 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002086 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002087 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2088 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002089 }
2090
Renato Goline7b3d5d2014-05-27 16:46:27 +00002091 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002092 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002093 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002094 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002095
John McCall7f416cc2015-09-08 08:05:57 +00002096 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002097
John McCall7f416cc2015-09-08 08:05:57 +00002098 // The variable should generally be present in the local decl map.
2099 auto iter = LocalDeclMap.find(VD);
2100 if (iter != LocalDeclMap.end()) {
2101 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002102
John McCall7f416cc2015-09-08 08:05:57 +00002103 // Otherwise, it might be static local we haven't emitted yet for
2104 // some reason; most likely, because it's in an outer function.
2105 } else if (VD->isStaticLocal()) {
2106 addr = Address(CGM.getOrCreateStaticVarDecl(
2107 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2108 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002109
John McCall7f416cc2015-09-08 08:05:57 +00002110 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002111 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002112 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2113 }
2114
2115
2116 // Check for OpenMP threadprivate variables.
2117 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2118 return EmitThreadPrivateVarDeclLValue(
2119 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2120 E->getExprLoc());
2121 }
2122
2123 // Drill into block byref variables.
2124 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2125 if (isBlockByref) {
2126 addr = emitBlockByrefAddress(addr, VD);
2127 }
2128
2129 // Drill into reference types.
2130 LValue LV;
2131 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2132 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2133 } else {
2134 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002135 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002136
John McCallcdda29c2013-03-13 03:10:54 +00002137 bool isLocalStorage = VD->hasLocalStorage();
2138
2139 bool NonGCable = isLocalStorage &&
2140 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002141 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002142 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002143 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002144 LV.setNonGC(true);
2145 }
John McCallcdda29c2013-03-13 03:10:54 +00002146
2147 bool isImpreciseLifetime =
2148 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2149 if (isImpreciseLifetime)
2150 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002151 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002152 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002153 }
John McCallf3a88602011-02-03 08:15:49 +00002154
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002155 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002156 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002157
David Blaikie83d382b2011-09-23 05:06:16 +00002158 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002159}
Chris Lattnere47e4402007-06-01 18:02:12 +00002160
Chris Lattner8394d792007-06-05 20:53:16 +00002161LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2162 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002163 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002164 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002165
Chris Lattner0f398c42008-07-26 22:37:01 +00002166 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002167 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002168 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002169 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002170 QualType T = E->getSubExpr()->getType()->getPointeeType();
2171 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002172
John McCall7f416cc2015-09-08 08:05:57 +00002173 AlignmentSource AlignSource;
2174 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2175 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002176 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002177
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002178 // We should not generate __weak write barrier on indirect reference
2179 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2180 // But, we continue to generate __strong write barrier on indirect write
2181 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002182 if (getLangOpts().ObjC1 &&
2183 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002184 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002185 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002186 return LV;
2187 }
John McCalle3027922010-08-25 11:45:40 +00002188 case UO_Real:
2189 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002190 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002191 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002192
Richard Smith0b6b8e42012-02-18 20:53:32 +00002193 // __real is valid on scalars. This is a faster way of testing that.
2194 // __imag can only produce an rvalue on scalars.
2195 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002196 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002197 assert(E->getSubExpr()->getType()->isArithmeticType());
2198 return LV;
2199 }
2200
2201 assert(E->getSubExpr()->getType()->isAnyComplexType());
2202
John McCall7f416cc2015-09-08 08:05:57 +00002203 Address Component =
2204 (E->getOpcode() == UO_Real
2205 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2206 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2207 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
Chris Lattner595db862007-10-30 22:53:42 +00002208 }
John McCalle3027922010-08-25 11:45:40 +00002209 case UO_PreInc:
2210 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002211 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002212 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002213
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002214 if (E->getType()->isAnyComplexType())
2215 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2216 else
2217 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2218 return LV;
2219 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002220 }
Chris Lattner8394d792007-06-05 20:53:16 +00002221}
2222
Chris Lattner4347e3692007-06-06 04:54:52 +00002223LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002224 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002225 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002226}
2227
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002228LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002229 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002230 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002231}
2232
Mike Stump4a3999f2009-09-09 13:00:44 +00002233LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002234 auto SL = E->getFunctionName();
2235 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2236 StringRef FnName = CurFn->getName();
2237 if (FnName.startswith("\01"))
2238 FnName = FnName.substr(1);
2239 StringRef NameItems[] = {
2240 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2241 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002242 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
John McCall7f416cc2015-09-08 08:05:57 +00002243 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2244 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002245 }
Alexey Bataevec474782014-10-09 08:45:04 +00002246 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002247 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002248}
2249
Richard Smithe30752c2012-10-09 19:52:38 +00002250/// Emit a type description suitable for use by a runtime sanitizer library. The
2251/// format of a type descriptor is
2252///
2253/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002254/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002255/// \endcode
2256///
Richard Smith683398a2012-10-09 23:55:19 +00002257/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2258/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002259llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002260 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002261 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002262 return C;
2263
Richard Smithe30752c2012-10-09 19:52:38 +00002264 uint16_t TypeKind = -1;
2265 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002266
Richard Smithe30752c2012-10-09 19:52:38 +00002267 if (T->isIntegerType()) {
2268 TypeKind = 0;
2269 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002270 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002271 } else if (T->isFloatingType()) {
2272 TypeKind = 1;
2273 TypeInfo = getContext().getTypeSize(T);
2274 }
2275
2276 // Format the type name as if for a diagnostic, including quotes and
2277 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002278 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002279 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2280 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002281 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002282 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002283
2284 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002285 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2286 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002287 };
2288 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2289
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002290 auto *GV = new llvm::GlobalVariable(
2291 CGM.getModule(), Descriptor->getType(),
2292 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Richard Smithe30752c2012-10-09 19:52:38 +00002293 GV->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002294 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002295
2296 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002297 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002298
Richard Smithe30752c2012-10-09 19:52:38 +00002299 return GV;
2300}
2301
2302llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2303 llvm::Type *TargetTy = IntPtrTy;
2304
Richard Smith48366f72013-03-22 00:47:07 +00002305 // Floating-point types which fit into intptr_t are bitcast to integers
2306 // and then passed directly (after zero-extension, if necessary).
2307 if (V->getType()->isFloatingPointTy()) {
2308 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2309 if (Bits <= TargetTy->getIntegerBitWidth())
2310 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2311 Bits));
2312 }
2313
Richard Smithe30752c2012-10-09 19:52:38 +00002314 // Integers which fit in intptr_t are zero-extended and passed directly.
2315 if (V->getType()->isIntegerTy() &&
2316 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2317 return Builder.CreateZExt(V, TargetTy);
2318
2319 // Pointers are passed directly, everything else is passed by address.
2320 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002321 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002322 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002323 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002324 }
2325 return Builder.CreatePtrToInt(V, TargetTy);
2326}
2327
2328/// \brief Emit a representation of a SourceLocation for passing to a handler
2329/// in a sanitizer runtime library. The format for this data is:
2330/// \code
2331/// struct SourceLocation {
2332/// const char *Filename;
2333/// int32_t Line, Column;
2334/// };
2335/// \endcode
2336/// For an invalid SourceLocation, the Filename pointer is null.
2337llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002338 llvm::Constant *Filename;
2339 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002340
Alexey Samsonov6c124142014-07-18 17:50:06 +00002341 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2342 if (PLoc.isValid()) {
2343 auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002344 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2345 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2346 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002347 Line = PLoc.getLine();
2348 Column = PLoc.getColumn();
2349 } else {
2350 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2351 Line = Column = 0;
2352 }
2353
2354 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2355 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002356
2357 return llvm::ConstantStruct::getAnon(Data);
2358}
2359
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002360namespace {
2361/// \brief Specify under what conditions this check can be recovered
2362enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002363 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002364 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002365 /// Check supports recovering, runtime has both fatal (noreturn) and
2366 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002367 Recoverable,
2368 /// Runtime conditionally aborts, always need to support recovery.
2369 AlwaysRecoverable
2370};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002371}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002372
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002373static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2374 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002375 switch (Kind) {
2376 case SanitizerKind::Vptr:
2377 return CheckRecoverableKind::AlwaysRecoverable;
2378 case SanitizerKind::Return:
2379 case SanitizerKind::Unreachable:
2380 return CheckRecoverableKind::Unrecoverable;
2381 default:
2382 return CheckRecoverableKind::Recoverable;
2383 }
2384}
2385
Alexey Samsonov88459522015-01-12 22:39:12 +00002386static void emitCheckHandlerCall(CodeGenFunction &CGF,
2387 llvm::FunctionType *FnType,
2388 ArrayRef<llvm::Value *> FnArgs,
2389 StringRef CheckName,
2390 CheckRecoverableKind RecoverKind, bool IsFatal,
2391 llvm::BasicBlock *ContBB) {
2392 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2393 bool NeedsAbortSuffix =
2394 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2395 std::string FnName = ("__ubsan_handle_" + CheckName +
2396 (NeedsAbortSuffix ? "_abort" : "")).str();
2397 bool MayReturn =
2398 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2399
2400 llvm::AttrBuilder B;
2401 if (!MayReturn) {
2402 B.addAttribute(llvm::Attribute::NoReturn)
2403 .addAttribute(llvm::Attribute::NoUnwind);
2404 }
2405 B.addAttribute(llvm::Attribute::UWTable);
2406
2407 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2408 FnType, FnName,
2409 llvm::AttributeSet::get(CGF.getLLVMContext(),
2410 llvm::AttributeSet::FunctionIndex, B));
2411 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2412 if (!MayReturn) {
2413 HandlerCall->setDoesNotReturn();
2414 CGF.Builder.CreateUnreachable();
2415 } else {
2416 CGF.Builder.CreateBr(ContBB);
2417 }
2418}
2419
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002420void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002421 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002422 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2423 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002424 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002425 assert(Checked.size() > 0);
Alexey Samsonov88459522015-01-12 22:39:12 +00002426
2427 llvm::Value *FatalCond = nullptr;
2428 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002429 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002430 for (int i = 0, n = Checked.size(); i < n; ++i) {
2431 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002432 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002433 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002434 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2435 ? TrapCond
2436 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2437 ? RecoverableCond
2438 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002439 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2440 }
2441
Peter Collingbourne9881b782015-06-18 23:59:22 +00002442 if (TrapCond)
2443 EmitTrapCheck(TrapCond);
2444 if (!FatalCond && !RecoverableCond)
2445 return;
2446
Alexey Samsonov88459522015-01-12 22:39:12 +00002447 llvm::Value *JointCond;
2448 if (FatalCond && RecoverableCond)
2449 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2450 else
2451 JointCond = FatalCond ? FatalCond : RecoverableCond;
2452 assert(JointCond);
2453
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002454 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2455 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002456#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002457 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002458 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002459 "All recoverable kinds in a single check must be same!");
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002460 assert(SanOpts.has(Checked[i].second));
2461 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002462#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002463
Richard Smith4d1458e2012-09-08 02:08:36 +00002464 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002465 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2466 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002467 // Give hint that we very much don't expect to execute the handler
2468 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2469 llvm::MDBuilder MDHelper(getLLVMContext());
2470 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2471 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002472 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002473
Alexey Samsonov88459522015-01-12 22:39:12 +00002474 // Emit handler arguments and create handler function type.
Richard Smithe30752c2012-10-09 19:52:38 +00002475 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002476 auto *InfoPtr =
Will Dietz450f1a12013-01-09 03:39:41 +00002477 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
Richard Smithe30752c2012-10-09 19:52:38 +00002478 llvm::GlobalVariable::PrivateLinkage, Info);
2479 InfoPtr->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002480 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
Richard Smithe30752c2012-10-09 19:52:38 +00002481
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002482 SmallVector<llvm::Value *, 4> Args;
2483 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002484 Args.reserve(DynamicArgs.size() + 1);
2485 ArgTypes.reserve(DynamicArgs.size() + 1);
2486
2487 // Handler functions take an i8* pointing to the (handler-specific) static
2488 // information block, followed by a sequence of intptr_t arguments
2489 // representing operand values.
2490 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2491 ArgTypes.push_back(Int8PtrTy);
2492 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2493 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2494 ArgTypes.push_back(IntPtrTy);
2495 }
2496
2497 llvm::FunctionType *FnType =
2498 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002499
Alexey Samsonov88459522015-01-12 22:39:12 +00002500 if (!FatalCond || !RecoverableCond) {
2501 // Simple case: we need to generate a single handler call, either
2502 // fatal, or non-fatal.
2503 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2504 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002505 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002506 // Emit two handler calls: first one for set of unrecoverable checks,
2507 // another one for recoverable.
2508 llvm::BasicBlock *NonFatalHandlerBB =
2509 createBasicBlock("non_fatal." + CheckName);
2510 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2511 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2512 EmitBlock(FatalHandlerBB);
2513 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2514 NonFatalHandlerBB);
2515 EmitBlock(NonFatalHandlerBB);
2516 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2517 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002518 }
Richard Smithe30752c2012-10-09 19:52:38 +00002519
Richard Smith4d1458e2012-09-08 02:08:36 +00002520 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002521}
2522
Chad Rosierae229d52013-01-29 23:31:22 +00002523void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002524 llvm::BasicBlock *Cont = createBasicBlock("cont");
2525
2526 // If we're optimizing, collapse all calls to trap down to just one per
2527 // function to save on code size.
2528 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2529 TrapBB = createBasicBlock("trap");
2530 Builder.CreateCondBr(Checked, Cont, TrapBB);
2531 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002532 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002533 TrapCall->setDoesNotReturn();
2534 TrapCall->setDoesNotThrow();
2535 Builder.CreateUnreachable();
2536 } else {
2537 Builder.CreateCondBr(Checked, Cont, TrapBB);
2538 }
2539
2540 EmitBlock(Cont);
2541}
2542
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002543llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002544 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002545
2546 if (!CGM.getCodeGenOpts().TrapFuncName.empty())
2547 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
2548 "trap-func-name",
2549 CGM.getCodeGenOpts().TrapFuncName);
2550
2551 return TrapCall;
2552}
2553
John McCall7f416cc2015-09-08 08:05:57 +00002554Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2555 AlignmentSource *AlignSource) {
2556 assert(E->getType()->isArrayType() &&
2557 "Array to pointer decay must have array source type!");
2558
2559 // Expressions of array type can't be bitfields or vector elements.
2560 LValue LV = EmitLValue(E);
2561 Address Addr = LV.getAddress();
2562 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2563
2564 // If the array type was an incomplete type, we need to make sure
2565 // the decay ends up being the right type.
2566 llvm::Type *NewTy = ConvertType(E->getType());
2567 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2568
2569 // Note that VLA pointers are always decayed, so we don't need to do
2570 // anything here.
2571 if (!E->getType()->isVariableArrayType()) {
2572 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2573 "Expected pointer to array");
2574 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2575 }
2576
2577 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2578 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2579}
2580
Chris Lattner6c5abe82010-06-26 23:03:20 +00002581/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2582/// array to pointer, return the array subexpression.
2583static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2584 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002585 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002586 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002587 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002588
Chris Lattner6c5abe82010-06-26 23:03:20 +00002589 // If this is a decay from variable width array, bail out.
2590 const Expr *SubExpr = CE->getSubExpr();
2591 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002592 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002593
Chris Lattner6c5abe82010-06-26 23:03:20 +00002594 return SubExpr;
2595}
2596
John McCall7f416cc2015-09-08 08:05:57 +00002597static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2598 llvm::Value *ptr,
2599 ArrayRef<llvm::Value*> indices,
2600 bool inbounds,
2601 const llvm::Twine &name = "arrayidx") {
2602 if (inbounds) {
2603 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2604 } else {
2605 return CGF.Builder.CreateGEP(ptr, indices, name);
2606 }
2607}
2608
2609static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2610 llvm::Value *idx,
2611 CharUnits eltSize) {
2612 // If we have a constant index, we can use the exact offset of the
2613 // element we're accessing.
2614 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2615 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2616 return arrayAlign.alignmentAtOffset(offset);
2617
2618 // Otherwise, use the worst-case alignment for any element.
2619 } else {
2620 return arrayAlign.alignmentOfArrayElement(eltSize);
2621 }
2622}
2623
2624static QualType getFixedSizeElementType(const ASTContext &ctx,
2625 const VariableArrayType *vla) {
2626 QualType eltType;
2627 do {
2628 eltType = vla->getElementType();
2629 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2630 return eltType;
2631}
2632
2633static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2634 ArrayRef<llvm::Value*> indices,
2635 QualType eltType, bool inbounds,
2636 const llvm::Twine &name = "arrayidx") {
2637 // All the indices except that last must be zero.
2638#ifndef NDEBUG
2639 for (auto idx : indices.drop_back())
2640 assert(isa<llvm::ConstantInt>(idx) &&
2641 cast<llvm::ConstantInt>(idx)->isZero());
2642#endif
2643
2644 // Determine the element size of the statically-sized base. This is
2645 // the thing that the indices are expressed in terms of.
2646 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2647 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2648 }
2649
2650 // We can use that to compute the best alignment of the element.
2651 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2652 CharUnits eltAlign =
2653 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2654
2655 llvm::Value *eltPtr =
2656 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2657 return Address(eltPtr, eltAlign);
2658}
2659
Richard Smith539e4a72013-02-23 02:53:19 +00002660LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2661 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002662 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002663 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002664 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002665 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002666
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002667 if (SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002668 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2669
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002670 // If the base is a vector type, then we are forming a vector element lvalue
2671 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002672 if (E->getBase()->getType()->isVectorType() &&
2673 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002674 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002675 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002676 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002677 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002678 E->getBase()->getType(),
2679 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002680 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002681
John McCall7f416cc2015-09-08 08:05:57 +00002682 // All the other cases basically behave like simple offsetting.
2683
Ted Kremenekc81614d2007-08-20 16:18:38 +00002684 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002685 if (Idx->getType() != IntPtrTy)
2686 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002687
John McCall7f416cc2015-09-08 08:05:57 +00002688 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002689 if (isa<ExtVectorElementExpr>(E->getBase())) {
2690 LValue LV = EmitLValue(E->getBase());
John McCall7f416cc2015-09-08 08:05:57 +00002691 Address Addr = EmitExtVectorElementLValue(LV);
2692
2693 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2694 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2695 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002696 }
John McCall7f416cc2015-09-08 08:05:57 +00002697
2698 AlignmentSource AlignSource;
2699 Address Addr = Address::invalid();
2700 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002701 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002702 // The base must be a pointer, which is not an aggregate. Emit
2703 // it. It needs to be emitted first in case it's what captures
2704 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002705 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002706
John McCall23c29fe2011-06-24 21:55:10 +00002707 // The element count here is the total number of non-VLA elements.
2708 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002709
John McCall77527a82011-06-25 01:32:37 +00002710 // Effectively, the multiply by the VLA size is part of the GEP.
2711 // GEP indexes are signed, and scaling an index isn't permitted to
2712 // signed-overflow, so we use the same semantics for our explicit
2713 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002714 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002715 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002716 } else {
2717 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002718 }
John McCall7f416cc2015-09-08 08:05:57 +00002719
2720 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2721 !getLangOpts().isSignedOverflowDefined());
2722
Chris Lattner6c5abe82010-06-26 23:03:20 +00002723 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2724 // Indexing over an interface, as in "NSString *P; P[4];"
John McCall7f416cc2015-09-08 08:05:57 +00002725 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2726 llvm::Value *InterfaceSizeVal =
2727 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());;
Mike Stump4a3999f2009-09-09 13:00:44 +00002728
John McCall7f416cc2015-09-08 08:05:57 +00002729 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002730
John McCall7f416cc2015-09-08 08:05:57 +00002731 // Emit the base pointer.
2732 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2733
2734 // We don't necessarily build correct LLVM struct types for ObjC
2735 // interfaces, so we can't rely on GEP to do this scaling
2736 // correctly, so we need to cast to i8*. FIXME: is this actually
2737 // true? A lot of other things in the fragile ABI would break...
2738 llvm::Type *OrigBaseTy = Addr.getType();
2739 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2740
2741 // Do the GEP.
2742 CharUnits EltAlign =
2743 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2744 llvm::Value *EltPtr =
2745 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2746 Addr = Address(EltPtr, EltAlign);
2747
2748 // Cast back.
2749 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00002750 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2751 // If this is A[i] where A is an array, the frontend will have decayed the
2752 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2753 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2754 // "gep x, i" here. Emit one "gep A, 0, i".
2755 assert(Array->getType()->isArrayType() &&
2756 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002757 LValue ArrayLV;
2758 // For simple multidimensional array indexing, set the 'accessed' flag for
2759 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002760 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002761 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2762 else
2763 ArrayLV = EmitLValue(Array);
Craig Topper99e79272013-07-26 05:59:26 +00002764
Daniel Dunbar82634272011-04-01 00:49:43 +00002765 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00002766 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
2767 {CGM.getSize(CharUnits::Zero()), Idx},
2768 E->getType(),
2769 !getLangOpts().isSignedOverflowDefined());
2770 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002771 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002772 // The base must be a pointer; emit it with an estimate of its alignment.
2773 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2774 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
2775 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00002776 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002777
John McCall7f416cc2015-09-08 08:05:57 +00002778 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002779
John McCall7f416cc2015-09-08 08:05:57 +00002780 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00002781
Richard Smith9c6890a2012-11-01 22:30:59 +00002782 if (getLangOpts().ObjC1 &&
2783 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002784 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002785 setObjCGCLValueClass(getContext(), E, LV);
2786 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002787 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002788}
2789
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002790LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2791 bool IsLowerBound) {
2792 LValue Base;
2793 if (auto *ASE =
2794 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
2795 Base = EmitOMPArraySectionExpr(ASE, IsLowerBound);
2796 else
2797 Base = EmitLValue(E->getBase());
2798 QualType BaseTy = Base.getType();
2799 llvm::Value *Idx = nullptr;
2800 QualType ResultExprTy;
2801 if (auto *AT = getContext().getAsArrayType(BaseTy))
2802 ResultExprTy = AT->getElementType();
2803 else
2804 ResultExprTy = BaseTy->getPointeeType();
2805 if (IsLowerBound || (!IsLowerBound && E->getColonLoc().isInvalid())) {
2806 // Requesting lower bound or upper bound, but without provided length and
2807 // without ':' symbol for the default length -> length = 1.
2808 // Idx = LowerBound ?: 0;
2809 if (auto *LowerBound = E->getLowerBound()) {
2810 Idx = Builder.CreateIntCast(
2811 EmitScalarExpr(LowerBound), IntPtrTy,
2812 LowerBound->getType()->hasSignedIntegerRepresentation());
2813 } else
2814 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
2815 } else {
2816 // Try to emit length or lower bound as constant. If this is possible, 1 is
2817 // subtracted from constant length or lower bound. Otherwise, emit LLVM IR
2818 // (LB + Len) - 1.
2819 auto &C = CGM.getContext();
2820 auto *Length = E->getLength();
2821 llvm::APSInt ConstLength;
2822 if (Length) {
2823 // Idx = LowerBound + Length - 1;
2824 if (Length->isIntegerConstantExpr(ConstLength, C)) {
2825 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2826 Length = nullptr;
2827 }
2828 auto *LowerBound = E->getLowerBound();
2829 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
2830 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
2831 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
2832 LowerBound = nullptr;
2833 }
2834 if (!Length)
2835 --ConstLength;
2836 else if (!LowerBound)
2837 --ConstLowerBound;
2838
2839 if (Length || LowerBound) {
2840 auto *LowerBoundVal =
2841 LowerBound
2842 ? Builder.CreateIntCast(
2843 EmitScalarExpr(LowerBound), IntPtrTy,
2844 LowerBound->getType()->hasSignedIntegerRepresentation())
2845 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
2846 auto *LengthVal =
2847 Length
2848 ? Builder.CreateIntCast(
2849 EmitScalarExpr(Length), IntPtrTy,
2850 Length->getType()->hasSignedIntegerRepresentation())
2851 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
2852 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
2853 /*HasNUW=*/false,
2854 !getLangOpts().isSignedOverflowDefined());
2855 if (Length && LowerBound) {
2856 Idx = Builder.CreateSub(
2857 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
2858 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2859 }
2860 } else
2861 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
2862 } else {
2863 // Idx = ArraySize - 1;
2864 if (auto *VAT = C.getAsVariableArrayType(BaseTy)) {
2865 Length = VAT->getSizeExpr();
2866 if (Length->isIntegerConstantExpr(ConstLength, C))
2867 Length = nullptr;
2868 } else {
2869 auto *CAT = C.getAsConstantArrayType(BaseTy);
2870 ConstLength = CAT->getSize();
2871 }
2872 if (Length) {
2873 auto *LengthVal = Builder.CreateIntCast(
2874 EmitScalarExpr(Length), IntPtrTy,
2875 Length->getType()->hasSignedIntegerRepresentation());
2876 Idx = Builder.CreateSub(
2877 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
2878 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2879 } else {
2880 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2881 --ConstLength;
2882 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
2883 }
2884 }
2885 }
2886 assert(Idx);
2887
John McCall7f416cc2015-09-08 08:05:57 +00002888 llvm::Value *EltPtr;
2889 QualType FixedSizeEltType = ResultExprTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002890 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
2891 // The element count here is the total number of non-VLA elements.
2892 llvm::Value *numElements = getVLASize(VLA).first;
John McCall7f416cc2015-09-08 08:05:57 +00002893 FixedSizeEltType = getFixedSizeElementType(getContext(), VLA);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002894
2895 // Effectively, the multiply by the VLA size is part of the GEP.
2896 // GEP indexes are signed, and scaling an index isn't permitted to
2897 // signed-overflow, so we use the same semantics for our explicit
2898 // multiply. We suppress this if overflow is not undefined behavior.
2899 if (getLangOpts().isSignedOverflowDefined()) {
2900 Idx = Builder.CreateMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002901 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002902 } else {
2903 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002904 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002905 }
2906 } else if (BaseTy->isConstantArrayType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002907 llvm::Value *ArrayPtr = Base.getPointer();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002908 llvm::Value *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
2909 llvm::Value *Args[] = {Zero, Idx};
2910
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002911 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002912 EltPtr = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002913 else
John McCall7f416cc2015-09-08 08:05:57 +00002914 EltPtr = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002915 } else {
2916 // The base must be a pointer, which is not an aggregate. Emit it.
2917 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002918 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002919 else
John McCall7f416cc2015-09-08 08:05:57 +00002920 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002921 }
2922
John McCall7f416cc2015-09-08 08:05:57 +00002923 CharUnits EltAlign =
2924 Base.getAlignment().alignmentOfArrayElement(
2925 getContext().getTypeSizeInChars(FixedSizeEltType));
2926
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002927 // Limit the alignment to that of the result type.
John McCall7f416cc2015-09-08 08:05:57 +00002928 LValue LV = MakeAddrLValue(Address(EltPtr, EltAlign), ResultExprTy,
2929 Base.getAlignmentSource());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002930
2931 LV.getQuals().setAddressSpace(BaseTy.getAddressSpace());
2932
2933 return LV;
2934}
2935
Chris Lattner9e751ca2007-08-02 23:37:31 +00002936LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002937EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002938 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002939 LValue Base;
2940
2941 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002942 if (E->isArrow()) {
2943 // If it is a pointer to a vector, emit the address and form an lvalue with
2944 // it.
John McCall7f416cc2015-09-08 08:05:57 +00002945 AlignmentSource AlignSource;
2946 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00002947 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00002948 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002949 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002950 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002951 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2952 // emit the base as an lvalue.
2953 assert(E->getBase()->getType()->isVectorType());
2954 Base = EmitLValue(E->getBase());
2955 } else {
2956 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002957 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002958 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002959 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00002960
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002961 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00002962 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002963 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00002964 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
2965 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00002966 }
John McCall1553b192011-06-16 04:16:24 +00002967
2968 QualType type =
2969 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00002970
Nate Begemand3862152008-05-13 21:03:02 +00002971 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00002972 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002973 E->getEncodedElementAccess(Indices);
2974
2975 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00002976 llvm::Constant *CV =
2977 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002978 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00002979 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00002980 }
2981 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2982
2983 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002984 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002985
Chris Lattner595ba3a2012-01-30 06:20:36 +00002986 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2987 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002988 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00002989 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
2990 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00002991}
2992
Devang Patel30efa2e2007-10-23 20:28:39 +00002993LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00002994 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00002995
Chris Lattner4e4186b2007-12-02 18:52:07 +00002996 // 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 +00002997 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00002998 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00002999 AlignmentSource AlignSource;
3000 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003001 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003002 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3003 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003004 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003005 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003006
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003007 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003008 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003009 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003010 setObjCGCLValueClass(getContext(), E, LV);
3011 return LV;
3012 }
Craig Topper99e79272013-07-26 05:59:26 +00003013
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003014 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003015 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003016
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003017 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003018 return EmitFunctionDeclLValue(*this, E, FD);
3019
David Blaikie83d382b2011-09-23 05:06:16 +00003020 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003021}
Devang Patel30efa2e2007-10-23 20:28:39 +00003022
John McCalldec348f72013-05-03 07:33:41 +00003023/// Given that we are currently emitting a lambda, emit an l-value for
3024/// one of its members.
3025LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3026 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3027 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3028 QualType LambdaTagType =
3029 getContext().getTagDeclType(Field->getParent());
3030 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3031 return EmitLValueForField(LambdaLV, Field);
3032}
3033
John McCall7f416cc2015-09-08 08:05:57 +00003034/// Drill down to the storage of a field without walking into
3035/// reference types.
3036///
3037/// The resulting address doesn't necessarily have the right type.
3038static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3039 const FieldDecl *field) {
3040 const RecordDecl *rec = field->getParent();
3041
3042 unsigned idx =
3043 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3044
3045 CharUnits offset;
3046 // Adjust the alignment down to the given offset.
3047 // As a special case, if the LLVM field index is 0, we know that this
3048 // is zero.
3049 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3050 .getFieldOffset(field->getFieldIndex()) == 0) &&
3051 "LLVM field at index zero had non-zero offset?");
3052 if (idx != 0) {
3053 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3054 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3055 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3056 }
3057
3058 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3059}
3060
Eli Friedman7f1ff602012-04-16 03:54:45 +00003061LValue CodeGenFunction::EmitLValueForField(LValue base,
3062 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003063 AlignmentSource fieldAlignSource =
3064 getFieldAlignmentSource(base.getAlignmentSource());
3065
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003066 if (field->isBitField()) {
3067 const CGRecordLayout &RL =
3068 CGM.getTypes().getCGRecordLayout(field->getParent());
3069 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003070 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003071 unsigned Idx = RL.getLLVMFieldNo(field);
3072 if (Idx != 0)
3073 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003074 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3075 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003076 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003077 llvm::Type *FieldIntTy =
3078 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3079 if (Addr.getElementType() != FieldIntTy)
3080 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003081
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003082 QualType fieldType =
3083 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003084 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003085 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003086
John McCall53fcbd22011-02-26 08:07:02 +00003087 const RecordDecl *rec = field->getParent();
3088 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003089
John McCall53fcbd22011-02-26 08:07:02 +00003090 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3091
John McCall7f416cc2015-09-08 08:05:57 +00003092 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003093 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003094 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003095 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003096 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003097 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003098 // TODO: handle path-aware TBAA for union.
3099 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003100 } else {
3101 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003102 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003103
3104 // If this is a reference field, load the reference right now.
3105 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3106 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3107 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3108
Manman Renc451e572013-04-04 21:53:22 +00003109 // Loading the reference will disable path-aware TBAA.
3110 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003111 if (CGM.shouldUseTBAA()) {
3112 llvm::MDNode *tbaa;
3113 if (mayAlias)
3114 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3115 else
3116 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003117 if (tbaa)
3118 CGM.DecorateInstruction(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003119 }
3120
John McCall53fcbd22011-02-26 08:07:02 +00003121 mayAlias = false;
3122 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003123
3124 CharUnits alignment =
3125 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3126 addr = Address(load, alignment);
3127
3128 // Qualifiers on the struct don't apply to the referencee, and
3129 // we'll pick up CVR from the actual type later, so reset these
3130 // additional qualifiers now.
3131 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003132 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003133 }
Craig Topper99e79272013-07-26 05:59:26 +00003134
Chris Lattner13ee4f42011-07-10 05:34:54 +00003135 // Make sure that the address is pointing to the right type. This is critical
3136 // for both unions and structs. A union needs a bitcast, a struct element
3137 // will need a bitcast if the LLVM type laid out doesn't match the desired
3138 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003139 addr = Builder.CreateElementBitCast(addr,
3140 CGM.getTypes().ConvertTypeForMem(type),
3141 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003142
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003143 if (field->hasAttr<AnnotateAttr>())
3144 addr = EmitFieldAnnotations(field, addr);
3145
John McCall7f416cc2015-09-08 08:05:57 +00003146 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003147 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003148 if (TBAAPath) {
3149 const ASTRecordLayout &Layout =
3150 getContext().getASTRecordLayout(field->getParent());
3151 // Set the base type to be the base type of the base LValue and
3152 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003153 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3154 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003155 Layout.getFieldOffset(field->getFieldIndex()) /
3156 getContext().getCharWidth());
3157 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003158
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003159 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003160 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3161 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003162
3163 // Fields of may_alias structs act like 'char' for TBAA purposes.
3164 // FIXME: this should get propagated down through anonymous structs
3165 // and unions.
3166 if (mayAlias && LV.getTBAAInfo())
3167 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3168
Daniel Dunbarf166a522010-08-21 03:44:13 +00003169 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003170}
3171
Craig Topper99e79272013-07-26 05:59:26 +00003172LValue
3173CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003174 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003175 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003176
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003177 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003178 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003179
John McCall7f416cc2015-09-08 08:05:57 +00003180 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003181
John McCall7f416cc2015-09-08 08:05:57 +00003182 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003183 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003184 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003185
John McCall7f416cc2015-09-08 08:05:57 +00003186 // TODO: access-path TBAA?
3187 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3188 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003189}
3190
Chris Lattnerf53c0962010-09-06 00:11:41 +00003191LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003192 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003193 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3194 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003195 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003196 if (E->getType()->isVariablyModifiedType())
3197 // make sure to emit the VLA size.
3198 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003199
John McCall7f416cc2015-09-08 08:05:57 +00003200 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003201 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003202 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003203
Chad Rosier615ed1a2012-03-29 17:37:10 +00003204 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3205 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003206
3207 return Result;
3208}
3209
Richard Smithbb653bd2012-05-14 21:57:21 +00003210LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3211 if (!E->isGLValue())
3212 // Initializing an aggregate temporary in C++11: T{...}.
3213 return EmitAggExprToLValue(E);
3214
3215 // An lvalue initializer list must be initializing a reference.
3216 assert(E->getNumInits() == 1 && "reference init with multiple values");
3217 return EmitLValue(E->getInit(0));
3218}
3219
Richard Smithf3076ff2014-06-20 18:43:47 +00003220/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3221/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3222/// LValue is returned and the current block has been terminated.
3223static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3224 const Expr *Operand) {
3225 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3226 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3227 return None;
3228 }
3229
3230 return CGF.EmitLValue(Operand);
3231}
3232
John McCallc07a0c72011-02-17 10:25:35 +00003233LValue CodeGenFunction::
3234EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3235 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003236 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003237 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003238 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003239 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003240 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003241
Eli Friedman59954892012-01-25 05:04:17 +00003242 OpaqueValueMapping binding(*this, expr);
3243
John McCallc07a0c72011-02-17 10:25:35 +00003244 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003245 bool CondExprBool;
3246 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003247 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003248 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003249
Justin Bogneref512b92014-01-06 22:27:43 +00003250 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003251 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003252 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003253 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003254 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003255 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003256 }
3257
John McCallc07a0c72011-02-17 10:25:35 +00003258 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3259 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3260 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003261
3262 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003263 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003264
John McCall0a6bf2e2011-01-26 19:21:13 +00003265 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003266 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003267 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003268 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003269 Optional<LValue> lhs =
3270 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003271 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003272
Richard Smithf3076ff2014-06-20 18:43:47 +00003273 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003274 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003275
John McCallc07a0c72011-02-17 10:25:35 +00003276 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003277 if (lhs)
3278 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003279
John McCall0a6bf2e2011-01-26 19:21:13 +00003280 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003281 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003282 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003283 Optional<LValue> rhs =
3284 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003285 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003286 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003287 return EmitUnsupportedLValue(expr, "conditional operator");
3288 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003289
John McCallc07a0c72011-02-17 10:25:35 +00003290 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003291
Richard Smithf3076ff2014-06-20 18:43:47 +00003292 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003293 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003294 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003295 phi->addIncoming(lhs->getPointer(), lhsBlock);
3296 phi->addIncoming(rhs->getPointer(), rhsBlock);
3297 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3298 AlignmentSource alignSource =
3299 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3300 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003301 } else {
3302 assert((lhs || rhs) &&
3303 "both operands of glvalue conditional are throw-expressions?");
3304 return lhs ? *lhs : *rhs;
3305 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003306}
3307
Richard Smithbb653bd2012-05-14 21:57:21 +00003308/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3309/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003310/// otherwise if a cast is needed by the code generator in an lvalue context,
3311/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003312/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003313/// are permitted with aggregate result, including noop aggregate casts, and
3314/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003315LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003316 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003317 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003318 case CK_BitCast:
3319 case CK_ArrayToPointerDecay:
3320 case CK_FunctionToPointerDecay:
3321 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003322 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003323 case CK_IntegralToPointer:
3324 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003325 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003326 case CK_VectorSplat:
3327 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00003328 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003329 case CK_IntegralToFloating:
3330 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003331 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003332 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003333 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003334 case CK_FloatingComplexToReal:
3335 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003336 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003337 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003338 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003339 case CK_IntegralComplexToReal:
3340 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003341 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003342 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003343 case CK_DerivedToBaseMemberPointer:
3344 case CK_BaseToDerivedMemberPointer:
3345 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003346 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003347 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003348 case CK_ARCProduceObject:
3349 case CK_ARCConsumeObject:
3350 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003351 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003352 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003353 case CK_AddressSpaceConversion:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003354 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3355
3356 case CK_Dependent:
3357 llvm_unreachable("dependent cast kind in IR gen!");
3358
3359 case CK_BuiltinFnToFnPtr:
3360 llvm_unreachable("builtin functions are handled elsewhere");
3361
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003362 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003363 case CK_NonAtomicToAtomic:
3364 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003365 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003366
Anders Carlsson8a01a752011-04-11 02:03:26 +00003367 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003368 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003369 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003370 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003371 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003372 }
3373
John McCalle3027922010-08-25 11:45:40 +00003374 case CK_ConstructorConversion:
3375 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003376 case CK_CPointerToObjCPointerCast:
3377 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003378 case CK_NoOp:
3379 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003380 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003381
John McCalle3027922010-08-25 11:45:40 +00003382 case CK_UncheckedDerivedToBase:
3383 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003384 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003385 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003386 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003387
Anders Carlssond95f9602009-09-12 16:16:49 +00003388 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003389 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003390
Anders Carlssond95f9602009-09-12 16:16:49 +00003391 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003392 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003393 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3394 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003395
John McCall7f416cc2015-09-08 08:05:57 +00003396 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003397 }
John McCalle3027922010-08-25 11:45:40 +00003398 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003399 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003400 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003401 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003402 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003403
Anders Carlsson8c793172009-11-23 17:57:54 +00003404 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003405
Anders Carlsson8c793172009-11-23 17:57:54 +00003406 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003407 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003408 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003409 E->path_begin(), E->path_end(),
3410 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003411
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003412 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3413 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003414 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003415 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003416 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003417
Peter Collingbourned2926c92015-03-14 02:42:25 +00003418 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003419 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3420 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003421 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003422
John McCall7f416cc2015-09-08 08:05:57 +00003423 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003424 }
John McCalle3027922010-08-25 11:45:40 +00003425 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003426 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003427 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003428
Anders Carlsson50cb3212009-11-14 21:21:42 +00003429 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003430 Address V = Builder.CreateBitCast(LV.getAddress(),
3431 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003432
3433 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003434 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3435 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003436 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003437
John McCall7f416cc2015-09-08 08:05:57 +00003438 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003439 }
John McCalle3027922010-08-25 11:45:40 +00003440 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003441 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003442 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3443 ConvertType(E->getType()));
3444 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003445 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003446 case CK_ZeroToOCLEvent:
3447 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003448 }
Craig Topper99e79272013-07-26 05:59:26 +00003449
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003450 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003451}
3452
John McCall1bf58462011-02-16 08:02:54 +00003453LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003454 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003455 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003456}
3457
Eli Friedman7f1ff602012-04-16 03:54:45 +00003458RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003459 const FieldDecl *FD,
3460 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003461 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003462 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003463 switch (getEvaluationKind(FT)) {
3464 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003465 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003466 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003467 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003468 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003469 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003470 }
3471 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003472}
Douglas Gregorfe314812011-06-21 17:03:29 +00003473
Chris Lattnere47e4402007-06-01 18:02:12 +00003474//===--------------------------------------------------------------------===//
3475// Expression Emission
3476//===--------------------------------------------------------------------===//
3477
Craig Topper99e79272013-07-26 05:59:26 +00003478RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003479 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003480 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003481 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003482 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003483
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003484 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003485 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003486
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003487 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003488 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3489
Douglas Gregore0e96302011-09-06 21:41:04 +00003490 const Decl *TargetDecl = E->getCalleeDecl();
3491 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3492 if (unsigned builtinID = FD->getBuiltinID())
Peter Collingbournef7706832014-12-12 23:41:25 +00003493 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003494 }
3495
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003496 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00003497 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003498 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003499
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003500 if (const auto *PseudoDtor =
3501 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00003502 QualType DestroyedType = PseudoDtor->getDestroyedType();
Richard Smith9c6890a2012-11-01 22:30:59 +00003503 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003504 DestroyedType->isObjCLifetimeType() &&
3505 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
3506 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003507 // Automatic Reference Counting:
3508 // If the pseudo-expression names a retainable object with weak or
3509 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00003510 Expr *BaseExpr = PseudoDtor->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003511 Address BaseValue = Address::invalid();
John McCall31168b02011-06-15 23:02:42 +00003512 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00003513
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003514 // 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 +00003515 if (PseudoDtor->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003516 BaseValue = EmitPointerWithAlignment(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003517 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3518 BaseQuals = PTy->getPointeeType().getQualifiers();
3519 } else {
3520 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003521 BaseValue = BaseLV.getAddress();
3522 QualType BaseTy = BaseExpr->getType();
3523 BaseQuals = BaseTy.getQualifiers();
3524 }
Craig Topper99e79272013-07-26 05:59:26 +00003525
John McCall31168b02011-06-15 23:02:42 +00003526 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
3527 case Qualifiers::OCL_None:
3528 case Qualifiers::OCL_ExplicitNone:
3529 case Qualifiers::OCL_Autoreleasing:
3530 break;
Craig Topper99e79272013-07-26 05:59:26 +00003531
John McCall31168b02011-06-15 23:02:42 +00003532 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00003533 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003534 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00003535 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00003536 break;
3537
3538 case Qualifiers::OCL_Weak:
3539 EmitARCDestroyWeak(BaseValue);
3540 break;
3541 }
3542 } else {
3543 // C++ [expr.pseudo]p1:
3544 // The result shall only be used as the operand for the function call
3545 // operator (), and the result of such a call has type void. The only
3546 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00003547 // arrow.
John McCall31168b02011-06-15 23:02:42 +00003548 EmitScalarExpr(E->getCallee());
3549 }
Craig Topper99e79272013-07-26 05:59:26 +00003550
Craig Topper8a13c412014-05-21 05:09:00 +00003551 return RValue::get(nullptr);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003552 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003553
Chris Lattner2da04b32007-08-24 05:35:26 +00003554 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003555 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3556 TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00003557}
3558
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003559LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003560 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003561 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003562 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003563 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003564 return EmitLValue(E->getRHS());
3565 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003566
John McCalle3027922010-08-25 11:45:40 +00003567 if (E->getOpcode() == BO_PtrMemD ||
3568 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003569 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003570
John McCalla2342eb2010-12-05 02:00:02 +00003571 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003572
3573 // Note that in all of these cases, __block variables need the RHS
3574 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003575
3576 switch (getEvaluationKind(E->getType())) {
3577 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003578 switch (E->getLHS()->getType().getObjCLifetime()) {
3579 case Qualifiers::OCL_Strong:
3580 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3581
3582 case Qualifiers::OCL_Autoreleasing:
3583 return EmitARCStoreAutoreleasing(E).first;
3584
3585 // No reason to do any of these differently.
3586 case Qualifiers::OCL_None:
3587 case Qualifiers::OCL_ExplicitNone:
3588 case Qualifiers::OCL_Weak:
3589 break;
3590 }
3591
John McCalld0a30012010-12-06 06:10:02 +00003592 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003593 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003594 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003595 return LV;
3596 }
John McCall4f29b492010-11-16 23:07:28 +00003597
John McCall47fb9502013-03-07 21:37:08 +00003598 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003599 return EmitComplexAssignmentLValue(E);
3600
John McCall47fb9502013-03-07 21:37:08 +00003601 case TEK_Aggregate:
3602 return EmitAggExprToLValue(E);
3603 }
3604 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003605}
3606
Christopher Lambd91c3d42007-12-29 05:02:41 +00003607LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003608 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003609
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003610 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003611 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3612 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003613
David Majnemerced8bdf2015-02-25 17:36:15 +00003614 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003615 "Can't have a scalar return unless the return type is a "
3616 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003617
John McCall7f416cc2015-09-08 08:05:57 +00003618 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003619}
3620
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003621LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3622 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003623 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003624}
3625
Anders Carlsson3be22e22009-05-30 23:23:33 +00003626LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003627 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3628 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003629 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003630 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003631 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3632 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003633}
3634
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003635LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003636CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003637 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003638}
3639
John McCall7f416cc2015-09-08 08:05:57 +00003640Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3641 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3642 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003643}
3644
3645LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003646 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3647 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00003648}
3649
Mike Stumpc9b231c2009-11-15 08:09:41 +00003650LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003651CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003652 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003653 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003654 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003655 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3656 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3657 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003658}
3659
Eli Friedman5bc17122012-02-08 05:34:55 +00003660LValue
3661CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003662 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003663 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003664 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3665 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00003666}
3667
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003668LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003669 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003670
Anders Carlsson280e61f12010-06-21 20:59:55 +00003671 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003672 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3673 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003674
Alp Toker314cc812014-01-25 16:55:45 +00003675 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003676 "Can't have a scalar return unless the return type is a "
3677 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003678
John McCall7f416cc2015-09-08 08:05:57 +00003679 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003680}
3681
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003682LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003683 Address V =
3684 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3685 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003686}
3687
Daniel Dunbar722f4242009-04-22 05:08:15 +00003688llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003689 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003690 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003691}
3692
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003693LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3694 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003695 const ObjCIvarDecl *Ivar,
3696 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003697 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003698 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003699}
3700
3701LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003702 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00003703 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003704 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003705 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003706 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003707 if (E->isArrow()) {
3708 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003709 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003710 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003711 } else {
3712 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00003713 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003714 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003715 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003716 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003717
Craig Topper99e79272013-07-26 05:59:26 +00003718 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003719 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3720 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003721 setObjCGCLValueClass(getContext(), E, LV);
3722 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003723}
3724
Chris Lattnera4185c52009-04-25 19:35:26 +00003725LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003726 // Can only get l-value for message expression returning aggregate type
3727 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00003728 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3729 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00003730}
3731
Anders Carlsson0435ed52009-12-24 19:08:58 +00003732RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003733 const CallExpr *E, ReturnValueSlot ReturnValue,
Peter Collingbournef7706832014-12-12 23:41:25 +00003734 const Decl *TargetDecl, llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003735 // Get the actual function type. The callee type will always be a pointer to
3736 // function type or a block pointer type.
3737 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003738 "Call must have function pointer type!");
3739
John McCall6fd4c232009-10-23 08:22:42 +00003740 CalleeType = getContext().getCanonicalType(CalleeType);
3741
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003742 const auto *FnType =
3743 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00003744
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003745 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003746 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3747 if (llvm::Constant *PrefixSig =
3748 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003749 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003750 llvm::Constant *FTRTTIConst =
3751 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
3752 llvm::Type *PrefixStructTyElems[] = {
3753 PrefixSig->getType(),
3754 FTRTTIConst->getType()
3755 };
3756 llvm::StructType *PrefixStructTy = llvm::StructType::get(
3757 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
3758
3759 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
3760 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
3761 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003762 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00003763 llvm::Value *CalleeSig =
3764 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003765 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
3766
3767 llvm::BasicBlock *Cont = createBasicBlock("cont");
3768 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
3769 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
3770
3771 EmitBlock(TypeCheck);
3772 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003773 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003774 llvm::Value *CalleeRTTI =
3775 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003776 llvm::Value *CalleeRTTIMatch =
3777 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
3778 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003779 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003780 EmitCheckTypeDescriptor(CalleeType)
3781 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003782 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
3783 "function_type_mismatch", StaticData, Callee);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003784
3785 Builder.CreateBr(Cont);
3786 EmitBlock(Cont);
3787 }
3788 }
3789
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00003790 // If we are checking indirect calls and this call is indirect, check that the
3791 // function pointer is a member of the bit set for the function type.
3792 if (SanOpts.has(SanitizerKind::CFIICall) &&
3793 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3794 SanitizerScope SanScope(this);
3795
3796 llvm::Value *BitSetName = llvm::MetadataAsValue::get(
3797 getLLVMContext(),
3798 CGM.CreateMetadataIdentifierForType(QualType(FnType, 0)));
3799
3800 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy);
3801 llvm::Value *BitSetTest =
3802 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
3803 {CastedCallee, BitSetName});
3804
3805 llvm::Constant *StaticData[] = {
3806 EmitCheckSourceLocation(E->getLocStart()),
3807 EmitCheckTypeDescriptor(QualType(FnType, 0)),
3808 };
3809 EmitCheck(std::make_pair(BitSetTest, SanitizerKind::CFIICall),
3810 "cfi_bad_icall", StaticData, CastedCallee);
3811 }
3812
Daniel Dunbarc722b852008-08-30 03:02:31 +00003813 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00003814 if (Chain)
3815 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
3816 CGM.getContext().VoidPtrTy);
David Blaikief05779e2015-07-21 18:37:18 +00003817 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
3818 E->getDirectCallee(), /*ParamsToSkip*/ 0);
Daniel Dunbarc722b852008-08-30 03:02:31 +00003819
Peter Collingbournef7706832014-12-12 23:41:25 +00003820 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
3821 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00003822
3823 // C99 6.5.2.2p6:
3824 // If the expression that denotes the called function has a type
3825 // that does not include a prototype, [the default argument
3826 // promotions are performed]. If the number of arguments does not
3827 // equal the number of parameters, the behavior is undefined. If
3828 // the function is defined with a type that includes a prototype,
3829 // and either the prototype ends with an ellipsis (, ...) or the
3830 // types of the arguments after promotion are not compatible with
3831 // the types of the parameters, the behavior is undefined. If the
3832 // function is defined with a type that does not include a
3833 // prototype, and the types of the arguments after promotion are
3834 // not compatible with those of the parameters after promotion,
3835 // the behavior is undefined [except in some trivial cases].
3836 // That is, in the general case, we should assume that a call
3837 // through an unprototyped function type works like a *non-variadic*
3838 // call. The way we make this work is to cast to the exact type
3839 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00003840 //
3841 // Chain calls use this same code path to add the invisible chain parameter
3842 // to the function type.
3843 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00003844 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00003845 CalleeTy = CalleeTy->getPointerTo();
3846 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3847 }
3848
3849 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00003850}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003851
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003852LValue CodeGenFunction::
3853EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003854 Address BaseAddr = Address::invalid();
3855 if (E->getOpcode() == BO_PtrMemI) {
3856 BaseAddr = EmitPointerWithAlignment(E->getLHS());
3857 } else {
3858 BaseAddr = EmitLValue(E->getLHS()).getAddress();
3859 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003860
John McCallc134eb52010-08-31 21:07:20 +00003861 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3862
3863 const MemberPointerType *MPT
3864 = E->getRHS()->getType()->getAs<MemberPointerType>();
3865
John McCall7f416cc2015-09-08 08:05:57 +00003866 AlignmentSource AlignSource;
3867 Address MemberAddr =
3868 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
3869 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00003870
John McCall7f416cc2015-09-08 08:05:57 +00003871 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003872}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003873
John McCall47fb9502013-03-07 21:37:08 +00003874/// Given the address of a temporary variable, produce an r-value of
3875/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00003876RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003877 QualType type,
3878 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00003879 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00003880 switch (getEvaluationKind(type)) {
3881 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003882 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003883 case TEK_Aggregate:
3884 return lvalue.asAggregateRValue();
3885 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003886 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003887 }
3888 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003889}
3890
Duncan Sandse81111c2012-04-10 08:23:07 +00003891void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003892 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003893 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003894 return;
3895
Duncan Sands65229ed2012-04-16 16:29:47 +00003896 llvm::MDBuilder MDHelper(getLLVMContext());
3897 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003898
Duncan Sands6fc46192012-04-14 12:37:26 +00003899 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003900}
John McCallfe96e0b2011-11-06 09:01:30 +00003901
3902namespace {
3903 struct LValueOrRValue {
3904 LValue LV;
3905 RValue RV;
3906 };
3907}
3908
3909static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3910 const PseudoObjectExpr *E,
3911 bool forLValue,
3912 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003913 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00003914
3915 // Find the result expression, if any.
3916 const Expr *resultExpr = E->getResultExpr();
3917 LValueOrRValue result;
3918
3919 for (PseudoObjectExpr::const_semantics_iterator
3920 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3921 const Expr *semantic = *i;
3922
3923 // If this semantic expression is an opaque value, bind it
3924 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003925 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00003926
3927 // If this is the result expression, we may need to evaluate
3928 // directly into the slot.
3929 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3930 OVMA opaqueData;
3931 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00003932 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00003933 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3934
John McCall7f416cc2015-09-08 08:05:57 +00003935 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
3936 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00003937 opaqueData = OVMA::bind(CGF, ov, LV);
3938 result.RV = slot.asRValue();
3939
3940 // Otherwise, emit as normal.
3941 } else {
3942 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3943
3944 // If this is the result, also evaluate the result now.
3945 if (ov == resultExpr) {
3946 if (forLValue)
3947 result.LV = CGF.EmitLValue(ov);
3948 else
3949 result.RV = CGF.EmitAnyExpr(ov, slot);
3950 }
3951 }
3952
3953 opaques.push_back(opaqueData);
3954
3955 // Otherwise, if the expression is the result, evaluate it
3956 // and remember the result.
3957 } else if (semantic == resultExpr) {
3958 if (forLValue)
3959 result.LV = CGF.EmitLValue(semantic);
3960 else
3961 result.RV = CGF.EmitAnyExpr(semantic, slot);
3962
3963 // Otherwise, evaluate the expression in an ignored context.
3964 } else {
3965 CGF.EmitIgnoredExpr(semantic);
3966 }
3967 }
3968
3969 // Unbind all the opaques now.
3970 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3971 opaques[i].unbind(CGF);
3972
3973 return result;
3974}
3975
3976RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3977 AggValueSlot slot) {
3978 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3979}
3980
3981LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3982 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3983}