blob: 158baf75862c6153d1326d49e29a96799a49651b [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
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGCall.h"
Tim Shen421119f2016-07-01 21:08:47 +000016#include "CGCleanup.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"
Tim Shen421119f2016-07-01 21:08:47 +000021#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000023#include "ConstantEmitter.h"
John McCallcbc038a2011-09-21 08:08:30 +000024#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000025#include "clang/AST/ASTContext.h"
Renato Golin230c5eb2014-05-19 18:15:42 +000026#include "clang/AST/Attr.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000027#include "clang/AST/DeclObjC.h"
Vedant Kumar4593a462016-12-09 23:48:18 +000028#include "clang/AST/NSAPI.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000029#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000031#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000036#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000037#include "llvm/Support/MathExtras.h"
Filipe Cabecinhasab731f72016-05-12 16:51:36 +000038#include "llvm/Support/Path.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000039#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000040
Filipe Cabecinhas84171bd2016-12-12 16:43:40 +000041#include <string>
42
Chris Lattnere47e4402007-06-01 18:02:12 +000043using namespace clang;
44using namespace CodeGen;
45
Chris Lattnerd7f58862007-06-02 05:24:33 +000046//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000047// Miscellaneous Helper Methods
48//===--------------------------------------------------------------------===//
49
John McCallad7c5c12011-02-08 08:22:06 +000050llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
51 unsigned addressSpace =
Yaxun Liu39195062017-08-04 18:16:31 +000052 cast<llvm::PointerType>(value->getType())->getAddressSpace();
John McCallad7c5c12011-02-08 08:22:06 +000053
Chris Lattner2192fe52011-07-18 04:24:23 +000054 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000055 if (addressSpace)
56 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
57
58 if (value->getType() == destType) return value;
59 return Builder.CreateBitCast(value, destType);
60}
61
Chris Lattnere9a64532007-06-22 21:44:33 +000062/// CreateTempAlloca - This creates a alloca and inserts it into the entry
63/// block.
John McCall7f416cc2015-09-08 08:05:57 +000064Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +000065 const Twine &Name,
66 llvm::Value *ArraySize,
67 bool CastToDefaultAddrSpace) {
68 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
John McCall7f416cc2015-09-08 08:05:57 +000069 Alloca->setAlignment(Align.getQuantity());
Yaxun Liu84744c12017-06-19 17:03:41 +000070 llvm::Value *V = Alloca;
71 // Alloca always returns a pointer in alloca address space, which may
72 // be different from the type defined by the language. For example,
73 // in C++ the auto variables are in the default address space. Therefore
74 // cast alloca to the default address space when necessary.
75 if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
76 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
Yaxun Liu9d33fb12017-07-18 14:46:03 +000077 auto CurIP = Builder.saveIP();
78 Builder.SetInsertPoint(AllocaInsertPt);
Yaxun Liu84744c12017-06-19 17:03:41 +000079 V = getTargetHooks().performAddrSpaceCast(
80 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
81 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
Yaxun Liu9d33fb12017-07-18 14:46:03 +000082 Builder.restoreIP(CurIP);
Yaxun Liu84744c12017-06-19 17:03:41 +000083 }
84
85 return Address(V, Align);
John McCall7f416cc2015-09-08 08:05:57 +000086}
87
Yaxun Liu84744c12017-06-19 17:03:41 +000088/// CreateTempAlloca - This creates an alloca and inserts it into the entry
89/// block if \p ArraySize is nullptr, otherwise inserts it at the current
90/// insertion point of the builder.
Chris Lattner2192fe52011-07-18 04:24:23 +000091llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Yaxun Liu84744c12017-06-19 17:03:41 +000092 const Twine &Name,
93 llvm::Value *ArraySize) {
94 if (ArraySize)
95 return Builder.CreateAlloca(Ty, ArraySize, Name);
Matt Arsenault502ad602017-04-10 22:28:02 +000096 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
Yaxun Liu84744c12017-06-19 17:03:41 +000097 ArraySize, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000098}
Chris Lattner8394d792007-06-05 20:53:16 +000099
John McCall7f416cc2015-09-08 08:05:57 +0000100/// CreateDefaultAlignTempAlloca - This creates an alloca with the
101/// default alignment of the corresponding LLVM type, which is *not*
102/// guaranteed to be related in any way to the expected alignment of
103/// an AST type that might have been lowered to Ty.
104Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
105 const Twine &Name) {
106 CharUnits Align =
107 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
108 return CreateTempAlloca(Ty, Align, Name);
109}
110
111void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
112 assert(isa<llvm::AllocaInst>(Var.getPointer()));
113 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
114 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +0000115 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000116 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +0000117}
118
John McCall7f416cc2015-09-08 08:05:57 +0000119Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +0000120 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +0000121 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +0000122}
123
Yaxun Liu84744c12017-06-19 17:03:41 +0000124Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
125 bool CastToDefaultAddrSpace) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000126 // FIXME: Should we prefer the preferred type alignment here?
Yaxun Liu84744c12017-06-19 17:03:41 +0000127 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
128 CastToDefaultAddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +0000129}
130
131Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +0000132 const Twine &Name,
133 bool CastToDefaultAddrSpace) {
134 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
135 CastToDefaultAddrSpace);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000136}
137
Chris Lattner8394d792007-06-05 20:53:16 +0000138/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
139/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000140llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000141 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000142 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000143 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000144 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000145 }
John McCall7a9aac22010-08-23 01:21:21 +0000146
147 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000148 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000149 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000150 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000151
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000152 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
153 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000154}
155
John McCalla2342eb2010-12-05 02:00:02 +0000156/// EmitIgnoredExpr - Emit code to compute the specified expression,
157/// ignoring the result.
158void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
159 if (E->isRValue())
160 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
161
162 // Just emit it as an l-value and drop the result.
163 EmitLValue(E);
164}
165
John McCall7a626f62010-09-15 10:14:12 +0000166/// EmitAnyExpr - Emit code to compute the specified expression which
167/// can have any type. The result is returned as an RValue struct.
168/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000169/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000170RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
171 AggValueSlot aggSlot,
172 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000173 switch (getEvaluationKind(E->getType())) {
174 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000175 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000176 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000177 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000178 case TEK_Aggregate:
179 if (!ignoreResult && aggSlot.isIgnored())
180 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
181 EmitAggExpr(E, aggSlot);
182 return aggSlot.asRValue();
183 }
184 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000185}
186
Mike Stump4a3999f2009-09-09 13:00:44 +0000187/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
188/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000189RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
190 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000191
John McCall47fb9502013-03-07 21:37:08 +0000192 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000193 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
194 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000195}
196
John McCall21886962010-04-21 10:05:39 +0000197/// EmitAnyExprToMem - Evaluate an expression into a given memory
198/// location.
199void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000200 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000201 Qualifiers Quals,
202 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000203 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000204 switch (getEvaluationKind(E->getType())) {
205 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000206 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000207 /*isInit*/ false);
208 return;
209
210 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000211 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000212 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000213 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000214 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000215 return;
216 }
217
218 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000219 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000220 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000221 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000222 return;
John McCall21886962010-04-21 10:05:39 +0000223 }
John McCall47fb9502013-03-07 21:37:08 +0000224 }
225 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000226}
227
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000228static void
229pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000230 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000231 // Objective-C++ ARC:
232 // If we are binding a reference to a temporary that has ownership, we
233 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000234 //
235 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000236 if (auto Lifetime = M->getType().getObjCLifetime()) {
237 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000238 case Qualifiers::OCL_None:
239 case Qualifiers::OCL_ExplicitNone:
240 // Carry on to normal cleanup handling.
241 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000242
Richard Smith736a9472013-06-12 20:42:33 +0000243 case Qualifiers::OCL_Autoreleasing:
244 // Nothing to do; cleaned up by an autorelease pool.
245 return;
246
247 case Qualifiers::OCL_Strong:
248 case Qualifiers::OCL_Weak:
249 switch (StorageDuration Duration = M->getStorageDuration()) {
250 case SD_Static:
251 // Note: we intentionally do not register a cleanup to release
252 // the object on program termination.
253 return;
254
255 case SD_Thread:
256 // FIXME: We should probably register a cleanup in this case.
257 return;
258
259 case SD_Automatic:
260 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000261 CodeGenFunction::Destroyer *Destroy;
262 CleanupKind CleanupKind;
263 if (Lifetime == Qualifiers::OCL_Strong) {
264 const ValueDecl *VD = M->getExtendingDecl();
265 bool Precise =
266 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
267 CleanupKind = CGF.getARCCleanupKind();
268 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
269 : &CodeGenFunction::destroyARCStrongImprecise;
270 } else {
271 // __weak objects always get EH cleanups; otherwise, exceptions
272 // could cause really nasty crashes instead of mere leaks.
273 CleanupKind = NormalAndEHCleanup;
274 Destroy = &CodeGenFunction::destroyARCWeak;
275 }
276 if (Duration == SD_FullExpression)
277 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000278 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000279 CleanupKind & EHCleanup);
280 else
281 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000282 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000283 *Destroy, CleanupKind & EHCleanup);
284 return;
285
286 case SD_Dynamic:
287 llvm_unreachable("temporary cannot have dynamic storage duration");
288 }
289 llvm_unreachable("unknown storage duration");
290 }
291 }
292
Craig Topper8a13c412014-05-21 05:09:00 +0000293 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000294 if (const RecordType *RT =
295 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
296 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000297 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000298 if (!ClassDecl->hasTrivialDestructor())
299 ReferenceTemporaryDtor = ClassDecl->getDestructor();
300 }
301
302 if (!ReferenceTemporaryDtor)
303 return;
304
305 // Call the destructor for the temporary.
306 switch (M->getStorageDuration()) {
307 case SD_Static:
308 case SD_Thread: {
309 llvm::Constant *CleanupFn;
310 llvm::Constant *CleanupArg;
311 if (E->getType()->isArrayType()) {
312 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000313 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000314 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
315 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000316 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
317 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000318 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
319 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000320 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000321 }
322 CGF.CGM.getCXXABI().registerGlobalDtor(
323 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
324 break;
325 }
326
327 case SD_FullExpression:
328 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
329 CodeGenFunction::destroyCXXObject,
330 CGF.getLangOpts().Exceptions);
331 break;
332
333 case SD_Automatic:
334 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
335 ReferenceTemporary, E->getType(),
336 CodeGenFunction::destroyCXXObject,
337 CGF.getLangOpts().Exceptions);
338 break;
339
340 case SD_Dynamic:
341 llvm_unreachable("temporary cannot have dynamic storage duration");
342 }
343}
344
Yaxun Liucbf647c2017-07-08 13:24:52 +0000345static Address createReferenceTemporary(CodeGenFunction &CGF,
346 const MaterializeTemporaryExpr *M,
347 const Expr *Inner) {
348 auto &TCG = CGF.getTargetHooks();
Richard Smith736a9472013-06-12 20:42:33 +0000349 switch (M->getStorageDuration()) {
350 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000351 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000352 // If we have a constant temporary array or record try to promote it into a
353 // constant global under the same rules a normal constant would've been
354 // promoted. This is easier on the optimizer and generally emits fewer
355 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000356 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000357 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000358 (Ty->isArrayType() || Ty->isRecordType()) &&
359 CGF.CGM.isTypeConstant(Ty, true))
John McCallde0fe072017-08-15 21:42:52 +0000360 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000361 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
362 auto AS = AddrSpace.getValue();
363 auto *GV = new llvm::GlobalVariable(
364 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
365 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
366 llvm::GlobalValue::NotThreadLocal,
367 CGF.getContext().getTargetAddressSpace(AS));
368 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
369 GV->setAlignment(alignment.getQuantity());
370 llvm::Constant *C = GV;
371 if (AS != LangAS::Default)
372 C = TCG.performAddrSpaceCast(
373 CGF.CGM, GV, AS, LangAS::Default,
374 GV->getValueType()->getPointerTo(
375 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
376 // FIXME: Should we put the new global into a COMDAT?
377 return Address(C, alignment);
378 }
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000379 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000380 return CGF.CreateMemTemp(Ty, "ref.tmp");
381 }
Richard Smith736a9472013-06-12 20:42:33 +0000382 case SD_Thread:
383 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000384 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000385
386 case SD_Dynamic:
387 llvm_unreachable("temporary can't have dynamic storage duration");
388 }
389 llvm_unreachable("unknown storage duration");
390}
391
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000392LValue CodeGenFunction::
393EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000394 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000395
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000396 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
397 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000398 auto ownership = M->getType().getObjCLifetime();
399 if (ownership != Qualifiers::OCL_None &&
400 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000401 Address Object = createReferenceTemporary(*this, M, E);
402 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
403 Object = Address(llvm::ConstantExpr::getBitCast(Var,
404 ConvertTypeForMem(E->getType())
405 ->getPointerTo(Object.getAddressSpace())),
406 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000407
408 // createReferenceTemporary will promote the temporary to a global with a
409 // constant initializer if it can. It can only do this to a value of
410 // ARC-manageable type if the value is global and therefore "immune" to
411 // ref-counting operations. Therefore we have no need to emit either a
412 // dynamic initialization or a cleanup and we can just return the address
413 // of the temporary.
414 if (Var->hasInitializer())
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000415 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000416
Richard Smitha509f2f2013-06-14 03:07:01 +0000417 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
418 }
John McCall7f416cc2015-09-08 08:05:57 +0000419 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000420 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000421
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000422 switch (getEvaluationKind(E->getType())) {
423 default: llvm_unreachable("expected scalar or aggregate expression");
424 case TEK_Scalar:
425 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
426 break;
427 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000428 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000429 E->getType().getQualifiers(),
430 AggValueSlot::IsDestructed,
431 AggValueSlot::DoesNotNeedGCBarriers,
432 AggValueSlot::IsNotAliased));
433 break;
434 }
435 }
Richard Smith736a9472013-06-12 20:42:33 +0000436
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000437 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000438 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000439 }
440
Richard Smithf3fabd22013-06-03 00:17:11 +0000441 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000442 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000443 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
444
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000445 for (const auto &Ignored : CommaLHSs)
446 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000447
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000448 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000449 if (opaque->getType()->isRecordType()) {
450 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000451 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000452 }
453 }
454
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000455 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000456 Address Object = createReferenceTemporary(*this, M, E);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000457 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
458 Object.getPointer()->stripPointerCasts())) {
John McCall7f416cc2015-09-08 08:05:57 +0000459 Object = Address(llvm::ConstantExpr::getBitCast(
Yaxun Liucbf647c2017-07-08 13:24:52 +0000460 cast<llvm::Constant>(Object.getPointer()),
461 ConvertTypeForMem(E->getType())->getPointerTo()),
John McCall7f416cc2015-09-08 08:05:57 +0000462 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000463 // If the temporary is a global and has a constant initializer or is a
464 // constant temporary that we promoted to a global, we may have already
465 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000466 if (!Var->hasInitializer()) {
467 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
468 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
469 }
470 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000471 switch (M->getStorageDuration()) {
472 case SD_Automatic:
473 case SD_FullExpression:
474 if (auto *Size = EmitLifetimeStart(
475 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
476 Object.getPointer())) {
477 if (M->getStorageDuration() == SD_Automatic)
478 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
479 Object, Size);
480 else
481 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
482 Size);
483 }
484 break;
485 default:
486 break;
487 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000488 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
489 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000490 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000491
Richard Smith736a9472013-06-12 20:42:33 +0000492 // Perform derived-to-base casts and/or field accesses, to get from the
493 // temporary object we created (and, potentially, for which we extended
494 // the lifetime) to the subobject we're binding the reference to.
495 for (unsigned I = Adjustments.size(); I != 0; --I) {
496 SubobjectAdjustment &Adjustment = Adjustments[I-1];
497 switch (Adjustment.Kind) {
498 case SubobjectAdjustment::DerivedToBaseAdjustment:
499 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000500 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
501 Adjustment.DerivedToBase.BasePath->path_begin(),
502 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000503 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000504 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000505
Richard Smith736a9472013-06-12 20:42:33 +0000506 case SubobjectAdjustment::FieldAdjustment: {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000507 LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000508 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000509 assert(LV.isSimple() &&
510 "materialized temporary field is not a simple lvalue");
511 Object = LV.getAddress();
512 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000513 }
514
Richard Smith736a9472013-06-12 20:42:33 +0000515 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000516 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000517 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
518 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000519 break;
520 }
521 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000522 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000523
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000524 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000525}
526
527RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000528CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
529 // Emit the expression as an lvalue.
530 LValue LV = EmitLValue(E);
531 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000532 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000533
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000534 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000535 // C++11 [dcl.ref]p5 (as amended by core issue 453):
536 // If a glvalue to which a reference is directly bound designates neither
537 // an existing object or function of an appropriate type nor a region of
538 // storage of suitable size and alignment to contain an object of the
539 // reference's type, the behavior is undefined.
540 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000541 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000542 }
John McCall8680f872010-07-21 06:29:51 +0000543
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000544 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000545}
546
547
Mike Stump4a3999f2009-09-09 13:00:44 +0000548/// getAccessedFieldNo - Given an encoded value and a result number, return the
549/// input field number being accessed.
550unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000551 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000552 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
553 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000554}
555
Richard Smith4d3110a2012-10-25 02:14:12 +0000556/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
557static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
558 llvm::Value *High) {
559 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
560 llvm::Value *K47 = Builder.getInt64(47);
561 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
562 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
563 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
564 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
565 return Builder.CreateMul(B1, KMul);
566}
567
Vedant Kumar24792e32017-10-03 01:27:25 +0000568bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
569 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
570 TCK == TCK_UpcastToVirtualBase;
571}
572
573bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
574 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
575 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
576 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
577 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
578 TCK == TCK_UpcastToVirtualBase);
579}
580
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000581bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000582 return SanOpts.has(SanitizerKind::Null) |
583 SanOpts.has(SanitizerKind::Alignment) |
584 SanOpts.has(SanitizerKind::ObjectSize) |
585 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000586}
587
Richard Smithe30752c2012-10-09 19:52:38 +0000588void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000589 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000590 CharUnits Alignment,
591 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000592 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000593 return;
594
Richard Smith2d8b2942012-11-01 07:22:08 +0000595 // Don't check pointers outside the default address space. The null check
596 // isn't correct, the object-size check isn't supported by LLVM, and we can't
597 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000598 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000599 return;
600
Vedant Kumarc420d142017-06-16 03:27:36 +0000601 // Don't check pointers to volatile data. The behavior here is implementation-
602 // defined.
603 if (Ty.isVolatileQualified())
604 return;
605
Alexey Samsonov24cad992014-07-17 18:46:27 +0000606 SanitizerScope SanScope(this);
607
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000608 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000609 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000610
Vedant Kumare859ebb2017-04-26 02:17:21 +0000611 // Quickly determine whether we have a pointer to an alloca. It's possible
612 // to skip null checks, and some alignment checks, for these pointers. This
613 // can reduce compile-time significantly.
614 auto PtrToAlloca =
615 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
616
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000617 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000618 llvm::Value *IsNonNull = nullptr;
619 bool IsGuaranteedNonNull =
620 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
Vedant Kumar24792e32017-10-03 01:27:25 +0000621 bool AllowNullPointers = isNullPointerAllowed(TCK);
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000622 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000623 !IsGuaranteedNonNull) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000624 // The glvalue must not be an empty glvalue.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000625 IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000626
Vedant Kumardbbdda42017-04-17 22:26:10 +0000627 // The IR builder can constant-fold the null check if the pointer points to
628 // a constant.
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000629 IsGuaranteedNonNull = IsNonNull == True;
Vedant Kumardbbdda42017-04-17 22:26:10 +0000630
631 // Skip the null check if the pointer is known to be non-null.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000632 if (!IsGuaranteedNonNull) {
Vedant Kumardbbdda42017-04-17 22:26:10 +0000633 if (AllowNullPointers) {
634 // When performing pointer casts, it's OK if the value is null.
635 // Skip the remaining checks in that case.
636 Done = createBasicBlock("null");
637 llvm::BasicBlock *Rest = createBasicBlock("not.null");
638 Builder.CreateCondBr(IsNonNull, Rest, Done);
639 EmitBlock(Rest);
640 } else {
641 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
642 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000643 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000644 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000645
Vedant Kumar18348ea2017-02-17 23:22:55 +0000646 if (SanOpts.has(SanitizerKind::ObjectSize) &&
647 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
648 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000649 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000650
Richard Smith69d0d262012-08-24 00:54:33 +0000651 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000652 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000653 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000654 // FIXME: Get object address space
655 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
656 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000657 llvm::Value *Min = Builder.getFalse();
George Burgess IVa63f9152017-03-21 20:09:35 +0000658 llvm::Value *NullIsUnknown = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000659 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
George Burgess IVa63f9152017-03-21 20:09:35 +0000660 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
661 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
662 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000663 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000664 }
Richard Smith69d0d262012-08-24 00:54:33 +0000665
Richard Smithb1b0ab42012-11-05 22:21:05 +0000666 uint64_t AlignVal = 0;
Vedant Kumar8a715332017-10-03 01:27:24 +0000667 llvm::Value *PtrAsInt = nullptr;
Richard Smithb1b0ab42012-11-05 22:21:05 +0000668
Vedant Kumar18348ea2017-02-17 23:22:55 +0000669 if (SanOpts.has(SanitizerKind::Alignment) &&
670 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000671 AlignVal = Alignment.getQuantity();
672 if (!Ty->isIncompleteType() && !AlignVal)
673 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
674
Richard Smith69d0d262012-08-24 00:54:33 +0000675 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000676 if (AlignVal > 1 &&
677 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Vedant Kumar8a715332017-10-03 01:27:24 +0000678 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
679 llvm::Value *Align = Builder.CreateAnd(
680 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000681 llvm::Value *Aligned =
Vedant Kumar8a715332017-10-03 01:27:24 +0000682 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000683 if (Aligned != True)
684 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000685 }
Richard Smith69d0d262012-08-24 00:54:33 +0000686 }
687
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000688 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000689 // Make sure we're not losing information. Alignment needs to be a power of
690 // 2
691 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000692 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000693 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
694 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
695 llvm::ConstantInt::get(Int8Ty, TCK)};
Vedant Kumar8a715332017-10-03 01:27:24 +0000696 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
697 PtrAsInt ? PtrAsInt : Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000698 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000699
Richard Smithb1b0ab42012-11-05 22:21:05 +0000700 // If possible, check that the vptr indicates that there is a subobject of
701 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000702 //
703 // C++11 [basic.life]p5,6:
704 // [For storage which does not refer to an object within its lifetime]
705 // The program has undefined behavior if:
706 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000707 // or call a non-static member function
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000708 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumar24792e32017-10-03 01:27:25 +0000709 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000710 // Ensure that the pointer is non-null before loading it. If there is no
Vedant Kumara0c36712017-08-02 18:10:31 +0000711 // compile-time guarantee, reuse the run-time null check or emit a new one.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000712 if (!IsGuaranteedNonNull) {
Vedant Kumara0c36712017-08-02 18:10:31 +0000713 if (!IsNonNull)
714 IsNonNull = Builder.CreateIsNotNull(Ptr);
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000715 if (!Done)
716 Done = createBasicBlock("vptr.null");
717 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
718 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
719 EmitBlock(VptrNotNull);
720 }
721
Richard Smith4d3110a2012-10-25 02:14:12 +0000722 // Compute a hash of the mangled name of the type.
723 //
724 // FIXME: This is not guaranteed to be deterministic! Move to a
725 // fingerprinting mechanism once LLVM provides one. For the time
726 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000727 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000728 llvm::raw_svector_ostream Out(MangledName);
729 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
730 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000731
Alexey Samsonov84856012014-07-10 22:34:19 +0000732 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000733 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +0000734 SanitizerKind::Vptr, Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000735 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000736
Alexey Samsonov84856012014-07-10 22:34:19 +0000737 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
738 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
739 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000740 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000741 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
742 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000743
Alexey Samsonov84856012014-07-10 22:34:19 +0000744 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
745 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000746
Alexey Samsonov84856012014-07-10 22:34:19 +0000747 // Look the hash up in our cache.
748 const int CacheSize = 128;
749 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
750 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
751 "__ubsan_vptr_type_cache");
752 llvm::Value *Slot = Builder.CreateAnd(Hash,
753 llvm::ConstantInt::get(IntPtrTy,
754 CacheSize-1));
755 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
756 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000757 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
758 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000759
760 // If the hash isn't in the cache, call a runtime handler to perform the
761 // hard work of checking whether the vptr is for an object of the right
762 // type. This will either fill in the cache and return, or produce a
763 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000764 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000765 llvm::Constant *StaticData[] = {
766 EmitCheckSourceLocation(Loc),
767 EmitCheckTypeDescriptor(Ty),
768 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
769 llvm::ConstantInt::get(Int8Ty, TCK)
770 };
John McCall7f416cc2015-09-08 08:05:57 +0000771 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000772 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000773 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
774 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000775 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000776 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000777
778 if (Done) {
779 Builder.CreateBr(Done);
780 EmitBlock(Done);
781 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000782}
Chris Lattner4647a212007-08-31 22:49:20 +0000783
Richard Smith539e4a72013-02-23 02:53:19 +0000784/// Determine whether this expression refers to a flexible array member in a
785/// struct. We disable array bounds checks for such members.
786static bool isFlexibleArrayMemberExpr(const Expr *E) {
787 // For compatibility with existing code, we treat arrays of length 0 or
788 // 1 as flexible array members.
789 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000790 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000791 if (CAT->getSize().ugt(1))
792 return false;
793 } else if (!isa<IncompleteArrayType>(AT))
794 return false;
795
796 E = E->IgnoreParens();
797
798 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000799 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000800 // FIXME: If the base type of the member expr is not FD->getParent(),
801 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000802 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000803 RecordDecl::field_iterator FI(
804 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
805 return ++FI == FD->getParent()->field_end();
806 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000807 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
808 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000809 }
810
811 return false;
812}
813
814/// If Base is known to point to the start of an array, return the length of
815/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000816static llvm::Value *getArrayIndexingBound(
817 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000818 // For the vector indexing extension, the bound is the number of elements.
819 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
820 IndexedType = Base->getType();
821 return CGF.Builder.getInt32(VT->getNumElements());
822 }
823
824 Base = Base->IgnoreParens();
825
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000826 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000827 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
828 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
829 IndexedType = CE->getSubExpr()->getType();
830 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000831 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000832 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000833 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000834 return CGF.getVLASize(VAT).first;
835 }
836 }
837
Craig Topper8a13c412014-05-21 05:09:00 +0000838 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000839}
840
841void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
842 llvm::Value *Index, QualType IndexType,
843 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000844 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000845 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000846 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000847
Richard Smith539e4a72013-02-23 02:53:19 +0000848 QualType IndexedType;
849 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
850 if (!Bound)
851 return;
852
853 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
854 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
855 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
856
857 llvm::Constant *StaticData[] = {
858 EmitCheckSourceLocation(E->getExprLoc()),
859 EmitCheckTypeDescriptor(IndexedType),
860 EmitCheckTypeDescriptor(IndexType)
861 };
862 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
863 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000864 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
865 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000866}
867
Chris Lattner116ce8f2010-01-09 21:40:03 +0000868
Chris Lattner116ce8f2010-01-09 21:40:03 +0000869CodeGenFunction::ComplexPairTy CodeGenFunction::
870EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
871 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000872 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000873
Chris Lattner116ce8f2010-01-09 21:40:03 +0000874 llvm::Value *NextVal;
875 if (isa<llvm::IntegerType>(InVal.first->getType())) {
876 uint64_t AmountVal = isInc ? 1 : -1;
877 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000878
Chris Lattner116ce8f2010-01-09 21:40:03 +0000879 // Add the inc/dec to the real part.
880 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
881 } else {
882 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
883 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
884 if (!isInc)
885 FVal.changeSign();
886 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000887
Chris Lattner116ce8f2010-01-09 21:40:03 +0000888 // Add the inc/dec to the real part.
889 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
890 }
Craig Topper99e79272013-07-26 05:59:26 +0000891
Chris Lattner116ce8f2010-01-09 21:40:03 +0000892 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000893
Chris Lattner116ce8f2010-01-09 21:40:03 +0000894 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000895 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000896
Chris Lattner116ce8f2010-01-09 21:40:03 +0000897 // If this is a postinc, return the value read from memory, otherwise use the
898 // updated value.
899 return isPre ? IncVal : InVal;
900}
901
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000902void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
903 CodeGenFunction *CGF) {
904 // Bind VLAs in the cast type.
905 if (CGF && E->getType()->isVariablyModifiedType())
906 CGF->EmitVariablyModifiedType(E->getType());
907
908 if (CGDebugInfo *DI = getModuleDebugInfo())
909 DI->EmitExplicitCastType(E->getType());
910}
911
Chris Lattnera45c5af2007-06-02 19:47:04 +0000912//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000913// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000914//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000915
John McCall7f416cc2015-09-08 08:05:57 +0000916/// EmitPointerWithAlignment - Given an expression of pointer type, try to
917/// derive a more accurate bound on the alignment of the pointer.
918Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000919 LValueBaseInfo *BaseInfo,
920 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000921 // We allow this with ObjC object pointers because of fragile ABIs.
922 assert(E->getType()->isPointerType() ||
923 E->getType()->isObjCObjectPointerType());
924 E = E->IgnoreParens();
925
926 // Casts:
927 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000928 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
929 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000930
931 switch (CE->getCastKind()) {
932 // Non-converting casts (but not C's implicit conversion from void*).
933 case CK_BitCast:
934 case CK_NoOp:
Anastasia Stulova0a72ed42017-09-27 14:37:00 +0000935 case CK_AddressSpaceConversion:
John McCall7f416cc2015-09-08 08:05:57 +0000936 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
937 if (PtrTy->getPointeeType()->isVoidType())
938 break;
939
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000940 LValueBaseInfo InnerBaseInfo;
941 TBAAAccessInfo InnerTBAAInfo;
942 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
943 &InnerBaseInfo,
944 &InnerTBAAInfo);
945 if (BaseInfo) *BaseInfo = InnerBaseInfo;
946 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +0000947
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000948 if (isa<ExplicitCastExpr>(CE)) {
949 LValueBaseInfo TargetTypeBaseInfo;
950 TBAAAccessInfo TargetTypeTBAAInfo;
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000951 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000952 &TargetTypeBaseInfo,
953 &TargetTypeTBAAInfo);
954 if (TBAAInfo)
955 *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
956 TargetTypeTBAAInfo);
957 // If the source l-value is opaque, honor the alignment of the
958 // casted-to type.
959 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
960 if (BaseInfo)
961 BaseInfo->mergeForCast(TargetTypeBaseInfo);
962 Addr = Address(Addr.getPointer(), Align);
963 }
John McCall7f416cc2015-09-08 08:05:57 +0000964 }
965
Peter Collingbourne574975e2016-01-14 02:49:48 +0000966 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
967 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000968 if (auto PT = E->getType()->getAs<PointerType>())
969 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
970 /*MayBeNull=*/true,
971 CodeGenFunction::CFITCK_UnrelatedCast,
972 CE->getLocStart());
973 }
Anastasia Stulova0a72ed42017-09-27 14:37:00 +0000974 return CE->getCastKind() != CK_AddressSpaceConversion
975 ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
976 : Builder.CreateAddrSpaceCast(Addr,
977 ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000978 }
979 break;
980
981 // Array-to-pointer decay.
982 case CK_ArrayToPointerDecay:
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000983 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000984
985 // Derived-to-base conversions.
986 case CK_UncheckedDerivedToBase:
987 case CK_DerivedToBase: {
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000988 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo,
989 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000990 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
991 return GetAddressOfBaseClass(Addr, Derived,
992 CE->path_begin(), CE->path_end(),
993 ShouldNullCheckClassCastValue(CE),
994 CE->getExprLoc());
995 }
996
997 // TODO: Is there any reason to treat base-to-derived conversions
998 // specially?
999 default:
1000 break;
1001 }
1002 }
1003
1004 // Unary &.
1005 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1006 if (UO->getOpcode() == UO_AddrOf) {
1007 LValue LV = EmitLValue(UO->getSubExpr());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001008 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001009 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
John McCall7f416cc2015-09-08 08:05:57 +00001010 return LV.getAddress();
1011 }
1012 }
1013
1014 // TODO: conditional operators, comma.
1015
1016 // Otherwise, use the alignment of the type.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001017 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo,
1018 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001019 return Address(EmitScalarExpr(E), Align);
1020}
1021
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001022RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001023 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001024 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +00001025
1026 switch (getEvaluationKind(Ty)) {
1027 case TEK_Complex: {
1028 llvm::Type *EltTy =
1029 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +00001030 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001031 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001032 }
Craig Topper99e79272013-07-26 05:59:26 +00001033
Chris Lattner65526f02010-08-23 05:26:13 +00001034 // If this is a use of an undefined aggregate type, the aggregate must have an
1035 // identifiable address. Just because the contents of the value are undefined
1036 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +00001037 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00001038 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +00001039 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001040 }
John McCall47fb9502013-03-07 21:37:08 +00001041
1042 case TEK_Scalar:
1043 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1044 }
1045 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +00001046}
1047
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001048RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1049 const char *Name) {
1050 ErrorUnsupported(E, Name);
1051 return GetUndefRValue(E->getType());
1052}
1053
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001054LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1055 const char *Name) {
1056 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001057 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001058 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1059 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001060}
1061
Vedant Kumarffd7c882017-04-14 22:03:34 +00001062bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001063 const Expr *Base = Obj;
1064 while (!isa<CXXThisExpr>(Base)) {
1065 // The result of a dynamic_cast can be null.
1066 if (isa<CXXDynamicCastExpr>(Base))
1067 return false;
1068
1069 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1070 Base = CE->getSubExpr();
1071 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1072 Base = PE->getSubExpr();
1073 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1074 if (UO->getOpcode() == UO_Extension)
1075 Base = UO->getSubExpr();
1076 else
1077 return false;
1078 } else {
1079 return false;
1080 }
1081 }
1082 return true;
1083}
1084
Richard Smith4d1458e2012-09-08 02:08:36 +00001085LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +00001086 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001087 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +00001088 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1089 else
1090 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001091 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1092 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001093 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1094 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1095 if (IsBaseCXXThis)
1096 SkippedChecks.set(SanitizerKind::Alignment, true);
1097 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001098 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001099 }
John McCall7f416cc2015-09-08 08:05:57 +00001100 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001101 E->getType(), LV.getAlignment(), SkippedChecks);
1102 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001103 return LV;
1104}
1105
Chris Lattner8394d792007-06-05 20:53:16 +00001106/// EmitLValue - Emit code to compute a designator that specifies the location
1107/// of the expression.
1108///
Mike Stump4a3999f2009-09-09 13:00:44 +00001109/// This can return one of two things: a simple address or a bitfield reference.
1110/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1111/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001112///
Mike Stump4a3999f2009-09-09 13:00:44 +00001113/// If this returns a bitfield reference, nothing about the pointee type of the
1114/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001115///
Mike Stump4a3999f2009-09-09 13:00:44 +00001116/// If this returns a normal address, and if the lvalue's C type is fixed size,
1117/// this method guarantees that the returned pointer type will point to an LLVM
1118/// type of the same size of the lvalue's type. If the lvalue has a variable
1119/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001120///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001121LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001122 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001123 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001124 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001125
John McCallc109a252011-11-07 03:59:57 +00001126 case Expr::ObjCPropertyRefExprClass:
1127 llvm_unreachable("cannot emit a property reference directly");
1128
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001129 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001130 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001131 case Expr::ObjCIsaExprClass:
1132 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001133 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001134 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001135 case Expr::CompoundAssignOperatorClass: {
1136 QualType Ty = E->getType();
1137 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1138 Ty = AT->getValueType();
1139 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001140 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1141 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001142 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001143 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001144 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001145 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001146 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001147 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001148 case Expr::VAArgExprClass:
1149 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001150 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001151 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001152 case Expr::ParenExprClass:
1153 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001154 case Expr::GenericSelectionExprClass:
1155 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001156 case Expr::PredefinedExprClass:
1157 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001158 case Expr::StringLiteralClass:
1159 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001160 case Expr::ObjCEncodeExprClass:
1161 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001162 case Expr::PseudoObjectExprClass:
1163 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001164 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001165 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001166 case Expr::CXXTemporaryObjectExprClass:
1167 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001168 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1169 case Expr::CXXBindTemporaryExprClass:
1170 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001171 case Expr::CXXUuidofExprClass:
1172 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001173 case Expr::LambdaExprClass:
1174 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001175
1176 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001177 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001178 enterFullExpression(cleanups);
1179 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001180 LValue LV = EmitLValue(cleanups->getSubExpr());
1181 if (LV.isSimple()) {
1182 // Defend against branches out of gnu statement expressions surrounded by
1183 // cleanups.
1184 llvm::Value *V = LV.getPointer();
1185 Scope.ForceCleanup({&V});
1186 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001187 getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
Reid Kleckner092d0652017-03-06 22:18:34 +00001188 }
1189 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1190 // bitfield lvalue or some other non-simple lvalue?
1191 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001192 }
1193
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001194 case Expr::CXXDefaultArgExprClass:
1195 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001196 case Expr::CXXDefaultInitExprClass: {
1197 CXXDefaultInitExprScope Scope(*this);
1198 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1199 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001200 case Expr::CXXTypeidExprClass:
1201 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001202
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001203 case Expr::ObjCMessageExprClass:
1204 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001205 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001206 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001207 case Expr::StmtExprClass:
1208 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001209 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001210 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001211 case Expr::ArraySubscriptExprClass:
1212 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001213 case Expr::OMPArraySectionExprClass:
1214 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001215 case Expr::ExtVectorElementExprClass:
1216 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001217 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001218 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001219 case Expr::CompoundLiteralExprClass:
1220 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001221 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001222 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001223 case Expr::BinaryConditionalOperatorClass:
1224 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001225 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001226 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001227 case Expr::OpaqueValueExprClass:
1228 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001229 case Expr::SubstNonTypeTemplateParmExprClass:
1230 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001231 case Expr::ImplicitCastExprClass:
1232 case Expr::CStyleCastExprClass:
1233 case Expr::CXXFunctionalCastExprClass:
1234 case Expr::CXXStaticCastExprClass:
1235 case Expr::CXXDynamicCastExprClass:
1236 case Expr::CXXReinterpretCastExprClass:
1237 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001238 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001239 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001240
Douglas Gregorfe314812011-06-21 17:03:29 +00001241 case Expr::MaterializeTemporaryExprClass:
1242 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Eric Fiseliercddaf872017-06-15 19:43:36 +00001243
1244 case Expr::CoawaitExprClass:
1245 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1246 case Expr::CoyieldExprClass:
1247 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001248 }
1249}
1250
John McCall71335052012-03-10 03:05:10 +00001251/// Given an object of the given canonical type, can we safely copy a
1252/// value out of it based on its initializer?
1253static bool isConstantEmittableObjectType(QualType type) {
1254 assert(type.isCanonical());
1255 assert(!type->isReferenceType());
1256
1257 // Must be const-qualified but non-volatile.
1258 Qualifiers qs = type.getLocalQualifiers();
1259 if (!qs.hasConst() || qs.hasVolatile()) return false;
1260
1261 // Otherwise, all object types satisfy this except C++ classes with
1262 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001263 if (const auto *RT = dyn_cast<RecordType>(type))
1264 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001265 if (RD->hasMutableFields() || !RD->isTrivial())
1266 return false;
1267
1268 return true;
1269}
1270
1271/// Can we constant-emit a load of a reference to a variable of the
1272/// given type? This is different from predicates like
1273/// Decl::isUsableInConstantExpressions because we do want it to apply
1274/// in situations that don't necessarily satisfy the language's rules
1275/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1276/// to do this with const float variables even if those variables
1277/// aren't marked 'constexpr'.
1278enum ConstantEmissionKind {
1279 CEK_None,
1280 CEK_AsReferenceOnly,
1281 CEK_AsValueOrReference,
1282 CEK_AsValueOnly
1283};
1284static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1285 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001286 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001287 if (isConstantEmittableObjectType(ref->getPointeeType()))
1288 return CEK_AsValueOrReference;
1289 return CEK_AsReferenceOnly;
1290 }
1291 if (isConstantEmittableObjectType(type))
1292 return CEK_AsValueOnly;
1293 return CEK_None;
1294}
1295
1296/// Try to emit a reference to the given value without producing it as
1297/// an l-value. This is actually more than an optimization: we can't
1298/// produce an l-value for variables that we never actually captured
1299/// in a block or lambda, which means const int variables or constexpr
1300/// literals or similar.
1301CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001302CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1303 ValueDecl *value = refExpr->getDecl();
1304
John McCall71335052012-03-10 03:05:10 +00001305 // The value needs to be an enum constant or a constant variable.
1306 ConstantEmissionKind CEK;
1307 if (isa<ParmVarDecl>(value)) {
1308 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001309 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001310 CEK = checkVarTypeForConstantEmission(var->getType());
1311 } else if (isa<EnumConstantDecl>(value)) {
1312 CEK = CEK_AsValueOnly;
1313 } else {
1314 CEK = CEK_None;
1315 }
1316 if (CEK == CEK_None) return ConstantEmission();
1317
John McCall71335052012-03-10 03:05:10 +00001318 Expr::EvalResult result;
1319 bool resultIsReference;
1320 QualType resultType;
1321
1322 // It's best to evaluate all the way as an r-value if that's permitted.
1323 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001324 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001325 resultIsReference = false;
1326 resultType = refExpr->getType();
1327
1328 // Otherwise, try to evaluate as an l-value.
1329 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001330 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001331 resultIsReference = true;
1332 resultType = value->getType();
1333
1334 // Failure.
1335 } else {
1336 return ConstantEmission();
1337 }
1338
1339 // In any case, if the initializer has side-effects, abandon ship.
1340 if (result.HasSideEffects)
1341 return ConstantEmission();
1342
1343 // Emit as a constant.
John McCallde0fe072017-08-15 21:42:52 +00001344 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1345 result.Val, resultType);
John McCall71335052012-03-10 03:05:10 +00001346
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001347 // Make sure we emit a debug reference to the global variable.
1348 // This should probably fire even for
1349 if (isa<VarDecl>(value)) {
1350 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001351 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001352 } else {
1353 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001354 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001355 }
John McCall71335052012-03-10 03:05:10 +00001356
1357 // If we emitted a reference constant, we need to dereference that.
1358 if (resultIsReference)
1359 return ConstantEmission::forReference(C);
1360
1361 return ConstantEmission::forValue(C);
1362}
1363
Alex Lorenz6cc83172017-08-25 10:07:00 +00001364static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1365 const MemberExpr *ME) {
1366 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1367 // Try to emit static variable member expressions as DREs.
1368 return DeclRefExpr::Create(
1369 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1370 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1371 ME->getType(), ME->getValueKind());
1372 }
1373 return nullptr;
1374}
1375
1376CodeGenFunction::ConstantEmission
1377CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1378 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1379 return tryEmitAsConstant(DRE);
1380 return ConstantEmission();
1381}
1382
Nick Lewycky2d84e842013-10-02 02:29:49 +00001383llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1384 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001385 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001386 lvalue.getType(), Loc, lvalue.getBaseInfo(),
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001387 lvalue.getTBAAInfo(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001388}
1389
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001390static bool hasBooleanRepresentation(QualType Ty) {
1391 if (Ty->isBooleanType())
1392 return true;
1393
1394 if (const EnumType *ET = Ty->getAs<EnumType>())
1395 return ET->getDecl()->getIntegerType()->isBooleanType();
1396
Douglas Gregor298f43d2012-04-12 20:42:30 +00001397 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1398 return hasBooleanRepresentation(AT->getValueType());
1399
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001400 return false;
1401}
1402
Richard Smith1629da92012-12-13 07:11:50 +00001403static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1404 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001405 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001406 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001407 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1408 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001409 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001410 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001411
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001412 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001413 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1414 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001415 } else {
1416 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001417 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001418 unsigned Bitwidth = LTy->getScalarSizeInBits();
1419 unsigned NumNegativeBits = ED->getNumNegativeBits();
1420 unsigned NumPositiveBits = ED->getNumPositiveBits();
1421
1422 if (NumNegativeBits) {
1423 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1424 assert(NumBits <= Bitwidth);
1425 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1426 Min = -End;
1427 } else {
1428 assert(NumPositiveBits <= Bitwidth);
1429 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1430 Min = llvm::APInt(Bitwidth, 0);
1431 }
1432 }
Richard Smith1629da92012-12-13 07:11:50 +00001433 return true;
1434}
1435
1436llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1437 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001438 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1439 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001440 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001441
Duncan Sandsc720e782012-04-15 18:04:54 +00001442 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001443 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001444}
1445
Vedant Kumar5a972652017-02-27 19:46:19 +00001446bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1447 SourceLocation Loc) {
1448 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1449 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1450 if (!HasBoolCheck && !HasEnumCheck)
1451 return false;
1452
1453 bool IsBool = hasBooleanRepresentation(Ty) ||
1454 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1455 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1456 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1457 if (!NeedsBoolCheck && !NeedsEnumCheck)
1458 return false;
1459
Vedant Kumar129edab2017-03-09 16:06:27 +00001460 // Single-bit booleans don't need to be checked. Special-case this to avoid
1461 // a bit width mismatch when handling bitfield values. This is handled by
1462 // EmitFromMemory for the non-bitfield case.
1463 if (IsBool &&
1464 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1465 return false;
1466
Vedant Kumar5a972652017-02-27 19:46:19 +00001467 llvm::APInt Min, End;
1468 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1469 return true;
1470
Vedant Kumar791f7012017-10-03 01:27:26 +00001471 auto &Ctx = getLLVMContext();
Vedant Kumar5a972652017-02-27 19:46:19 +00001472 SanitizerScope SanScope(this);
1473 llvm::Value *Check;
1474 --End;
1475 if (!Min) {
Vedant Kumar791f7012017-10-03 01:27:26 +00001476 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
Vedant Kumar5a972652017-02-27 19:46:19 +00001477 } else {
Vedant Kumar791f7012017-10-03 01:27:26 +00001478 llvm::Value *Upper =
1479 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1480 llvm::Value *Lower =
1481 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
Vedant Kumar5a972652017-02-27 19:46:19 +00001482 Check = Builder.CreateAnd(Upper, Lower);
1483 }
1484 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1485 EmitCheckTypeDescriptor(Ty)};
1486 SanitizerMask Kind =
1487 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1488 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1489 StaticArgs, EmitCheckValue(Value));
1490 return true;
1491}
1492
John McCall7f416cc2015-09-08 08:05:57 +00001493llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1494 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001495 SourceLocation Loc,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001496 LValueBaseInfo BaseInfo,
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001497 TBAAAccessInfo TBAAInfo,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001498 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001499 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1500 // For better performance, handle vector loads differently.
1501 if (Ty->isVectorType()) {
1502 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001503
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001504 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001505
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001506 // Handle vectors of size 3 like size 4 for better performance.
1507 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001508
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001509 // Bitcast to vec4 type.
1510 llvm::VectorType *vec4Ty =
1511 llvm::VectorType::get(VTy->getElementType(), 4);
1512 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1513 // Now load value.
1514 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001515
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001516 // Shuffle vector to get vec3.
1517 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1518 {0, 1, 2}, "extractVec");
1519 return EmitFromMemory(V, Ty);
1520 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001521 }
1522 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001523
1524 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001525 LValue AtomicLValue =
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001526 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001527 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1528 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001529 }
Craig Topper99e79272013-07-26 05:59:26 +00001530
John McCall7f416cc2015-09-08 08:05:57 +00001531 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001532 if (isNontemporal) {
1533 llvm::MDNode *Node = llvm::MDNode::get(
1534 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1535 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1536 }
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001537
1538 if (BaseInfo.getMayAlias())
1539 TBAAInfo = CGM.getTBAAMayAliasAccessInfo();
1540 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001541
Vedant Kumar5a972652017-02-27 19:46:19 +00001542 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1543 // In order to prevent the optimizer from throwing away the check, don't
1544 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001545 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001546 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1547 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001548
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001549 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001550}
1551
John McCall3a7f6922010-10-27 20:58:56 +00001552llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1553 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001554 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001555 // This should really always be an i1, but sometimes it's already
1556 // an i8, and it's awkward to track those cases down.
1557 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001558 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1559 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1560 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001561 }
1562
1563 return Value;
1564}
1565
1566llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1567 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001568 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001569 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1570 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001571 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1572 }
1573
1574 return Value;
1575}
1576
John McCall7f416cc2015-09-08 08:05:57 +00001577void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1578 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001579 LValueBaseInfo BaseInfo,
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001580 TBAAAccessInfo TBAAInfo,
1581 bool isInit, bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001582 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1583 // Handle vectors differently to get better performance.
1584 if (Ty->isVectorType()) {
1585 llvm::Type *SrcTy = Value->getType();
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001586 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001587 // Handle vec3 special.
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001588 if (VecTy && VecTy->getNumElements() == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001589 // Our source is a vec3, do a shuffle vector to make it a vec4.
1590 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1591 Builder.getInt32(2),
1592 llvm::UndefValue::get(Builder.getInt32Ty())};
1593 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1594 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1595 MaskV, "extractVec");
1596 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1597 }
1598 if (Addr.getElementType() != SrcTy) {
1599 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1600 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001601 }
1602 }
Craig Topper99e79272013-07-26 05:59:26 +00001603
John McCall3a7f6922010-10-27 20:58:56 +00001604 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001605
David Majnemera38c9f12016-05-24 16:09:25 +00001606 LValue AtomicLValue =
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001607 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001608 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001609 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1610 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001611 return;
1612 }
1613
Daniel Dunbar03816342010-08-21 02:24:36 +00001614 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001615 if (isNontemporal) {
1616 llvm::MDNode *Node =
1617 llvm::MDNode::get(Store->getContext(),
1618 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1619 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1620 }
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001621
1622 if (BaseInfo.getMayAlias())
1623 TBAAInfo = CGM.getTBAAMayAliasAccessInfo();
1624 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001625}
1626
David Chisnallfa35df62012-01-16 17:27:18 +00001627void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001628 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001629 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001630 lvalue.getType(), lvalue.getBaseInfo(),
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001631 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001632}
1633
Mike Stump4a3999f2009-09-09 13:00:44 +00001634/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1635/// method emits the address of the lvalue, then loads the result as an rvalue,
1636/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001637RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001638 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001639 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001640 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001641 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1642 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001643 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001644 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001645 // In MRC mode, we do a load+autorelease.
1646 if (!getLangOpts().ObjCAutoRefCount) {
1647 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1648 }
1649
1650 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001651 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1652 Object = EmitObjCConsumeObject(LV.getType(), Object);
1653 return RValue::get(Object);
1654 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001655
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001656 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001657 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001658
John McCalla1dee5302010-08-22 10:59:02 +00001659 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001660 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001661 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001662
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001663 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001664 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001665 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001666 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001667 "vecext"));
1668 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001669
1670 // If this is a reference to a subset of the elements of a vector, either
1671 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001672 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001673 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001674
Renato Golin230c5eb2014-05-19 18:15:42 +00001675 // Global Register variables always invoke intrinsics
1676 if (LV.isGlobalReg())
1677 return EmitLoadOfGlobalRegLValue(LV);
1678
John McCallc109a252011-11-07 03:59:57 +00001679 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001680 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001681}
1682
Vedant Kumar129edab2017-03-09 16:06:27 +00001683RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1684 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001685 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001686
Daniel Dunbar3447a022010-04-13 23:34:15 +00001687 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001688 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001689
John McCall7f416cc2015-09-08 08:05:57 +00001690 Address Ptr = LV.getBitFieldAddress();
1691 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001692
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001693 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001694 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001695 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1696 if (HighBits)
1697 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1698 if (Info.Offset + HighBits)
1699 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1700 } else {
1701 if (Info.Offset)
1702 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001703 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001704 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1705 Info.Size),
1706 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001707 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001708 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001709 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001710 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001711}
1712
Nate Begemanb699c9b2009-01-18 06:42:49 +00001713// If this is a reference to a subset of the elements of a vector, create an
1714// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001715RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001716 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1717 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001718
Nate Begemanf322eab2008-05-09 06:41:27 +00001719 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001720
1721 // If the result of the expression is a non-vector type, we must be extracting
1722 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001723 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001724 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001725 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001726 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001727 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001728 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001729
1730 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001731 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001732
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001733 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001734 for (unsigned i = 0; i != NumResultElts; ++i)
1735 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001736
Chris Lattner91c08ad2011-02-15 00:14:06 +00001737 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1738 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001739 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001740 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001741}
1742
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001743/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001744Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1745 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001746 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1747 QualType EQT = ExprVT->getElementType();
1748 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001749
John McCall7f416cc2015-09-08 08:05:57 +00001750 Address CastToPointerElement =
1751 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1752 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001753
1754 const llvm::Constant *Elts = LV.getExtVectorElts();
1755 unsigned ix = getAccessedFieldNo(0, Elts);
1756
John McCall7f416cc2015-09-08 08:05:57 +00001757 Address VectorBasePtrPlusIx =
1758 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1759 getContext().getTypeSizeInChars(EQT),
1760 "vector.elt");
1761
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001762 return VectorBasePtrPlusIx;
1763}
1764
Renato Golin230c5eb2014-05-19 18:15:42 +00001765/// @brief Load of global gamed gegisters are always calls to intrinsics.
1766RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001767 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1768 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001769 llvm::MDNode *RegName = cast<llvm::MDNode>(
1770 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001771
1772 // We accept integer and pointer types only
1773 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1774 llvm::Type *Ty = OrigTy;
1775 if (OrigTy->isPointerTy())
1776 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1777 llvm::Type *Types[] = { Ty };
1778
Renato Golin230c5eb2014-05-19 18:15:42 +00001779 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001780 llvm::Value *Call = Builder.CreateCall(
1781 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001782 if (OrigTy->isPointerTy())
1783 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001784 return RValue::get(Call);
1785}
Chris Lattner40ff7012007-08-03 16:18:34 +00001786
Chris Lattner9369a562007-06-29 16:31:29 +00001787
Chris Lattner8394d792007-06-05 20:53:16 +00001788/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1789/// lvalue, where both are guaranteed to the have the same type, and that type
1790/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001791void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001792 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001793 if (!Dst.isSimple()) {
1794 if (Dst.isVectorElt()) {
1795 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001796 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1797 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001798 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001799 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001800 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1801 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001802 return;
1803 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001804
Nate Begemance4d7fc2008-04-18 23:10:10 +00001805 // If this is an update of extended vector elements, insert them as
1806 // appropriate.
1807 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001808 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001809
Renato Golin230c5eb2014-05-19 18:15:42 +00001810 if (Dst.isGlobalReg())
1811 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1812
John McCallc109a252011-11-07 03:59:57 +00001813 assert(Dst.isBitField() && "Unknown LValue type");
1814 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001815 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001816
John McCall31168b02011-06-15 23:02:42 +00001817 // There's special magic for assigning into an ARC-qualified l-value.
1818 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1819 switch (Lifetime) {
1820 case Qualifiers::OCL_None:
1821 llvm_unreachable("present but none");
1822
1823 case Qualifiers::OCL_ExplicitNone:
1824 // nothing special
1825 break;
1826
1827 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001828 if (isInit) {
1829 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1830 break;
1831 }
John McCall55e1fbc2011-06-25 02:11:03 +00001832 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001833 return;
1834
1835 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001836 if (isInit)
1837 // Initialize and then skip the primitive store.
1838 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1839 else
1840 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001841 return;
1842
1843 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001844 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1845 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001846 // fall into the normal path
1847 break;
1848 }
1849 }
1850
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001851 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001852 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001853 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001854 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001855 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001856 return;
1857 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001858
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001859 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001860 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001861 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001862 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001863 if (Dst.isObjCIvar()) {
1864 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001865 llvm::Type *ResultType = IntPtrTy;
1866 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1867 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001868 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001869 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001870 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1871 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001872 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001873 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001874 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001875 } else if (Dst.isGlobalObjCRef()) {
1876 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1877 Dst.isThreadLocalRef());
1878 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001879 else
1880 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001881 return;
1882 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001883
Chris Lattner6278e6a2007-08-11 00:04:45 +00001884 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001885 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001886}
1887
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001888void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001889 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001890 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001891 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001892 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001893
Daniel Dunbar67aba792010-04-15 03:47:33 +00001894 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001895 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001896
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001897 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001898 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001899 /*IsSigned=*/false);
1900 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001901
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001902 // See if there are other bits in the bitfield's storage we'll need to load
1903 // and mask together with source before storing.
1904 if (Info.StorageSize != Info.Size) {
1905 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001906 llvm::Value *Val =
1907 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001908
1909 // Mask the source value as needed.
1910 if (!hasBooleanRepresentation(Dst.getType()))
1911 SrcVal = Builder.CreateAnd(SrcVal,
1912 llvm::APInt::getLowBitsSet(Info.StorageSize,
1913 Info.Size),
1914 "bf.value");
1915 MaskedVal = SrcVal;
1916 if (Info.Offset)
1917 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1918
1919 // Mask out the original value.
1920 Val = Builder.CreateAnd(Val,
1921 ~llvm::APInt::getBitsSet(Info.StorageSize,
1922 Info.Offset,
1923 Info.Offset + Info.Size),
1924 "bf.clear");
1925
1926 // Or together the unchanged values and the source value.
1927 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1928 } else {
1929 assert(Info.Offset == 0);
1930 }
1931
1932 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001933 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001934
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001935 // Return the new value of the bit-field, if requested.
1936 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001937 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001938
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001939 // Sign extend the value if needed.
1940 if (Info.IsSigned) {
1941 assert(Info.Size <= Info.StorageSize);
1942 unsigned HighBits = Info.StorageSize - Info.Size;
1943 if (HighBits) {
1944 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1945 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1946 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001947 }
1948
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001949 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1950 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001951 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001952 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001953}
1954
Nate Begemance4d7fc2008-04-18 23:10:10 +00001955void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001956 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001957 // This access turns into a read/modify/write of the vector. Load the input
1958 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001959 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1960 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001961 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001962
Chris Lattner4647a212007-08-31 22:49:20 +00001963 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001964
John McCall55e1fbc2011-06-25 02:11:03 +00001965 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001966 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001967 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001968 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001969 // Use shuffle vector is the src and destination are the same number of
1970 // elements and restore the vector mask since it is on the side it will be
1971 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001972 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001973 for (unsigned i = 0; i != NumSrcElts; ++i)
1974 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001975
Chris Lattner91c08ad2011-02-15 00:14:06 +00001976 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001977 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001978 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001979 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001980 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001981 // Extended the source vector to the same length and then shuffle it
1982 // into the destination.
1983 // FIXME: since we're shuffling with undef, can we just use the indices
1984 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001985 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001986 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001987 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001988 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001989 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001990 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001991 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001992 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001993 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001994 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001995 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001996 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001997 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001998
Joey Goulycf4143b2013-11-21 17:09:05 +00001999 // When the vector size is odd and .odd or .hi is used, the last element
2000 // of the Elts constant array will be one past the size of the vector.
2001 // Ignore the last element here, if it is greater than the mask size.
2002 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2003 NumSrcElts--;
2004
Nate Begemanb699c9b2009-01-18 06:42:49 +00002005 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002006 for (unsigned i = 0; i != NumSrcElts; ++i)
2007 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00002008 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002009 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00002010 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00002011 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00002012 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00002013 }
2014 } else {
2015 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00002016 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00002017 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002018 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00002019 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002020
John McCall7f416cc2015-09-08 08:05:57 +00002021 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2022 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00002023}
2024
Renato Golin230c5eb2014-05-19 18:15:42 +00002025/// @brief Store of global named registers are always calls to intrinsics.
2026void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00002027 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2028 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002029 llvm::MDNode *RegName = cast<llvm::MDNode>(
2030 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00002031 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00002032
2033 // We accept integer and pointer types only
2034 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2035 llvm::Type *Ty = OrigTy;
2036 if (OrigTy->isPointerTy())
2037 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2038 llvm::Type *Types[] = { Ty };
2039
Renato Golin230c5eb2014-05-19 18:15:42 +00002040 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2041 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00002042 if (OrigTy->isPointerTy())
2043 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00002044 Builder.CreateCall(
2045 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00002046}
2047
Eric Christopherc9e2a682014-05-20 17:10:39 +00002048// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002049// generating write-barries API. It is currently a global, ivar,
2050// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002051static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002052 LValue &LV,
2053 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002054 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002055 return;
Craig Topper99e79272013-07-26 05:59:26 +00002056
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002057 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002058 QualType ExpTy = E->getType();
2059 if (IsMemberAccess && ExpTy->isPointerType()) {
2060 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00002061 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002062 // writer-barrier conservatively.
2063 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2064 if (ExpTy->isRecordType()) {
2065 LV.setObjCIvar(false);
2066 return;
2067 }
2068 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002069 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002070 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002071 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002072 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002073 return;
2074 }
Craig Topper99e79272013-07-26 05:59:26 +00002075
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002076 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2077 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00002078 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002079 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00002080 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002081 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002082 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002083 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002084 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002085 }
Craig Topper99e79272013-07-26 05:59:26 +00002086
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002087 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002088 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002089 return;
2090 }
Craig Topper99e79272013-07-26 05:59:26 +00002091
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002092 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002093 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002094 if (LV.isObjCIvar()) {
2095 // If cast is to a structure pointer, follow gcc's behavior and make it
2096 // a non-ivar write-barrier.
2097 QualType ExpTy = E->getType();
2098 if (ExpTy->isPointerType())
2099 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2100 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002101 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002102 }
2103 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002104 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002105
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002106 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002107 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2108 return;
2109 }
2110
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002111 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002112 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002113 return;
2114 }
Craig Topper99e79272013-07-26 05:59:26 +00002115
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002116 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002117 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002118 return;
2119 }
John McCall31168b02011-06-15 23:02:42 +00002120
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002121 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002122 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002123 return;
2124 }
2125
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002126 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002127 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002128 if (LV.isObjCIvar() && !LV.isObjCArray())
2129 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002130 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002131 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002132 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002133 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002134 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002135 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002136 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002137 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002138
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002139 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002140 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002141 // We don't know if member is an 'ivar', but this flag is looked at
2142 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002143 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002144 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002145 }
2146}
2147
Chris Lattner3f32d692011-07-12 06:52:18 +00002148static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002149EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002150 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002151 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002152 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002153 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002154}
2155
Alexey Bataev97720002014-11-11 04:05:39 +00002156static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002157 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2158 llvm::Type *RealVarTy, SourceLocation Loc) {
2159 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2160 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002161 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
John McCall7f416cc2015-09-08 08:05:57 +00002162}
2163
2164Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2165 const ReferenceType *RefTy,
Ivan A. Kosarev1590fd32017-10-13 16:50:50 +00002166 LValueBaseInfo *BaseInfo,
2167 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002168 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2169 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +00002170 BaseInfo, TBAAInfo,
2171 /* forPointeeType= */ true));
John McCall7f416cc2015-09-08 08:05:57 +00002172}
2173
2174LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2175 const ReferenceType *RefTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002176 LValueBaseInfo BaseInfo;
Ivan A. Kosarev1590fd32017-10-13 16:50:50 +00002177 TBAAAccessInfo TBAAInfo;
2178 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo, &TBAAInfo);
2179 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo, TBAAInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002180}
2181
Alexey Bataev31300ed2016-02-04 11:27:03 +00002182Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2183 const PointerType *PtrTy,
Ivan A. Kosarev90295642017-10-13 16:47:22 +00002184 LValueBaseInfo *BaseInfo,
2185 TBAAAccessInfo *TBAAInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002186 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002187 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +00002188 BaseInfo, TBAAInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002189 /*forPointeeType=*/true));
2190}
2191
2192LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2193 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002194 LValueBaseInfo BaseInfo;
Ivan A. Kosarev90295642017-10-13 16:47:22 +00002195 TBAAAccessInfo TBAAInfo;
2196 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2197 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002198}
2199
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002200static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2201 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002202 QualType T = E->getType();
2203
2204 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002205 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2206 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002207 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2208
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002209 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002210 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2211 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002212 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002213 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002214 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002215 // Emit reference to the private copy of the variable if it is an OpenMP
2216 // threadprivate variable.
2217 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002218 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002219 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002220 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2221 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002222 } else {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002223 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002224 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002225 setObjCGCLValueClass(CGF.getContext(), E, LV);
2226 return LV;
2227}
2228
John McCallb92ab1a2016-10-26 23:46:34 +00002229static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2230 const FunctionDecl *FD) {
2231 if (FD->hasAttr<WeakRefAttr>()) {
2232 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2233 return aliasee.getPointer();
2234 }
2235
2236 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002237 if (!FD->hasPrototype()) {
2238 if (const FunctionProtoType *Proto =
2239 FD->getType()->getAs<FunctionProtoType>()) {
2240 // Ugly case: for a K&R-style definition, the type of the definition
2241 // isn't the same as the type of a use. Correct for this with a
2242 // bitcast.
2243 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002244 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2245 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2246 V = llvm::ConstantExpr::getBitCast(V,
2247 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002248 }
2249 }
John McCallb92ab1a2016-10-26 23:46:34 +00002250 return V;
2251}
2252
2253static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2254 const Expr *E, const FunctionDecl *FD) {
2255 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002256 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002257 return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2258 AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002259}
2260
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002261static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2262 llvm::Value *ThisValue) {
2263 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2264 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2265 return CGF.EmitLValueForField(LV, FD);
2266}
2267
Renato Golin230c5eb2014-05-19 18:15:42 +00002268/// Named Registers are named metadata pointing to the register name
2269/// which will be read from/written to as an argument to the intrinsic
2270/// @llvm.read/write_register.
2271/// So far, only the name is being passed down, but other options such as
2272/// register type, allocation type or even optimization options could be
2273/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002274static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002275 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002276 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002277 assert(Asm->getLabel().size() < 64-Name.size() &&
2278 "Register name too big");
2279 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002280 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002281 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002282 if (M->getNumOperands() == 0) {
2283 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2284 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002285 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002286 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2287 }
John McCall7f416cc2015-09-08 08:05:57 +00002288
2289 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2290
2291 llvm::Value *Ptr =
2292 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2293 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002294}
2295
Chris Lattnerd7f58862007-06-02 05:24:33 +00002296LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002297 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002298 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002299
Renato Goline7b3d5d2014-05-27 16:46:27 +00002300 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2301 // Global Named registers access via intrinsics only
2302 if (VD->getStorageClass() == SC_Register &&
2303 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002304 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002305
Renato Goline7b3d5d2014-05-27 16:46:27 +00002306 // A DeclRefExpr for a reference initialized by a constant expression can
2307 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002308 const Expr *Init = VD->getAnyInitializer(VD);
2309 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2310 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002311 VD->checkInitIsICE() &&
2312 // Do not emit if it is private OpenMP variable.
Alexey Bataevcab496d2017-10-06 16:17:25 +00002313 !(E->refersToEnclosingVariableOrCapture() &&
2314 ((CapturedStmtInfo &&
2315 (LocalDeclMap.count(VD->getCanonicalDecl()) ||
2316 CapturedStmtInfo->lookup(VD->getCanonicalDecl()))) ||
2317 LambdaCaptureFields.lookup(VD->getCanonicalDecl()) ||
2318 isa<BlockDecl>(CurCodeDecl)))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002319 llvm::Constant *Val =
John McCallde0fe072017-08-15 21:42:52 +00002320 ConstantEmitter(*this).emitAbstract(E->getLocation(),
2321 *VD->evaluateValue(),
2322 VD->getType());
Richard Smith5a1104b2012-10-20 01:38:33 +00002323 assert(Val && "failed to emit reference constant expression");
2324 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002325
2326 // Should we be using the alignment of the constant pointer we emitted?
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +00002327 CharUnits Alignment = getNaturalTypeAlignment(E->getType(),
2328 /* BaseInfo= */ nullptr,
2329 /* TBAAInfo= */ nullptr,
2330 /* forPointeeType= */ true);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002331 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002332 }
David Majnemer602cfe72015-01-01 09:49:44 +00002333
2334 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002335 if (E->refersToEnclosingVariableOrCapture()) {
Alexey Bataev6a71f362017-08-22 17:54:52 +00002336 VD = VD->getCanonicalDecl();
David Majnemer602cfe72015-01-01 09:49:44 +00002337 if (auto *FD = LambdaCaptureFields.lookup(VD))
2338 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2339 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002340 auto I = LocalDeclMap.find(VD);
2341 if (I != LocalDeclMap.end()) {
2342 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2343 return EmitLoadOfReferenceLValue(I->second, RefTy);
2344 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002345 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002346 LValue CapLVal =
2347 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2348 CapturedStmtInfo->getContextValue());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002349 bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002350 return MakeAddrLValue(
2351 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00002352 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias),
2353 CGM.getTBAAAccessInfo(CapLVal.getType()));
David Majnemer602cfe72015-01-01 09:49:44 +00002354 }
John McCall7f416cc2015-09-08 08:05:57 +00002355
David Majnemer602cfe72015-01-01 09:49:44 +00002356 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002357 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002358 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002359 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002360 }
2361
Eli Friedman5720e342012-01-21 04:52:58 +00002362 // FIXME: We should be able to assert this for FunctionDecls as well!
2363 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2364 // those with a valid source location.
2365 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2366 !E->getLocation().isValid()) &&
2367 "Should not use decl without marking it used!");
2368
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002369 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002370 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002371 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002372 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002373 }
2374
Renato Goline7b3d5d2014-05-27 16:46:27 +00002375 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002376 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002377 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002378 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002379
John McCall7f416cc2015-09-08 08:05:57 +00002380 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002381
John McCall7f416cc2015-09-08 08:05:57 +00002382 // The variable should generally be present in the local decl map.
2383 auto iter = LocalDeclMap.find(VD);
2384 if (iter != LocalDeclMap.end()) {
2385 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002386
John McCall7f416cc2015-09-08 08:05:57 +00002387 // Otherwise, it might be static local we haven't emitted yet for
2388 // some reason; most likely, because it's in an outer function.
2389 } else if (VD->isStaticLocal()) {
2390 addr = Address(CGM.getOrCreateStaticVarDecl(
2391 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2392 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002393
John McCall7f416cc2015-09-08 08:05:57 +00002394 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002395 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002396 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2397 }
2398
2399
2400 // Check for OpenMP threadprivate variables.
2401 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2402 return EmitThreadPrivateVarDeclLValue(
2403 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2404 E->getExprLoc());
2405 }
2406
2407 // Drill into block byref variables.
2408 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2409 if (isBlockByref) {
2410 addr = emitBlockByrefAddress(addr, VD);
2411 }
2412
2413 // Drill into reference types.
2414 LValue LV;
2415 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2416 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2417 } else {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002418 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002419 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002420
John McCallcdda29c2013-03-13 03:10:54 +00002421 bool isLocalStorage = VD->hasLocalStorage();
2422
2423 bool NonGCable = isLocalStorage &&
2424 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002425 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002426 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002427 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002428 LV.setNonGC(true);
2429 }
John McCallcdda29c2013-03-13 03:10:54 +00002430
2431 bool isImpreciseLifetime =
2432 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2433 if (isImpreciseLifetime)
2434 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002435 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002436 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002437 }
John McCallf3a88602011-02-03 08:15:49 +00002438
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002439 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002440 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002441
Richard Smithda383632016-08-15 01:33:41 +00002442 // FIXME: While we're emitting a binding from an enclosing scope, all other
2443 // DeclRefExprs we see should be implicitly treated as if they also refer to
2444 // an enclosing scope.
2445 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2446 return EmitLValue(BD->getBinding());
2447
David Blaikie83d382b2011-09-23 05:06:16 +00002448 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002449}
Chris Lattnere47e4402007-06-01 18:02:12 +00002450
Chris Lattner8394d792007-06-05 20:53:16 +00002451LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2452 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002453 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002454 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002455
Chris Lattner0f398c42008-07-26 22:37:01 +00002456 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002457 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002458 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002459 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002460 QualType T = E->getSubExpr()->getType()->getPointeeType();
2461 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002462
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002463 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00002464 TBAAAccessInfo TBAAInfo;
2465 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2466 &TBAAInfo);
2467 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002468 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002469
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002470 // We should not generate __weak write barrier on indirect reference
2471 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2472 // But, we continue to generate __strong write barrier on indirect write
2473 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002474 if (getLangOpts().ObjC1 &&
2475 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002476 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002477 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002478 return LV;
2479 }
John McCalle3027922010-08-25 11:45:40 +00002480 case UO_Real:
2481 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002482 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002483 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002484
Richard Smith0b6b8e42012-02-18 20:53:32 +00002485 // __real is valid on scalars. This is a faster way of testing that.
2486 // __imag can only produce an rvalue on scalars.
2487 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002488 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002489 assert(E->getSubExpr()->getType()->isArithmeticType());
2490 return LV;
2491 }
2492
Alexey Bataev611b0a12016-11-07 18:15:02 +00002493 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002494
John McCall7f416cc2015-09-08 08:05:57 +00002495 Address Component =
2496 (E->getOpcode() == UO_Real
2497 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2498 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00002499 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
2500 CGM.getTBAAAccessInfo(T));
Alexey Bataev611b0a12016-11-07 18:15:02 +00002501 ElemLV.getQuals().addQualifiers(LV.getQuals());
2502 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002503 }
John McCalle3027922010-08-25 11:45:40 +00002504 case UO_PreInc:
2505 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002506 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002507 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002508
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002509 if (E->getType()->isAnyComplexType())
2510 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2511 else
2512 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2513 return LV;
2514 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002515 }
Chris Lattner8394d792007-06-05 20:53:16 +00002516}
2517
Chris Lattner4347e3692007-06-06 04:54:52 +00002518LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002519 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002520 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002521}
2522
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002523LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002524 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002525 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002526}
2527
Mike Stump4a3999f2009-09-09 13:00:44 +00002528LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002529 auto SL = E->getFunctionName();
2530 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2531 StringRef FnName = CurFn->getName();
2532 if (FnName.startswith("\01"))
2533 FnName = FnName.substr(1);
2534 StringRef NameItems[] = {
2535 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2536 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002537 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2538 std::string Name = SL->getString();
2539 if (!Name.empty()) {
2540 unsigned Discriminator =
2541 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2542 if (Discriminator)
2543 Name += "_" + Twine(Discriminator + 1).str();
2544 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002545 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002546 } else {
2547 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002548 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002549 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002550 }
Alexey Bataevec474782014-10-09 08:45:04 +00002551 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002552 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002553}
2554
Richard Smithe30752c2012-10-09 19:52:38 +00002555/// Emit a type description suitable for use by a runtime sanitizer library. The
2556/// format of a type descriptor is
2557///
2558/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002559/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002560/// \endcode
2561///
Richard Smith683398a2012-10-09 23:55:19 +00002562/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2563/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002564llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002565 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002566 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002567 return C;
2568
Richard Smithe30752c2012-10-09 19:52:38 +00002569 uint16_t TypeKind = -1;
2570 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002571
Richard Smithe30752c2012-10-09 19:52:38 +00002572 if (T->isIntegerType()) {
2573 TypeKind = 0;
2574 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002575 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002576 } else if (T->isFloatingType()) {
2577 TypeKind = 1;
2578 TypeInfo = getContext().getTypeSize(T);
2579 }
2580
2581 // Format the type name as if for a diagnostic, including quotes and
2582 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002583 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002584 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2585 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002586 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002587 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002588
2589 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002590 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2591 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002592 };
2593 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2594
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002595 auto *GV = new llvm::GlobalVariable(
2596 CGM.getModule(), Descriptor->getType(),
2597 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002598 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002599 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002600
2601 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002602 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002603
Richard Smithe30752c2012-10-09 19:52:38 +00002604 return GV;
2605}
2606
2607llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2608 llvm::Type *TargetTy = IntPtrTy;
2609
Vedant Kumar8a715332017-10-03 01:27:24 +00002610 if (V->getType() == TargetTy)
2611 return V;
2612
Richard Smith48366f72013-03-22 00:47:07 +00002613 // Floating-point types which fit into intptr_t are bitcast to integers
2614 // and then passed directly (after zero-extension, if necessary).
2615 if (V->getType()->isFloatingPointTy()) {
2616 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2617 if (Bits <= TargetTy->getIntegerBitWidth())
2618 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2619 Bits));
2620 }
2621
Richard Smithe30752c2012-10-09 19:52:38 +00002622 // Integers which fit in intptr_t are zero-extended and passed directly.
2623 if (V->getType()->isIntegerTy() &&
2624 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2625 return Builder.CreateZExt(V, TargetTy);
2626
2627 // Pointers are passed directly, everything else is passed by address.
2628 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002629 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002630 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002631 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002632 }
2633 return Builder.CreatePtrToInt(V, TargetTy);
2634}
2635
2636/// \brief Emit a representation of a SourceLocation for passing to a handler
2637/// in a sanitizer runtime library. The format for this data is:
2638/// \code
2639/// struct SourceLocation {
2640/// const char *Filename;
2641/// int32_t Line, Column;
2642/// };
2643/// \endcode
2644/// For an invalid SourceLocation, the Filename pointer is null.
2645llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002646 llvm::Constant *Filename;
2647 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002648
Alexey Samsonov6c124142014-07-18 17:50:06 +00002649 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2650 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002651 StringRef FilenameString = PLoc.getFilename();
2652
2653 int PathComponentsToStrip =
2654 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2655 if (PathComponentsToStrip < 0) {
2656 assert(PathComponentsToStrip != INT_MIN);
2657 int PathComponentsToKeep = -PathComponentsToStrip;
2658 auto I = llvm::sys::path::rbegin(FilenameString);
2659 auto E = llvm::sys::path::rend(FilenameString);
2660 while (I != E && --PathComponentsToKeep)
2661 ++I;
2662
2663 FilenameString = FilenameString.substr(I - E);
2664 } else if (PathComponentsToStrip > 0) {
2665 auto I = llvm::sys::path::begin(FilenameString);
2666 auto E = llvm::sys::path::end(FilenameString);
2667 while (I != E && PathComponentsToStrip--)
2668 ++I;
2669
2670 if (I != E)
2671 FilenameString =
2672 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2673 else
2674 FilenameString = llvm::sys::path::filename(FilenameString);
2675 }
2676
2677 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002678 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2679 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2680 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002681 Line = PLoc.getLine();
2682 Column = PLoc.getColumn();
2683 } else {
2684 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2685 Line = Column = 0;
2686 }
2687
2688 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2689 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002690
2691 return llvm::ConstantStruct::getAnon(Data);
2692}
2693
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002694namespace {
2695/// \brief Specify under what conditions this check can be recovered
2696enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002697 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002698 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002699 /// Check supports recovering, runtime has both fatal (noreturn) and
2700 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002701 Recoverable,
2702 /// Runtime conditionally aborts, always need to support recovery.
2703 AlwaysRecoverable
2704};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002705}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002706
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002707static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2708 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002709 switch (Kind) {
2710 case SanitizerKind::Vptr:
2711 return CheckRecoverableKind::AlwaysRecoverable;
2712 case SanitizerKind::Return:
2713 case SanitizerKind::Unreachable:
2714 return CheckRecoverableKind::Unrecoverable;
2715 default:
2716 return CheckRecoverableKind::Recoverable;
2717 }
2718}
2719
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002720namespace {
2721struct SanitizerHandlerInfo {
2722 char const *const Name;
2723 unsigned Version;
2724};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002725}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002726
2727const SanitizerHandlerInfo SanitizerHandlers[] = {
2728#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2729 LIST_SANITIZER_CHECKS
2730#undef SANITIZER_CHECK
2731};
2732
Alexey Samsonov88459522015-01-12 22:39:12 +00002733static void emitCheckHandlerCall(CodeGenFunction &CGF,
2734 llvm::FunctionType *FnType,
2735 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002736 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002737 CheckRecoverableKind RecoverKind, bool IsFatal,
2738 llvm::BasicBlock *ContBB) {
2739 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2740 bool NeedsAbortSuffix =
2741 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002742 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002743 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2744 const StringRef CheckName = CheckInfo.Name;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002745 std::string FnName = "__ubsan_handle_" + CheckName.str();
2746 if (CheckInfo.Version && !MinimalRuntime)
2747 FnName += "_v" + llvm::utostr(CheckInfo.Version);
2748 if (MinimalRuntime)
2749 FnName += "_minimal";
2750 if (NeedsAbortSuffix)
2751 FnName += "_abort";
Alexey Samsonov88459522015-01-12 22:39:12 +00002752 bool MayReturn =
2753 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2754
2755 llvm::AttrBuilder B;
2756 if (!MayReturn) {
2757 B.addAttribute(llvm::Attribute::NoReturn)
2758 .addAttribute(llvm::Attribute::NoUnwind);
2759 }
2760 B.addAttribute(llvm::Attribute::UWTable);
2761
2762 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2763 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002764 llvm::AttributeList::get(CGF.getLLVMContext(),
2765 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002766 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002767 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2768 if (!MayReturn) {
2769 HandlerCall->setDoesNotReturn();
2770 CGF.Builder.CreateUnreachable();
2771 } else {
2772 CGF.Builder.CreateBr(ContBB);
2773 }
2774}
2775
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002776void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002777 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002778 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002779 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002780 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002781 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002782 assert(CheckHandler >= 0 &&
2783 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2784 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002785
2786 llvm::Value *FatalCond = nullptr;
2787 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002788 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002789 for (int i = 0, n = Checked.size(); i < n; ++i) {
2790 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002791 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002792 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002793 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2794 ? TrapCond
2795 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2796 ? RecoverableCond
2797 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002798 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2799 }
2800
Peter Collingbourne9881b782015-06-18 23:59:22 +00002801 if (TrapCond)
2802 EmitTrapCheck(TrapCond);
2803 if (!FatalCond && !RecoverableCond)
2804 return;
2805
Alexey Samsonov88459522015-01-12 22:39:12 +00002806 llvm::Value *JointCond;
2807 if (FatalCond && RecoverableCond)
2808 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2809 else
2810 JointCond = FatalCond ? FatalCond : RecoverableCond;
2811 assert(JointCond);
2812
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002813 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002814 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002815#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002816 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002817 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002818 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002819 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002820 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002821#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002822
Richard Smith4d1458e2012-09-08 02:08:36 +00002823 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002824 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2825 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002826 // Give hint that we very much don't expect to execute the handler
2827 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2828 llvm::MDBuilder MDHelper(getLLVMContext());
2829 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2830 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002831 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002832
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002833 // Handler functions take an i8* pointing to the (handler-specific) static
2834 // information block, followed by a sequence of intptr_t arguments
2835 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002836 SmallVector<llvm::Value *, 4> Args;
2837 SmallVector<llvm::Type *, 4> ArgTypes;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002838 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
2839 Args.reserve(DynamicArgs.size() + 1);
2840 ArgTypes.reserve(DynamicArgs.size() + 1);
Richard Smithe30752c2012-10-09 19:52:38 +00002841
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002842 // Emit handler arguments and create handler function type.
2843 if (!StaticArgs.empty()) {
2844 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2845 auto *InfoPtr =
2846 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2847 llvm::GlobalVariable::PrivateLinkage, Info);
2848 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2849 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2850 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2851 ArgTypes.push_back(Int8PtrTy);
2852 }
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002853
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002854 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2855 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2856 ArgTypes.push_back(IntPtrTy);
2857 }
Richard Smithe30752c2012-10-09 19:52:38 +00002858 }
2859
2860 llvm::FunctionType *FnType =
2861 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002862
Alexey Samsonov88459522015-01-12 22:39:12 +00002863 if (!FatalCond || !RecoverableCond) {
2864 // Simple case: we need to generate a single handler call, either
2865 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002866 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002867 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002868 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002869 // Emit two handler calls: first one for set of unrecoverable checks,
2870 // another one for recoverable.
2871 llvm::BasicBlock *NonFatalHandlerBB =
2872 createBasicBlock("non_fatal." + CheckName);
2873 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2874 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2875 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002876 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002877 NonFatalHandlerBB);
2878 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002879 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002880 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002881 }
Richard Smithe30752c2012-10-09 19:52:38 +00002882
Richard Smith4d1458e2012-09-08 02:08:36 +00002883 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002884}
2885
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002886void CodeGenFunction::EmitCfiSlowPathCheck(
2887 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2888 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002889 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2890
2891 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2892 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2893
2894 llvm::MDBuilder MDHelper(getLLVMContext());
2895 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2896 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2897
2898 EmitBlock(CheckBB);
2899
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002900 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2901
2902 llvm::CallInst *CheckCall;
2903 if (WithDiag) {
2904 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2905 auto *InfoPtr =
2906 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2907 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002908 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002909 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2910
2911 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2912 "__cfi_slowpath_diag",
2913 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2914 false));
2915 CheckCall = Builder.CreateCall(
2916 SlowPathDiagFn,
2917 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2918 } else {
2919 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2920 "__cfi_slowpath",
2921 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2922 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2923 }
2924
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002925 CheckCall->setDoesNotThrow();
2926
2927 EmitBlock(Cont);
2928}
2929
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00002930// Emit a stub for __cfi_check function so that the linker knows about this
2931// symbol in LTO mode.
2932void CodeGenFunction::EmitCfiCheckStub() {
2933 llvm::Module *M = &CGM.getModule();
2934 auto &Ctx = M->getContext();
2935 llvm::Function *F = llvm::Function::Create(
2936 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2937 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2938 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2939 // FIXME: consider emitting an intrinsic call like
2940 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2941 // which can be lowered in CrossDSOCFI pass to the actual contents of
2942 // __cfi_check. This would allow inlining of __cfi_check calls.
2943 llvm::CallInst::Create(
2944 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2945 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2946}
2947
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002948// This function is basically a switch over the CFI failure kind, which is
2949// extracted from CFICheckFailData (1st function argument). Each case is either
2950// llvm.trap or a call to one of the two runtime handlers, based on
2951// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2952// failure kind) traps, but this should really never happen. CFICheckFailData
2953// can be nullptr if the calling module has -fsanitize-trap behavior for this
2954// check kind; in this case __cfi_check_fail traps as well.
2955void CodeGenFunction::EmitCfiCheckFail() {
2956 SanitizerScope SanScope(this);
2957 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002958 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2959 ImplicitParamDecl::Other);
2960 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2961 ImplicitParamDecl::Other);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002962 Args.push_back(&ArgData);
2963 Args.push_back(&ArgAddr);
2964
John McCallc56a8b32016-03-11 04:30:31 +00002965 const CGFunctionInfo &FI =
2966 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002967
2968 llvm::Function *F = llvm::Function::Create(
2969 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2970 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2971 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2972
2973 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2974 SourceLocation());
2975
2976 llvm::Value *Data =
2977 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2978 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2979 llvm::Value *Addr =
2980 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2981 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2982
2983 // Data == nullptr means the calling module has trap behaviour for this check.
2984 llvm::Value *DataIsNotNullPtr =
2985 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2986 EmitTrapCheck(DataIsNotNullPtr);
2987
2988 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002989 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002990 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002991 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002992
2993 llvm::Value *V = Builder.CreateConstGEP2_32(
2994 CfiCheckFailDataTy,
2995 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2996 0);
2997 Address CheckKindAddr(V, getIntAlign());
2998 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2999
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003000 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3001 CGM.getLLVMContext(),
3002 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3003 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00003004 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003005 {Addr, AllVtables}),
3006 IntPtrTy);
3007
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00003008 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003009 {CFITCK_VCall, SanitizerKind::CFIVCall},
3010 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3011 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3012 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3013 {CFITCK_ICall, SanitizerKind::CFIICall}};
3014
3015 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3016 for (auto CheckKindMaskPair : CheckKinds) {
3017 int Kind = CheckKindMaskPair.first;
3018 SanitizerMask Mask = CheckKindMaskPair.second;
3019 llvm::Value *Cond =
3020 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003021 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003022 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003023 {Data, Addr, ValidVtable});
3024 else
3025 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003026 }
3027
3028 FinishFunction();
3029 // The only reference to this function will be created during LTO link.
3030 // Make sure it survives until then.
3031 CGM.addUsedGlobal(F);
3032}
3033
Chad Rosierae229d52013-01-29 23:31:22 +00003034void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00003035 llvm::BasicBlock *Cont = createBasicBlock("cont");
3036
3037 // If we're optimizing, collapse all calls to trap down to just one per
3038 // function to save on code size.
3039 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3040 TrapBB = createBasicBlock("trap");
3041 Builder.CreateCondBr(Checked, Cont, TrapBB);
3042 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003043 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00003044 TrapCall->setDoesNotReturn();
3045 TrapCall->setDoesNotThrow();
3046 Builder.CreateUnreachable();
3047 } else {
3048 Builder.CreateCondBr(Checked, Cont, TrapBB);
3049 }
3050
3051 EmitBlock(Cont);
3052}
3053
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003054llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00003055 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003056
Amaury Sechet21f51b32016-09-09 04:42:49 +00003057 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3058 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3059 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00003060 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00003061 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003062
3063 return TrapCall;
3064}
3065
John McCall7f416cc2015-09-08 08:05:57 +00003066Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003067 LValueBaseInfo *BaseInfo,
3068 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00003069 assert(E->getType()->isArrayType() &&
3070 "Array to pointer decay must have array source type!");
3071
3072 // Expressions of array type can't be bitfields or vector elements.
3073 LValue LV = EmitLValue(E);
3074 Address Addr = LV.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003075 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003076 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003077
3078 // If the array type was an incomplete type, we need to make sure
3079 // the decay ends up being the right type.
3080 llvm::Type *NewTy = ConvertType(E->getType());
3081 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3082
3083 // Note that VLA pointers are always decayed, so we don't need to do
3084 // anything here.
3085 if (!E->getType()->isVariableArrayType()) {
3086 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3087 "Expected pointer to array");
3088 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3089 }
3090
3091 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3092 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3093}
3094
Chris Lattner6c5abe82010-06-26 23:03:20 +00003095/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3096/// array to pointer, return the array subexpression.
3097static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3098 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003099 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00003100 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00003101 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003102
Chris Lattner6c5abe82010-06-26 23:03:20 +00003103 // If this is a decay from variable width array, bail out.
3104 const Expr *SubExpr = CE->getSubExpr();
3105 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00003106 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003107
Chris Lattner6c5abe82010-06-26 23:03:20 +00003108 return SubExpr;
3109}
3110
John McCall7f416cc2015-09-08 08:05:57 +00003111static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3112 llvm::Value *ptr,
3113 ArrayRef<llvm::Value*> indices,
3114 bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003115 bool signedIndices,
Vedant Kumara125eb52017-06-01 19:22:18 +00003116 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003117 const llvm::Twine &name = "arrayidx") {
3118 if (inbounds) {
Vedant Kumar175b6d12017-07-13 20:55:26 +00003119 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3120 CodeGenFunction::NotSubtraction, loc,
3121 name);
John McCall7f416cc2015-09-08 08:05:57 +00003122 } else {
3123 return CGF.Builder.CreateGEP(ptr, indices, name);
3124 }
3125}
3126
3127static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3128 llvm::Value *idx,
3129 CharUnits eltSize) {
3130 // If we have a constant index, we can use the exact offset of the
3131 // element we're accessing.
3132 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3133 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3134 return arrayAlign.alignmentAtOffset(offset);
3135
3136 // Otherwise, use the worst-case alignment for any element.
3137 } else {
3138 return arrayAlign.alignmentOfArrayElement(eltSize);
3139 }
3140}
3141
3142static QualType getFixedSizeElementType(const ASTContext &ctx,
3143 const VariableArrayType *vla) {
3144 QualType eltType;
3145 do {
3146 eltType = vla->getElementType();
3147 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3148 return eltType;
3149}
3150
3151static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
Vedant Kumara125eb52017-06-01 19:22:18 +00003152 ArrayRef<llvm::Value *> indices,
John McCall7f416cc2015-09-08 08:05:57 +00003153 QualType eltType, bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003154 bool signedIndices, SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003155 const llvm::Twine &name = "arrayidx") {
3156 // All the indices except that last must be zero.
3157#ifndef NDEBUG
3158 for (auto idx : indices.drop_back())
3159 assert(isa<llvm::ConstantInt>(idx) &&
3160 cast<llvm::ConstantInt>(idx)->isZero());
3161#endif
3162
3163 // Determine the element size of the statically-sized base. This is
3164 // the thing that the indices are expressed in terms of.
3165 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3166 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3167 }
3168
3169 // We can use that to compute the best alignment of the element.
3170 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3171 CharUnits eltAlign =
3172 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3173
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003174 llvm::Value *eltPtr = emitArraySubscriptGEP(
3175 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
John McCall7f416cc2015-09-08 08:05:57 +00003176 return Address(eltPtr, eltAlign);
3177}
3178
Richard Smith539e4a72013-02-23 02:53:19 +00003179LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3180 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003181 // The index must always be an integer, which is not an aggregate. Emit it
3182 // in lexical order (this complexity is, sadly, required by C++17).
3183 llvm::Value *IdxPre =
3184 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003185 bool SignedIndices = false;
Richard Smith40885712016-09-27 00:53:24 +00003186 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003187 auto *Idx = IdxPre;
3188 if (E->getLHS() != E->getIdx()) {
3189 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3190 Idx = EmitScalarExpr(E->getIdx());
3191 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003192
Richard Smith9e67b992016-09-26 23:49:47 +00003193 QualType IdxTy = E->getIdx()->getType();
3194 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003195 SignedIndices |= IdxSigned;
Richard Smith9e67b992016-09-26 23:49:47 +00003196
3197 if (SanOpts.has(SanitizerKind::ArrayBounds))
3198 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3199
3200 // Extend or truncate the index type to 32 or 64-bits.
3201 if (Promote && Idx->getType() != IntPtrTy)
3202 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3203
3204 return Idx;
3205 };
3206 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003207
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003208 // If the base is a vector type, then we are forming a vector element lvalue
3209 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003210 if (E->getBase()->getType()->isVectorType() &&
3211 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003212 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003213 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003214 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003215 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003216 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
3217 LHS.getBaseInfo(), TBAAAccessInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003218 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003219
John McCall7f416cc2015-09-08 08:05:57 +00003220 // All the other cases basically behave like simple offsetting.
3221
John McCall7f416cc2015-09-08 08:05:57 +00003222 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003223 if (isa<ExtVectorElementExpr>(E->getBase())) {
3224 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003225 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003226 Address Addr = EmitExtVectorElementLValue(LV);
3227
3228 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
Vedant Kumara125eb52017-06-01 19:22:18 +00003229 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003230 SignedIndices, E->getExprLoc());
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00003231 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3232 CGM.getTBAAAccessInfo(EltType));
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003233 }
John McCall7f416cc2015-09-08 08:05:57 +00003234
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003235 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003236 TBAAAccessInfo TBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003237 Address Addr = Address::invalid();
3238 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003239 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003240 // The base must be a pointer, which is not an aggregate. Emit
3241 // it. It needs to be emitted first in case it's what captures
3242 // the VLA bounds.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003243 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003244 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003245
John McCall23c29fe2011-06-24 21:55:10 +00003246 // The element count here is the total number of non-VLA elements.
3247 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003248
John McCall77527a82011-06-25 01:32:37 +00003249 // Effectively, the multiply by the VLA size is part of the GEP.
3250 // GEP indexes are signed, and scaling an index isn't permitted to
3251 // signed-overflow, so we use the same semantics for our explicit
3252 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003253 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003254 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003255 } else {
3256 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003257 }
John McCall7f416cc2015-09-08 08:05:57 +00003258
3259 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003260 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003261 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003262
Chris Lattner6c5abe82010-06-26 23:03:20 +00003263 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3264 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003265
John McCall7f416cc2015-09-08 08:05:57 +00003266 // Emit the base pointer.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003267 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003268 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3269
3270 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3271 llvm::Value *InterfaceSizeVal =
3272 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3273
3274 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003275
3276 // We don't necessarily build correct LLVM struct types for ObjC
3277 // interfaces, so we can't rely on GEP to do this scaling
3278 // correctly, so we need to cast to i8*. FIXME: is this actually
3279 // true? A lot of other things in the fragile ABI would break...
3280 llvm::Type *OrigBaseTy = Addr.getType();
3281 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3282
3283 // Do the GEP.
3284 CharUnits EltAlign =
3285 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003286 llvm::Value *EltPtr =
3287 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3288 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003289 Addr = Address(EltPtr, EltAlign);
3290
3291 // Cast back.
3292 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003293 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3294 // If this is A[i] where A is an array, the frontend will have decayed the
3295 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3296 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3297 // "gep x, i" here. Emit one "gep A, 0, i".
3298 assert(Array->getType()->isArrayType() &&
3299 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003300 LValue ArrayLV;
3301 // For simple multidimensional array indexing, set the 'accessed' flag for
3302 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003303 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003304 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3305 else
3306 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003307 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003308
Daniel Dunbar82634272011-04-01 00:49:43 +00003309 // Propagate the alignment from the array itself to the result.
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003310 Addr = emitArraySubscriptGEP(
3311 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3312 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3313 E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003314 BaseInfo = ArrayLV.getBaseInfo();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003315 TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003316 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003317 // The base must be a pointer; emit it with an estimate of its alignment.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003318 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003319 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003320 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003321 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003322 SignedIndices, E->getExprLoc());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003323 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003324
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003325 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo, TBAAInfo);
John McCall8ccfcb52009-09-24 19:53:00 +00003326
Richard Smith9c6890a2012-11-01 22:30:59 +00003327 if (getLangOpts().ObjC1 &&
3328 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003329 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003330 setObjCGCLValueClass(getContext(), E, LV);
3331 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003332 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003333}
3334
Alexey Bataev31300ed2016-02-04 11:27:03 +00003335static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003336 LValueBaseInfo &BaseInfo,
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003337 TBAAAccessInfo &TBAAInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003338 QualType BaseTy, QualType ElTy,
3339 bool IsLowerBound) {
3340 LValue BaseLVal;
3341 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3342 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3343 if (BaseTy->isArrayType()) {
3344 Address Addr = BaseLVal.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003345 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003346
3347 // If the array type was an incomplete type, we need to make sure
3348 // the decay ends up being the right type.
3349 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3350 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3351
3352 // Note that VLA pointers are always decayed, so we don't need to do
3353 // anything here.
3354 if (!BaseTy->isVariableArrayType()) {
3355 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3356 "Expected pointer to array");
3357 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3358 "arraydecay");
3359 }
3360
3361 return CGF.Builder.CreateElementBitCast(Addr,
3362 CGF.ConvertTypeForMem(ElTy));
3363 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003364 LValueBaseInfo TypeInfo;
3365 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3366 BaseInfo.mergeForCast(TypeInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003367 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3368 }
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003369 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003370}
3371
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003372LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3373 bool IsLowerBound) {
Alexey Bataev7b0f1f02017-10-12 15:18:41 +00003374 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003375 QualType ResultExprTy;
3376 if (auto *AT = getContext().getAsArrayType(BaseTy))
3377 ResultExprTy = AT->getElementType();
3378 else
3379 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003380 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003381 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003382 // Requesting lower bound or upper bound, but without provided length and
3383 // without ':' symbol for the default length -> length = 1.
3384 // Idx = LowerBound ?: 0;
3385 if (auto *LowerBound = E->getLowerBound()) {
3386 Idx = Builder.CreateIntCast(
3387 EmitScalarExpr(LowerBound), IntPtrTy,
3388 LowerBound->getType()->hasSignedIntegerRepresentation());
3389 } else
3390 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3391 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003392 // Try to emit length or lower bound as constant. If this is possible, 1
3393 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3394 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003395 auto &C = CGM.getContext();
3396 auto *Length = E->getLength();
3397 llvm::APSInt ConstLength;
3398 if (Length) {
3399 // Idx = LowerBound + Length - 1;
3400 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3401 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3402 Length = nullptr;
3403 }
3404 auto *LowerBound = E->getLowerBound();
3405 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3406 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3407 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3408 LowerBound = nullptr;
3409 }
3410 if (!Length)
3411 --ConstLength;
3412 else if (!LowerBound)
3413 --ConstLowerBound;
3414
3415 if (Length || LowerBound) {
3416 auto *LowerBoundVal =
3417 LowerBound
3418 ? Builder.CreateIntCast(
3419 EmitScalarExpr(LowerBound), IntPtrTy,
3420 LowerBound->getType()->hasSignedIntegerRepresentation())
3421 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3422 auto *LengthVal =
3423 Length
3424 ? Builder.CreateIntCast(
3425 EmitScalarExpr(Length), IntPtrTy,
3426 Length->getType()->hasSignedIntegerRepresentation())
3427 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3428 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3429 /*HasNUW=*/false,
3430 !getLangOpts().isSignedOverflowDefined());
3431 if (Length && LowerBound) {
3432 Idx = Builder.CreateSub(
3433 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3434 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3435 }
3436 } else
3437 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3438 } else {
3439 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003440 QualType ArrayTy = BaseTy->isPointerType()
3441 ? E->getBase()->IgnoreParenImpCasts()->getType()
3442 : BaseTy;
3443 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003444 Length = VAT->getSizeExpr();
3445 if (Length->isIntegerConstantExpr(ConstLength, C))
3446 Length = nullptr;
3447 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003448 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003449 ConstLength = CAT->getSize();
3450 }
3451 if (Length) {
3452 auto *LengthVal = Builder.CreateIntCast(
3453 EmitScalarExpr(Length), IntPtrTy,
3454 Length->getType()->hasSignedIntegerRepresentation());
3455 Idx = Builder.CreateSub(
3456 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3457 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3458 } else {
3459 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3460 --ConstLength;
3461 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3462 }
3463 }
3464 }
3465 assert(Idx);
3466
Alexey Bataev31300ed2016-02-04 11:27:03 +00003467 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003468 LValueBaseInfo BaseInfo;
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003469 TBAAAccessInfo TBAAInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003470 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003471 // The base must be a pointer, which is not an aggregate. Emit
3472 // it. It needs to be emitted first in case it's what captures
3473 // the VLA bounds.
3474 Address Base =
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003475 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
3476 BaseTy, VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003477 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003478 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003479
3480 // Effectively, the multiply by the VLA size is part of the GEP.
3481 // GEP indexes are signed, and scaling an index isn't permitted to
3482 // signed-overflow, so we use the same semantics for our explicit
3483 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003484 if (getLangOpts().isSignedOverflowDefined())
3485 Idx = Builder.CreateMul(Idx, NumElements);
3486 else
3487 Idx = Builder.CreateNSWMul(Idx, NumElements);
3488 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003489 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003490 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003491 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3492 // If this is A[i] where A is an array, the frontend will have decayed the
3493 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3494 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3495 // "gep x, i" here. Emit one "gep A, 0, i".
3496 assert(Array->getType()->isArrayType() &&
3497 "Array to pointer decay must have array source type!");
3498 LValue ArrayLV;
3499 // For simple multidimensional array indexing, set the 'accessed' flag for
3500 // better bounds-checking of the base expression.
3501 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3502 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3503 else
3504 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003505
Alexey Bataev31300ed2016-02-04 11:27:03 +00003506 // Propagate the alignment from the array itself to the result.
3507 EltPtr = emitArraySubscriptGEP(
3508 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumara125eb52017-06-01 19:22:18 +00003509 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003510 /*SignedIndices=*/false, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003511 BaseInfo = ArrayLV.getBaseInfo();
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003512 TBAAInfo = CGM.getTBAAAccessInfo(ResultExprTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003513 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003514 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003515 TBAAInfo, BaseTy, ResultExprTy,
3516 IsLowerBound);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003517 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
Vedant Kumara125eb52017-06-01 19:22:18 +00003518 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003519 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003520 }
3521
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003522 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003523}
3524
Chris Lattner9e751ca2007-08-02 23:37:31 +00003525LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003526EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003527 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003528 LValue Base;
3529
3530 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003531 if (E->isArrow()) {
3532 // If it is a pointer to a vector, emit the address and form an lvalue with
3533 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003534 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003535 TBAAAccessInfo TBAAInfo;
3536 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003537 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003538 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003539 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003540 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003541 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3542 // emit the base as an lvalue.
3543 assert(E->getBase()->getType()->isVectorType());
3544 Base = EmitLValue(E->getBase());
3545 } else {
3546 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003547 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003548 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003549 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003550
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003551 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003552 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003553 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003554 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003555 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003556 }
John McCall1553b192011-06-16 04:16:24 +00003557
3558 QualType type =
3559 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003560
Nate Begemand3862152008-05-13 21:03:02 +00003561 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003562 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003563 E->getEncodedElementAccess(Indices);
3564
3565 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003566 llvm::Constant *CV =
3567 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003568 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003569 Base.getBaseInfo(), TBAAAccessInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003570 }
3571 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3572
3573 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003574 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003575
Chris Lattner595ba3a2012-01-30 06:20:36 +00003576 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3577 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003578 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003579 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003580 Base.getBaseInfo(), TBAAAccessInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003581}
3582
Devang Patel30efa2e2007-10-23 20:28:39 +00003583LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00003584 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3585 EmitIgnoredExpr(E->getBase());
3586 return EmitDeclRefLValue(DRE);
3587 }
3588
Devang Pateld68df202007-10-24 22:26:28 +00003589 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003590 // 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 +00003591 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003592 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003593 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003594 TBAAAccessInfo TBAAInfo;
3595 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003596 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003597 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003598 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3599 if (IsBaseCXXThis)
3600 SkippedChecks.set(SanitizerKind::Alignment, true);
3601 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003602 SkippedChecks.set(SanitizerKind::Null, true);
3603 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3604 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003605 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003606 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003607 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003608
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003609 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003610 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003611 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003612 setObjCGCLValueClass(getContext(), E, LV);
3613 return LV;
3614 }
Craig Topper99e79272013-07-26 05:59:26 +00003615
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003616 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003617 return EmitFunctionDeclLValue(*this, E, FD);
3618
David Blaikie83d382b2011-09-23 05:06:16 +00003619 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003620}
Devang Patel30efa2e2007-10-23 20:28:39 +00003621
John McCalldec348f72013-05-03 07:33:41 +00003622/// Given that we are currently emitting a lambda, emit an l-value for
3623/// one of its members.
3624LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3625 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3626 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3627 QualType LambdaTagType =
3628 getContext().getTagDeclType(Field->getParent());
3629 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3630 return EmitLValueForField(LambdaLV, Field);
3631}
3632
John McCall7f416cc2015-09-08 08:05:57 +00003633/// Drill down to the storage of a field without walking into
3634/// reference types.
3635///
3636/// The resulting address doesn't necessarily have the right type.
3637static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3638 const FieldDecl *field) {
3639 const RecordDecl *rec = field->getParent();
3640
3641 unsigned idx =
3642 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3643
3644 CharUnits offset;
3645 // Adjust the alignment down to the given offset.
3646 // As a special case, if the LLVM field index is 0, we know that this
3647 // is zero.
3648 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3649 .getFieldOffset(field->getFieldIndex()) == 0) &&
3650 "LLVM field at index zero had non-zero offset?");
3651 if (idx != 0) {
3652 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3653 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3654 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3655 }
3656
3657 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3658}
3659
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003660static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3661 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3662 if (!RD)
3663 return false;
3664
3665 if (RD->isDynamicClass())
3666 return true;
3667
3668 for (const auto &Base : RD->bases())
3669 if (hasAnyVptr(Base.getType(), Context))
3670 return true;
3671
3672 for (const FieldDecl *Field : RD->fields())
3673 if (hasAnyVptr(Field->getType(), Context))
3674 return true;
3675
3676 return false;
3677}
3678
Eli Friedman7f1ff602012-04-16 03:54:45 +00003679LValue CodeGenFunction::EmitLValueForField(LValue base,
3680 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003681 LValueBaseInfo BaseInfo = base.getBaseInfo();
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003682
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003683 if (field->isBitField()) {
3684 const CGRecordLayout &RL =
3685 CGM.getTypes().getCGRecordLayout(field->getParent());
3686 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003687 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003688 unsigned Idx = RL.getLLVMFieldNo(field);
3689 if (Idx != 0)
3690 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003691 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3692 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003693 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003694 llvm::Type *FieldIntTy =
3695 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3696 if (Addr.getElementType() != FieldIntTy)
3697 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003698
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003699 QualType fieldType =
3700 field->getType().withCVRQualifiers(base.getVRQualifiers());
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003701 // TODO: Support TBAA for bit fields.
3702 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource(), false);
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003703 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
3704 TBAAAccessInfo());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003705 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003706
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003707 // Fields of may-alias structures are may-alias themselves.
3708 // FIXME: this should get propagated down through anonymous structs
3709 // and unions.
3710 QualType FieldType = field->getType();
3711 const RecordDecl *rec = field->getParent();
3712 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
3713 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource), false);
3714 TBAAAccessInfo FieldTBAAInfo;
3715 if (BaseInfo.getMayAlias() || rec->hasAttr<MayAliasAttr>() ||
3716 FieldType->isVectorType()) {
3717 FieldBaseInfo.setMayAlias(true);
3718 FieldTBAAInfo = CGM.getTBAAMayAliasAccessInfo();
3719 } else if (rec->isUnion()) {
3720 // TODO: Support TBAA for unions.
3721 FieldBaseInfo.setMayAlias(true);
3722 FieldTBAAInfo = CGM.getTBAAMayAliasAccessInfo();
3723 } else {
3724 // If no base type been assigned for the base access, then try to generate
3725 // one for this base lvalue.
3726 FieldTBAAInfo = base.getTBAAInfo();
3727 if (!FieldTBAAInfo.BaseType) {
3728 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
3729 assert(!FieldTBAAInfo.Offset &&
3730 "Nonzero offset for an access with no base type!");
3731 }
3732
3733 // Adjust offset to be relative to the base type.
3734 const ASTRecordLayout &Layout =
3735 getContext().getASTRecordLayout(field->getParent());
3736 unsigned CharWidth = getContext().getCharWidth();
3737 if (FieldTBAAInfo.BaseType)
3738 FieldTBAAInfo.Offset +=
3739 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
3740
3741 // Update the final access type.
3742 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
3743 }
3744
John McCall7f416cc2015-09-08 08:05:57 +00003745 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003746 unsigned cvr = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00003747 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003748 // For unions, there is no pointer adjustment.
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003749 assert(!FieldType->isReferenceType() && "union has reference member");
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003750 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3751 hasAnyVptr(FieldType, getContext()))
3752 // Because unions can easily skip invariant.barriers, we need to add
3753 // a barrier every time CXXRecord field with vptr is referenced.
3754 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3755 addr.getAlignment());
John McCall53fcbd22011-02-26 08:07:02 +00003756 } else {
3757 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003758 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003759
3760 // If this is a reference field, load the reference right now.
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003761 if (const ReferenceType *refType = FieldType->getAs<ReferenceType>()) {
John McCall53fcbd22011-02-26 08:07:02 +00003762 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3763 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3764
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003765 CGM.DecorateInstructionWithTBAA(load, FieldTBAAInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003766
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003767 FieldType = refType->getPointeeType();
3768 CharUnits Align = getNaturalTypeAlignment(FieldType, &FieldBaseInfo,
3769 &FieldTBAAInfo,
3770 /* forPointeeType= */ true);
3771 addr = Address(load, Align);
John McCall7f416cc2015-09-08 08:05:57 +00003772
3773 // Qualifiers on the struct don't apply to the referencee, and
3774 // we'll pick up CVR from the actual type later, so reset these
3775 // additional qualifiers now.
3776 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003777 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003778 }
Craig Topper99e79272013-07-26 05:59:26 +00003779
Chris Lattner13ee4f42011-07-10 05:34:54 +00003780 // Make sure that the address is pointing to the right type. This is critical
3781 // for both unions and structs. A union needs a bitcast, a struct element
3782 // will need a bitcast if the LLVM type laid out doesn't match the desired
3783 // type.
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003784 addr = Builder.CreateElementBitCast(
3785 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003786
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003787 if (field->hasAttr<AnnotateAttr>())
3788 addr = EmitFieldAnnotations(field, addr);
3789
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003790 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003791 LV.getQuals().addCVRQualifiers(cvr);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00003792
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003793 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003794 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3795 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003796
Daniel Dunbarf166a522010-08-21 03:44:13 +00003797 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003798}
3799
Craig Topper99e79272013-07-26 05:59:26 +00003800LValue
3801CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003802 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003803 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003804
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003805 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003806 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003807
John McCall7f416cc2015-09-08 08:05:57 +00003808 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003809
John McCall7f416cc2015-09-08 08:05:57 +00003810 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003811 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003812 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003813
John McCall7f416cc2015-09-08 08:05:57 +00003814 // TODO: access-path TBAA?
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003815 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3816 LValueBaseInfo FieldBaseInfo(
3817 getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3818 BaseInfo.getMayAlias());
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00003819 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
3820 CGM.getTBAAAccessInfo(FieldType));
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003821}
3822
Chris Lattnerf53c0962010-09-06 00:11:41 +00003823LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003824 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003825 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003826 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003827 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003828 if (E->getType()->isVariablyModifiedType())
3829 // make sure to emit the VLA size.
3830 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003831
John McCall7f416cc2015-09-08 08:05:57 +00003832 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003833 const Expr *InitExpr = E->getInitializer();
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003834 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003835
Chad Rosier615ed1a2012-03-29 17:37:10 +00003836 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3837 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003838
3839 return Result;
3840}
3841
Richard Smithbb653bd2012-05-14 21:57:21 +00003842LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3843 if (!E->isGLValue())
3844 // Initializing an aggregate temporary in C++11: T{...}.
3845 return EmitAggExprToLValue(E);
3846
3847 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003848 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003849 return EmitLValue(E->getInit(0));
3850}
3851
Richard Smithf3076ff2014-06-20 18:43:47 +00003852/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3853/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3854/// LValue is returned and the current block has been terminated.
3855static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3856 const Expr *Operand) {
3857 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3858 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3859 return None;
3860 }
3861
3862 return CGF.EmitLValue(Operand);
3863}
3864
John McCallc07a0c72011-02-17 10:25:35 +00003865LValue CodeGenFunction::
3866EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3867 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003868 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003869 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003870 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003871 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003872 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003873
Eli Friedman59954892012-01-25 05:04:17 +00003874 OpaqueValueMapping binding(*this, expr);
3875
John McCallc07a0c72011-02-17 10:25:35 +00003876 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003877 bool CondExprBool;
3878 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003879 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003880 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003881
Justin Bogneref512b92014-01-06 22:27:43 +00003882 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003883 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003884 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003885 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003886 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003887 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003888 }
3889
John McCallc07a0c72011-02-17 10:25:35 +00003890 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3891 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3892 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003893
3894 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003895 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003896
John McCall0a6bf2e2011-01-26 19:21:13 +00003897 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003898 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003899 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003900 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003901 Optional<LValue> lhs =
3902 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003903 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003904
Richard Smithf3076ff2014-06-20 18:43:47 +00003905 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003906 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003907
John McCallc07a0c72011-02-17 10:25:35 +00003908 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003909 if (lhs)
3910 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003911
John McCall0a6bf2e2011-01-26 19:21:13 +00003912 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003913 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003914 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003915 Optional<LValue> rhs =
3916 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003917 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003918 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003919 return EmitUnsupportedLValue(expr, "conditional operator");
3920 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003921
John McCallc07a0c72011-02-17 10:25:35 +00003922 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003923
Richard Smithf3076ff2014-06-20 18:43:47 +00003924 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003925 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003926 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003927 phi->addIncoming(lhs->getPointer(), lhsBlock);
3928 phi->addIncoming(rhs->getPointer(), rhsBlock);
3929 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3930 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003931 std::max(lhs->getBaseInfo().getAlignmentSource(),
3932 rhs->getBaseInfo().getAlignmentSource());
3933 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3934 rhs->getBaseInfo().getMayAlias();
3935 return MakeAddrLValue(result, expr->getType(),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00003936 LValueBaseInfo(alignSource, MayAlias),
3937 CGM.getTBAAAccessInfo(expr->getType()));
Richard Smithf3076ff2014-06-20 18:43:47 +00003938 } else {
3939 assert((lhs || rhs) &&
3940 "both operands of glvalue conditional are throw-expressions?");
3941 return lhs ? *lhs : *rhs;
3942 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003943}
3944
Richard Smithbb653bd2012-05-14 21:57:21 +00003945/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3946/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003947/// otherwise if a cast is needed by the code generator in an lvalue context,
3948/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003949/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003950/// are permitted with aggregate result, including noop aggregate casts, and
3951/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003952LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003953 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003954 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003955 case CK_BitCast:
3956 case CK_ArrayToPointerDecay:
3957 case CK_FunctionToPointerDecay:
3958 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003959 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003960 case CK_IntegralToPointer:
3961 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003962 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003963 case CK_VectorSplat:
3964 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003965 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003966 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003967 case CK_IntegralToFloating:
3968 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003969 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003970 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003971 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003972 case CK_FloatingComplexToReal:
3973 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003974 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003975 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003976 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003977 case CK_IntegralComplexToReal:
3978 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003979 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003980 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003981 case CK_DerivedToBaseMemberPointer:
3982 case CK_BaseToDerivedMemberPointer:
3983 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003984 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003985 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003986 case CK_ARCProduceObject:
3987 case CK_ARCConsumeObject:
3988 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003989 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003990 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003991 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003992 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003993 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3994
3995 case CK_Dependent:
3996 llvm_unreachable("dependent cast kind in IR gen!");
3997
3998 case CK_BuiltinFnToFnPtr:
3999 llvm_unreachable("builtin functions are handled elsewhere");
4000
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004001 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004002 case CK_NonAtomicToAtomic:
4003 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004004 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00004005
Anders Carlsson8a01a752011-04-11 02:03:26 +00004006 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00004007 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004008 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004009 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00004010 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00004011 }
4012
John McCalle3027922010-08-25 11:45:40 +00004013 case CK_ConstructorConversion:
4014 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00004015 case CK_CPointerToObjCPointerCast:
4016 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004017 case CK_NoOp:
4018 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004019 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00004020
John McCalle3027922010-08-25 11:45:40 +00004021 case CK_UncheckedDerivedToBase:
4022 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00004023 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00004024 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004025 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004026
Anders Carlssond95f9602009-09-12 16:16:49 +00004027 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004028 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00004029
Anders Carlssond95f9602009-09-12 16:16:49 +00004030 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00004031 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00004032 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4033 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00004034
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004035 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4036 CGM.getTBAAAccessInfo(E->getType()));
Anders Carlssond95f9602009-09-12 16:16:49 +00004037 }
John McCalle3027922010-08-25 11:45:40 +00004038 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00004039 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00004040 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00004041 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004042 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004043
Anders Carlsson8c793172009-11-23 17:57:54 +00004044 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00004045
Anders Carlsson8c793172009-11-23 17:57:54 +00004046 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00004047 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00004048 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00004049 E->path_begin(), E->path_end(),
4050 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00004051
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004052 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4053 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00004054 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004055 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00004056 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004057
Peter Collingbourned2926c92015-03-14 02:42:25 +00004058 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004059 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4060 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004061 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004062
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004063 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4064 CGM.getTBAAAccessInfo(E->getType()));
Eli Friedman8c98dff2009-11-16 05:48:01 +00004065 }
John McCalle3027922010-08-25 11:45:40 +00004066 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00004067 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004068 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00004069
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00004070 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00004071 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004072 Address V = Builder.CreateBitCast(LV.getAddress(),
4073 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00004074
4075 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004076 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4077 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004078 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004079
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004080 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4081 CGM.getTBAAAccessInfo(E->getType()));
Anders Carlsson50cb3212009-11-14 21:21:42 +00004082 }
John McCalle3027922010-08-25 11:45:40 +00004083 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004084 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004085 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4086 ConvertType(E->getType()));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004087 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4088 CGM.getTBAAAccessInfo(E->getType()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004089 }
Egor Churaev89831422016-12-23 14:55:49 +00004090 case CK_ZeroToOCLQueue:
4091 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004092 case CK_ZeroToOCLEvent:
4093 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00004094 }
Craig Topper99e79272013-07-26 05:59:26 +00004095
Douglas Gregorcdb466e2010-07-15 18:58:16 +00004096 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004097}
4098
John McCall1bf58462011-02-16 08:02:54 +00004099LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00004100 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00004101 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00004102}
4103
Eli Friedman7f1ff602012-04-16 03:54:45 +00004104RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004105 const FieldDecl *FD,
4106 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004107 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00004108 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00004109 switch (getEvaluationKind(FT)) {
4110 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004111 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00004112 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00004113 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00004114 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00004115 // This routine is used to load fields one-by-one to perform a copy, so
4116 // don't load reference fields.
4117 if (FD->getType()->isReferenceType())
4118 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00004119 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00004120 }
4121 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004122}
Douglas Gregorfe314812011-06-21 17:03:29 +00004123
Chris Lattnere47e4402007-06-01 18:02:12 +00004124//===--------------------------------------------------------------------===//
4125// Expression Emission
4126//===--------------------------------------------------------------------===//
4127
Craig Topper99e79272013-07-26 05:59:26 +00004128RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00004129 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00004130 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004131 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00004132 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004133
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004134 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004135 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004136
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004137 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00004138 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4139
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004140 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00004141 if (const CXXMethodDecl *MD =
4142 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004143 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004144
John McCallb92ab1a2016-10-26 23:46:34 +00004145 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00004146
John McCallb92ab1a2016-10-26 23:46:34 +00004147 if (callee.isBuiltin()) {
4148 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4149 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004150 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004151
John McCallb92ab1a2016-10-26 23:46:34 +00004152 if (callee.isPseudoDestructor()) {
4153 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4154 }
4155
4156 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4157}
4158
4159/// Emit a CallExpr without considering whether it might be a subclass.
4160RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4161 ReturnValueSlot ReturnValue) {
4162 CGCallee Callee = EmitCallee(E->getCallee());
4163 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4164}
4165
4166static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4167 if (auto builtinID = FD->getBuiltinID()) {
4168 return CGCallee::forBuiltin(builtinID, FD);
4169 }
4170
4171 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4172 return CGCallee::forDirect(calleePtr, FD);
4173}
4174
4175CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4176 E = E->IgnoreParens();
4177
4178 // Look through function-to-pointer decay.
4179 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4180 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4181 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4182 return EmitCallee(ICE->getSubExpr());
4183 }
4184
4185 // Resolve direct calls.
4186 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4187 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4188 return EmitDirectCallee(*this, FD);
4189 }
4190 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4191 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4192 EmitIgnoredExpr(ME->getBase());
4193 return EmitDirectCallee(*this, FD);
4194 }
4195
4196 // Look through template substitutions.
4197 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4198 return EmitCallee(NTTP->getReplacement());
4199
4200 // Treat pseudo-destructor calls differently.
4201 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4202 return CGCallee::forPseudoDestructor(PDE);
4203 }
4204
4205 // Otherwise, we have an indirect reference.
4206 llvm::Value *calleePtr;
4207 QualType functionType;
4208 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4209 calleePtr = EmitScalarExpr(E);
4210 functionType = ptrType->getPointeeType();
4211 } else {
4212 functionType = E->getType();
4213 calleePtr = EmitLValue(E).getPointer();
4214 }
4215 assert(functionType->isFunctionType());
4216 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4217 E->getReferencedDeclOfCallee());
4218 CGCallee callee(calleeInfo, calleePtr);
4219 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004220}
4221
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004222LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004223 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004224 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004225 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004226 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004227 return EmitLValue(E->getRHS());
4228 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004229
John McCalle3027922010-08-25 11:45:40 +00004230 if (E->getOpcode() == BO_PtrMemD ||
4231 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004232 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004233
John McCalla2342eb2010-12-05 02:00:02 +00004234 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004235
4236 // Note that in all of these cases, __block variables need the RHS
4237 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004238
4239 switch (getEvaluationKind(E->getType())) {
4240 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004241 switch (E->getLHS()->getType().getObjCLifetime()) {
4242 case Qualifiers::OCL_Strong:
4243 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4244
4245 case Qualifiers::OCL_Autoreleasing:
4246 return EmitARCStoreAutoreleasing(E).first;
4247
4248 // No reason to do any of these differently.
4249 case Qualifiers::OCL_None:
4250 case Qualifiers::OCL_ExplicitNone:
4251 case Qualifiers::OCL_Weak:
4252 break;
4253 }
4254
John McCalld0a30012010-12-06 06:10:02 +00004255 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004256 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004257 if (RV.isScalar())
4258 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004259 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004260 return LV;
4261 }
John McCall4f29b492010-11-16 23:07:28 +00004262
John McCall47fb9502013-03-07 21:37:08 +00004263 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004264 return EmitComplexAssignmentLValue(E);
4265
John McCall47fb9502013-03-07 21:37:08 +00004266 case TEK_Aggregate:
4267 return EmitAggExprToLValue(E);
4268 }
4269 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004270}
4271
Christopher Lambd91c3d42007-12-29 05:02:41 +00004272LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004273 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004274
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004275 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004276 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004277 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004278
David Majnemerced8bdf2015-02-25 17:36:15 +00004279 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004280 "Can't have a scalar return unless the return type is a "
4281 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004282
John McCall7f416cc2015-09-08 08:05:57 +00004283 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004284}
4285
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004286LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4287 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004288 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004289}
4290
Anders Carlsson3be22e22009-05-30 23:23:33 +00004291LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004292 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4293 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004294 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004295 EmitCXXConstructExpr(E, Slot);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004296 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00004297}
4298
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004299LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004300CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004301 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004302}
4303
John McCall7f416cc2015-09-08 08:05:57 +00004304Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4305 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4306 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004307}
4308
4309LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004310 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004311 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00004312}
4313
Mike Stumpc9b231c2009-11-15 08:09:41 +00004314LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004315CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004316 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004317 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004318 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004319 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004320 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004321}
4322
Eli Friedman5bc17122012-02-08 05:34:55 +00004323LValue
4324CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004325 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004326 EmitLambdaExpr(E, Slot);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004327 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00004328}
4329
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004330LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004331 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004332
Anders Carlsson280e61f12010-06-21 20:59:55 +00004333 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004334 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004335 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004336
Alp Toker314cc812014-01-25 16:55:45 +00004337 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004338 "Can't have a scalar return unless the return type is a "
4339 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004340
John McCall7f416cc2015-09-08 08:05:57 +00004341 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004342}
4343
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004344LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004345 Address V =
4346 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004347 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004348}
4349
Daniel Dunbar722f4242009-04-22 05:08:15 +00004350llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004351 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004352 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004353}
4354
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004355LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4356 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004357 const ObjCIvarDecl *Ivar,
4358 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004359 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004360 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004361}
4362
4363LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004364 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004365 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004366 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004367 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004368 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004369 if (E->isArrow()) {
4370 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004371 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004372 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004373 } else {
4374 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004375 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004376 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004377 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004378 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004379
Craig Topper99e79272013-07-26 05:59:26 +00004380 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004381 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4382 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004383 setObjCGCLValueClass(getContext(), E, LV);
4384 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004385}
4386
Chris Lattnera4185c52009-04-25 19:35:26 +00004387LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004388 // Can only get l-value for message expression returning aggregate type
4389 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004390 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004391 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00004392}
4393
John McCallb92ab1a2016-10-26 23:46:34 +00004394RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004395 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004396 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004397 // Get the actual function type. The callee type will always be a pointer to
4398 // function type or a block pointer type.
4399 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004400 "Call must have function pointer type!");
4401
John McCallb92ab1a2016-10-26 23:46:34 +00004402 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004403
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004404 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004405 // We can only guarantee that a function is called from the correct
4406 // context/function based on the appropriate target attributes,
4407 // so only check in the case where we have both always_inline and target
4408 // since otherwise we could be making a conditional call after a check for
4409 // the proper cpu features (and it won't cause code generation issues due to
4410 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004411 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4412 TargetDecl->hasAttr<TargetAttr>())
4413 checkTargetFeatures(E, FD);
4414
John McCall6fd4c232009-10-23 08:22:42 +00004415 CalleeType = getContext().getCanonicalType(CalleeType);
4416
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004417 const auto *FnType =
4418 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004419
John McCallb92ab1a2016-10-26 23:46:34 +00004420 CGCallee Callee = OrigCallee;
4421
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004422 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004423 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4424 if (llvm::Constant *PrefixSig =
4425 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004426 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004427 llvm::Constant *FTRTTIConst =
4428 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004429 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004430 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4431 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4432
John McCallb92ab1a2016-10-26 23:46:34 +00004433 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4434
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004435 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004436 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004437 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004438 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004439 llvm::Value *CalleeSig =
4440 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004441 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4442
4443 llvm::BasicBlock *Cont = createBasicBlock("cont");
4444 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4445 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4446
4447 EmitBlock(TypeCheck);
4448 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004449 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004450 llvm::Value *CalleeRTTIEncoded =
John McCall7f416cc2015-09-08 08:05:57 +00004451 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004452 llvm::Value *CalleeRTTI =
4453 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004454 llvm::Value *CalleeRTTIMatch =
4455 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4456 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004457 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004458 EmitCheckTypeDescriptor(CalleeType)
4459 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004460 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004461 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004462
4463 Builder.CreateBr(Cont);
4464 EmitBlock(Cont);
4465 }
4466 }
4467
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004468 // If we are checking indirect calls and this call is indirect, check that the
4469 // function pointer is a member of the bit set for the function type.
4470 if (SanOpts.has(SanitizerKind::CFIICall) &&
4471 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4472 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004473 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004474
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004475 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004476 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004477
John McCallb92ab1a2016-10-26 23:46:34 +00004478 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4479 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004480 llvm::Value *TypeTest = Builder.CreateCall(
4481 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004482
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004483 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004484 llvm::Constant *StaticData[] = {
4485 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4486 EmitCheckSourceLocation(E->getLocStart()),
4487 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4488 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004489 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4490 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004491 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004492 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004493 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004494 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004495 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004496 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004497 }
4498
Daniel Dunbarc722b852008-08-30 03:02:31 +00004499 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004500 if (Chain)
4501 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4502 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004503
4504 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004505 // right-to-left, and that we evaluate arguments to certain other operators
4506 // left-to-right. Note that we allow this to override the order dictated by
4507 // the calling convention on the MS ABI, which means that parameter
4508 // destruction order is not necessarily reverse construction order.
4509 // FIXME: Revisit this based on C++ committee response to unimplementability.
4510 EvaluationOrder Order = EvaluationOrder::Default;
4511 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4512 if (OCE->isAssignmentOp())
4513 Order = EvaluationOrder::ForceRightToLeft;
4514 else {
4515 switch (OCE->getOperator()) {
4516 case OO_LessLess:
4517 case OO_GreaterGreater:
4518 case OO_AmpAmp:
4519 case OO_PipePipe:
4520 case OO_Comma:
4521 case OO_ArrowStar:
4522 Order = EvaluationOrder::ForceLeftToRight;
4523 break;
4524 default:
4525 break;
4526 }
4527 }
4528 }
Richard Smith762672a2016-09-28 19:09:10 +00004529
David Blaikief05779e2015-07-21 18:37:18 +00004530 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004531 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004532
Peter Collingbournef7706832014-12-12 23:41:25 +00004533 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4534 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004535
4536 // C99 6.5.2.2p6:
4537 // If the expression that denotes the called function has a type
4538 // that does not include a prototype, [the default argument
4539 // promotions are performed]. If the number of arguments does not
4540 // equal the number of parameters, the behavior is undefined. If
4541 // the function is defined with a type that includes a prototype,
4542 // and either the prototype ends with an ellipsis (, ...) or the
4543 // types of the arguments after promotion are not compatible with
4544 // the types of the parameters, the behavior is undefined. If the
4545 // function is defined with a type that does not include a
4546 // prototype, and the types of the arguments after promotion are
4547 // not compatible with those of the parameters after promotion,
4548 // the behavior is undefined [except in some trivial cases].
4549 // That is, in the general case, we should assume that a call
4550 // through an unprototyped function type works like a *non-variadic*
4551 // call. The way we make this work is to cast to the exact type
4552 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004553 //
4554 // Chain calls use this same code path to add the invisible chain parameter
4555 // to the function type.
4556 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004557 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004558 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004559
4560 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4561 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4562 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004563 }
4564
John McCallb92ab1a2016-10-26 23:46:34 +00004565 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004566}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004567
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004568LValue CodeGenFunction::
4569EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004570 Address BaseAddr = Address::invalid();
4571 if (E->getOpcode() == BO_PtrMemI) {
4572 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4573 } else {
4574 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4575 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004576
John McCallc134eb52010-08-31 21:07:20 +00004577 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4578
4579 const MemberPointerType *MPT
4580 = E->getRHS()->getType()->getAs<MemberPointerType>();
4581
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004582 LValueBaseInfo BaseInfo;
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004583 TBAAAccessInfo TBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00004584 Address MemberAddr =
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004585 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
4586 &TBAAInfo);
John McCallc134eb52010-08-31 21:07:20 +00004587
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004588 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004589}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004590
John McCall47fb9502013-03-07 21:37:08 +00004591/// Given the address of a temporary variable, produce an r-value of
4592/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004593RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004594 QualType type,
4595 SourceLocation loc) {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004596 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004597 switch (getEvaluationKind(type)) {
4598 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004599 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004600 case TEK_Aggregate:
4601 return lvalue.asAggregateRValue();
4602 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004603 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004604 }
4605 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004606}
4607
Duncan Sandse81111c2012-04-10 08:23:07 +00004608void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004609 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004610 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004611 return;
4612
Duncan Sands65229ed2012-04-16 16:29:47 +00004613 llvm::MDBuilder MDHelper(getLLVMContext());
4614 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004615
Duncan Sands6fc46192012-04-14 12:37:26 +00004616 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004617}
John McCallfe96e0b2011-11-06 09:01:30 +00004618
4619namespace {
4620 struct LValueOrRValue {
4621 LValue LV;
4622 RValue RV;
4623 };
4624}
4625
4626static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4627 const PseudoObjectExpr *E,
4628 bool forLValue,
4629 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004630 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004631
4632 // Find the result expression, if any.
4633 const Expr *resultExpr = E->getResultExpr();
4634 LValueOrRValue result;
4635
4636 for (PseudoObjectExpr::const_semantics_iterator
4637 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4638 const Expr *semantic = *i;
4639
4640 // If this semantic expression is an opaque value, bind it
4641 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004642 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004643
4644 // If this is the result expression, we may need to evaluate
4645 // directly into the slot.
4646 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4647 OVMA opaqueData;
4648 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004649 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004650 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
John McCall7f416cc2015-09-08 08:05:57 +00004651 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004652 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004653 opaqueData = OVMA::bind(CGF, ov, LV);
4654 result.RV = slot.asRValue();
4655
4656 // Otherwise, emit as normal.
4657 } else {
4658 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4659
4660 // If this is the result, also evaluate the result now.
4661 if (ov == resultExpr) {
4662 if (forLValue)
4663 result.LV = CGF.EmitLValue(ov);
4664 else
4665 result.RV = CGF.EmitAnyExpr(ov, slot);
4666 }
4667 }
4668
4669 opaques.push_back(opaqueData);
4670
4671 // Otherwise, if the expression is the result, evaluate it
4672 // and remember the result.
4673 } else if (semantic == resultExpr) {
4674 if (forLValue)
4675 result.LV = CGF.EmitLValue(semantic);
4676 else
4677 result.RV = CGF.EmitAnyExpr(semantic, slot);
4678
4679 // Otherwise, evaluate the expression in an ignored context.
4680 } else {
4681 CGF.EmitIgnoredExpr(semantic);
4682 }
4683 }
4684
4685 // Unbind all the opaques now.
4686 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4687 opaques[i].unbind(CGF);
4688
4689 return result;
4690}
4691
4692RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4693 AggValueSlot slot) {
4694 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4695}
4696
4697LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4698 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4699}