blob: e918cd81f0b1263d75319266f0b7f7571443d735 [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();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +000089 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +000090}
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.
John McCall460ce582015-10-22 18:38:17 +0000205 if (auto Lifetime = M->getType().getObjCLifetime()) {
206 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000207 case Qualifiers::OCL_None:
208 case Qualifiers::OCL_ExplicitNone:
209 // Carry on to normal cleanup handling.
210 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000211
Richard Smith736a9472013-06-12 20:42:33 +0000212 case Qualifiers::OCL_Autoreleasing:
213 // Nothing to do; cleaned up by an autorelease pool.
214 return;
215
216 case Qualifiers::OCL_Strong:
217 case Qualifiers::OCL_Weak:
218 switch (StorageDuration Duration = M->getStorageDuration()) {
219 case SD_Static:
220 // Note: we intentionally do not register a cleanup to release
221 // the object on program termination.
222 return;
223
224 case SD_Thread:
225 // FIXME: We should probably register a cleanup in this case.
226 return;
227
228 case SD_Automatic:
229 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000230 CodeGenFunction::Destroyer *Destroy;
231 CleanupKind CleanupKind;
232 if (Lifetime == Qualifiers::OCL_Strong) {
233 const ValueDecl *VD = M->getExtendingDecl();
234 bool Precise =
235 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
236 CleanupKind = CGF.getARCCleanupKind();
237 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
238 : &CodeGenFunction::destroyARCStrongImprecise;
239 } else {
240 // __weak objects always get EH cleanups; otherwise, exceptions
241 // could cause really nasty crashes instead of mere leaks.
242 CleanupKind = NormalAndEHCleanup;
243 Destroy = &CodeGenFunction::destroyARCWeak;
244 }
245 if (Duration == SD_FullExpression)
246 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000247 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000248 CleanupKind & EHCleanup);
249 else
250 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000251 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000252 *Destroy, CleanupKind & EHCleanup);
253 return;
254
255 case SD_Dynamic:
256 llvm_unreachable("temporary cannot have dynamic storage duration");
257 }
258 llvm_unreachable("unknown storage duration");
259 }
260 }
261
Craig Topper8a13c412014-05-21 05:09:00 +0000262 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000263 if (const RecordType *RT =
264 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
265 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000266 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000267 if (!ClassDecl->hasTrivialDestructor())
268 ReferenceTemporaryDtor = ClassDecl->getDestructor();
269 }
270
271 if (!ReferenceTemporaryDtor)
272 return;
273
274 // Call the destructor for the temporary.
275 switch (M->getStorageDuration()) {
276 case SD_Static:
277 case SD_Thread: {
278 llvm::Constant *CleanupFn;
279 llvm::Constant *CleanupArg;
280 if (E->getType()->isArrayType()) {
281 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000282 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000283 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
284 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000285 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
286 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000287 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
288 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000289 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000290 }
291 CGF.CGM.getCXXABI().registerGlobalDtor(
292 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
293 break;
294 }
295
296 case SD_FullExpression:
297 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
298 CodeGenFunction::destroyCXXObject,
299 CGF.getLangOpts().Exceptions);
300 break;
301
302 case SD_Automatic:
303 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
304 ReferenceTemporary, E->getType(),
305 CodeGenFunction::destroyCXXObject,
306 CGF.getLangOpts().Exceptions);
307 break;
308
309 case SD_Dynamic:
310 llvm_unreachable("temporary cannot have dynamic storage duration");
311 }
312}
313
John McCall7f416cc2015-09-08 08:05:57 +0000314static Address
Richard Smith736a9472013-06-12 20:42:33 +0000315createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000316 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000317 switch (M->getStorageDuration()) {
318 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000319 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000320 // If we have a constant temporary array or record try to promote it into a
321 // constant global under the same rules a normal constant would've been
322 // promoted. This is easier on the optimizer and generally emits fewer
323 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000324 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000325 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000326 (Ty->isArrayType() || Ty->isRecordType()) &&
327 CGF.CGM.isTypeConstant(Ty, true))
328 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000329 auto *GV = new llvm::GlobalVariable(
330 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
331 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000332 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
333 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000334 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000335 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000336 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000337 return CGF.CreateMemTemp(Ty, "ref.tmp");
338 }
Richard Smith736a9472013-06-12 20:42:33 +0000339 case SD_Thread:
340 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000341 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000342
343 case SD_Dynamic:
344 llvm_unreachable("temporary can't have dynamic storage duration");
345 }
346 llvm_unreachable("unknown storage duration");
347}
348
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000349LValue CodeGenFunction::
350EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000351 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000352
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000353 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
354 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000355 auto ownership = M->getType().getObjCLifetime();
356 if (ownership != Qualifiers::OCL_None &&
357 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000358 Address Object = createReferenceTemporary(*this, M, E);
359 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
360 Object = Address(llvm::ConstantExpr::getBitCast(Var,
361 ConvertTypeForMem(E->getType())
362 ->getPointerTo(Object.getAddressSpace())),
363 Object.getAlignment());
Richard Smitha509f2f2013-06-14 03:07:01 +0000364 // We should not have emitted the initializer for this temporary as a
365 // constant.
366 assert(!Var->hasInitializer());
367 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
368 }
John McCall7f416cc2015-09-08 08:05:57 +0000369 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
370 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000371
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000372 switch (getEvaluationKind(E->getType())) {
373 default: llvm_unreachable("expected scalar or aggregate expression");
374 case TEK_Scalar:
375 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
376 break;
377 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000378 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000379 E->getType().getQualifiers(),
380 AggValueSlot::IsDestructed,
381 AggValueSlot::DoesNotNeedGCBarriers,
382 AggValueSlot::IsNotAliased));
383 break;
384 }
385 }
Richard Smith736a9472013-06-12 20:42:33 +0000386
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000387 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000388 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000389 }
390
Richard Smithf3fabd22013-06-03 00:17:11 +0000391 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000392 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000393 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
394
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000395 for (const auto &Ignored : CommaLHSs)
396 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000397
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000398 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000399 if (opaque->getType()->isRecordType()) {
400 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000401 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000402 }
403 }
404
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000405 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000406 Address Object = createReferenceTemporary(*this, M, E);
407 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
408 Object = Address(llvm::ConstantExpr::getBitCast(
409 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
410 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000411 // If the temporary is a global and has a constant initializer or is a
412 // constant temporary that we promoted to a global, we may have already
413 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000414 if (!Var->hasInitializer()) {
415 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
416 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
417 }
418 } else {
419 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
420 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000421 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000422
Richard Smith736a9472013-06-12 20:42:33 +0000423 // Perform derived-to-base casts and/or field accesses, to get from the
424 // temporary object we created (and, potentially, for which we extended
425 // the lifetime) to the subobject we're binding the reference to.
426 for (unsigned I = Adjustments.size(); I != 0; --I) {
427 SubobjectAdjustment &Adjustment = Adjustments[I-1];
428 switch (Adjustment.Kind) {
429 case SubobjectAdjustment::DerivedToBaseAdjustment:
430 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000431 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
432 Adjustment.DerivedToBase.BasePath->path_begin(),
433 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000434 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000435 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000436
Richard Smith736a9472013-06-12 20:42:33 +0000437 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000438 LValue LV = MakeAddrLValue(Object, E->getType(),
439 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000440 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000441 assert(LV.isSimple() &&
442 "materialized temporary field is not a simple lvalue");
443 Object = LV.getAddress();
444 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000445 }
446
Richard Smith736a9472013-06-12 20:42:33 +0000447 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000448 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000449 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
450 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000451 break;
452 }
453 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000454 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000455
John McCall7f416cc2015-09-08 08:05:57 +0000456 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000457}
458
459RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000460CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
461 // Emit the expression as an lvalue.
462 LValue LV = EmitLValue(E);
463 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000464 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000465
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000466 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000467 // C++11 [dcl.ref]p5 (as amended by core issue 453):
468 // If a glvalue to which a reference is directly bound designates neither
469 // an existing object or function of an appropriate type nor a region of
470 // storage of suitable size and alignment to contain an object of the
471 // reference's type, the behavior is undefined.
472 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000473 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000474 }
John McCall8680f872010-07-21 06:29:51 +0000475
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000476 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000477}
478
479
Mike Stump4a3999f2009-09-09 13:00:44 +0000480/// getAccessedFieldNo - Given an encoded value and a result number, return the
481/// input field number being accessed.
482unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000483 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000484 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
485 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000486}
487
Richard Smith4d3110a2012-10-25 02:14:12 +0000488/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
489static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
490 llvm::Value *High) {
491 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
492 llvm::Value *K47 = Builder.getInt64(47);
493 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
494 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
495 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
496 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
497 return Builder.CreateMul(B1, KMul);
498}
499
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000500bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000501 return SanOpts.has(SanitizerKind::Null) |
502 SanOpts.has(SanitizerKind::Alignment) |
503 SanOpts.has(SanitizerKind::ObjectSize) |
504 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000505}
506
Richard Smithe30752c2012-10-09 19:52:38 +0000507void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000508 llvm::Value *Ptr, QualType Ty,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000509 CharUnits Alignment, bool SkipNullCheck) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000510 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000511 return;
512
Richard Smith2d8b2942012-11-01 07:22:08 +0000513 // Don't check pointers outside the default address space. The null check
514 // isn't correct, the object-size check isn't supported by LLVM, and we can't
515 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000516 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000517 return;
518
Alexey Samsonov24cad992014-07-17 18:46:27 +0000519 SanitizerScope SanScope(this);
520
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000521 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000522 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000523
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000524 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
525 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000526 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
527 !SkipNullCheck) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000528 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000529 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000530
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000531 if (AllowNullPointers) {
532 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000533 // Skip the remaining checks in that case.
534 Done = createBasicBlock("null");
535 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000536 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000537 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000538 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000539 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000540 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000541 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000542
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000543 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000544 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000545
Richard Smith69d0d262012-08-24 00:54:33 +0000546 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000547 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000548 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000549 // FIXME: Get object address space
550 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
551 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000552 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000553 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000554 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000555 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000556 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000557 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000558 }
Richard Smith69d0d262012-08-24 00:54:33 +0000559
Richard Smithb1b0ab42012-11-05 22:21:05 +0000560 uint64_t AlignVal = 0;
561
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000562 if (SanOpts.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000563 AlignVal = Alignment.getQuantity();
564 if (!Ty->isIncompleteType() && !AlignVal)
565 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
566
Richard Smith69d0d262012-08-24 00:54:33 +0000567 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000568 if (AlignVal) {
569 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000570 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000571 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
572 llvm::Value *Aligned =
573 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000574 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000575 }
Richard Smith69d0d262012-08-24 00:54:33 +0000576 }
577
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000578 if (Checks.size() > 0) {
Richard Smithe30752c2012-10-09 19:52:38 +0000579 llvm::Constant *StaticData[] = {
580 EmitCheckSourceLocation(Loc),
581 EmitCheckTypeDescriptor(Ty),
582 llvm::ConstantInt::get(SizeTy, AlignVal),
583 llvm::ConstantInt::get(Int8Ty, TCK)
584 };
John McCall7f416cc2015-09-08 08:05:57 +0000585 EmitCheck(Checks, "type_mismatch", StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000586 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000587
Richard Smithb1b0ab42012-11-05 22:21:05 +0000588 // If possible, check that the vptr indicates that there is a subobject of
589 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000590 //
591 // C++11 [basic.life]p5,6:
592 // [For storage which does not refer to an object within its lifetime]
593 // The program has undefined behavior if:
594 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000595 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000596 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000597 if (SanOpts.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000598 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000599 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
600 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000601 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000602 // Compute a hash of the mangled name of the type.
603 //
604 // FIXME: This is not guaranteed to be deterministic! Move to a
605 // fingerprinting mechanism once LLVM provides one. For the time
606 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000607 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000608 llvm::raw_svector_ostream Out(MangledName);
609 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
610 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000611
Alexey Samsonov84856012014-07-10 22:34:19 +0000612 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000613 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
614 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000615 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000616
Alexey Samsonov84856012014-07-10 22:34:19 +0000617 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
618 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
619 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000620 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000621 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
622 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000623
Alexey Samsonov84856012014-07-10 22:34:19 +0000624 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
625 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000626
Alexey Samsonov84856012014-07-10 22:34:19 +0000627 // Look the hash up in our cache.
628 const int CacheSize = 128;
629 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
630 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
631 "__ubsan_vptr_type_cache");
632 llvm::Value *Slot = Builder.CreateAnd(Hash,
633 llvm::ConstantInt::get(IntPtrTy,
634 CacheSize-1));
635 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
636 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000637 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
638 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000639
640 // If the hash isn't in the cache, call a runtime handler to perform the
641 // hard work of checking whether the vptr is for an object of the right
642 // type. This will either fill in the cache and return, or produce a
643 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000644 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000645 llvm::Constant *StaticData[] = {
646 EmitCheckSourceLocation(Loc),
647 EmitCheckTypeDescriptor(Ty),
648 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
649 llvm::ConstantInt::get(Int8Ty, TCK)
650 };
John McCall7f416cc2015-09-08 08:05:57 +0000651 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000652 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
653 "dynamic_type_cache_miss", StaticData, DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000654 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000655 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000656
657 if (Done) {
658 Builder.CreateBr(Done);
659 EmitBlock(Done);
660 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000661}
Chris Lattner4647a212007-08-31 22:49:20 +0000662
Richard Smith539e4a72013-02-23 02:53:19 +0000663/// Determine whether this expression refers to a flexible array member in a
664/// struct. We disable array bounds checks for such members.
665static bool isFlexibleArrayMemberExpr(const Expr *E) {
666 // For compatibility with existing code, we treat arrays of length 0 or
667 // 1 as flexible array members.
668 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000669 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000670 if (CAT->getSize().ugt(1))
671 return false;
672 } else if (!isa<IncompleteArrayType>(AT))
673 return false;
674
675 E = E->IgnoreParens();
676
677 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000678 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000679 // FIXME: If the base type of the member expr is not FD->getParent(),
680 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000681 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000682 RecordDecl::field_iterator FI(
683 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
684 return ++FI == FD->getParent()->field_end();
685 }
686 }
687
688 return false;
689}
690
691/// If Base is known to point to the start of an array, return the length of
692/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000693static llvm::Value *getArrayIndexingBound(
694 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000695 // For the vector indexing extension, the bound is the number of elements.
696 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
697 IndexedType = Base->getType();
698 return CGF.Builder.getInt32(VT->getNumElements());
699 }
700
701 Base = Base->IgnoreParens();
702
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000703 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000704 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
705 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
706 IndexedType = CE->getSubExpr()->getType();
707 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000708 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000709 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000710 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000711 return CGF.getVLASize(VAT).first;
712 }
713 }
714
Craig Topper8a13c412014-05-21 05:09:00 +0000715 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000716}
717
718void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
719 llvm::Value *Index, QualType IndexType,
720 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000721 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000722 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000723 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000724
Richard Smith539e4a72013-02-23 02:53:19 +0000725 QualType IndexedType;
726 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
727 if (!Bound)
728 return;
729
730 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
731 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
732 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
733
734 llvm::Constant *StaticData[] = {
735 EmitCheckSourceLocation(E->getExprLoc()),
736 EmitCheckTypeDescriptor(IndexedType),
737 EmitCheckTypeDescriptor(IndexType)
738 };
739 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
740 : Builder.CreateICmpULE(IndexVal, BoundVal);
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000741 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
742 StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000743}
744
Chris Lattner116ce8f2010-01-09 21:40:03 +0000745
Chris Lattner116ce8f2010-01-09 21:40:03 +0000746CodeGenFunction::ComplexPairTy CodeGenFunction::
747EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
748 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000749 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000750
Chris Lattner116ce8f2010-01-09 21:40:03 +0000751 llvm::Value *NextVal;
752 if (isa<llvm::IntegerType>(InVal.first->getType())) {
753 uint64_t AmountVal = isInc ? 1 : -1;
754 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000755
Chris Lattner116ce8f2010-01-09 21:40:03 +0000756 // Add the inc/dec to the real part.
757 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
758 } else {
759 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
760 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
761 if (!isInc)
762 FVal.changeSign();
763 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000764
Chris Lattner116ce8f2010-01-09 21:40:03 +0000765 // Add the inc/dec to the real part.
766 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
767 }
Craig Topper99e79272013-07-26 05:59:26 +0000768
Chris Lattner116ce8f2010-01-09 21:40:03 +0000769 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000770
Chris Lattner116ce8f2010-01-09 21:40:03 +0000771 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000772 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000773
Chris Lattner116ce8f2010-01-09 21:40:03 +0000774 // If this is a postinc, return the value read from memory, otherwise use the
775 // updated value.
776 return isPre ? IncVal : InVal;
777}
778
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000779void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
780 CodeGenFunction *CGF) {
781 // Bind VLAs in the cast type.
782 if (CGF && E->getType()->isVariablyModifiedType())
783 CGF->EmitVariablyModifiedType(E->getType());
784
785 if (CGDebugInfo *DI = getModuleDebugInfo())
786 DI->EmitExplicitCastType(E->getType());
787}
788
Chris Lattnera45c5af2007-06-02 19:47:04 +0000789//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000790// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000791//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000792
John McCall7f416cc2015-09-08 08:05:57 +0000793/// EmitPointerWithAlignment - Given an expression of pointer type, try to
794/// derive a more accurate bound on the alignment of the pointer.
795Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
796 AlignmentSource *Source) {
797 // We allow this with ObjC object pointers because of fragile ABIs.
798 assert(E->getType()->isPointerType() ||
799 E->getType()->isObjCObjectPointerType());
800 E = E->IgnoreParens();
801
802 // Casts:
803 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000804 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
805 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000806
807 switch (CE->getCastKind()) {
808 // Non-converting casts (but not C's implicit conversion from void*).
809 case CK_BitCast:
810 case CK_NoOp:
811 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
812 if (PtrTy->getPointeeType()->isVoidType())
813 break;
814
815 AlignmentSource InnerSource;
816 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
817 if (Source) *Source = InnerSource;
818
819 // If this is an explicit bitcast, and the source l-value is
820 // opaque, honor the alignment of the casted-to type.
821 if (isa<ExplicitCastExpr>(CE) &&
John McCall7f416cc2015-09-08 08:05:57 +0000822 InnerSource != AlignmentSource::Decl) {
823 Addr = Address(Addr.getPointer(),
824 getNaturalPointeeTypeAlignment(E->getType(), Source));
825 }
826
Peter Collingbourne574975e2016-01-14 02:49:48 +0000827 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
828 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000829 if (auto PT = E->getType()->getAs<PointerType>())
830 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
831 /*MayBeNull=*/true,
832 CodeGenFunction::CFITCK_UnrelatedCast,
833 CE->getLocStart());
834 }
835
John McCall7f416cc2015-09-08 08:05:57 +0000836 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
837 }
838 break;
839
840 // Array-to-pointer decay.
841 case CK_ArrayToPointerDecay:
842 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
843
844 // Derived-to-base conversions.
845 case CK_UncheckedDerivedToBase:
846 case CK_DerivedToBase: {
847 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
848 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
849 return GetAddressOfBaseClass(Addr, Derived,
850 CE->path_begin(), CE->path_end(),
851 ShouldNullCheckClassCastValue(CE),
852 CE->getExprLoc());
853 }
854
855 // TODO: Is there any reason to treat base-to-derived conversions
856 // specially?
857 default:
858 break;
859 }
860 }
861
862 // Unary &.
863 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
864 if (UO->getOpcode() == UO_AddrOf) {
865 LValue LV = EmitLValue(UO->getSubExpr());
866 if (Source) *Source = LV.getAlignmentSource();
867 return LV.getAddress();
868 }
869 }
870
871 // TODO: conditional operators, comma.
872
873 // Otherwise, use the alignment of the type.
874 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
875 return Address(EmitScalarExpr(E), Align);
876}
877
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000878RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000879 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000880 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000881
882 switch (getEvaluationKind(Ty)) {
883 case TEK_Complex: {
884 llvm::Type *EltTy =
885 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000886 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000887 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000888 }
Craig Topper99e79272013-07-26 05:59:26 +0000889
Chris Lattner65526f02010-08-23 05:26:13 +0000890 // If this is a use of an undefined aggregate type, the aggregate must have an
891 // identifiable address. Just because the contents of the value are undefined
892 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000893 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000894 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000895 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000896 }
John McCall47fb9502013-03-07 21:37:08 +0000897
898 case TEK_Scalar:
899 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
900 }
901 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000902}
903
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000904RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
905 const char *Name) {
906 ErrorUnsupported(E, Name);
907 return GetUndefRValue(E->getType());
908}
909
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000910LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
911 const char *Name) {
912 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000913 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000914 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
915 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000916}
917
Richard Smith4d1458e2012-09-08 02:08:36 +0000918LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000919 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000920 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000921 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
922 else
923 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000924 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000925 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000926 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000927 return LV;
928}
929
Chris Lattner8394d792007-06-05 20:53:16 +0000930/// EmitLValue - Emit code to compute a designator that specifies the location
931/// of the expression.
932///
Mike Stump4a3999f2009-09-09 13:00:44 +0000933/// This can return one of two things: a simple address or a bitfield reference.
934/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
935/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000936///
Mike Stump4a3999f2009-09-09 13:00:44 +0000937/// If this returns a bitfield reference, nothing about the pointee type of the
938/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000939///
Mike Stump4a3999f2009-09-09 13:00:44 +0000940/// If this returns a normal address, and if the lvalue's C type is fixed size,
941/// this method guarantees that the returned pointer type will point to an LLVM
942/// type of the same size of the lvalue's type. If the lvalue has a variable
943/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000944///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000945LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000946 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000947 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000948 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000949
John McCallc109a252011-11-07 03:59:57 +0000950 case Expr::ObjCPropertyRefExprClass:
951 llvm_unreachable("cannot emit a property reference directly");
952
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000953 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000954 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000955 case Expr::ObjCIsaExprClass:
956 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000957 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000958 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000959 case Expr::CompoundAssignOperatorClass: {
960 QualType Ty = E->getType();
961 if (const AtomicType *AT = Ty->getAs<AtomicType>())
962 Ty = AT->getValueType();
963 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000964 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
965 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000966 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000967 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000968 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000969 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000970 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000971 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000972 case Expr::VAArgExprClass:
973 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000974 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000975 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000976 case Expr::ParenExprClass:
977 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000978 case Expr::GenericSelectionExprClass:
979 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000980 case Expr::PredefinedExprClass:
981 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000982 case Expr::StringLiteralClass:
983 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000984 case Expr::ObjCEncodeExprClass:
985 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000986 case Expr::PseudoObjectExprClass:
987 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000988 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000989 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000990 case Expr::CXXTemporaryObjectExprClass:
991 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000992 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
993 case Expr::CXXBindTemporaryExprClass:
994 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000995 case Expr::CXXUuidofExprClass:
996 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000997 case Expr::LambdaExprClass:
998 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000999
1000 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001001 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001002 enterFullExpression(cleanups);
1003 RunCleanupsScope Scope(*this);
1004 return EmitLValue(cleanups->getSubExpr());
1005 }
1006
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001007 case Expr::CXXDefaultArgExprClass:
1008 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001009 case Expr::CXXDefaultInitExprClass: {
1010 CXXDefaultInitExprScope Scope(*this);
1011 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1012 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001013 case Expr::CXXTypeidExprClass:
1014 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001015
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001016 case Expr::ObjCMessageExprClass:
1017 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001018 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001019 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001020 case Expr::StmtExprClass:
1021 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001022 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001023 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001024 case Expr::ArraySubscriptExprClass:
1025 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001026 case Expr::OMPArraySectionExprClass:
1027 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001028 case Expr::ExtVectorElementExprClass:
1029 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001030 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001031 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001032 case Expr::CompoundLiteralExprClass:
1033 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001034 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001035 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001036 case Expr::BinaryConditionalOperatorClass:
1037 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001038 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001039 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001040 case Expr::OpaqueValueExprClass:
1041 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001042 case Expr::SubstNonTypeTemplateParmExprClass:
1043 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001044 case Expr::ImplicitCastExprClass:
1045 case Expr::CStyleCastExprClass:
1046 case Expr::CXXFunctionalCastExprClass:
1047 case Expr::CXXStaticCastExprClass:
1048 case Expr::CXXDynamicCastExprClass:
1049 case Expr::CXXReinterpretCastExprClass:
1050 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001051 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001052 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001053
Douglas Gregorfe314812011-06-21 17:03:29 +00001054 case Expr::MaterializeTemporaryExprClass:
1055 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001056 }
1057}
1058
John McCall71335052012-03-10 03:05:10 +00001059/// Given an object of the given canonical type, can we safely copy a
1060/// value out of it based on its initializer?
1061static bool isConstantEmittableObjectType(QualType type) {
1062 assert(type.isCanonical());
1063 assert(!type->isReferenceType());
1064
1065 // Must be const-qualified but non-volatile.
1066 Qualifiers qs = type.getLocalQualifiers();
1067 if (!qs.hasConst() || qs.hasVolatile()) return false;
1068
1069 // Otherwise, all object types satisfy this except C++ classes with
1070 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001071 if (const auto *RT = dyn_cast<RecordType>(type))
1072 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001073 if (RD->hasMutableFields() || !RD->isTrivial())
1074 return false;
1075
1076 return true;
1077}
1078
1079/// Can we constant-emit a load of a reference to a variable of the
1080/// given type? This is different from predicates like
1081/// Decl::isUsableInConstantExpressions because we do want it to apply
1082/// in situations that don't necessarily satisfy the language's rules
1083/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1084/// to do this with const float variables even if those variables
1085/// aren't marked 'constexpr'.
1086enum ConstantEmissionKind {
1087 CEK_None,
1088 CEK_AsReferenceOnly,
1089 CEK_AsValueOrReference,
1090 CEK_AsValueOnly
1091};
1092static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1093 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001094 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001095 if (isConstantEmittableObjectType(ref->getPointeeType()))
1096 return CEK_AsValueOrReference;
1097 return CEK_AsReferenceOnly;
1098 }
1099 if (isConstantEmittableObjectType(type))
1100 return CEK_AsValueOnly;
1101 return CEK_None;
1102}
1103
1104/// Try to emit a reference to the given value without producing it as
1105/// an l-value. This is actually more than an optimization: we can't
1106/// produce an l-value for variables that we never actually captured
1107/// in a block or lambda, which means const int variables or constexpr
1108/// literals or similar.
1109CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001110CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1111 ValueDecl *value = refExpr->getDecl();
1112
John McCall71335052012-03-10 03:05:10 +00001113 // The value needs to be an enum constant or a constant variable.
1114 ConstantEmissionKind CEK;
1115 if (isa<ParmVarDecl>(value)) {
1116 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001117 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001118 CEK = checkVarTypeForConstantEmission(var->getType());
1119 } else if (isa<EnumConstantDecl>(value)) {
1120 CEK = CEK_AsValueOnly;
1121 } else {
1122 CEK = CEK_None;
1123 }
1124 if (CEK == CEK_None) return ConstantEmission();
1125
John McCall71335052012-03-10 03:05:10 +00001126 Expr::EvalResult result;
1127 bool resultIsReference;
1128 QualType resultType;
1129
1130 // It's best to evaluate all the way as an r-value if that's permitted.
1131 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001132 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001133 resultIsReference = false;
1134 resultType = refExpr->getType();
1135
1136 // Otherwise, try to evaluate as an l-value.
1137 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001138 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001139 resultIsReference = true;
1140 resultType = value->getType();
1141
1142 // Failure.
1143 } else {
1144 return ConstantEmission();
1145 }
1146
1147 // In any case, if the initializer has side-effects, abandon ship.
1148 if (result.HasSideEffects)
1149 return ConstantEmission();
1150
1151 // Emit as a constant.
1152 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1153
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001154 // Make sure we emit a debug reference to the global variable.
1155 // This should probably fire even for
1156 if (isa<VarDecl>(value)) {
1157 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1158 EmitDeclRefExprDbgValue(refExpr, C);
1159 } else {
1160 assert(isa<EnumConstantDecl>(value));
1161 EmitDeclRefExprDbgValue(refExpr, C);
1162 }
John McCall71335052012-03-10 03:05:10 +00001163
1164 // If we emitted a reference constant, we need to dereference that.
1165 if (resultIsReference)
1166 return ConstantEmission::forReference(C);
1167
1168 return ConstantEmission::forValue(C);
1169}
1170
Nick Lewycky2d84e842013-10-02 02:29:49 +00001171llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1172 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001173 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001174 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1175 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001176 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1177 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001178}
1179
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001180static bool hasBooleanRepresentation(QualType Ty) {
1181 if (Ty->isBooleanType())
1182 return true;
1183
1184 if (const EnumType *ET = Ty->getAs<EnumType>())
1185 return ET->getDecl()->getIntegerType()->isBooleanType();
1186
Douglas Gregor298f43d2012-04-12 20:42:30 +00001187 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1188 return hasBooleanRepresentation(AT->getValueType());
1189
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001190 return false;
1191}
1192
Richard Smith1629da92012-12-13 07:11:50 +00001193static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1194 llvm::APInt &Min, llvm::APInt &End,
1195 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001196 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001197 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1198 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001199 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001200 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001201 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001202
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001203 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001204 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1205 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001206 } else {
1207 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001208 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001209 unsigned Bitwidth = LTy->getScalarSizeInBits();
1210 unsigned NumNegativeBits = ED->getNumNegativeBits();
1211 unsigned NumPositiveBits = ED->getNumPositiveBits();
1212
1213 if (NumNegativeBits) {
1214 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1215 assert(NumBits <= Bitwidth);
1216 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1217 Min = -End;
1218 } else {
1219 assert(NumPositiveBits <= Bitwidth);
1220 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1221 Min = llvm::APInt(Bitwidth, 0);
1222 }
1223 }
Richard Smith1629da92012-12-13 07:11:50 +00001224 return true;
1225}
1226
1227llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1228 llvm::APInt Min, End;
1229 if (!getRangeForType(*this, Ty, Min, End,
1230 CGM.getCodeGenOpts().StrictEnums))
Craig Topper8a13c412014-05-21 05:09:00 +00001231 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001232
Duncan Sandsc720e782012-04-15 18:04:54 +00001233 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001234 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001235}
1236
John McCall7f416cc2015-09-08 08:05:57 +00001237llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1238 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001239 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001240 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001241 llvm::MDNode *TBAAInfo,
1242 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001243 uint64_t TBAAOffset,
1244 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001245 // For better performance, handle vector loads differently.
1246 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001247 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001248
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001249 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001250
John McCall7f416cc2015-09-08 08:05:57 +00001251 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001252 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001253
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001254 // Bitcast to vec4 type.
1255 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1256 4);
John McCall7f416cc2015-09-08 08:05:57 +00001257 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001258 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001259 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001260
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001261 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001262 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001263 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001264 return EmitFromMemory(V, Ty);
1265 }
1266 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001267
1268 // Atomic operations have to be done on integral types.
David Majnemera5b195a2015-02-14 01:35:12 +00001269 if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
John McCall7f416cc2015-09-08 08:05:57 +00001270 LValue lvalue =
1271 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemereeaec262015-02-14 02:18:14 +00001272 return EmitAtomicLoad(lvalue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001273 }
Craig Topper99e79272013-07-26 05:59:26 +00001274
John McCall7f416cc2015-09-08 08:05:57 +00001275 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001276 if (isNontemporal) {
1277 llvm::MDNode *Node = llvm::MDNode::get(
1278 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1279 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1280 }
Manman Renc451e572013-04-04 21:53:22 +00001281 if (TBAAInfo) {
1282 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1283 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001284 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001285 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1286 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001287 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001288
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001289 bool NeedsBoolCheck =
1290 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1291 bool NeedsEnumCheck =
1292 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1293 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001294 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001295 llvm::APInt Min, End;
1296 if (getRangeForType(*this, Ty, Min, End, true)) {
1297 --End;
1298 llvm::Value *Check;
1299 if (!Min)
1300 Check = Builder.CreateICmpULE(
1301 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1302 else {
1303 llvm::Value *Upper = Builder.CreateICmpSLE(
1304 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1305 llvm::Value *Lower = Builder.CreateICmpSGE(
1306 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1307 Check = Builder.CreateAnd(Upper, Lower);
1308 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001309 llvm::Constant *StaticArgs[] = {
1310 EmitCheckSourceLocation(Loc),
1311 EmitCheckTypeDescriptor(Ty)
1312 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001313 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001314 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1315 EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001316 }
1317 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001318 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1319 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001320
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001321 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001322}
1323
John McCall3a7f6922010-10-27 20:58:56 +00001324llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1325 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001326 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001327 // This should really always be an i1, but sometimes it's already
1328 // an i8, and it's awkward to track those cases down.
1329 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001330 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1331 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1332 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001333 }
1334
1335 return Value;
1336}
1337
1338llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1339 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001340 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001341 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1342 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001343 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1344 }
1345
1346 return Value;
1347}
1348
John McCall7f416cc2015-09-08 08:05:57 +00001349void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1350 bool Volatile, QualType Ty,
1351 AlignmentSource AlignSource,
1352 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001353 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001354 uint64_t TBAAOffset,
1355 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001356
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001357 // Handle vectors differently to get better performance.
1358 if (Ty->isVectorType()) {
1359 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001360 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001361 // Handle vec3 special.
1362 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001363 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001364 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1365 Builder.getInt32(2),
1366 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001367 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1368 Value = Builder.CreateShuffleVector(Value,
1369 llvm::UndefValue::get(VecTy),
1370 MaskV, "extractVec");
1371 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1372 }
John McCall7f416cc2015-09-08 08:05:57 +00001373 if (Addr.getElementType() != SrcTy) {
1374 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001375 }
1376 }
Craig Topper99e79272013-07-26 05:59:26 +00001377
John McCall3a7f6922010-10-27 20:58:56 +00001378 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001379
David Majnemera5b195a2015-02-14 01:35:12 +00001380 if (Ty->isAtomicType() ||
1381 (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001382 EmitAtomicStore(RValue::get(Value),
John McCall7f416cc2015-09-08 08:05:57 +00001383 LValue::MakeAddr(Addr, Ty, getContext(),
1384 AlignSource, TBAAInfo),
John McCalla8ec7eb2013-03-07 21:37:17 +00001385 isInit);
1386 return;
1387 }
1388
Daniel Dunbar03816342010-08-21 02:24:36 +00001389 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001390 if (isNontemporal) {
1391 llvm::MDNode *Node =
1392 llvm::MDNode::get(Store->getContext(),
1393 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1394 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1395 }
Manman Renc451e572013-04-04 21:53:22 +00001396 if (TBAAInfo) {
1397 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1398 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001399 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001400 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1401 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001402 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001403}
1404
David Chisnallfa35df62012-01-16 17:27:18 +00001405void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001406 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001407 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001408 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001409 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001410 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001411}
1412
Mike Stump4a3999f2009-09-09 13:00:44 +00001413/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1414/// method emits the address of the lvalue, then loads the result as an rvalue,
1415/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001416RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001417 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001418 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001419 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001420 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1421 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001422 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001423 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001424 // In MRC mode, we do a load+autorelease.
1425 if (!getLangOpts().ObjCAutoRefCount) {
1426 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1427 }
1428
1429 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001430 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1431 Object = EmitObjCConsumeObject(LV.getType(), Object);
1432 return RValue::get(Object);
1433 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001434
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001435 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001436 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001437
John McCalla1dee5302010-08-22 10:59:02 +00001438 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001439 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001440 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001441
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001442 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001443 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001444 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001445 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001446 "vecext"));
1447 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001448
1449 // If this is a reference to a subset of the elements of a vector, either
1450 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001451 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001452 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001453
Renato Golin230c5eb2014-05-19 18:15:42 +00001454 // Global Register variables always invoke intrinsics
1455 if (LV.isGlobalReg())
1456 return EmitLoadOfGlobalRegLValue(LV);
1457
John McCallc109a252011-11-07 03:59:57 +00001458 assert(LV.isBitField() && "Unknown LValue type!");
1459 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001460}
1461
John McCall55e1fbc2011-06-25 02:11:03 +00001462RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001463 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001464
Daniel Dunbar3447a022010-04-13 23:34:15 +00001465 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001466 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001467
John McCall7f416cc2015-09-08 08:05:57 +00001468 Address Ptr = LV.getBitFieldAddress();
1469 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001470
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001471 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001472 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001473 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1474 if (HighBits)
1475 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1476 if (Info.Offset + HighBits)
1477 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1478 } else {
1479 if (Info.Offset)
1480 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001481 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001482 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1483 Info.Size),
1484 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001485 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001486 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001487
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001488 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001489}
1490
Nate Begemanb699c9b2009-01-18 06:42:49 +00001491// If this is a reference to a subset of the elements of a vector, create an
1492// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001493RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001494 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1495 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001496
Nate Begemanf322eab2008-05-09 06:41:27 +00001497 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001498
1499 // If the result of the expression is a non-vector type, we must be extracting
1500 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001501 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001502 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001503 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001504 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001505 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001506 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001507
1508 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001509 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001510
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001511 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001512 for (unsigned i = 0; i != NumResultElts; ++i)
1513 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001514
Chris Lattner91c08ad2011-02-15 00:14:06 +00001515 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1516 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001517 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001518 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001519}
1520
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001521/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001522Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1523 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001524 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1525 QualType EQT = ExprVT->getElementType();
1526 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001527
John McCall7f416cc2015-09-08 08:05:57 +00001528 Address CastToPointerElement =
1529 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1530 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001531
1532 const llvm::Constant *Elts = LV.getExtVectorElts();
1533 unsigned ix = getAccessedFieldNo(0, Elts);
1534
John McCall7f416cc2015-09-08 08:05:57 +00001535 Address VectorBasePtrPlusIx =
1536 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1537 getContext().getTypeSizeInChars(EQT),
1538 "vector.elt");
1539
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001540 return VectorBasePtrPlusIx;
1541}
1542
Renato Golin230c5eb2014-05-19 18:15:42 +00001543/// @brief Load of global gamed gegisters are always calls to intrinsics.
1544RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001545 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1546 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001547 llvm::MDNode *RegName = cast<llvm::MDNode>(
1548 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001549
1550 // We accept integer and pointer types only
1551 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1552 llvm::Type *Ty = OrigTy;
1553 if (OrigTy->isPointerTy())
1554 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1555 llvm::Type *Types[] = { Ty };
1556
Renato Golin230c5eb2014-05-19 18:15:42 +00001557 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001558 llvm::Value *Call = Builder.CreateCall(
1559 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001560 if (OrigTy->isPointerTy())
1561 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001562 return RValue::get(Call);
1563}
Chris Lattner40ff7012007-08-03 16:18:34 +00001564
Chris Lattner9369a562007-06-29 16:31:29 +00001565
Chris Lattner8394d792007-06-05 20:53:16 +00001566/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1567/// lvalue, where both are guaranteed to the have the same type, and that type
1568/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001569void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001570 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001571 if (!Dst.isSimple()) {
1572 if (Dst.isVectorElt()) {
1573 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001574 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1575 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001576 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001577 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001578 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1579 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001580 return;
1581 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001582
Nate Begemance4d7fc2008-04-18 23:10:10 +00001583 // If this is an update of extended vector elements, insert them as
1584 // appropriate.
1585 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001586 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001587
Renato Golin230c5eb2014-05-19 18:15:42 +00001588 if (Dst.isGlobalReg())
1589 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1590
John McCallc109a252011-11-07 03:59:57 +00001591 assert(Dst.isBitField() && "Unknown LValue type");
1592 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001593 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001594
John McCall31168b02011-06-15 23:02:42 +00001595 // There's special magic for assigning into an ARC-qualified l-value.
1596 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1597 switch (Lifetime) {
1598 case Qualifiers::OCL_None:
1599 llvm_unreachable("present but none");
1600
1601 case Qualifiers::OCL_ExplicitNone:
1602 // nothing special
1603 break;
1604
1605 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001606 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001607 return;
1608
1609 case Qualifiers::OCL_Weak:
1610 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1611 return;
1612
1613 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001614 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1615 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001616 // fall into the normal path
1617 break;
1618 }
1619 }
1620
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001621 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001622 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001623 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001624 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001625 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001626 return;
1627 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001628
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001629 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001630 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001631 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001632 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001633 if (Dst.isObjCIvar()) {
1634 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001635 llvm::Type *ResultType = IntPtrTy;
1636 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1637 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001638 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001639 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001640 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1641 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001642 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001643 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001644 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001645 } else if (Dst.isGlobalObjCRef()) {
1646 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1647 Dst.isThreadLocalRef());
1648 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001649 else
1650 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001651 return;
1652 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001653
Chris Lattner6278e6a2007-08-11 00:04:45 +00001654 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001655 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001656}
1657
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001658void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001659 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001660 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001661 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001662 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001663
Daniel Dunbar67aba792010-04-15 03:47:33 +00001664 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001665 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001666
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001667 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001668 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001669 /*IsSigned=*/false);
1670 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001671
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001672 // See if there are other bits in the bitfield's storage we'll need to load
1673 // and mask together with source before storing.
1674 if (Info.StorageSize != Info.Size) {
1675 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001676 llvm::Value *Val =
1677 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001678
1679 // Mask the source value as needed.
1680 if (!hasBooleanRepresentation(Dst.getType()))
1681 SrcVal = Builder.CreateAnd(SrcVal,
1682 llvm::APInt::getLowBitsSet(Info.StorageSize,
1683 Info.Size),
1684 "bf.value");
1685 MaskedVal = SrcVal;
1686 if (Info.Offset)
1687 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1688
1689 // Mask out the original value.
1690 Val = Builder.CreateAnd(Val,
1691 ~llvm::APInt::getBitsSet(Info.StorageSize,
1692 Info.Offset,
1693 Info.Offset + Info.Size),
1694 "bf.clear");
1695
1696 // Or together the unchanged values and the source value.
1697 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1698 } else {
1699 assert(Info.Offset == 0);
1700 }
1701
1702 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001703 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001704
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001705 // Return the new value of the bit-field, if requested.
1706 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001707 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001708
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001709 // Sign extend the value if needed.
1710 if (Info.IsSigned) {
1711 assert(Info.Size <= Info.StorageSize);
1712 unsigned HighBits = Info.StorageSize - Info.Size;
1713 if (HighBits) {
1714 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1715 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1716 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001717 }
1718
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001719 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1720 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001721 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001722 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001723}
1724
Nate Begemance4d7fc2008-04-18 23:10:10 +00001725void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001726 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001727 // This access turns into a read/modify/write of the vector. Load the input
1728 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001729 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1730 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001731 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001732
Chris Lattner4647a212007-08-31 22:49:20 +00001733 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001734
John McCall55e1fbc2011-06-25 02:11:03 +00001735 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001736 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001737 unsigned NumDstElts =
1738 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1739 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001740 // Use shuffle vector is the src and destination are the same number of
1741 // elements and restore the vector mask since it is on the side it will be
1742 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001743 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001744 for (unsigned i = 0; i != NumSrcElts; ++i)
1745 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001746
Chris Lattner91c08ad2011-02-15 00:14:06 +00001747 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001748 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001749 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001750 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001751 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001752 // Extended the source vector to the same length and then shuffle it
1753 // into the destination.
1754 // FIXME: since we're shuffling with undef, can we just use the indices
1755 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001756 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001757 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001758 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001759 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001760 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001761 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001762 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001763 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001764 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001765 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001766 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001767 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001768 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001769
Joey Goulycf4143b2013-11-21 17:09:05 +00001770 // When the vector size is odd and .odd or .hi is used, the last element
1771 // of the Elts constant array will be one past the size of the vector.
1772 // Ignore the last element here, if it is greater than the mask size.
1773 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1774 NumSrcElts--;
1775
Nate Begemanb699c9b2009-01-18 06:42:49 +00001776 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001777 for (unsigned i = 0; i != NumSrcElts; ++i)
1778 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001779 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001780 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001781 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001782 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001783 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001784 }
1785 } else {
1786 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001787 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001788 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001789 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001790 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001791
John McCall7f416cc2015-09-08 08:05:57 +00001792 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1793 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001794}
1795
Renato Golin230c5eb2014-05-19 18:15:42 +00001796/// @brief Store of global named registers are always calls to intrinsics.
1797void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001798 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1799 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001800 llvm::MDNode *RegName = cast<llvm::MDNode>(
1801 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001802 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001803
1804 // We accept integer and pointer types only
1805 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1806 llvm::Type *Ty = OrigTy;
1807 if (OrigTy->isPointerTy())
1808 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1809 llvm::Type *Types[] = { Ty };
1810
Renato Golin230c5eb2014-05-19 18:15:42 +00001811 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1812 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001813 if (OrigTy->isPointerTy())
1814 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001815 Builder.CreateCall(
1816 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001817}
1818
Eric Christopherc9e2a682014-05-20 17:10:39 +00001819// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001820// generating write-barries API. It is currently a global, ivar,
1821// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001822static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001823 LValue &LV,
1824 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001825 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001826 return;
Craig Topper99e79272013-07-26 05:59:26 +00001827
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001828 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001829 QualType ExpTy = E->getType();
1830 if (IsMemberAccess && ExpTy->isPointerType()) {
1831 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001832 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001833 // writer-barrier conservatively.
1834 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1835 if (ExpTy->isRecordType()) {
1836 LV.setObjCIvar(false);
1837 return;
1838 }
1839 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001840 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001841 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001842 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001843 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001844 return;
1845 }
Craig Topper99e79272013-07-26 05:59:26 +00001846
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001847 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1848 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001849 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001850 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001851 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001852 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001853 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001854 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001855 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001856 }
Craig Topper99e79272013-07-26 05:59:26 +00001857
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001858 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001859 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001860 return;
1861 }
Craig Topper99e79272013-07-26 05:59:26 +00001862
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001863 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001864 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001865 if (LV.isObjCIvar()) {
1866 // If cast is to a structure pointer, follow gcc's behavior and make it
1867 // a non-ivar write-barrier.
1868 QualType ExpTy = E->getType();
1869 if (ExpTy->isPointerType())
1870 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1871 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001872 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001873 }
1874 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001875 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001876
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001877 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001878 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1879 return;
1880 }
1881
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001882 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001883 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001884 return;
1885 }
Craig Topper99e79272013-07-26 05:59:26 +00001886
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001887 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001888 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001889 return;
1890 }
John McCall31168b02011-06-15 23:02:42 +00001891
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001892 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001893 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001894 return;
1895 }
1896
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001897 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001898 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001899 if (LV.isObjCIvar() && !LV.isObjCArray())
1900 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001901 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001902 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001903 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001904 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001905 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001906 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001907 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001908 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001909
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001910 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001911 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001912 // We don't know if member is an 'ivar', but this flag is looked at
1913 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001914 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001915 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001916 }
1917}
1918
Chris Lattner3f32d692011-07-12 06:52:18 +00001919static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001920EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001921 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001922 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001923 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001924 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001925}
1926
Alexey Bataev97720002014-11-11 04:05:39 +00001927static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001928 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1929 llvm::Type *RealVarTy, SourceLocation Loc) {
1930 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1931 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1932 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1933}
1934
1935Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1936 const ReferenceType *RefTy,
1937 AlignmentSource *Source) {
1938 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1939 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1940 Source, /*forPointee*/ true));
1941
1942}
1943
1944LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1945 const ReferenceType *RefTy) {
1946 AlignmentSource Source;
1947 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1948 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001949}
1950
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001951static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1952 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001953 QualType T = E->getType();
1954
1955 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00001956 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1957 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00001958 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1959
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001960 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001961 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1962 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001963 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00001964 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001965 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00001966 // Emit reference to the private copy of the variable if it is an OpenMP
1967 // threadprivate variable.
1968 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001969 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001970 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001971 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
1972 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001973 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001974 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001975 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001976 setObjCGCLValueClass(CGF.getContext(), E, LV);
1977 return LV;
1978}
1979
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001980static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001981 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001982 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001983 if (!FD->hasPrototype()) {
1984 if (const FunctionProtoType *Proto =
1985 FD->getType()->getAs<FunctionProtoType>()) {
1986 // Ugly case: for a K&R-style definition, the type of the definition
1987 // isn't the same as the type of a use. Correct for this with a
1988 // bitcast.
1989 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00001990 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001991 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001992 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001993 }
1994 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001995 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00001996 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001997}
1998
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00001999static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2000 llvm::Value *ThisValue) {
2001 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2002 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2003 return CGF.EmitLValueForField(LV, FD);
2004}
2005
Renato Golin230c5eb2014-05-19 18:15:42 +00002006/// Named Registers are named metadata pointing to the register name
2007/// which will be read from/written to as an argument to the intrinsic
2008/// @llvm.read/write_register.
2009/// So far, only the name is being passed down, but other options such as
2010/// register type, allocation type or even optimization options could be
2011/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002012static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002013 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002014 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002015 assert(Asm->getLabel().size() < 64-Name.size() &&
2016 "Register name too big");
2017 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002018 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002019 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002020 if (M->getNumOperands() == 0) {
2021 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2022 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002023 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002024 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2025 }
John McCall7f416cc2015-09-08 08:05:57 +00002026
2027 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2028
2029 llvm::Value *Ptr =
2030 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2031 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002032}
2033
Chris Lattnerd7f58862007-06-02 05:24:33 +00002034LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002035 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002036 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002037
Renato Goline7b3d5d2014-05-27 16:46:27 +00002038 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2039 // Global Named registers access via intrinsics only
2040 if (VD->getStorageClass() == SC_Register &&
2041 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002042 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002043
Renato Goline7b3d5d2014-05-27 16:46:27 +00002044 // A DeclRefExpr for a reference initialized by a constant expression can
2045 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002046 const Expr *Init = VD->getAnyInitializer(VD);
2047 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2048 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002049 VD->checkInitIsICE() &&
2050 // Do not emit if it is private OpenMP variable.
2051 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2052 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002053 llvm::Constant *Val =
2054 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2055 assert(Val && "failed to emit reference constant expression");
2056 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002057
2058 // Should we be using the alignment of the constant pointer we emitted?
2059 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2060 /*pointee*/ true);
2061
2062 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002063 }
David Majnemer602cfe72015-01-01 09:49:44 +00002064
2065 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002066 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002067 if (auto *FD = LambdaCaptureFields.lookup(VD))
2068 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2069 else if (CapturedStmtInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002070 auto it = LocalDeclMap.find(VD);
2071 if (it != LocalDeclMap.end()) {
2072 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2073 return EmitLoadOfReferenceLValue(it->second, RefTy);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002074 }
John McCall7f416cc2015-09-08 08:05:57 +00002075 return MakeAddrLValue(it->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002076 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002077 LValue CapLVal =
2078 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2079 CapturedStmtInfo->getContextValue());
2080 return MakeAddrLValue(
2081 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2082 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002083 }
John McCall7f416cc2015-09-08 08:05:57 +00002084
David Majnemer602cfe72015-01-01 09:49:44 +00002085 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002086 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2087 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002088 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002089 }
2090
Eli Friedman5720e342012-01-21 04:52:58 +00002091 // FIXME: We should be able to assert this for FunctionDecls as well!
2092 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2093 // those with a valid source location.
2094 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2095 !E->getLocation().isValid()) &&
2096 "Should not use decl without marking it used!");
2097
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002098 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002099 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002100 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2101 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002102 }
2103
Renato Goline7b3d5d2014-05-27 16:46:27 +00002104 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002105 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002106 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002107 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002108
John McCall7f416cc2015-09-08 08:05:57 +00002109 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002110
John McCall7f416cc2015-09-08 08:05:57 +00002111 // The variable should generally be present in the local decl map.
2112 auto iter = LocalDeclMap.find(VD);
2113 if (iter != LocalDeclMap.end()) {
2114 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002115
John McCall7f416cc2015-09-08 08:05:57 +00002116 // Otherwise, it might be static local we haven't emitted yet for
2117 // some reason; most likely, because it's in an outer function.
2118 } else if (VD->isStaticLocal()) {
2119 addr = Address(CGM.getOrCreateStaticVarDecl(
2120 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2121 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002122
John McCall7f416cc2015-09-08 08:05:57 +00002123 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002124 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002125 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2126 }
2127
2128
2129 // Check for OpenMP threadprivate variables.
2130 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2131 return EmitThreadPrivateVarDeclLValue(
2132 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2133 E->getExprLoc());
2134 }
2135
2136 // Drill into block byref variables.
2137 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2138 if (isBlockByref) {
2139 addr = emitBlockByrefAddress(addr, VD);
2140 }
2141
2142 // Drill into reference types.
2143 LValue LV;
2144 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2145 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2146 } else {
2147 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002148 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002149
John McCallcdda29c2013-03-13 03:10:54 +00002150 bool isLocalStorage = VD->hasLocalStorage();
2151
2152 bool NonGCable = isLocalStorage &&
2153 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002154 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002155 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002156 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002157 LV.setNonGC(true);
2158 }
John McCallcdda29c2013-03-13 03:10:54 +00002159
2160 bool isImpreciseLifetime =
2161 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2162 if (isImpreciseLifetime)
2163 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002164 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002165 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002166 }
John McCallf3a88602011-02-03 08:15:49 +00002167
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002168 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002169 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002170
David Blaikie83d382b2011-09-23 05:06:16 +00002171 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002172}
Chris Lattnere47e4402007-06-01 18:02:12 +00002173
Chris Lattner8394d792007-06-05 20:53:16 +00002174LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2175 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002176 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002177 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002178
Chris Lattner0f398c42008-07-26 22:37:01 +00002179 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002180 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002181 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002182 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002183 QualType T = E->getSubExpr()->getType()->getPointeeType();
2184 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002185
John McCall7f416cc2015-09-08 08:05:57 +00002186 AlignmentSource AlignSource;
2187 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2188 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002189 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002190
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002191 // We should not generate __weak write barrier on indirect reference
2192 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2193 // But, we continue to generate __strong write barrier on indirect write
2194 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002195 if (getLangOpts().ObjC1 &&
2196 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002197 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002198 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002199 return LV;
2200 }
John McCalle3027922010-08-25 11:45:40 +00002201 case UO_Real:
2202 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002203 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002204 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002205
Richard Smith0b6b8e42012-02-18 20:53:32 +00002206 // __real is valid on scalars. This is a faster way of testing that.
2207 // __imag can only produce an rvalue on scalars.
2208 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002209 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002210 assert(E->getSubExpr()->getType()->isArithmeticType());
2211 return LV;
2212 }
2213
2214 assert(E->getSubExpr()->getType()->isAnyComplexType());
2215
John McCall7f416cc2015-09-08 08:05:57 +00002216 Address Component =
2217 (E->getOpcode() == UO_Real
2218 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2219 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2220 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
Chris Lattner595db862007-10-30 22:53:42 +00002221 }
John McCalle3027922010-08-25 11:45:40 +00002222 case UO_PreInc:
2223 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002224 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002225 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002226
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002227 if (E->getType()->isAnyComplexType())
2228 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2229 else
2230 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2231 return LV;
2232 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002233 }
Chris Lattner8394d792007-06-05 20:53:16 +00002234}
2235
Chris Lattner4347e3692007-06-06 04:54:52 +00002236LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002237 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002238 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002239}
2240
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002241LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002242 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002243 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002244}
2245
Mike Stump4a3999f2009-09-09 13:00:44 +00002246LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002247 auto SL = E->getFunctionName();
2248 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2249 StringRef FnName = CurFn->getName();
2250 if (FnName.startswith("\01"))
2251 FnName = FnName.substr(1);
2252 StringRef NameItems[] = {
2253 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2254 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002255 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
John McCall7f416cc2015-09-08 08:05:57 +00002256 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2257 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002258 }
Alexey Bataevec474782014-10-09 08:45:04 +00002259 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002260 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002261}
2262
Richard Smithe30752c2012-10-09 19:52:38 +00002263/// Emit a type description suitable for use by a runtime sanitizer library. The
2264/// format of a type descriptor is
2265///
2266/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002267/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002268/// \endcode
2269///
Richard Smith683398a2012-10-09 23:55:19 +00002270/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2271/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002272llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002273 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002274 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002275 return C;
2276
Richard Smithe30752c2012-10-09 19:52:38 +00002277 uint16_t TypeKind = -1;
2278 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002279
Richard Smithe30752c2012-10-09 19:52:38 +00002280 if (T->isIntegerType()) {
2281 TypeKind = 0;
2282 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002283 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002284 } else if (T->isFloatingType()) {
2285 TypeKind = 1;
2286 TypeInfo = getContext().getTypeSize(T);
2287 }
2288
2289 // Format the type name as if for a diagnostic, including quotes and
2290 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002291 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002292 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2293 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002294 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002295 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002296
2297 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002298 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2299 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002300 };
2301 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2302
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002303 auto *GV = new llvm::GlobalVariable(
2304 CGM.getModule(), Descriptor->getType(),
2305 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Richard Smithe30752c2012-10-09 19:52:38 +00002306 GV->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002307 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002308
2309 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002310 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002311
Richard Smithe30752c2012-10-09 19:52:38 +00002312 return GV;
2313}
2314
2315llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2316 llvm::Type *TargetTy = IntPtrTy;
2317
Richard Smith48366f72013-03-22 00:47:07 +00002318 // Floating-point types which fit into intptr_t are bitcast to integers
2319 // and then passed directly (after zero-extension, if necessary).
2320 if (V->getType()->isFloatingPointTy()) {
2321 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2322 if (Bits <= TargetTy->getIntegerBitWidth())
2323 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2324 Bits));
2325 }
2326
Richard Smithe30752c2012-10-09 19:52:38 +00002327 // Integers which fit in intptr_t are zero-extended and passed directly.
2328 if (V->getType()->isIntegerTy() &&
2329 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2330 return Builder.CreateZExt(V, TargetTy);
2331
2332 // Pointers are passed directly, everything else is passed by address.
2333 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002334 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002335 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002336 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002337 }
2338 return Builder.CreatePtrToInt(V, TargetTy);
2339}
2340
2341/// \brief Emit a representation of a SourceLocation for passing to a handler
2342/// in a sanitizer runtime library. The format for this data is:
2343/// \code
2344/// struct SourceLocation {
2345/// const char *Filename;
2346/// int32_t Line, Column;
2347/// };
2348/// \endcode
2349/// For an invalid SourceLocation, the Filename pointer is null.
2350llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002351 llvm::Constant *Filename;
2352 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002353
Alexey Samsonov6c124142014-07-18 17:50:06 +00002354 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2355 if (PLoc.isValid()) {
2356 auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002357 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2358 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2359 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002360 Line = PLoc.getLine();
2361 Column = PLoc.getColumn();
2362 } else {
2363 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2364 Line = Column = 0;
2365 }
2366
2367 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2368 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002369
2370 return llvm::ConstantStruct::getAnon(Data);
2371}
2372
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002373namespace {
2374/// \brief Specify under what conditions this check can be recovered
2375enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002376 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002377 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002378 /// Check supports recovering, runtime has both fatal (noreturn) and
2379 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002380 Recoverable,
2381 /// Runtime conditionally aborts, always need to support recovery.
2382 AlwaysRecoverable
2383};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002384}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002385
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002386static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2387 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002388 switch (Kind) {
2389 case SanitizerKind::Vptr:
2390 return CheckRecoverableKind::AlwaysRecoverable;
2391 case SanitizerKind::Return:
2392 case SanitizerKind::Unreachable:
2393 return CheckRecoverableKind::Unrecoverable;
2394 default:
2395 return CheckRecoverableKind::Recoverable;
2396 }
2397}
2398
Alexey Samsonov88459522015-01-12 22:39:12 +00002399static void emitCheckHandlerCall(CodeGenFunction &CGF,
2400 llvm::FunctionType *FnType,
2401 ArrayRef<llvm::Value *> FnArgs,
2402 StringRef CheckName,
2403 CheckRecoverableKind RecoverKind, bool IsFatal,
2404 llvm::BasicBlock *ContBB) {
2405 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2406 bool NeedsAbortSuffix =
2407 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2408 std::string FnName = ("__ubsan_handle_" + CheckName +
2409 (NeedsAbortSuffix ? "_abort" : "")).str();
2410 bool MayReturn =
2411 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2412
2413 llvm::AttrBuilder B;
2414 if (!MayReturn) {
2415 B.addAttribute(llvm::Attribute::NoReturn)
2416 .addAttribute(llvm::Attribute::NoUnwind);
2417 }
2418 B.addAttribute(llvm::Attribute::UWTable);
2419
2420 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2421 FnType, FnName,
2422 llvm::AttributeSet::get(CGF.getLLVMContext(),
2423 llvm::AttributeSet::FunctionIndex, B));
2424 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2425 if (!MayReturn) {
2426 HandlerCall->setDoesNotReturn();
2427 CGF.Builder.CreateUnreachable();
2428 } else {
2429 CGF.Builder.CreateBr(ContBB);
2430 }
2431}
2432
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002433void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002434 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002435 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2436 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002437 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002438 assert(Checked.size() > 0);
Alexey Samsonov88459522015-01-12 22:39:12 +00002439
2440 llvm::Value *FatalCond = nullptr;
2441 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002442 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002443 for (int i = 0, n = Checked.size(); i < n; ++i) {
2444 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002445 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002446 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002447 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2448 ? TrapCond
2449 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2450 ? RecoverableCond
2451 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002452 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2453 }
2454
Peter Collingbourne9881b782015-06-18 23:59:22 +00002455 if (TrapCond)
2456 EmitTrapCheck(TrapCond);
2457 if (!FatalCond && !RecoverableCond)
2458 return;
2459
Alexey Samsonov88459522015-01-12 22:39:12 +00002460 llvm::Value *JointCond;
2461 if (FatalCond && RecoverableCond)
2462 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2463 else
2464 JointCond = FatalCond ? FatalCond : RecoverableCond;
2465 assert(JointCond);
2466
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002467 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2468 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002469#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002470 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002471 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002472 "All recoverable kinds in a single check must be same!");
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002473 assert(SanOpts.has(Checked[i].second));
2474 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002475#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002476
Richard Smith4d1458e2012-09-08 02:08:36 +00002477 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002478 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2479 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002480 // Give hint that we very much don't expect to execute the handler
2481 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2482 llvm::MDBuilder MDHelper(getLLVMContext());
2483 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2484 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002485 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002486
Alexey Samsonov88459522015-01-12 22:39:12 +00002487 // Emit handler arguments and create handler function type.
Richard Smithe30752c2012-10-09 19:52:38 +00002488 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002489 auto *InfoPtr =
Will Dietz450f1a12013-01-09 03:39:41 +00002490 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
Richard Smithe30752c2012-10-09 19:52:38 +00002491 llvm::GlobalVariable::PrivateLinkage, Info);
2492 InfoPtr->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002493 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
Richard Smithe30752c2012-10-09 19:52:38 +00002494
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002495 SmallVector<llvm::Value *, 4> Args;
2496 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002497 Args.reserve(DynamicArgs.size() + 1);
2498 ArgTypes.reserve(DynamicArgs.size() + 1);
2499
2500 // Handler functions take an i8* pointing to the (handler-specific) static
2501 // information block, followed by a sequence of intptr_t arguments
2502 // representing operand values.
2503 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2504 ArgTypes.push_back(Int8PtrTy);
2505 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2506 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2507 ArgTypes.push_back(IntPtrTy);
2508 }
2509
2510 llvm::FunctionType *FnType =
2511 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002512
Alexey Samsonov88459522015-01-12 22:39:12 +00002513 if (!FatalCond || !RecoverableCond) {
2514 // Simple case: we need to generate a single handler call, either
2515 // fatal, or non-fatal.
2516 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2517 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002518 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002519 // Emit two handler calls: first one for set of unrecoverable checks,
2520 // another one for recoverable.
2521 llvm::BasicBlock *NonFatalHandlerBB =
2522 createBasicBlock("non_fatal." + CheckName);
2523 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2524 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2525 EmitBlock(FatalHandlerBB);
2526 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2527 NonFatalHandlerBB);
2528 EmitBlock(NonFatalHandlerBB);
2529 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2530 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002531 }
Richard Smithe30752c2012-10-09 19:52:38 +00002532
Richard Smith4d1458e2012-09-08 02:08:36 +00002533 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002534}
2535
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002536void CodeGenFunction::EmitCfiSlowPathCheck(llvm::Value *Cond,
2537 llvm::ConstantInt *TypeId,
2538 llvm::Value *Ptr) {
2539 auto &Ctx = getLLVMContext();
2540 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2541
2542 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2543 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2544
2545 llvm::MDBuilder MDHelper(getLLVMContext());
2546 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2547 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2548
2549 EmitBlock(CheckBB);
2550
2551 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2552 "__cfi_slowpath",
2553 llvm::FunctionType::get(
2554 llvm::Type::getVoidTy(Ctx),
2555 {llvm::Type::getInt64Ty(Ctx),
2556 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(Ctx))},
2557 false));
2558 llvm::CallInst *CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2559 CheckCall->setDoesNotThrow();
2560
2561 EmitBlock(Cont);
2562}
2563
Chad Rosierae229d52013-01-29 23:31:22 +00002564void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002565 llvm::BasicBlock *Cont = createBasicBlock("cont");
2566
2567 // If we're optimizing, collapse all calls to trap down to just one per
2568 // function to save on code size.
2569 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2570 TrapBB = createBasicBlock("trap");
2571 Builder.CreateCondBr(Checked, Cont, TrapBB);
2572 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002573 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002574 TrapCall->setDoesNotReturn();
2575 TrapCall->setDoesNotThrow();
2576 Builder.CreateUnreachable();
2577 } else {
2578 Builder.CreateCondBr(Checked, Cont, TrapBB);
2579 }
2580
2581 EmitBlock(Cont);
2582}
2583
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002584llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002585 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002586
2587 if (!CGM.getCodeGenOpts().TrapFuncName.empty())
2588 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
2589 "trap-func-name",
2590 CGM.getCodeGenOpts().TrapFuncName);
2591
2592 return TrapCall;
2593}
2594
John McCall7f416cc2015-09-08 08:05:57 +00002595Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2596 AlignmentSource *AlignSource) {
2597 assert(E->getType()->isArrayType() &&
2598 "Array to pointer decay must have array source type!");
2599
2600 // Expressions of array type can't be bitfields or vector elements.
2601 LValue LV = EmitLValue(E);
2602 Address Addr = LV.getAddress();
2603 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2604
2605 // If the array type was an incomplete type, we need to make sure
2606 // the decay ends up being the right type.
2607 llvm::Type *NewTy = ConvertType(E->getType());
2608 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2609
2610 // Note that VLA pointers are always decayed, so we don't need to do
2611 // anything here.
2612 if (!E->getType()->isVariableArrayType()) {
2613 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2614 "Expected pointer to array");
2615 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2616 }
2617
2618 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2619 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2620}
2621
Chris Lattner6c5abe82010-06-26 23:03:20 +00002622/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2623/// array to pointer, return the array subexpression.
2624static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2625 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002626 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002627 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002628 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002629
Chris Lattner6c5abe82010-06-26 23:03:20 +00002630 // If this is a decay from variable width array, bail out.
2631 const Expr *SubExpr = CE->getSubExpr();
2632 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002633 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002634
Chris Lattner6c5abe82010-06-26 23:03:20 +00002635 return SubExpr;
2636}
2637
John McCall7f416cc2015-09-08 08:05:57 +00002638static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2639 llvm::Value *ptr,
2640 ArrayRef<llvm::Value*> indices,
2641 bool inbounds,
2642 const llvm::Twine &name = "arrayidx") {
2643 if (inbounds) {
2644 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2645 } else {
2646 return CGF.Builder.CreateGEP(ptr, indices, name);
2647 }
2648}
2649
2650static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2651 llvm::Value *idx,
2652 CharUnits eltSize) {
2653 // If we have a constant index, we can use the exact offset of the
2654 // element we're accessing.
2655 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2656 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2657 return arrayAlign.alignmentAtOffset(offset);
2658
2659 // Otherwise, use the worst-case alignment for any element.
2660 } else {
2661 return arrayAlign.alignmentOfArrayElement(eltSize);
2662 }
2663}
2664
2665static QualType getFixedSizeElementType(const ASTContext &ctx,
2666 const VariableArrayType *vla) {
2667 QualType eltType;
2668 do {
2669 eltType = vla->getElementType();
2670 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2671 return eltType;
2672}
2673
2674static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2675 ArrayRef<llvm::Value*> indices,
2676 QualType eltType, bool inbounds,
2677 const llvm::Twine &name = "arrayidx") {
2678 // All the indices except that last must be zero.
2679#ifndef NDEBUG
2680 for (auto idx : indices.drop_back())
2681 assert(isa<llvm::ConstantInt>(idx) &&
2682 cast<llvm::ConstantInt>(idx)->isZero());
2683#endif
2684
2685 // Determine the element size of the statically-sized base. This is
2686 // the thing that the indices are expressed in terms of.
2687 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2688 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2689 }
2690
2691 // We can use that to compute the best alignment of the element.
2692 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2693 CharUnits eltAlign =
2694 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2695
2696 llvm::Value *eltPtr =
2697 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2698 return Address(eltPtr, eltAlign);
2699}
2700
Richard Smith539e4a72013-02-23 02:53:19 +00002701LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2702 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002703 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002704 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002705 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002706 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002707
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002708 if (SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002709 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2710
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002711 // If the base is a vector type, then we are forming a vector element lvalue
2712 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002713 if (E->getBase()->getType()->isVectorType() &&
2714 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002715 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002716 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002717 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002718 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002719 E->getBase()->getType(),
2720 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002721 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002722
John McCall7f416cc2015-09-08 08:05:57 +00002723 // All the other cases basically behave like simple offsetting.
2724
Ted Kremenekc81614d2007-08-20 16:18:38 +00002725 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002726 if (Idx->getType() != IntPtrTy)
2727 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002728
John McCall7f416cc2015-09-08 08:05:57 +00002729 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002730 if (isa<ExtVectorElementExpr>(E->getBase())) {
2731 LValue LV = EmitLValue(E->getBase());
John McCall7f416cc2015-09-08 08:05:57 +00002732 Address Addr = EmitExtVectorElementLValue(LV);
2733
2734 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2735 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2736 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002737 }
John McCall7f416cc2015-09-08 08:05:57 +00002738
2739 AlignmentSource AlignSource;
2740 Address Addr = Address::invalid();
2741 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002742 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002743 // The base must be a pointer, which is not an aggregate. Emit
2744 // it. It needs to be emitted first in case it's what captures
2745 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002746 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002747
John McCall23c29fe2011-06-24 21:55:10 +00002748 // The element count here is the total number of non-VLA elements.
2749 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002750
John McCall77527a82011-06-25 01:32:37 +00002751 // Effectively, the multiply by the VLA size is part of the GEP.
2752 // GEP indexes are signed, and scaling an index isn't permitted to
2753 // signed-overflow, so we use the same semantics for our explicit
2754 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002755 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002756 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002757 } else {
2758 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002759 }
John McCall7f416cc2015-09-08 08:05:57 +00002760
2761 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2762 !getLangOpts().isSignedOverflowDefined());
2763
Chris Lattner6c5abe82010-06-26 23:03:20 +00002764 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2765 // Indexing over an interface, as in "NSString *P; P[4];"
John McCall7f416cc2015-09-08 08:05:57 +00002766 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2767 llvm::Value *InterfaceSizeVal =
2768 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());;
Mike Stump4a3999f2009-09-09 13:00:44 +00002769
John McCall7f416cc2015-09-08 08:05:57 +00002770 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002771
John McCall7f416cc2015-09-08 08:05:57 +00002772 // Emit the base pointer.
2773 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2774
2775 // We don't necessarily build correct LLVM struct types for ObjC
2776 // interfaces, so we can't rely on GEP to do this scaling
2777 // correctly, so we need to cast to i8*. FIXME: is this actually
2778 // true? A lot of other things in the fragile ABI would break...
2779 llvm::Type *OrigBaseTy = Addr.getType();
2780 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2781
2782 // Do the GEP.
2783 CharUnits EltAlign =
2784 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2785 llvm::Value *EltPtr =
2786 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2787 Addr = Address(EltPtr, EltAlign);
2788
2789 // Cast back.
2790 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00002791 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2792 // If this is A[i] where A is an array, the frontend will have decayed the
2793 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2794 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2795 // "gep x, i" here. Emit one "gep A, 0, i".
2796 assert(Array->getType()->isArrayType() &&
2797 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002798 LValue ArrayLV;
2799 // For simple multidimensional array indexing, set the 'accessed' flag for
2800 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002801 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002802 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2803 else
2804 ArrayLV = EmitLValue(Array);
Craig Topper99e79272013-07-26 05:59:26 +00002805
Daniel Dunbar82634272011-04-01 00:49:43 +00002806 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00002807 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
2808 {CGM.getSize(CharUnits::Zero()), Idx},
2809 E->getType(),
2810 !getLangOpts().isSignedOverflowDefined());
2811 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002812 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002813 // The base must be a pointer; emit it with an estimate of its alignment.
2814 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2815 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
2816 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00002817 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002818
John McCall7f416cc2015-09-08 08:05:57 +00002819 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002820
John McCall7f416cc2015-09-08 08:05:57 +00002821 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00002822
Richard Smith9c6890a2012-11-01 22:30:59 +00002823 if (getLangOpts().ObjC1 &&
2824 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002825 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002826 setObjCGCLValueClass(getContext(), E, LV);
2827 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002828 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002829}
2830
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002831LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2832 bool IsLowerBound) {
2833 LValue Base;
2834 if (auto *ASE =
2835 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
2836 Base = EmitOMPArraySectionExpr(ASE, IsLowerBound);
2837 else
2838 Base = EmitLValue(E->getBase());
2839 QualType BaseTy = Base.getType();
2840 llvm::Value *Idx = nullptr;
2841 QualType ResultExprTy;
2842 if (auto *AT = getContext().getAsArrayType(BaseTy))
2843 ResultExprTy = AT->getElementType();
2844 else
2845 ResultExprTy = BaseTy->getPointeeType();
2846 if (IsLowerBound || (!IsLowerBound && E->getColonLoc().isInvalid())) {
2847 // Requesting lower bound or upper bound, but without provided length and
2848 // without ':' symbol for the default length -> length = 1.
2849 // Idx = LowerBound ?: 0;
2850 if (auto *LowerBound = E->getLowerBound()) {
2851 Idx = Builder.CreateIntCast(
2852 EmitScalarExpr(LowerBound), IntPtrTy,
2853 LowerBound->getType()->hasSignedIntegerRepresentation());
2854 } else
2855 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
2856 } else {
2857 // Try to emit length or lower bound as constant. If this is possible, 1 is
2858 // subtracted from constant length or lower bound. Otherwise, emit LLVM IR
2859 // (LB + Len) - 1.
2860 auto &C = CGM.getContext();
2861 auto *Length = E->getLength();
2862 llvm::APSInt ConstLength;
2863 if (Length) {
2864 // Idx = LowerBound + Length - 1;
2865 if (Length->isIntegerConstantExpr(ConstLength, C)) {
2866 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2867 Length = nullptr;
2868 }
2869 auto *LowerBound = E->getLowerBound();
2870 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
2871 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
2872 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
2873 LowerBound = nullptr;
2874 }
2875 if (!Length)
2876 --ConstLength;
2877 else if (!LowerBound)
2878 --ConstLowerBound;
2879
2880 if (Length || LowerBound) {
2881 auto *LowerBoundVal =
2882 LowerBound
2883 ? Builder.CreateIntCast(
2884 EmitScalarExpr(LowerBound), IntPtrTy,
2885 LowerBound->getType()->hasSignedIntegerRepresentation())
2886 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
2887 auto *LengthVal =
2888 Length
2889 ? Builder.CreateIntCast(
2890 EmitScalarExpr(Length), IntPtrTy,
2891 Length->getType()->hasSignedIntegerRepresentation())
2892 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
2893 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
2894 /*HasNUW=*/false,
2895 !getLangOpts().isSignedOverflowDefined());
2896 if (Length && LowerBound) {
2897 Idx = Builder.CreateSub(
2898 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
2899 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2900 }
2901 } else
2902 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
2903 } else {
2904 // Idx = ArraySize - 1;
2905 if (auto *VAT = C.getAsVariableArrayType(BaseTy)) {
2906 Length = VAT->getSizeExpr();
2907 if (Length->isIntegerConstantExpr(ConstLength, C))
2908 Length = nullptr;
2909 } else {
2910 auto *CAT = C.getAsConstantArrayType(BaseTy);
2911 ConstLength = CAT->getSize();
2912 }
2913 if (Length) {
2914 auto *LengthVal = Builder.CreateIntCast(
2915 EmitScalarExpr(Length), IntPtrTy,
2916 Length->getType()->hasSignedIntegerRepresentation());
2917 Idx = Builder.CreateSub(
2918 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
2919 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2920 } else {
2921 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2922 --ConstLength;
2923 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
2924 }
2925 }
2926 }
2927 assert(Idx);
2928
John McCall7f416cc2015-09-08 08:05:57 +00002929 llvm::Value *EltPtr;
2930 QualType FixedSizeEltType = ResultExprTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002931 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
2932 // The element count here is the total number of non-VLA elements.
2933 llvm::Value *numElements = getVLASize(VLA).first;
John McCall7f416cc2015-09-08 08:05:57 +00002934 FixedSizeEltType = getFixedSizeElementType(getContext(), VLA);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002935
2936 // Effectively, the multiply by the VLA size is part of the GEP.
2937 // GEP indexes are signed, and scaling an index isn't permitted to
2938 // signed-overflow, so we use the same semantics for our explicit
2939 // multiply. We suppress this if overflow is not undefined behavior.
2940 if (getLangOpts().isSignedOverflowDefined()) {
2941 Idx = Builder.CreateMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002942 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002943 } else {
2944 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002945 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002946 }
2947 } else if (BaseTy->isConstantArrayType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002948 llvm::Value *ArrayPtr = Base.getPointer();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002949 llvm::Value *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
2950 llvm::Value *Args[] = {Zero, Idx};
2951
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002952 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002953 EltPtr = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002954 else
John McCall7f416cc2015-09-08 08:05:57 +00002955 EltPtr = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002956 } else {
2957 // The base must be a pointer, which is not an aggregate. Emit it.
2958 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002959 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002960 else
John McCall7f416cc2015-09-08 08:05:57 +00002961 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002962 }
2963
John McCall7f416cc2015-09-08 08:05:57 +00002964 CharUnits EltAlign =
2965 Base.getAlignment().alignmentOfArrayElement(
2966 getContext().getTypeSizeInChars(FixedSizeEltType));
2967
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002968 // Limit the alignment to that of the result type.
John McCall7f416cc2015-09-08 08:05:57 +00002969 LValue LV = MakeAddrLValue(Address(EltPtr, EltAlign), ResultExprTy,
2970 Base.getAlignmentSource());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002971
2972 LV.getQuals().setAddressSpace(BaseTy.getAddressSpace());
2973
2974 return LV;
2975}
2976
Chris Lattner9e751ca2007-08-02 23:37:31 +00002977LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002978EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002979 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002980 LValue Base;
2981
2982 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002983 if (E->isArrow()) {
2984 // If it is a pointer to a vector, emit the address and form an lvalue with
2985 // it.
John McCall7f416cc2015-09-08 08:05:57 +00002986 AlignmentSource AlignSource;
2987 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00002988 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00002989 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002990 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002991 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002992 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2993 // emit the base as an lvalue.
2994 assert(E->getBase()->getType()->isVectorType());
2995 Base = EmitLValue(E->getBase());
2996 } else {
2997 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002998 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002999 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003000 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003001
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003002 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003003 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003004 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003005 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3006 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003007 }
John McCall1553b192011-06-16 04:16:24 +00003008
3009 QualType type =
3010 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003011
Nate Begemand3862152008-05-13 21:03:02 +00003012 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003013 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003014 E->getEncodedElementAccess(Indices);
3015
3016 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003017 llvm::Constant *CV =
3018 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003019 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00003020 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00003021 }
3022 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3023
3024 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003025 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003026
Chris Lattner595ba3a2012-01-30 06:20:36 +00003027 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3028 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003029 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003030 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3031 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003032}
3033
Devang Patel30efa2e2007-10-23 20:28:39 +00003034LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003035 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003036
Chris Lattner4e4186b2007-12-02 18:52:07 +00003037 // 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 +00003038 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003039 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003040 AlignmentSource AlignSource;
3041 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003042 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003043 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3044 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003045 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003046 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003047
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003048 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003049 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003050 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003051 setObjCGCLValueClass(getContext(), E, LV);
3052 return LV;
3053 }
Craig Topper99e79272013-07-26 05:59:26 +00003054
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003055 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003056 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003057
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003058 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003059 return EmitFunctionDeclLValue(*this, E, FD);
3060
David Blaikie83d382b2011-09-23 05:06:16 +00003061 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003062}
Devang Patel30efa2e2007-10-23 20:28:39 +00003063
John McCalldec348f72013-05-03 07:33:41 +00003064/// Given that we are currently emitting a lambda, emit an l-value for
3065/// one of its members.
3066LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3067 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3068 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3069 QualType LambdaTagType =
3070 getContext().getTagDeclType(Field->getParent());
3071 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3072 return EmitLValueForField(LambdaLV, Field);
3073}
3074
John McCall7f416cc2015-09-08 08:05:57 +00003075/// Drill down to the storage of a field without walking into
3076/// reference types.
3077///
3078/// The resulting address doesn't necessarily have the right type.
3079static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3080 const FieldDecl *field) {
3081 const RecordDecl *rec = field->getParent();
3082
3083 unsigned idx =
3084 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3085
3086 CharUnits offset;
3087 // Adjust the alignment down to the given offset.
3088 // As a special case, if the LLVM field index is 0, we know that this
3089 // is zero.
3090 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3091 .getFieldOffset(field->getFieldIndex()) == 0) &&
3092 "LLVM field at index zero had non-zero offset?");
3093 if (idx != 0) {
3094 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3095 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3096 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3097 }
3098
3099 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3100}
3101
Eli Friedman7f1ff602012-04-16 03:54:45 +00003102LValue CodeGenFunction::EmitLValueForField(LValue base,
3103 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003104 AlignmentSource fieldAlignSource =
3105 getFieldAlignmentSource(base.getAlignmentSource());
3106
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003107 if (field->isBitField()) {
3108 const CGRecordLayout &RL =
3109 CGM.getTypes().getCGRecordLayout(field->getParent());
3110 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003111 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003112 unsigned Idx = RL.getLLVMFieldNo(field);
3113 if (Idx != 0)
3114 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003115 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3116 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003117 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003118 llvm::Type *FieldIntTy =
3119 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3120 if (Addr.getElementType() != FieldIntTy)
3121 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003122
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003123 QualType fieldType =
3124 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003125 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003126 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003127
John McCall53fcbd22011-02-26 08:07:02 +00003128 const RecordDecl *rec = field->getParent();
3129 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003130
John McCall53fcbd22011-02-26 08:07:02 +00003131 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3132
John McCall7f416cc2015-09-08 08:05:57 +00003133 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003134 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003135 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003136 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003137 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003138 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003139 // TODO: handle path-aware TBAA for union.
3140 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003141 } else {
3142 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003143 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003144
3145 // If this is a reference field, load the reference right now.
3146 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3147 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3148 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3149
Manman Renc451e572013-04-04 21:53:22 +00003150 // Loading the reference will disable path-aware TBAA.
3151 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003152 if (CGM.shouldUseTBAA()) {
3153 llvm::MDNode *tbaa;
3154 if (mayAlias)
3155 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3156 else
3157 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003158 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003159 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003160 }
3161
John McCall53fcbd22011-02-26 08:07:02 +00003162 mayAlias = false;
3163 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003164
3165 CharUnits alignment =
3166 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3167 addr = Address(load, alignment);
3168
3169 // Qualifiers on the struct don't apply to the referencee, and
3170 // we'll pick up CVR from the actual type later, so reset these
3171 // additional qualifiers now.
3172 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003173 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003174 }
Craig Topper99e79272013-07-26 05:59:26 +00003175
Chris Lattner13ee4f42011-07-10 05:34:54 +00003176 // Make sure that the address is pointing to the right type. This is critical
3177 // for both unions and structs. A union needs a bitcast, a struct element
3178 // will need a bitcast if the LLVM type laid out doesn't match the desired
3179 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003180 addr = Builder.CreateElementBitCast(addr,
3181 CGM.getTypes().ConvertTypeForMem(type),
3182 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003183
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003184 if (field->hasAttr<AnnotateAttr>())
3185 addr = EmitFieldAnnotations(field, addr);
3186
John McCall7f416cc2015-09-08 08:05:57 +00003187 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003188 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003189 if (TBAAPath) {
3190 const ASTRecordLayout &Layout =
3191 getContext().getASTRecordLayout(field->getParent());
3192 // Set the base type to be the base type of the base LValue and
3193 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003194 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3195 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003196 Layout.getFieldOffset(field->getFieldIndex()) /
3197 getContext().getCharWidth());
3198 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003199
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003200 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003201 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3202 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003203
3204 // Fields of may_alias structs act like 'char' for TBAA purposes.
3205 // FIXME: this should get propagated down through anonymous structs
3206 // and unions.
3207 if (mayAlias && LV.getTBAAInfo())
3208 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3209
Daniel Dunbarf166a522010-08-21 03:44:13 +00003210 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003211}
3212
Craig Topper99e79272013-07-26 05:59:26 +00003213LValue
3214CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003215 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003216 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003217
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003218 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003219 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003220
John McCall7f416cc2015-09-08 08:05:57 +00003221 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003222
John McCall7f416cc2015-09-08 08:05:57 +00003223 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003224 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003225 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003226
John McCall7f416cc2015-09-08 08:05:57 +00003227 // TODO: access-path TBAA?
3228 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3229 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003230}
3231
Chris Lattnerf53c0962010-09-06 00:11:41 +00003232LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003233 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003234 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3235 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003236 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003237 if (E->getType()->isVariablyModifiedType())
3238 // make sure to emit the VLA size.
3239 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003240
John McCall7f416cc2015-09-08 08:05:57 +00003241 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003242 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003243 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003244
Chad Rosier615ed1a2012-03-29 17:37:10 +00003245 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3246 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003247
3248 return Result;
3249}
3250
Richard Smithbb653bd2012-05-14 21:57:21 +00003251LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3252 if (!E->isGLValue())
3253 // Initializing an aggregate temporary in C++11: T{...}.
3254 return EmitAggExprToLValue(E);
3255
3256 // An lvalue initializer list must be initializing a reference.
3257 assert(E->getNumInits() == 1 && "reference init with multiple values");
3258 return EmitLValue(E->getInit(0));
3259}
3260
Richard Smithf3076ff2014-06-20 18:43:47 +00003261/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3262/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3263/// LValue is returned and the current block has been terminated.
3264static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3265 const Expr *Operand) {
3266 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3267 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3268 return None;
3269 }
3270
3271 return CGF.EmitLValue(Operand);
3272}
3273
John McCallc07a0c72011-02-17 10:25:35 +00003274LValue CodeGenFunction::
3275EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3276 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003277 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003278 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003279 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003280 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003281 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003282
Eli Friedman59954892012-01-25 05:04:17 +00003283 OpaqueValueMapping binding(*this, expr);
3284
John McCallc07a0c72011-02-17 10:25:35 +00003285 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003286 bool CondExprBool;
3287 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003288 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003289 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003290
Justin Bogneref512b92014-01-06 22:27:43 +00003291 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003292 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003293 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003294 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003295 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003296 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003297 }
3298
John McCallc07a0c72011-02-17 10:25:35 +00003299 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3300 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3301 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003302
3303 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003304 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003305
John McCall0a6bf2e2011-01-26 19:21:13 +00003306 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003307 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003308 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003309 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003310 Optional<LValue> lhs =
3311 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003312 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003313
Richard Smithf3076ff2014-06-20 18:43:47 +00003314 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003315 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003316
John McCallc07a0c72011-02-17 10:25:35 +00003317 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003318 if (lhs)
3319 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003320
John McCall0a6bf2e2011-01-26 19:21:13 +00003321 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003322 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003323 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003324 Optional<LValue> rhs =
3325 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003326 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003327 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003328 return EmitUnsupportedLValue(expr, "conditional operator");
3329 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003330
John McCallc07a0c72011-02-17 10:25:35 +00003331 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003332
Richard Smithf3076ff2014-06-20 18:43:47 +00003333 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003334 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003335 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003336 phi->addIncoming(lhs->getPointer(), lhsBlock);
3337 phi->addIncoming(rhs->getPointer(), rhsBlock);
3338 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3339 AlignmentSource alignSource =
3340 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3341 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003342 } else {
3343 assert((lhs || rhs) &&
3344 "both operands of glvalue conditional are throw-expressions?");
3345 return lhs ? *lhs : *rhs;
3346 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003347}
3348
Richard Smithbb653bd2012-05-14 21:57:21 +00003349/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3350/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003351/// otherwise if a cast is needed by the code generator in an lvalue context,
3352/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003353/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003354/// are permitted with aggregate result, including noop aggregate casts, and
3355/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003356LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003357 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003358 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003359 case CK_BitCast:
3360 case CK_ArrayToPointerDecay:
3361 case CK_FunctionToPointerDecay:
3362 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003363 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003364 case CK_IntegralToPointer:
3365 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003366 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003367 case CK_VectorSplat:
3368 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003369 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003370 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003371 case CK_IntegralToFloating:
3372 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003373 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003374 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003375 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003376 case CK_FloatingComplexToReal:
3377 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003378 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003379 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003380 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003381 case CK_IntegralComplexToReal:
3382 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003383 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003384 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003385 case CK_DerivedToBaseMemberPointer:
3386 case CK_BaseToDerivedMemberPointer:
3387 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003388 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003389 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003390 case CK_ARCProduceObject:
3391 case CK_ARCConsumeObject:
3392 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003393 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003394 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003395 case CK_AddressSpaceConversion:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003396 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3397
3398 case CK_Dependent:
3399 llvm_unreachable("dependent cast kind in IR gen!");
3400
3401 case CK_BuiltinFnToFnPtr:
3402 llvm_unreachable("builtin functions are handled elsewhere");
3403
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003404 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003405 case CK_NonAtomicToAtomic:
3406 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003407 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003408
Anders Carlsson8a01a752011-04-11 02:03:26 +00003409 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003410 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003411 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003412 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003413 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003414 }
3415
John McCalle3027922010-08-25 11:45:40 +00003416 case CK_ConstructorConversion:
3417 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003418 case CK_CPointerToObjCPointerCast:
3419 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003420 case CK_NoOp:
3421 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003422 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003423
John McCalle3027922010-08-25 11:45:40 +00003424 case CK_UncheckedDerivedToBase:
3425 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003426 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003427 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003428 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003429
Anders Carlssond95f9602009-09-12 16:16:49 +00003430 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003431 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003432
Anders Carlssond95f9602009-09-12 16:16:49 +00003433 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003434 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003435 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3436 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003437
John McCall7f416cc2015-09-08 08:05:57 +00003438 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003439 }
John McCalle3027922010-08-25 11:45:40 +00003440 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003441 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003442 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003443 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003444 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003445
Anders Carlsson8c793172009-11-23 17:57:54 +00003446 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003447
Anders Carlsson8c793172009-11-23 17:57:54 +00003448 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003449 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003450 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003451 E->path_begin(), E->path_end(),
3452 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003453
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003454 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3455 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003456 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003457 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003458 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003459
Peter Collingbourned2926c92015-03-14 02:42:25 +00003460 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003461 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3462 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003463 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003464
John McCall7f416cc2015-09-08 08:05:57 +00003465 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003466 }
John McCalle3027922010-08-25 11:45:40 +00003467 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003468 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003469 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003470
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003471 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003472 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003473 Address V = Builder.CreateBitCast(LV.getAddress(),
3474 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003475
3476 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003477 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3478 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003479 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003480
John McCall7f416cc2015-09-08 08:05:57 +00003481 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003482 }
John McCalle3027922010-08-25 11:45:40 +00003483 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003484 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003485 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3486 ConvertType(E->getType()));
3487 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003488 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003489 case CK_ZeroToOCLEvent:
3490 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003491 }
Craig Topper99e79272013-07-26 05:59:26 +00003492
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003493 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003494}
3495
John McCall1bf58462011-02-16 08:02:54 +00003496LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003497 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003498 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003499}
3500
Eli Friedman7f1ff602012-04-16 03:54:45 +00003501RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003502 const FieldDecl *FD,
3503 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003504 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003505 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003506 switch (getEvaluationKind(FT)) {
3507 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003508 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003509 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003510 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003511 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003512 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003513 }
3514 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003515}
Douglas Gregorfe314812011-06-21 17:03:29 +00003516
Chris Lattnere47e4402007-06-01 18:02:12 +00003517//===--------------------------------------------------------------------===//
3518// Expression Emission
3519//===--------------------------------------------------------------------===//
3520
Craig Topper99e79272013-07-26 05:59:26 +00003521RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003522 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003523 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003524 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003525 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003526
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003527 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003528 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003529
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003530 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003531 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3532
Douglas Gregore0e96302011-09-06 21:41:04 +00003533 const Decl *TargetDecl = E->getCalleeDecl();
3534 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3535 if (unsigned builtinID = FD->getBuiltinID())
Peter Collingbournef7706832014-12-12 23:41:25 +00003536 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003537 }
3538
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003539 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00003540 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003541 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003542
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003543 if (const auto *PseudoDtor =
3544 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00003545 QualType DestroyedType = PseudoDtor->getDestroyedType();
John McCall460ce582015-10-22 18:38:17 +00003546 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003547 // Automatic Reference Counting:
3548 // If the pseudo-expression names a retainable object with weak or
3549 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00003550 Expr *BaseExpr = PseudoDtor->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003551 Address BaseValue = Address::invalid();
John McCall31168b02011-06-15 23:02:42 +00003552 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00003553
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003554 // 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 +00003555 if (PseudoDtor->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003556 BaseValue = EmitPointerWithAlignment(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003557 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3558 BaseQuals = PTy->getPointeeType().getQualifiers();
3559 } else {
3560 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003561 BaseValue = BaseLV.getAddress();
3562 QualType BaseTy = BaseExpr->getType();
3563 BaseQuals = BaseTy.getQualifiers();
3564 }
Craig Topper99e79272013-07-26 05:59:26 +00003565
John McCall460ce582015-10-22 18:38:17 +00003566 switch (DestroyedType.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00003567 case Qualifiers::OCL_None:
3568 case Qualifiers::OCL_ExplicitNone:
3569 case Qualifiers::OCL_Autoreleasing:
3570 break;
Craig Topper99e79272013-07-26 05:59:26 +00003571
John McCall31168b02011-06-15 23:02:42 +00003572 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00003573 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003574 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00003575 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00003576 break;
3577
3578 case Qualifiers::OCL_Weak:
3579 EmitARCDestroyWeak(BaseValue);
3580 break;
3581 }
3582 } else {
3583 // C++ [expr.pseudo]p1:
3584 // The result shall only be used as the operand for the function call
3585 // operator (), and the result of such a call has type void. The only
3586 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00003587 // arrow.
John McCall31168b02011-06-15 23:02:42 +00003588 EmitScalarExpr(E->getCallee());
3589 }
Craig Topper99e79272013-07-26 05:59:26 +00003590
Craig Topper8a13c412014-05-21 05:09:00 +00003591 return RValue::get(nullptr);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003592 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003593
Chris Lattner2da04b32007-08-24 05:35:26 +00003594 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003595 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3596 TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00003597}
3598
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003599LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003600 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003601 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003602 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003603 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003604 return EmitLValue(E->getRHS());
3605 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003606
John McCalle3027922010-08-25 11:45:40 +00003607 if (E->getOpcode() == BO_PtrMemD ||
3608 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003609 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003610
John McCalla2342eb2010-12-05 02:00:02 +00003611 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003612
3613 // Note that in all of these cases, __block variables need the RHS
3614 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003615
3616 switch (getEvaluationKind(E->getType())) {
3617 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003618 switch (E->getLHS()->getType().getObjCLifetime()) {
3619 case Qualifiers::OCL_Strong:
3620 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3621
3622 case Qualifiers::OCL_Autoreleasing:
3623 return EmitARCStoreAutoreleasing(E).first;
3624
3625 // No reason to do any of these differently.
3626 case Qualifiers::OCL_None:
3627 case Qualifiers::OCL_ExplicitNone:
3628 case Qualifiers::OCL_Weak:
3629 break;
3630 }
3631
John McCalld0a30012010-12-06 06:10:02 +00003632 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003633 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003634 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003635 return LV;
3636 }
John McCall4f29b492010-11-16 23:07:28 +00003637
John McCall47fb9502013-03-07 21:37:08 +00003638 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003639 return EmitComplexAssignmentLValue(E);
3640
John McCall47fb9502013-03-07 21:37:08 +00003641 case TEK_Aggregate:
3642 return EmitAggExprToLValue(E);
3643 }
3644 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003645}
3646
Christopher Lambd91c3d42007-12-29 05:02:41 +00003647LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003648 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003649
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003650 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003651 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3652 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003653
David Majnemerced8bdf2015-02-25 17:36:15 +00003654 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003655 "Can't have a scalar return unless the return type is a "
3656 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003657
John McCall7f416cc2015-09-08 08:05:57 +00003658 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003659}
3660
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003661LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3662 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003663 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003664}
3665
Anders Carlsson3be22e22009-05-30 23:23:33 +00003666LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003667 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3668 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003669 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003670 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003671 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3672 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003673}
3674
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003675LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003676CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003677 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003678}
3679
John McCall7f416cc2015-09-08 08:05:57 +00003680Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3681 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3682 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003683}
3684
3685LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003686 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3687 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00003688}
3689
Mike Stumpc9b231c2009-11-15 08:09:41 +00003690LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003691CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003692 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003693 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003694 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003695 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3696 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3697 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003698}
3699
Eli Friedman5bc17122012-02-08 05:34:55 +00003700LValue
3701CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003702 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003703 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003704 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3705 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00003706}
3707
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003708LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003709 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003710
Anders Carlsson280e61f12010-06-21 20:59:55 +00003711 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003712 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3713 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003714
Alp Toker314cc812014-01-25 16:55:45 +00003715 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003716 "Can't have a scalar return unless the return type is a "
3717 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003718
John McCall7f416cc2015-09-08 08:05:57 +00003719 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003720}
3721
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003722LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003723 Address V =
3724 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3725 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003726}
3727
Daniel Dunbar722f4242009-04-22 05:08:15 +00003728llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003729 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003730 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003731}
3732
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003733LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3734 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003735 const ObjCIvarDecl *Ivar,
3736 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003737 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003738 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003739}
3740
3741LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003742 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00003743 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003744 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003745 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003746 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003747 if (E->isArrow()) {
3748 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003749 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003750 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003751 } else {
3752 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00003753 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003754 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003755 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003756 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003757
Craig Topper99e79272013-07-26 05:59:26 +00003758 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003759 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3760 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003761 setObjCGCLValueClass(getContext(), E, LV);
3762 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003763}
3764
Chris Lattnera4185c52009-04-25 19:35:26 +00003765LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003766 // Can only get l-value for message expression returning aggregate type
3767 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00003768 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3769 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00003770}
3771
Anders Carlsson0435ed52009-12-24 19:08:58 +00003772RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003773 const CallExpr *E, ReturnValueSlot ReturnValue,
Samuel Antao798f11c2015-11-23 22:04:44 +00003774 CGCalleeInfo CalleeInfo, llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003775 // Get the actual function type. The callee type will always be a pointer to
3776 // function type or a block pointer type.
3777 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003778 "Call must have function pointer type!");
3779
Samuel Antao798f11c2015-11-23 22:04:44 +00003780 // Preserve the non-canonical function type because things like exception
3781 // specifications disappear in the canonical type. That information is useful
3782 // to drive the generation of more accurate code for this call later on.
3783 const FunctionProtoType *NonCanonicalFTP = CalleeType->getAs<PointerType>()
3784 ->getPointeeType()
3785 ->getAs<FunctionProtoType>();
3786
3787 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
3788
Eric Christopher2b2d56f2015-11-12 00:44:12 +00003789 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00003790 // We can only guarantee that a function is called from the correct
3791 // context/function based on the appropriate target attributes,
3792 // so only check in the case where we have both always_inline and target
3793 // since otherwise we could be making a conditional call after a check for
3794 // the proper cpu features (and it won't cause code generation issues due to
3795 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00003796 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
3797 TargetDecl->hasAttr<TargetAttr>())
3798 checkTargetFeatures(E, FD);
3799
John McCall6fd4c232009-10-23 08:22:42 +00003800 CalleeType = getContext().getCanonicalType(CalleeType);
3801
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003802 const auto *FnType =
3803 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00003804
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003805 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003806 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3807 if (llvm::Constant *PrefixSig =
3808 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003809 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003810 llvm::Constant *FTRTTIConst =
3811 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
3812 llvm::Type *PrefixStructTyElems[] = {
3813 PrefixSig->getType(),
3814 FTRTTIConst->getType()
3815 };
3816 llvm::StructType *PrefixStructTy = llvm::StructType::get(
3817 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
3818
3819 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
3820 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
3821 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003822 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00003823 llvm::Value *CalleeSig =
3824 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003825 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
3826
3827 llvm::BasicBlock *Cont = createBasicBlock("cont");
3828 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
3829 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
3830
3831 EmitBlock(TypeCheck);
3832 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003833 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003834 llvm::Value *CalleeRTTI =
3835 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003836 llvm::Value *CalleeRTTIMatch =
3837 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
3838 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003839 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003840 EmitCheckTypeDescriptor(CalleeType)
3841 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003842 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
3843 "function_type_mismatch", StaticData, Callee);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003844
3845 Builder.CreateBr(Cont);
3846 EmitBlock(Cont);
3847 }
3848 }
3849
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00003850 // If we are checking indirect calls and this call is indirect, check that the
3851 // function pointer is a member of the bit set for the function type.
3852 if (SanOpts.has(SanitizerKind::CFIICall) &&
3853 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3854 SanitizerScope SanScope(this);
3855
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00003856 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
3857 llvm::Value *BitSetName = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00003858
3859 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy);
3860 llvm::Value *BitSetTest =
3861 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
3862 {CastedCallee, BitSetName});
3863
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00003864 auto TypeId = CGM.CreateCfiIdForTypeMetadata(MD);
3865 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && TypeId) {
3866 EmitCfiSlowPathCheck(BitSetTest, TypeId, CastedCallee);
3867 } else {
3868 llvm::Constant *StaticData[] = {
3869 EmitCheckSourceLocation(E->getLocStart()),
3870 EmitCheckTypeDescriptor(QualType(FnType, 0)),
3871 };
3872 EmitCheck(std::make_pair(BitSetTest, SanitizerKind::CFIICall),
3873 "cfi_bad_icall", StaticData, CastedCallee);
3874 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00003875 }
3876
Daniel Dunbarc722b852008-08-30 03:02:31 +00003877 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00003878 if (Chain)
3879 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
3880 CGM.getContext().VoidPtrTy);
David Blaikief05779e2015-07-21 18:37:18 +00003881 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
3882 E->getDirectCallee(), /*ParamsToSkip*/ 0);
Daniel Dunbarc722b852008-08-30 03:02:31 +00003883
Peter Collingbournef7706832014-12-12 23:41:25 +00003884 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
3885 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00003886
3887 // C99 6.5.2.2p6:
3888 // If the expression that denotes the called function has a type
3889 // that does not include a prototype, [the default argument
3890 // promotions are performed]. If the number of arguments does not
3891 // equal the number of parameters, the behavior is undefined. If
3892 // the function is defined with a type that includes a prototype,
3893 // and either the prototype ends with an ellipsis (, ...) or the
3894 // types of the arguments after promotion are not compatible with
3895 // the types of the parameters, the behavior is undefined. If the
3896 // function is defined with a type that does not include a
3897 // prototype, and the types of the arguments after promotion are
3898 // not compatible with those of the parameters after promotion,
3899 // the behavior is undefined [except in some trivial cases].
3900 // That is, in the general case, we should assume that a call
3901 // through an unprototyped function type works like a *non-variadic*
3902 // call. The way we make this work is to cast to the exact type
3903 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00003904 //
3905 // Chain calls use this same code path to add the invisible chain parameter
3906 // to the function type.
3907 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00003908 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00003909 CalleeTy = CalleeTy->getPointerTo();
3910 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3911 }
3912
Samuel Antao798f11c2015-11-23 22:04:44 +00003913 return EmitCall(FnInfo, Callee, ReturnValue, Args,
3914 CGCalleeInfo(NonCanonicalFTP, TargetDecl));
Daniel Dunbar97db84c2008-08-23 03:46:30 +00003915}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003916
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003917LValue CodeGenFunction::
3918EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003919 Address BaseAddr = Address::invalid();
3920 if (E->getOpcode() == BO_PtrMemI) {
3921 BaseAddr = EmitPointerWithAlignment(E->getLHS());
3922 } else {
3923 BaseAddr = EmitLValue(E->getLHS()).getAddress();
3924 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003925
John McCallc134eb52010-08-31 21:07:20 +00003926 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3927
3928 const MemberPointerType *MPT
3929 = E->getRHS()->getType()->getAs<MemberPointerType>();
3930
John McCall7f416cc2015-09-08 08:05:57 +00003931 AlignmentSource AlignSource;
3932 Address MemberAddr =
3933 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
3934 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00003935
John McCall7f416cc2015-09-08 08:05:57 +00003936 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003937}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003938
John McCall47fb9502013-03-07 21:37:08 +00003939/// Given the address of a temporary variable, produce an r-value of
3940/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00003941RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003942 QualType type,
3943 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00003944 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00003945 switch (getEvaluationKind(type)) {
3946 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003947 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003948 case TEK_Aggregate:
3949 return lvalue.asAggregateRValue();
3950 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003951 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003952 }
3953 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003954}
3955
Duncan Sandse81111c2012-04-10 08:23:07 +00003956void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003957 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003958 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003959 return;
3960
Duncan Sands65229ed2012-04-16 16:29:47 +00003961 llvm::MDBuilder MDHelper(getLLVMContext());
3962 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003963
Duncan Sands6fc46192012-04-14 12:37:26 +00003964 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003965}
John McCallfe96e0b2011-11-06 09:01:30 +00003966
3967namespace {
3968 struct LValueOrRValue {
3969 LValue LV;
3970 RValue RV;
3971 };
3972}
3973
3974static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3975 const PseudoObjectExpr *E,
3976 bool forLValue,
3977 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003978 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00003979
3980 // Find the result expression, if any.
3981 const Expr *resultExpr = E->getResultExpr();
3982 LValueOrRValue result;
3983
3984 for (PseudoObjectExpr::const_semantics_iterator
3985 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3986 const Expr *semantic = *i;
3987
3988 // If this semantic expression is an opaque value, bind it
3989 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003990 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00003991
3992 // If this is the result expression, we may need to evaluate
3993 // directly into the slot.
3994 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3995 OVMA opaqueData;
3996 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00003997 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00003998 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3999
John McCall7f416cc2015-09-08 08:05:57 +00004000 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4001 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004002 opaqueData = OVMA::bind(CGF, ov, LV);
4003 result.RV = slot.asRValue();
4004
4005 // Otherwise, emit as normal.
4006 } else {
4007 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4008
4009 // If this is the result, also evaluate the result now.
4010 if (ov == resultExpr) {
4011 if (forLValue)
4012 result.LV = CGF.EmitLValue(ov);
4013 else
4014 result.RV = CGF.EmitAnyExpr(ov, slot);
4015 }
4016 }
4017
4018 opaques.push_back(opaqueData);
4019
4020 // Otherwise, if the expression is the result, evaluate it
4021 // and remember the result.
4022 } else if (semantic == resultExpr) {
4023 if (forLValue)
4024 result.LV = CGF.EmitLValue(semantic);
4025 else
4026 result.RV = CGF.EmitAnyExpr(semantic, slot);
4027
4028 // Otherwise, evaluate the expression in an ignored context.
4029 } else {
4030 CGF.EmitIgnoredExpr(semantic);
4031 }
4032 }
4033
4034 // Unbind all the opaques now.
4035 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4036 opaques[i].unbind(CGF);
4037
4038 return result;
4039}
4040
4041RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4042 AggValueSlot slot) {
4043 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4044}
4045
4046LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4047 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4048}