blob: d3c2f47093c8e119f3acdd1237f29a8b9c5fbb6f [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 Liue45b3d52017-10-24 19:14:43 +000077 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
Yaxun Liu561ac062017-10-30 14:38:30 +000078 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
79 // otherwise alloca is inserted at the current insertion point of the
80 // builder.
81 if (!ArraySize)
82 Builder.SetInsertPoint(AllocaInsertPt);
Yaxun Liu84744c12017-06-19 17:03:41 +000083 V = getTargetHooks().performAddrSpaceCast(
84 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
85 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
86 }
87
88 return Address(V, Align);
John McCall7f416cc2015-09-08 08:05:57 +000089}
90
Yaxun Liu84744c12017-06-19 17:03:41 +000091/// CreateTempAlloca - This creates an alloca and inserts it into the entry
92/// block if \p ArraySize is nullptr, otherwise inserts it at the current
93/// insertion point of the builder.
Chris Lattner2192fe52011-07-18 04:24:23 +000094llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Yaxun Liu84744c12017-06-19 17:03:41 +000095 const Twine &Name,
96 llvm::Value *ArraySize) {
97 if (ArraySize)
98 return Builder.CreateAlloca(Ty, ArraySize, Name);
Matt Arsenault502ad602017-04-10 22:28:02 +000099 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
Yaxun Liu84744c12017-06-19 17:03:41 +0000100 ArraySize, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +0000101}
Chris Lattner8394d792007-06-05 20:53:16 +0000102
John McCall7f416cc2015-09-08 08:05:57 +0000103/// CreateDefaultAlignTempAlloca - This creates an alloca with the
104/// default alignment of the corresponding LLVM type, which is *not*
105/// guaranteed to be related in any way to the expected alignment of
106/// an AST type that might have been lowered to Ty.
107Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
108 const Twine &Name) {
109 CharUnits Align =
110 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
111 return CreateTempAlloca(Ty, Align, Name);
112}
113
114void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
115 assert(isa<llvm::AllocaInst>(Var.getPointer()));
116 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
117 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +0000118 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000119 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +0000120}
121
John McCall7f416cc2015-09-08 08:05:57 +0000122Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +0000123 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +0000124 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +0000125}
126
Yaxun Liu84744c12017-06-19 17:03:41 +0000127Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
128 bool CastToDefaultAddrSpace) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000129 // FIXME: Should we prefer the preferred type alignment here?
Yaxun Liu84744c12017-06-19 17:03:41 +0000130 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
131 CastToDefaultAddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +0000132}
133
134Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +0000135 const Twine &Name,
136 bool CastToDefaultAddrSpace) {
137 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
138 CastToDefaultAddrSpace);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000139}
140
Chris Lattner8394d792007-06-05 20:53:16 +0000141/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
142/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000143llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000144 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000145 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000146 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000147 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000148 }
John McCall7a9aac22010-08-23 01:21:21 +0000149
150 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000151 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000152 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000153 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000154
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000155 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
156 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000157}
158
John McCalla2342eb2010-12-05 02:00:02 +0000159/// EmitIgnoredExpr - Emit code to compute the specified expression,
160/// ignoring the result.
161void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
162 if (E->isRValue())
163 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
164
165 // Just emit it as an l-value and drop the result.
166 EmitLValue(E);
167}
168
John McCall7a626f62010-09-15 10:14:12 +0000169/// EmitAnyExpr - Emit code to compute the specified expression which
170/// can have any type. The result is returned as an RValue struct.
171/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000172/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000173RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
174 AggValueSlot aggSlot,
175 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000176 switch (getEvaluationKind(E->getType())) {
177 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000178 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000179 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000180 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000181 case TEK_Aggregate:
182 if (!ignoreResult && aggSlot.isIgnored())
183 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
184 EmitAggExpr(E, aggSlot);
185 return aggSlot.asRValue();
186 }
187 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000188}
189
Mike Stump4a3999f2009-09-09 13:00:44 +0000190/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
191/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000192RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
193 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000194
John McCall47fb9502013-03-07 21:37:08 +0000195 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000196 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
197 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000198}
199
John McCall21886962010-04-21 10:05:39 +0000200/// EmitAnyExprToMem - Evaluate an expression into a given memory
201/// location.
202void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000203 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000204 Qualifiers Quals,
205 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000206 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000207 switch (getEvaluationKind(E->getType())) {
208 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000209 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000210 /*isInit*/ false);
211 return;
212
213 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000214 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000215 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000216 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000217 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000218 return;
219 }
220
221 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000222 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000223 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000224 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000225 return;
John McCall21886962010-04-21 10:05:39 +0000226 }
John McCall47fb9502013-03-07 21:37:08 +0000227 }
228 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000229}
230
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000231static void
232pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000233 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000234 // Objective-C++ ARC:
235 // If we are binding a reference to a temporary that has ownership, we
236 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000237 //
238 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000239 if (auto Lifetime = M->getType().getObjCLifetime()) {
240 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000241 case Qualifiers::OCL_None:
242 case Qualifiers::OCL_ExplicitNone:
243 // Carry on to normal cleanup handling.
244 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000245
Richard Smith736a9472013-06-12 20:42:33 +0000246 case Qualifiers::OCL_Autoreleasing:
247 // Nothing to do; cleaned up by an autorelease pool.
248 return;
249
250 case Qualifiers::OCL_Strong:
251 case Qualifiers::OCL_Weak:
252 switch (StorageDuration Duration = M->getStorageDuration()) {
253 case SD_Static:
254 // Note: we intentionally do not register a cleanup to release
255 // the object on program termination.
256 return;
257
258 case SD_Thread:
259 // FIXME: We should probably register a cleanup in this case.
260 return;
261
262 case SD_Automatic:
263 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000264 CodeGenFunction::Destroyer *Destroy;
265 CleanupKind CleanupKind;
266 if (Lifetime == Qualifiers::OCL_Strong) {
267 const ValueDecl *VD = M->getExtendingDecl();
268 bool Precise =
269 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
270 CleanupKind = CGF.getARCCleanupKind();
271 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
272 : &CodeGenFunction::destroyARCStrongImprecise;
273 } else {
274 // __weak objects always get EH cleanups; otherwise, exceptions
275 // could cause really nasty crashes instead of mere leaks.
276 CleanupKind = NormalAndEHCleanup;
277 Destroy = &CodeGenFunction::destroyARCWeak;
278 }
279 if (Duration == SD_FullExpression)
280 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000281 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000282 CleanupKind & EHCleanup);
283 else
284 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000285 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000286 *Destroy, CleanupKind & EHCleanup);
287 return;
288
289 case SD_Dynamic:
290 llvm_unreachable("temporary cannot have dynamic storage duration");
291 }
292 llvm_unreachable("unknown storage duration");
293 }
294 }
295
Craig Topper8a13c412014-05-21 05:09:00 +0000296 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000297 if (const RecordType *RT =
298 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
299 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000300 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000301 if (!ClassDecl->hasTrivialDestructor())
302 ReferenceTemporaryDtor = ClassDecl->getDestructor();
303 }
304
305 if (!ReferenceTemporaryDtor)
306 return;
307
308 // Call the destructor for the temporary.
309 switch (M->getStorageDuration()) {
310 case SD_Static:
311 case SD_Thread: {
312 llvm::Constant *CleanupFn;
313 llvm::Constant *CleanupArg;
314 if (E->getType()->isArrayType()) {
315 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000316 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000317 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
318 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000319 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
320 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000321 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
322 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000323 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000324 }
325 CGF.CGM.getCXXABI().registerGlobalDtor(
326 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
327 break;
328 }
329
330 case SD_FullExpression:
331 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
332 CodeGenFunction::destroyCXXObject,
333 CGF.getLangOpts().Exceptions);
334 break;
335
336 case SD_Automatic:
337 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
338 ReferenceTemporary, E->getType(),
339 CodeGenFunction::destroyCXXObject,
340 CGF.getLangOpts().Exceptions);
341 break;
342
343 case SD_Dynamic:
344 llvm_unreachable("temporary cannot have dynamic storage duration");
345 }
346}
347
Yaxun Liucbf647c2017-07-08 13:24:52 +0000348static Address createReferenceTemporary(CodeGenFunction &CGF,
349 const MaterializeTemporaryExpr *M,
350 const Expr *Inner) {
351 auto &TCG = CGF.getTargetHooks();
Richard Smith736a9472013-06-12 20:42:33 +0000352 switch (M->getStorageDuration()) {
353 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000354 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000355 // If we have a constant temporary array or record try to promote it into a
356 // constant global under the same rules a normal constant would've been
357 // promoted. This is easier on the optimizer and generally emits fewer
358 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000359 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000360 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000361 (Ty->isArrayType() || Ty->isRecordType()) &&
362 CGF.CGM.isTypeConstant(Ty, true))
John McCallde0fe072017-08-15 21:42:52 +0000363 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000364 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
365 auto AS = AddrSpace.getValue();
366 auto *GV = new llvm::GlobalVariable(
367 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
368 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
369 llvm::GlobalValue::NotThreadLocal,
370 CGF.getContext().getTargetAddressSpace(AS));
371 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
372 GV->setAlignment(alignment.getQuantity());
373 llvm::Constant *C = GV;
374 if (AS != LangAS::Default)
375 C = TCG.performAddrSpaceCast(
376 CGF.CGM, GV, AS, LangAS::Default,
377 GV->getValueType()->getPointerTo(
378 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
379 // FIXME: Should we put the new global into a COMDAT?
380 return Address(C, alignment);
381 }
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000382 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000383 return CGF.CreateMemTemp(Ty, "ref.tmp");
384 }
Richard Smith736a9472013-06-12 20:42:33 +0000385 case SD_Thread:
386 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000387 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000388
389 case SD_Dynamic:
390 llvm_unreachable("temporary can't have dynamic storage duration");
391 }
392 llvm_unreachable("unknown storage duration");
393}
394
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000395LValue CodeGenFunction::
396EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000397 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000398
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000399 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
400 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000401 auto ownership = M->getType().getObjCLifetime();
402 if (ownership != Qualifiers::OCL_None &&
403 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000404 Address Object = createReferenceTemporary(*this, M, E);
405 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
406 Object = Address(llvm::ConstantExpr::getBitCast(Var,
407 ConvertTypeForMem(E->getType())
408 ->getPointerTo(Object.getAddressSpace())),
409 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000410
411 // createReferenceTemporary will promote the temporary to a global with a
412 // constant initializer if it can. It can only do this to a value of
413 // ARC-manageable type if the value is global and therefore "immune" to
414 // ref-counting operations. Therefore we have no need to emit either a
415 // dynamic initialization or a cleanup and we can just return the address
416 // of the temporary.
417 if (Var->hasInitializer())
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000418 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000419
Richard Smitha509f2f2013-06-14 03:07:01 +0000420 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
421 }
John McCall7f416cc2015-09-08 08:05:57 +0000422 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000423 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000424
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000425 switch (getEvaluationKind(E->getType())) {
426 default: llvm_unreachable("expected scalar or aggregate expression");
427 case TEK_Scalar:
428 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
429 break;
430 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000431 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000432 E->getType().getQualifiers(),
433 AggValueSlot::IsDestructed,
434 AggValueSlot::DoesNotNeedGCBarriers,
435 AggValueSlot::IsNotAliased));
436 break;
437 }
438 }
Richard Smith736a9472013-06-12 20:42:33 +0000439
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000440 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000441 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000442 }
443
Richard Smithf3fabd22013-06-03 00:17:11 +0000444 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000445 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000446 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
447
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000448 for (const auto &Ignored : CommaLHSs)
449 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000450
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000451 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000452 if (opaque->getType()->isRecordType()) {
453 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000454 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000455 }
456 }
457
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000458 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000459 Address Object = createReferenceTemporary(*this, M, E);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000460 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
461 Object.getPointer()->stripPointerCasts())) {
John McCall7f416cc2015-09-08 08:05:57 +0000462 Object = Address(llvm::ConstantExpr::getBitCast(
Yaxun Liucbf647c2017-07-08 13:24:52 +0000463 cast<llvm::Constant>(Object.getPointer()),
464 ConvertTypeForMem(E->getType())->getPointerTo()),
John McCall7f416cc2015-09-08 08:05:57 +0000465 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000466 // If the temporary is a global and has a constant initializer or is a
467 // constant temporary that we promoted to a global, we may have already
468 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000469 if (!Var->hasInitializer()) {
470 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
471 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
472 }
473 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000474 switch (M->getStorageDuration()) {
475 case SD_Automatic:
476 case SD_FullExpression:
477 if (auto *Size = EmitLifetimeStart(
478 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
479 Object.getPointer())) {
480 if (M->getStorageDuration() == SD_Automatic)
481 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
482 Object, Size);
483 else
484 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
485 Size);
486 }
487 break;
488 default:
489 break;
490 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000491 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
492 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000493 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000494
Richard Smith736a9472013-06-12 20:42:33 +0000495 // Perform derived-to-base casts and/or field accesses, to get from the
496 // temporary object we created (and, potentially, for which we extended
497 // the lifetime) to the subobject we're binding the reference to.
498 for (unsigned I = Adjustments.size(); I != 0; --I) {
499 SubobjectAdjustment &Adjustment = Adjustments[I-1];
500 switch (Adjustment.Kind) {
501 case SubobjectAdjustment::DerivedToBaseAdjustment:
502 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000503 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
504 Adjustment.DerivedToBase.BasePath->path_begin(),
505 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000506 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000507 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000508
Richard Smith736a9472013-06-12 20:42:33 +0000509 case SubobjectAdjustment::FieldAdjustment: {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000510 LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000511 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000512 assert(LV.isSimple() &&
513 "materialized temporary field is not a simple lvalue");
514 Object = LV.getAddress();
515 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000516 }
517
Richard Smith736a9472013-06-12 20:42:33 +0000518 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000519 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000520 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
521 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000522 break;
523 }
524 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000525 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000526
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000527 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000528}
529
530RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000531CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
532 // Emit the expression as an lvalue.
533 LValue LV = EmitLValue(E);
534 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000535 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000536
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000537 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000538 // C++11 [dcl.ref]p5 (as amended by core issue 453):
539 // If a glvalue to which a reference is directly bound designates neither
540 // an existing object or function of an appropriate type nor a region of
541 // storage of suitable size and alignment to contain an object of the
542 // reference's type, the behavior is undefined.
543 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000544 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000545 }
John McCall8680f872010-07-21 06:29:51 +0000546
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000547 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000548}
549
550
Mike Stump4a3999f2009-09-09 13:00:44 +0000551/// getAccessedFieldNo - Given an encoded value and a result number, return the
552/// input field number being accessed.
553unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000554 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000555 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
556 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000557}
558
Richard Smith4d3110a2012-10-25 02:14:12 +0000559/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
560static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
561 llvm::Value *High) {
562 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
563 llvm::Value *K47 = Builder.getInt64(47);
564 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
565 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
566 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
567 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
568 return Builder.CreateMul(B1, KMul);
569}
570
Vedant Kumar24792e32017-10-03 01:27:25 +0000571bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
572 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
573 TCK == TCK_UpcastToVirtualBase;
574}
575
576bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
577 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
578 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
579 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
580 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
581 TCK == TCK_UpcastToVirtualBase);
582}
583
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000584bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000585 return SanOpts.has(SanitizerKind::Null) |
586 SanOpts.has(SanitizerKind::Alignment) |
587 SanOpts.has(SanitizerKind::ObjectSize) |
588 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000589}
590
Richard Smithe30752c2012-10-09 19:52:38 +0000591void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000592 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000593 CharUnits Alignment,
594 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000595 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000596 return;
597
Richard Smith2d8b2942012-11-01 07:22:08 +0000598 // Don't check pointers outside the default address space. The null check
599 // isn't correct, the object-size check isn't supported by LLVM, and we can't
600 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000601 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000602 return;
603
Vedant Kumarc420d142017-06-16 03:27:36 +0000604 // Don't check pointers to volatile data. The behavior here is implementation-
605 // defined.
606 if (Ty.isVolatileQualified())
607 return;
608
Alexey Samsonov24cad992014-07-17 18:46:27 +0000609 SanitizerScope SanScope(this);
610
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000611 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000612 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000613
Vedant Kumare859ebb2017-04-26 02:17:21 +0000614 // Quickly determine whether we have a pointer to an alloca. It's possible
615 // to skip null checks, and some alignment checks, for these pointers. This
616 // can reduce compile-time significantly.
617 auto PtrToAlloca =
618 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
619
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000620 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000621 llvm::Value *IsNonNull = nullptr;
622 bool IsGuaranteedNonNull =
623 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
Vedant Kumar24792e32017-10-03 01:27:25 +0000624 bool AllowNullPointers = isNullPointerAllowed(TCK);
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000625 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000626 !IsGuaranteedNonNull) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000627 // The glvalue must not be an empty glvalue.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000628 IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000629
Vedant Kumardbbdda42017-04-17 22:26:10 +0000630 // The IR builder can constant-fold the null check if the pointer points to
631 // a constant.
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000632 IsGuaranteedNonNull = IsNonNull == True;
Vedant Kumardbbdda42017-04-17 22:26:10 +0000633
634 // Skip the null check if the pointer is known to be non-null.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000635 if (!IsGuaranteedNonNull) {
Vedant Kumardbbdda42017-04-17 22:26:10 +0000636 if (AllowNullPointers) {
637 // When performing pointer casts, it's OK if the value is null.
638 // Skip the remaining checks in that case.
639 Done = createBasicBlock("null");
640 llvm::BasicBlock *Rest = createBasicBlock("not.null");
641 Builder.CreateCondBr(IsNonNull, Rest, Done);
642 EmitBlock(Rest);
643 } else {
644 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
645 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000646 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000647 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000648
Vedant Kumar18348ea2017-02-17 23:22:55 +0000649 if (SanOpts.has(SanitizerKind::ObjectSize) &&
650 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
651 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000652 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000653
Richard Smith69d0d262012-08-24 00:54:33 +0000654 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000655 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000656 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000657 // FIXME: Get object address space
658 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
659 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000660 llvm::Value *Min = Builder.getFalse();
George Burgess IVa63f9152017-03-21 20:09:35 +0000661 llvm::Value *NullIsUnknown = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000662 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
George Burgess IVa63f9152017-03-21 20:09:35 +0000663 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
664 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
665 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000666 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000667 }
Richard Smith69d0d262012-08-24 00:54:33 +0000668
Richard Smithb1b0ab42012-11-05 22:21:05 +0000669 uint64_t AlignVal = 0;
Vedant Kumar8a715332017-10-03 01:27:24 +0000670 llvm::Value *PtrAsInt = nullptr;
Richard Smithb1b0ab42012-11-05 22:21:05 +0000671
Vedant Kumar18348ea2017-02-17 23:22:55 +0000672 if (SanOpts.has(SanitizerKind::Alignment) &&
673 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000674 AlignVal = Alignment.getQuantity();
675 if (!Ty->isIncompleteType() && !AlignVal)
676 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
677
Richard Smith69d0d262012-08-24 00:54:33 +0000678 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000679 if (AlignVal > 1 &&
680 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Vedant Kumar8a715332017-10-03 01:27:24 +0000681 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
682 llvm::Value *Align = Builder.CreateAnd(
683 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000684 llvm::Value *Aligned =
Vedant Kumar8a715332017-10-03 01:27:24 +0000685 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000686 if (Aligned != True)
687 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000688 }
Richard Smith69d0d262012-08-24 00:54:33 +0000689 }
690
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000691 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000692 // Make sure we're not losing information. Alignment needs to be a power of
693 // 2
694 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000695 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000696 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
697 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
698 llvm::ConstantInt::get(Int8Ty, TCK)};
Vedant Kumar8a715332017-10-03 01:27:24 +0000699 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
700 PtrAsInt ? PtrAsInt : Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000701 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000702
Richard Smithb1b0ab42012-11-05 22:21:05 +0000703 // If possible, check that the vptr indicates that there is a subobject of
704 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000705 //
706 // C++11 [basic.life]p5,6:
707 // [For storage which does not refer to an object within its lifetime]
708 // The program has undefined behavior if:
709 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000710 // or call a non-static member function
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000711 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumar24792e32017-10-03 01:27:25 +0000712 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000713 // Ensure that the pointer is non-null before loading it. If there is no
Vedant Kumara0c36712017-08-02 18:10:31 +0000714 // compile-time guarantee, reuse the run-time null check or emit a new one.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000715 if (!IsGuaranteedNonNull) {
Vedant Kumara0c36712017-08-02 18:10:31 +0000716 if (!IsNonNull)
717 IsNonNull = Builder.CreateIsNotNull(Ptr);
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000718 if (!Done)
719 Done = createBasicBlock("vptr.null");
720 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
721 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
722 EmitBlock(VptrNotNull);
723 }
724
Richard Smith4d3110a2012-10-25 02:14:12 +0000725 // Compute a hash of the mangled name of the type.
726 //
727 // FIXME: This is not guaranteed to be deterministic! Move to a
728 // fingerprinting mechanism once LLVM provides one. For the time
729 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000730 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000731 llvm::raw_svector_ostream Out(MangledName);
732 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
733 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000734
Alexey Samsonov84856012014-07-10 22:34:19 +0000735 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000736 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +0000737 SanitizerKind::Vptr, Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000738 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000739
Alexey Samsonov84856012014-07-10 22:34:19 +0000740 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
741 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
742 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000743 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000744 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
745 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000746
Alexey Samsonov84856012014-07-10 22:34:19 +0000747 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
748 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000749
Alexey Samsonov84856012014-07-10 22:34:19 +0000750 // Look the hash up in our cache.
751 const int CacheSize = 128;
752 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
753 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
754 "__ubsan_vptr_type_cache");
755 llvm::Value *Slot = Builder.CreateAnd(Hash,
756 llvm::ConstantInt::get(IntPtrTy,
757 CacheSize-1));
758 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
759 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000760 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
761 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000762
763 // If the hash isn't in the cache, call a runtime handler to perform the
764 // hard work of checking whether the vptr is for an object of the right
765 // type. This will either fill in the cache and return, or produce a
766 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000767 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000768 llvm::Constant *StaticData[] = {
769 EmitCheckSourceLocation(Loc),
770 EmitCheckTypeDescriptor(Ty),
771 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
772 llvm::ConstantInt::get(Int8Ty, TCK)
773 };
John McCall7f416cc2015-09-08 08:05:57 +0000774 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000775 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000776 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
777 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000778 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000779 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000780
781 if (Done) {
782 Builder.CreateBr(Done);
783 EmitBlock(Done);
784 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000785}
Chris Lattner4647a212007-08-31 22:49:20 +0000786
Richard Smith539e4a72013-02-23 02:53:19 +0000787/// Determine whether this expression refers to a flexible array member in a
788/// struct. We disable array bounds checks for such members.
789static bool isFlexibleArrayMemberExpr(const Expr *E) {
790 // For compatibility with existing code, we treat arrays of length 0 or
791 // 1 as flexible array members.
792 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000793 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000794 if (CAT->getSize().ugt(1))
795 return false;
796 } else if (!isa<IncompleteArrayType>(AT))
797 return false;
798
799 E = E->IgnoreParens();
800
801 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000802 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000803 // FIXME: If the base type of the member expr is not FD->getParent(),
804 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000805 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000806 RecordDecl::field_iterator FI(
807 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
808 return ++FI == FD->getParent()->field_end();
809 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000810 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
811 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000812 }
813
814 return false;
815}
816
817/// If Base is known to point to the start of an array, return the length of
818/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000819static llvm::Value *getArrayIndexingBound(
820 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000821 // For the vector indexing extension, the bound is the number of elements.
822 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
823 IndexedType = Base->getType();
824 return CGF.Builder.getInt32(VT->getNumElements());
825 }
826
827 Base = Base->IgnoreParens();
828
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000829 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000830 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
831 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
832 IndexedType = CE->getSubExpr()->getType();
833 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000834 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000835 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000836 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000837 return CGF.getVLASize(VAT).first;
838 }
839 }
840
Craig Topper8a13c412014-05-21 05:09:00 +0000841 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000842}
843
844void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
845 llvm::Value *Index, QualType IndexType,
846 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000847 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000848 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000849 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000850
Richard Smith539e4a72013-02-23 02:53:19 +0000851 QualType IndexedType;
852 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
853 if (!Bound)
854 return;
855
856 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
857 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
858 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
859
860 llvm::Constant *StaticData[] = {
861 EmitCheckSourceLocation(E->getExprLoc()),
862 EmitCheckTypeDescriptor(IndexedType),
863 EmitCheckTypeDescriptor(IndexType)
864 };
865 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
866 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000867 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
868 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000869}
870
Chris Lattner116ce8f2010-01-09 21:40:03 +0000871
Chris Lattner116ce8f2010-01-09 21:40:03 +0000872CodeGenFunction::ComplexPairTy CodeGenFunction::
873EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
874 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000875 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000876
Chris Lattner116ce8f2010-01-09 21:40:03 +0000877 llvm::Value *NextVal;
878 if (isa<llvm::IntegerType>(InVal.first->getType())) {
879 uint64_t AmountVal = isInc ? 1 : -1;
880 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000881
Chris Lattner116ce8f2010-01-09 21:40:03 +0000882 // Add the inc/dec to the real part.
883 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
884 } else {
885 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
886 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
887 if (!isInc)
888 FVal.changeSign();
889 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000890
Chris Lattner116ce8f2010-01-09 21:40:03 +0000891 // Add the inc/dec to the real part.
892 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
893 }
Craig Topper99e79272013-07-26 05:59:26 +0000894
Chris Lattner116ce8f2010-01-09 21:40:03 +0000895 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000896
Chris Lattner116ce8f2010-01-09 21:40:03 +0000897 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000898 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000899
Chris Lattner116ce8f2010-01-09 21:40:03 +0000900 // If this is a postinc, return the value read from memory, otherwise use the
901 // updated value.
902 return isPre ? IncVal : InVal;
903}
904
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000905void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
906 CodeGenFunction *CGF) {
907 // Bind VLAs in the cast type.
908 if (CGF && E->getType()->isVariablyModifiedType())
909 CGF->EmitVariablyModifiedType(E->getType());
910
911 if (CGDebugInfo *DI = getModuleDebugInfo())
912 DI->EmitExplicitCastType(E->getType());
913}
914
Chris Lattnera45c5af2007-06-02 19:47:04 +0000915//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000916// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000917//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000918
John McCall7f416cc2015-09-08 08:05:57 +0000919/// EmitPointerWithAlignment - Given an expression of pointer type, try to
920/// derive a more accurate bound on the alignment of the pointer.
921Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000922 LValueBaseInfo *BaseInfo,
923 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000924 // We allow this with ObjC object pointers because of fragile ABIs.
925 assert(E->getType()->isPointerType() ||
926 E->getType()->isObjCObjectPointerType());
927 E = E->IgnoreParens();
928
929 // Casts:
930 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000931 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
932 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000933
934 switch (CE->getCastKind()) {
935 // Non-converting casts (but not C's implicit conversion from void*).
936 case CK_BitCast:
937 case CK_NoOp:
Anastasia Stulova0a72ed42017-09-27 14:37:00 +0000938 case CK_AddressSpaceConversion:
John McCall7f416cc2015-09-08 08:05:57 +0000939 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
940 if (PtrTy->getPointeeType()->isVoidType())
941 break;
942
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000943 LValueBaseInfo InnerBaseInfo;
944 TBAAAccessInfo InnerTBAAInfo;
945 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
946 &InnerBaseInfo,
947 &InnerTBAAInfo);
948 if (BaseInfo) *BaseInfo = InnerBaseInfo;
949 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +0000950
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000951 if (isa<ExplicitCastExpr>(CE)) {
952 LValueBaseInfo TargetTypeBaseInfo;
953 TBAAAccessInfo TargetTypeTBAAInfo;
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000954 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000955 &TargetTypeBaseInfo,
956 &TargetTypeTBAAInfo);
957 if (TBAAInfo)
958 *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
959 TargetTypeTBAAInfo);
960 // If the source l-value is opaque, honor the alignment of the
961 // casted-to type.
962 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
963 if (BaseInfo)
964 BaseInfo->mergeForCast(TargetTypeBaseInfo);
965 Addr = Address(Addr.getPointer(), Align);
966 }
John McCall7f416cc2015-09-08 08:05:57 +0000967 }
968
Peter Collingbourne574975e2016-01-14 02:49:48 +0000969 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
970 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000971 if (auto PT = E->getType()->getAs<PointerType>())
972 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
973 /*MayBeNull=*/true,
974 CodeGenFunction::CFITCK_UnrelatedCast,
975 CE->getLocStart());
976 }
Anastasia Stulova0a72ed42017-09-27 14:37:00 +0000977 return CE->getCastKind() != CK_AddressSpaceConversion
978 ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
979 : Builder.CreateAddrSpaceCast(Addr,
980 ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000981 }
982 break;
983
984 // Array-to-pointer decay.
985 case CK_ArrayToPointerDecay:
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000986 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000987
988 // Derived-to-base conversions.
989 case CK_UncheckedDerivedToBase:
990 case CK_DerivedToBase: {
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000991 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo,
992 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000993 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
994 return GetAddressOfBaseClass(Addr, Derived,
995 CE->path_begin(), CE->path_end(),
996 ShouldNullCheckClassCastValue(CE),
997 CE->getExprLoc());
998 }
999
1000 // TODO: Is there any reason to treat base-to-derived conversions
1001 // specially?
1002 default:
1003 break;
1004 }
1005 }
1006
1007 // Unary &.
1008 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1009 if (UO->getOpcode() == UO_AddrOf) {
1010 LValue LV = EmitLValue(UO->getSubExpr());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001011 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001012 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
John McCall7f416cc2015-09-08 08:05:57 +00001013 return LV.getAddress();
1014 }
1015 }
1016
1017 // TODO: conditional operators, comma.
1018
1019 // Otherwise, use the alignment of the type.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001020 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo,
1021 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001022 return Address(EmitScalarExpr(E), Align);
1023}
1024
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001025RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001026 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001027 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +00001028
1029 switch (getEvaluationKind(Ty)) {
1030 case TEK_Complex: {
1031 llvm::Type *EltTy =
1032 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +00001033 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001034 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001035 }
Craig Topper99e79272013-07-26 05:59:26 +00001036
Chris Lattner65526f02010-08-23 05:26:13 +00001037 // If this is a use of an undefined aggregate type, the aggregate must have an
1038 // identifiable address. Just because the contents of the value are undefined
1039 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +00001040 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00001041 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +00001042 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001043 }
John McCall47fb9502013-03-07 21:37:08 +00001044
1045 case TEK_Scalar:
1046 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1047 }
1048 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +00001049}
1050
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001051RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1052 const char *Name) {
1053 ErrorUnsupported(E, Name);
1054 return GetUndefRValue(E->getType());
1055}
1056
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001057LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1058 const char *Name) {
1059 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001060 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001061 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1062 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001063}
1064
Vedant Kumarffd7c882017-04-14 22:03:34 +00001065bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001066 const Expr *Base = Obj;
1067 while (!isa<CXXThisExpr>(Base)) {
1068 // The result of a dynamic_cast can be null.
1069 if (isa<CXXDynamicCastExpr>(Base))
1070 return false;
1071
1072 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1073 Base = CE->getSubExpr();
1074 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1075 Base = PE->getSubExpr();
1076 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1077 if (UO->getOpcode() == UO_Extension)
1078 Base = UO->getSubExpr();
1079 else
1080 return false;
1081 } else {
1082 return false;
1083 }
1084 }
1085 return true;
1086}
1087
Richard Smith4d1458e2012-09-08 02:08:36 +00001088LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +00001089 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001090 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +00001091 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1092 else
1093 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001094 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1095 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001096 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1097 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1098 if (IsBaseCXXThis)
1099 SkippedChecks.set(SanitizerKind::Alignment, true);
1100 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001101 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001102 }
John McCall7f416cc2015-09-08 08:05:57 +00001103 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001104 E->getType(), LV.getAlignment(), SkippedChecks);
1105 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001106 return LV;
1107}
1108
Chris Lattner8394d792007-06-05 20:53:16 +00001109/// EmitLValue - Emit code to compute a designator that specifies the location
1110/// of the expression.
1111///
Mike Stump4a3999f2009-09-09 13:00:44 +00001112/// This can return one of two things: a simple address or a bitfield reference.
1113/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1114/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001115///
Mike Stump4a3999f2009-09-09 13:00:44 +00001116/// If this returns a bitfield reference, nothing about the pointee type of the
1117/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001118///
Mike Stump4a3999f2009-09-09 13:00:44 +00001119/// If this returns a normal address, and if the lvalue's C type is fixed size,
1120/// this method guarantees that the returned pointer type will point to an LLVM
1121/// type of the same size of the lvalue's type. If the lvalue has a variable
1122/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001123///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001124LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001125 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001126 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001127 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001128
John McCallc109a252011-11-07 03:59:57 +00001129 case Expr::ObjCPropertyRefExprClass:
1130 llvm_unreachable("cannot emit a property reference directly");
1131
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001132 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001133 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001134 case Expr::ObjCIsaExprClass:
1135 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001136 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001137 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001138 case Expr::CompoundAssignOperatorClass: {
1139 QualType Ty = E->getType();
1140 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1141 Ty = AT->getValueType();
1142 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001143 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1144 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001145 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001146 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001147 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001148 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001149 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001150 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001151 case Expr::VAArgExprClass:
1152 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001153 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001154 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001155 case Expr::ParenExprClass:
1156 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001157 case Expr::GenericSelectionExprClass:
1158 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001159 case Expr::PredefinedExprClass:
1160 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001161 case Expr::StringLiteralClass:
1162 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001163 case Expr::ObjCEncodeExprClass:
1164 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001165 case Expr::PseudoObjectExprClass:
1166 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001167 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001168 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001169 case Expr::CXXTemporaryObjectExprClass:
1170 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001171 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1172 case Expr::CXXBindTemporaryExprClass:
1173 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001174 case Expr::CXXUuidofExprClass:
1175 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001176 case Expr::LambdaExprClass:
1177 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001178
1179 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001180 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001181 enterFullExpression(cleanups);
1182 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001183 LValue LV = EmitLValue(cleanups->getSubExpr());
1184 if (LV.isSimple()) {
1185 // Defend against branches out of gnu statement expressions surrounded by
1186 // cleanups.
1187 llvm::Value *V = LV.getPointer();
1188 Scope.ForceCleanup({&V});
1189 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001190 getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
Reid Kleckner092d0652017-03-06 22:18:34 +00001191 }
1192 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1193 // bitfield lvalue or some other non-simple lvalue?
1194 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001195 }
1196
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001197 case Expr::CXXDefaultArgExprClass:
1198 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001199 case Expr::CXXDefaultInitExprClass: {
1200 CXXDefaultInitExprScope Scope(*this);
1201 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1202 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001203 case Expr::CXXTypeidExprClass:
1204 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001205
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001206 case Expr::ObjCMessageExprClass:
1207 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001208 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001209 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001210 case Expr::StmtExprClass:
1211 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001212 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001213 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001214 case Expr::ArraySubscriptExprClass:
1215 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001216 case Expr::OMPArraySectionExprClass:
1217 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001218 case Expr::ExtVectorElementExprClass:
1219 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001220 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001221 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001222 case Expr::CompoundLiteralExprClass:
1223 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001224 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001225 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001226 case Expr::BinaryConditionalOperatorClass:
1227 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001228 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001229 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001230 case Expr::OpaqueValueExprClass:
1231 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001232 case Expr::SubstNonTypeTemplateParmExprClass:
1233 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001234 case Expr::ImplicitCastExprClass:
1235 case Expr::CStyleCastExprClass:
1236 case Expr::CXXFunctionalCastExprClass:
1237 case Expr::CXXStaticCastExprClass:
1238 case Expr::CXXDynamicCastExprClass:
1239 case Expr::CXXReinterpretCastExprClass:
1240 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001241 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001242 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001243
Douglas Gregorfe314812011-06-21 17:03:29 +00001244 case Expr::MaterializeTemporaryExprClass:
1245 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Eric Fiseliercddaf872017-06-15 19:43:36 +00001246
1247 case Expr::CoawaitExprClass:
1248 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1249 case Expr::CoyieldExprClass:
1250 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001251 }
1252}
1253
John McCall71335052012-03-10 03:05:10 +00001254/// Given an object of the given canonical type, can we safely copy a
1255/// value out of it based on its initializer?
1256static bool isConstantEmittableObjectType(QualType type) {
1257 assert(type.isCanonical());
1258 assert(!type->isReferenceType());
1259
1260 // Must be const-qualified but non-volatile.
1261 Qualifiers qs = type.getLocalQualifiers();
1262 if (!qs.hasConst() || qs.hasVolatile()) return false;
1263
1264 // Otherwise, all object types satisfy this except C++ classes with
1265 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001266 if (const auto *RT = dyn_cast<RecordType>(type))
1267 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001268 if (RD->hasMutableFields() || !RD->isTrivial())
1269 return false;
1270
1271 return true;
1272}
1273
1274/// Can we constant-emit a load of a reference to a variable of the
1275/// given type? This is different from predicates like
1276/// Decl::isUsableInConstantExpressions because we do want it to apply
1277/// in situations that don't necessarily satisfy the language's rules
1278/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1279/// to do this with const float variables even if those variables
1280/// aren't marked 'constexpr'.
1281enum ConstantEmissionKind {
1282 CEK_None,
1283 CEK_AsReferenceOnly,
1284 CEK_AsValueOrReference,
1285 CEK_AsValueOnly
1286};
1287static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1288 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001289 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001290 if (isConstantEmittableObjectType(ref->getPointeeType()))
1291 return CEK_AsValueOrReference;
1292 return CEK_AsReferenceOnly;
1293 }
1294 if (isConstantEmittableObjectType(type))
1295 return CEK_AsValueOnly;
1296 return CEK_None;
1297}
1298
1299/// Try to emit a reference to the given value without producing it as
1300/// an l-value. This is actually more than an optimization: we can't
1301/// produce an l-value for variables that we never actually captured
1302/// in a block or lambda, which means const int variables or constexpr
1303/// literals or similar.
1304CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001305CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1306 ValueDecl *value = refExpr->getDecl();
1307
John McCall71335052012-03-10 03:05:10 +00001308 // The value needs to be an enum constant or a constant variable.
1309 ConstantEmissionKind CEK;
1310 if (isa<ParmVarDecl>(value)) {
1311 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001312 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001313 CEK = checkVarTypeForConstantEmission(var->getType());
1314 } else if (isa<EnumConstantDecl>(value)) {
1315 CEK = CEK_AsValueOnly;
1316 } else {
1317 CEK = CEK_None;
1318 }
1319 if (CEK == CEK_None) return ConstantEmission();
1320
John McCall71335052012-03-10 03:05:10 +00001321 Expr::EvalResult result;
1322 bool resultIsReference;
1323 QualType resultType;
1324
1325 // It's best to evaluate all the way as an r-value if that's permitted.
1326 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001327 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001328 resultIsReference = false;
1329 resultType = refExpr->getType();
1330
1331 // Otherwise, try to evaluate as an l-value.
1332 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001333 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001334 resultIsReference = true;
1335 resultType = value->getType();
1336
1337 // Failure.
1338 } else {
1339 return ConstantEmission();
1340 }
1341
1342 // In any case, if the initializer has side-effects, abandon ship.
1343 if (result.HasSideEffects)
1344 return ConstantEmission();
1345
1346 // Emit as a constant.
John McCallde0fe072017-08-15 21:42:52 +00001347 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1348 result.Val, resultType);
John McCall71335052012-03-10 03:05:10 +00001349
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001350 // Make sure we emit a debug reference to the global variable.
1351 // This should probably fire even for
1352 if (isa<VarDecl>(value)) {
1353 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001354 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001355 } else {
1356 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001357 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001358 }
John McCall71335052012-03-10 03:05:10 +00001359
1360 // If we emitted a reference constant, we need to dereference that.
1361 if (resultIsReference)
1362 return ConstantEmission::forReference(C);
1363
1364 return ConstantEmission::forValue(C);
1365}
1366
Alex Lorenz6cc83172017-08-25 10:07:00 +00001367static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1368 const MemberExpr *ME) {
1369 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1370 // Try to emit static variable member expressions as DREs.
1371 return DeclRefExpr::Create(
1372 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1373 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1374 ME->getType(), ME->getValueKind());
1375 }
1376 return nullptr;
1377}
1378
1379CodeGenFunction::ConstantEmission
1380CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1381 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1382 return tryEmitAsConstant(DRE);
1383 return ConstantEmission();
1384}
1385
Nick Lewycky2d84e842013-10-02 02:29:49 +00001386llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1387 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001388 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001389 lvalue.getType(), Loc, lvalue.getBaseInfo(),
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001390 lvalue.getTBAAInfo(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001391}
1392
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001393static bool hasBooleanRepresentation(QualType Ty) {
1394 if (Ty->isBooleanType())
1395 return true;
1396
1397 if (const EnumType *ET = Ty->getAs<EnumType>())
1398 return ET->getDecl()->getIntegerType()->isBooleanType();
1399
Douglas Gregor298f43d2012-04-12 20:42:30 +00001400 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1401 return hasBooleanRepresentation(AT->getValueType());
1402
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001403 return false;
1404}
1405
Richard Smith1629da92012-12-13 07:11:50 +00001406static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1407 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001408 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001409 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001410 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1411 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001412 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001413 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001414
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001415 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001416 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1417 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001418 } else {
1419 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001420 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001421 unsigned Bitwidth = LTy->getScalarSizeInBits();
1422 unsigned NumNegativeBits = ED->getNumNegativeBits();
1423 unsigned NumPositiveBits = ED->getNumPositiveBits();
1424
1425 if (NumNegativeBits) {
1426 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1427 assert(NumBits <= Bitwidth);
1428 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1429 Min = -End;
1430 } else {
1431 assert(NumPositiveBits <= Bitwidth);
1432 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1433 Min = llvm::APInt(Bitwidth, 0);
1434 }
1435 }
Richard Smith1629da92012-12-13 07:11:50 +00001436 return true;
1437}
1438
1439llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1440 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001441 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1442 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001443 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001444
Duncan Sandsc720e782012-04-15 18:04:54 +00001445 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001446 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001447}
1448
Vedant Kumar5a972652017-02-27 19:46:19 +00001449bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1450 SourceLocation Loc) {
1451 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1452 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1453 if (!HasBoolCheck && !HasEnumCheck)
1454 return false;
1455
1456 bool IsBool = hasBooleanRepresentation(Ty) ||
1457 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1458 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1459 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1460 if (!NeedsBoolCheck && !NeedsEnumCheck)
1461 return false;
1462
Vedant Kumar129edab2017-03-09 16:06:27 +00001463 // Single-bit booleans don't need to be checked. Special-case this to avoid
1464 // a bit width mismatch when handling bitfield values. This is handled by
1465 // EmitFromMemory for the non-bitfield case.
1466 if (IsBool &&
1467 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1468 return false;
1469
Vedant Kumar5a972652017-02-27 19:46:19 +00001470 llvm::APInt Min, End;
1471 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1472 return true;
1473
Vedant Kumar791f7012017-10-03 01:27:26 +00001474 auto &Ctx = getLLVMContext();
Vedant Kumar5a972652017-02-27 19:46:19 +00001475 SanitizerScope SanScope(this);
1476 llvm::Value *Check;
1477 --End;
1478 if (!Min) {
Vedant Kumar791f7012017-10-03 01:27:26 +00001479 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
Vedant Kumar5a972652017-02-27 19:46:19 +00001480 } else {
Vedant Kumar791f7012017-10-03 01:27:26 +00001481 llvm::Value *Upper =
1482 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1483 llvm::Value *Lower =
1484 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
Vedant Kumar5a972652017-02-27 19:46:19 +00001485 Check = Builder.CreateAnd(Upper, Lower);
1486 }
1487 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1488 EmitCheckTypeDescriptor(Ty)};
1489 SanitizerMask Kind =
1490 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1491 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1492 StaticArgs, EmitCheckValue(Value));
1493 return true;
1494}
1495
John McCall7f416cc2015-09-08 08:05:57 +00001496llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1497 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001498 SourceLocation Loc,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001499 LValueBaseInfo BaseInfo,
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001500 TBAAAccessInfo TBAAInfo,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001501 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001502 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1503 // For better performance, handle vector loads differently.
1504 if (Ty->isVectorType()) {
1505 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001506
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001507 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001508
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001509 // Handle vectors of size 3 like size 4 for better performance.
1510 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001511
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001512 // Bitcast to vec4 type.
1513 llvm::VectorType *vec4Ty =
1514 llvm::VectorType::get(VTy->getElementType(), 4);
1515 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1516 // Now load value.
1517 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001518
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001519 // Shuffle vector to get vec3.
1520 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1521 {0, 1, 2}, "extractVec");
1522 return EmitFromMemory(V, Ty);
1523 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001524 }
1525 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001526
1527 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001528 LValue AtomicLValue =
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001529 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001530 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1531 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001532 }
Craig Topper99e79272013-07-26 05:59:26 +00001533
John McCall7f416cc2015-09-08 08:05:57 +00001534 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001535 if (isNontemporal) {
1536 llvm::MDNode *Node = llvm::MDNode::get(
1537 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1538 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1539 }
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001540
1541 if (BaseInfo.getMayAlias())
1542 TBAAInfo = CGM.getTBAAMayAliasAccessInfo();
1543 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001544
Vedant Kumar5a972652017-02-27 19:46:19 +00001545 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1546 // In order to prevent the optimizer from throwing away the check, don't
1547 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001548 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001549 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1550 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001551
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001552 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001553}
1554
John McCall3a7f6922010-10-27 20:58:56 +00001555llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1556 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001557 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001558 // This should really always be an i1, but sometimes it's already
1559 // an i8, and it's awkward to track those cases down.
1560 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001561 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1562 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1563 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001564 }
1565
1566 return Value;
1567}
1568
1569llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1570 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001571 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001572 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1573 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001574 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1575 }
1576
1577 return Value;
1578}
1579
John McCall7f416cc2015-09-08 08:05:57 +00001580void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1581 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001582 LValueBaseInfo BaseInfo,
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001583 TBAAAccessInfo TBAAInfo,
1584 bool isInit, bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001585 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1586 // Handle vectors differently to get better performance.
1587 if (Ty->isVectorType()) {
1588 llvm::Type *SrcTy = Value->getType();
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001589 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001590 // Handle vec3 special.
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001591 if (VecTy && VecTy->getNumElements() == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001592 // Our source is a vec3, do a shuffle vector to make it a vec4.
1593 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1594 Builder.getInt32(2),
1595 llvm::UndefValue::get(Builder.getInt32Ty())};
1596 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1597 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1598 MaskV, "extractVec");
1599 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1600 }
1601 if (Addr.getElementType() != SrcTy) {
1602 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1603 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001604 }
1605 }
Craig Topper99e79272013-07-26 05:59:26 +00001606
John McCall3a7f6922010-10-27 20:58:56 +00001607 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001608
David Majnemera38c9f12016-05-24 16:09:25 +00001609 LValue AtomicLValue =
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001610 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001611 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001612 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1613 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001614 return;
1615 }
1616
Daniel Dunbar03816342010-08-21 02:24:36 +00001617 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001618 if (isNontemporal) {
1619 llvm::MDNode *Node =
1620 llvm::MDNode::get(Store->getContext(),
1621 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1622 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1623 }
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001624
1625 if (BaseInfo.getMayAlias())
1626 TBAAInfo = CGM.getTBAAMayAliasAccessInfo();
1627 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001628}
1629
David Chisnallfa35df62012-01-16 17:27:18 +00001630void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001631 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001632 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001633 lvalue.getType(), lvalue.getBaseInfo(),
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001634 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001635}
1636
Mike Stump4a3999f2009-09-09 13:00:44 +00001637/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1638/// method emits the address of the lvalue, then loads the result as an rvalue,
1639/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001640RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001641 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001642 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001643 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001644 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1645 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001646 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001647 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001648 // In MRC mode, we do a load+autorelease.
1649 if (!getLangOpts().ObjCAutoRefCount) {
1650 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1651 }
1652
1653 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001654 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1655 Object = EmitObjCConsumeObject(LV.getType(), Object);
1656 return RValue::get(Object);
1657 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001658
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001659 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001660 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001661
John McCalla1dee5302010-08-22 10:59:02 +00001662 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001663 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001664 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001665
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001666 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001667 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001668 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001669 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001670 "vecext"));
1671 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001672
1673 // If this is a reference to a subset of the elements of a vector, either
1674 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001675 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001676 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001677
Renato Golin230c5eb2014-05-19 18:15:42 +00001678 // Global Register variables always invoke intrinsics
1679 if (LV.isGlobalReg())
1680 return EmitLoadOfGlobalRegLValue(LV);
1681
John McCallc109a252011-11-07 03:59:57 +00001682 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001683 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001684}
1685
Vedant Kumar129edab2017-03-09 16:06:27 +00001686RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1687 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001688 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001689
Daniel Dunbar3447a022010-04-13 23:34:15 +00001690 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001691 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001692
John McCall7f416cc2015-09-08 08:05:57 +00001693 Address Ptr = LV.getBitFieldAddress();
1694 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001695
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001696 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001697 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001698 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1699 if (HighBits)
1700 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1701 if (Info.Offset + HighBits)
1702 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1703 } else {
1704 if (Info.Offset)
1705 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001706 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001707 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1708 Info.Size),
1709 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001710 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001711 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001712 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001713 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001714}
1715
Nate Begemanb699c9b2009-01-18 06:42:49 +00001716// If this is a reference to a subset of the elements of a vector, create an
1717// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001718RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001719 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1720 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001721
Nate Begemanf322eab2008-05-09 06:41:27 +00001722 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001723
1724 // If the result of the expression is a non-vector type, we must be extracting
1725 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001726 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001727 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001728 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001729 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001730 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001731 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001732
1733 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001734 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001735
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001736 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001737 for (unsigned i = 0; i != NumResultElts; ++i)
1738 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001739
Chris Lattner91c08ad2011-02-15 00:14:06 +00001740 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1741 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001742 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001743 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001744}
1745
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001746/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001747Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1748 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001749 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1750 QualType EQT = ExprVT->getElementType();
1751 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001752
John McCall7f416cc2015-09-08 08:05:57 +00001753 Address CastToPointerElement =
1754 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1755 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001756
1757 const llvm::Constant *Elts = LV.getExtVectorElts();
1758 unsigned ix = getAccessedFieldNo(0, Elts);
1759
John McCall7f416cc2015-09-08 08:05:57 +00001760 Address VectorBasePtrPlusIx =
1761 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1762 getContext().getTypeSizeInChars(EQT),
1763 "vector.elt");
1764
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001765 return VectorBasePtrPlusIx;
1766}
1767
Renato Golin230c5eb2014-05-19 18:15:42 +00001768/// @brief Load of global gamed gegisters are always calls to intrinsics.
1769RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001770 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1771 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001772 llvm::MDNode *RegName = cast<llvm::MDNode>(
1773 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001774
1775 // We accept integer and pointer types only
1776 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1777 llvm::Type *Ty = OrigTy;
1778 if (OrigTy->isPointerTy())
1779 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1780 llvm::Type *Types[] = { Ty };
1781
Renato Golin230c5eb2014-05-19 18:15:42 +00001782 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001783 llvm::Value *Call = Builder.CreateCall(
1784 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001785 if (OrigTy->isPointerTy())
1786 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001787 return RValue::get(Call);
1788}
Chris Lattner40ff7012007-08-03 16:18:34 +00001789
Chris Lattner9369a562007-06-29 16:31:29 +00001790
Chris Lattner8394d792007-06-05 20:53:16 +00001791/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1792/// lvalue, where both are guaranteed to the have the same type, and that type
1793/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001794void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001795 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001796 if (!Dst.isSimple()) {
1797 if (Dst.isVectorElt()) {
1798 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001799 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1800 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001801 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001802 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001803 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1804 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001805 return;
1806 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001807
Nate Begemance4d7fc2008-04-18 23:10:10 +00001808 // If this is an update of extended vector elements, insert them as
1809 // appropriate.
1810 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001811 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001812
Renato Golin230c5eb2014-05-19 18:15:42 +00001813 if (Dst.isGlobalReg())
1814 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1815
John McCallc109a252011-11-07 03:59:57 +00001816 assert(Dst.isBitField() && "Unknown LValue type");
1817 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001818 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001819
John McCall31168b02011-06-15 23:02:42 +00001820 // There's special magic for assigning into an ARC-qualified l-value.
1821 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1822 switch (Lifetime) {
1823 case Qualifiers::OCL_None:
1824 llvm_unreachable("present but none");
1825
1826 case Qualifiers::OCL_ExplicitNone:
1827 // nothing special
1828 break;
1829
1830 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001831 if (isInit) {
1832 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1833 break;
1834 }
John McCall55e1fbc2011-06-25 02:11:03 +00001835 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001836 return;
1837
1838 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001839 if (isInit)
1840 // Initialize and then skip the primitive store.
1841 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1842 else
1843 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001844 return;
1845
1846 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001847 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1848 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001849 // fall into the normal path
1850 break;
1851 }
1852 }
1853
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001854 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001855 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001856 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001857 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001858 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001859 return;
1860 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001861
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001862 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001863 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001864 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001865 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001866 if (Dst.isObjCIvar()) {
1867 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001868 llvm::Type *ResultType = IntPtrTy;
1869 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1870 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001871 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001872 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001873 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1874 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001875 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001876 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001877 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001878 } else if (Dst.isGlobalObjCRef()) {
1879 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1880 Dst.isThreadLocalRef());
1881 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001882 else
1883 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001884 return;
1885 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001886
Chris Lattner6278e6a2007-08-11 00:04:45 +00001887 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001888 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001889}
1890
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001891void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001892 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001893 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001894 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001895 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001896
Daniel Dunbar67aba792010-04-15 03:47:33 +00001897 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001898 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001899
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001900 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001901 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001902 /*IsSigned=*/false);
1903 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001904
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001905 // See if there are other bits in the bitfield's storage we'll need to load
1906 // and mask together with source before storing.
1907 if (Info.StorageSize != Info.Size) {
1908 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001909 llvm::Value *Val =
1910 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001911
1912 // Mask the source value as needed.
1913 if (!hasBooleanRepresentation(Dst.getType()))
1914 SrcVal = Builder.CreateAnd(SrcVal,
1915 llvm::APInt::getLowBitsSet(Info.StorageSize,
1916 Info.Size),
1917 "bf.value");
1918 MaskedVal = SrcVal;
1919 if (Info.Offset)
1920 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1921
1922 // Mask out the original value.
1923 Val = Builder.CreateAnd(Val,
1924 ~llvm::APInt::getBitsSet(Info.StorageSize,
1925 Info.Offset,
1926 Info.Offset + Info.Size),
1927 "bf.clear");
1928
1929 // Or together the unchanged values and the source value.
1930 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1931 } else {
1932 assert(Info.Offset == 0);
1933 }
1934
1935 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001936 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001937
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001938 // Return the new value of the bit-field, if requested.
1939 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001940 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001941
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001942 // Sign extend the value if needed.
1943 if (Info.IsSigned) {
1944 assert(Info.Size <= Info.StorageSize);
1945 unsigned HighBits = Info.StorageSize - Info.Size;
1946 if (HighBits) {
1947 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1948 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1949 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001950 }
1951
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001952 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1953 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001954 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001955 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001956}
1957
Nate Begemance4d7fc2008-04-18 23:10:10 +00001958void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001959 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001960 // This access turns into a read/modify/write of the vector. Load the input
1961 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001962 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1963 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001964 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001965
Chris Lattner4647a212007-08-31 22:49:20 +00001966 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001967
John McCall55e1fbc2011-06-25 02:11:03 +00001968 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001969 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001970 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001971 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001972 // Use shuffle vector is the src and destination are the same number of
1973 // elements and restore the vector mask since it is on the side it will be
1974 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001975 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001976 for (unsigned i = 0; i != NumSrcElts; ++i)
1977 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001978
Chris Lattner91c08ad2011-02-15 00:14:06 +00001979 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001980 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001981 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001982 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001983 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001984 // Extended the source vector to the same length and then shuffle it
1985 // into the destination.
1986 // FIXME: since we're shuffling with undef, can we just use the indices
1987 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001988 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001989 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001990 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001991 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001992 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001993 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001994 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001995 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001996 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001997 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001998 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001999 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002000 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002001
Joey Goulycf4143b2013-11-21 17:09:05 +00002002 // When the vector size is odd and .odd or .hi is used, the last element
2003 // of the Elts constant array will be one past the size of the vector.
2004 // Ignore the last element here, if it is greater than the mask size.
2005 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2006 NumSrcElts--;
2007
Nate Begemanb699c9b2009-01-18 06:42:49 +00002008 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002009 for (unsigned i = 0; i != NumSrcElts; ++i)
2010 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00002011 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002012 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00002013 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00002014 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00002015 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00002016 }
2017 } else {
2018 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00002019 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00002020 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002021 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00002022 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002023
John McCall7f416cc2015-09-08 08:05:57 +00002024 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2025 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00002026}
2027
Renato Golin230c5eb2014-05-19 18:15:42 +00002028/// @brief Store of global named registers are always calls to intrinsics.
2029void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00002030 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2031 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002032 llvm::MDNode *RegName = cast<llvm::MDNode>(
2033 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00002034 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00002035
2036 // We accept integer and pointer types only
2037 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2038 llvm::Type *Ty = OrigTy;
2039 if (OrigTy->isPointerTy())
2040 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2041 llvm::Type *Types[] = { Ty };
2042
Renato Golin230c5eb2014-05-19 18:15:42 +00002043 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2044 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00002045 if (OrigTy->isPointerTy())
2046 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00002047 Builder.CreateCall(
2048 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00002049}
2050
Eric Christopherc9e2a682014-05-20 17:10:39 +00002051// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002052// generating write-barries API. It is currently a global, ivar,
2053// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002054static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002055 LValue &LV,
2056 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002057 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002058 return;
Craig Topper99e79272013-07-26 05:59:26 +00002059
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002060 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002061 QualType ExpTy = E->getType();
2062 if (IsMemberAccess && ExpTy->isPointerType()) {
2063 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00002064 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002065 // writer-barrier conservatively.
2066 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2067 if (ExpTy->isRecordType()) {
2068 LV.setObjCIvar(false);
2069 return;
2070 }
2071 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002072 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002073 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002074 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002075 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002076 return;
2077 }
Craig Topper99e79272013-07-26 05:59:26 +00002078
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002079 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2080 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00002081 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002082 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00002083 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002084 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002085 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002086 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002087 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002088 }
Craig Topper99e79272013-07-26 05:59:26 +00002089
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002090 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002091 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002092 return;
2093 }
Craig Topper99e79272013-07-26 05:59:26 +00002094
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002095 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002096 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002097 if (LV.isObjCIvar()) {
2098 // If cast is to a structure pointer, follow gcc's behavior and make it
2099 // a non-ivar write-barrier.
2100 QualType ExpTy = E->getType();
2101 if (ExpTy->isPointerType())
2102 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2103 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002104 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002105 }
2106 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002107 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002108
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002109 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002110 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2111 return;
2112 }
2113
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002114 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002115 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002116 return;
2117 }
Craig Topper99e79272013-07-26 05:59:26 +00002118
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002119 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002120 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002121 return;
2122 }
John McCall31168b02011-06-15 23:02:42 +00002123
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002124 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002125 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002126 return;
2127 }
2128
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002129 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002130 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002131 if (LV.isObjCIvar() && !LV.isObjCArray())
2132 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002133 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002134 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002135 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002136 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002137 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002138 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002139 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002140 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002141
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002142 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002143 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002144 // We don't know if member is an 'ivar', but this flag is looked at
2145 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002146 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002147 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002148 }
2149}
2150
Chris Lattner3f32d692011-07-12 06:52:18 +00002151static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002152EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002153 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002154 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002155 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002156 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002157}
2158
Alexey Bataev97720002014-11-11 04:05:39 +00002159static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002160 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2161 llvm::Type *RealVarTy, SourceLocation Loc) {
2162 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2163 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002164 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
John McCall7f416cc2015-09-08 08:05:57 +00002165}
2166
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002167Address
2168CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2169 LValueBaseInfo *PointeeBaseInfo,
2170 TBAAAccessInfo *PointeeTBAAInfo) {
2171 llvm::LoadInst *Load = Builder.CreateLoad(RefLVal.getAddress(),
2172 RefLVal.isVolatile());
2173 TBAAAccessInfo RefTBAAInfo = RefLVal.getTBAAInfo();
2174 if (RefLVal.getBaseInfo().getMayAlias())
2175 RefTBAAInfo = CGM.getTBAAMayAliasAccessInfo();
2176 CGM.DecorateInstructionWithTBAA(Load, RefTBAAInfo);
2177
2178 CharUnits Align = getNaturalTypeAlignment(RefLVal.getType()->getPointeeType(),
2179 PointeeBaseInfo, PointeeTBAAInfo,
2180 /* forPointeeType= */ true);
2181 return Address(Load, Align);
John McCall7f416cc2015-09-08 08:05:57 +00002182}
2183
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002184LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2185 LValueBaseInfo PointeeBaseInfo;
2186 TBAAAccessInfo PointeeTBAAInfo;
2187 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2188 &PointeeTBAAInfo);
2189 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2190 PointeeBaseInfo, PointeeTBAAInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002191}
2192
Alexey Bataev31300ed2016-02-04 11:27:03 +00002193Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2194 const PointerType *PtrTy,
Ivan A. Kosarev90295642017-10-13 16:47:22 +00002195 LValueBaseInfo *BaseInfo,
2196 TBAAAccessInfo *TBAAInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002197 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002198 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +00002199 BaseInfo, TBAAInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002200 /*forPointeeType=*/true));
2201}
2202
2203LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2204 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002205 LValueBaseInfo BaseInfo;
Ivan A. Kosarev90295642017-10-13 16:47:22 +00002206 TBAAAccessInfo TBAAInfo;
2207 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2208 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002209}
2210
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002211static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2212 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002213 QualType T = E->getType();
2214
2215 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002216 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2217 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002218 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2219
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002220 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002221 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2222 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002223 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002224 Address Addr(V, Alignment);
Alexey Bataev97720002014-11-11 04:05:39 +00002225 // Emit reference to the private copy of the variable if it is an OpenMP
2226 // threadprivate variable.
2227 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002228 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002229 E->getExprLoc());
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002230 LValue LV = VD->getType()->isReferenceType() ?
2231 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2232 AlignmentSource::Decl) :
2233 CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002234 setObjCGCLValueClass(CGF.getContext(), E, LV);
2235 return LV;
2236}
2237
John McCallb92ab1a2016-10-26 23:46:34 +00002238static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2239 const FunctionDecl *FD) {
2240 if (FD->hasAttr<WeakRefAttr>()) {
2241 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2242 return aliasee.getPointer();
2243 }
2244
2245 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002246 if (!FD->hasPrototype()) {
2247 if (const FunctionProtoType *Proto =
2248 FD->getType()->getAs<FunctionProtoType>()) {
2249 // Ugly case: for a K&R-style definition, the type of the definition
2250 // isn't the same as the type of a use. Correct for this with a
2251 // bitcast.
2252 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002253 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2254 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2255 V = llvm::ConstantExpr::getBitCast(V,
2256 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002257 }
2258 }
John McCallb92ab1a2016-10-26 23:46:34 +00002259 return V;
2260}
2261
2262static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2263 const Expr *E, const FunctionDecl *FD) {
2264 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002265 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002266 return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2267 AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002268}
2269
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002270static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2271 llvm::Value *ThisValue) {
2272 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2273 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2274 return CGF.EmitLValueForField(LV, FD);
2275}
2276
Renato Golin230c5eb2014-05-19 18:15:42 +00002277/// Named Registers are named metadata pointing to the register name
2278/// which will be read from/written to as an argument to the intrinsic
2279/// @llvm.read/write_register.
2280/// So far, only the name is being passed down, but other options such as
2281/// register type, allocation type or even optimization options could be
2282/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002283static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002284 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002285 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002286 assert(Asm->getLabel().size() < 64-Name.size() &&
2287 "Register name too big");
2288 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002289 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002290 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002291 if (M->getNumOperands() == 0) {
2292 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2293 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002294 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002295 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2296 }
John McCall7f416cc2015-09-08 08:05:57 +00002297
2298 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2299
2300 llvm::Value *Ptr =
2301 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2302 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002303}
2304
Chris Lattnerd7f58862007-06-02 05:24:33 +00002305LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002306 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002307 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002308
Renato Goline7b3d5d2014-05-27 16:46:27 +00002309 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2310 // Global Named registers access via intrinsics only
2311 if (VD->getStorageClass() == SC_Register &&
2312 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002313 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002314
Renato Goline7b3d5d2014-05-27 16:46:27 +00002315 // A DeclRefExpr for a reference initialized by a constant expression can
2316 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002317 const Expr *Init = VD->getAnyInitializer(VD);
2318 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2319 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002320 VD->checkInitIsICE() &&
2321 // Do not emit if it is private OpenMP variable.
Alexey Bataevcab496d2017-10-06 16:17:25 +00002322 !(E->refersToEnclosingVariableOrCapture() &&
2323 ((CapturedStmtInfo &&
2324 (LocalDeclMap.count(VD->getCanonicalDecl()) ||
2325 CapturedStmtInfo->lookup(VD->getCanonicalDecl()))) ||
2326 LambdaCaptureFields.lookup(VD->getCanonicalDecl()) ||
2327 isa<BlockDecl>(CurCodeDecl)))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002328 llvm::Constant *Val =
John McCallde0fe072017-08-15 21:42:52 +00002329 ConstantEmitter(*this).emitAbstract(E->getLocation(),
2330 *VD->evaluateValue(),
2331 VD->getType());
Richard Smith5a1104b2012-10-20 01:38:33 +00002332 assert(Val && "failed to emit reference constant expression");
2333 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002334
2335 // Should we be using the alignment of the constant pointer we emitted?
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +00002336 CharUnits Alignment = getNaturalTypeAlignment(E->getType(),
2337 /* BaseInfo= */ nullptr,
2338 /* TBAAInfo= */ nullptr,
2339 /* forPointeeType= */ true);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002340 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002341 }
David Majnemer602cfe72015-01-01 09:49:44 +00002342
2343 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002344 if (E->refersToEnclosingVariableOrCapture()) {
Alexey Bataev6a71f362017-08-22 17:54:52 +00002345 VD = VD->getCanonicalDecl();
David Majnemer602cfe72015-01-01 09:49:44 +00002346 if (auto *FD = LambdaCaptureFields.lookup(VD))
2347 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2348 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002349 auto I = LocalDeclMap.find(VD);
2350 if (I != LocalDeclMap.end()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002351 if (VD->getType()->isReferenceType())
2352 return EmitLoadOfReferenceLValue(I->second, VD->getType(),
2353 AlignmentSource::Decl);
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002354 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002355 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002356 LValue CapLVal =
2357 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2358 CapturedStmtInfo->getContextValue());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002359 bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002360 return MakeAddrLValue(
2361 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00002362 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias),
2363 CGM.getTBAAAccessInfo(CapLVal.getType()));
David Majnemer602cfe72015-01-01 09:49:44 +00002364 }
John McCall7f416cc2015-09-08 08:05:57 +00002365
David Majnemer602cfe72015-01-01 09:49:44 +00002366 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002367 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002368 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002369 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002370 }
2371
Eli Friedman5720e342012-01-21 04:52:58 +00002372 // FIXME: We should be able to assert this for FunctionDecls as well!
2373 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2374 // those with a valid source location.
2375 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2376 !E->getLocation().isValid()) &&
2377 "Should not use decl without marking it used!");
2378
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002379 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002380 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002381 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002382 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002383 }
2384
Renato Goline7b3d5d2014-05-27 16:46:27 +00002385 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002386 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002387 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002388 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002389
John McCall7f416cc2015-09-08 08:05:57 +00002390 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002391
John McCall7f416cc2015-09-08 08:05:57 +00002392 // The variable should generally be present in the local decl map.
2393 auto iter = LocalDeclMap.find(VD);
2394 if (iter != LocalDeclMap.end()) {
2395 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002396
John McCall7f416cc2015-09-08 08:05:57 +00002397 // Otherwise, it might be static local we haven't emitted yet for
2398 // some reason; most likely, because it's in an outer function.
2399 } else if (VD->isStaticLocal()) {
2400 addr = Address(CGM.getOrCreateStaticVarDecl(
2401 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2402 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002403
John McCall7f416cc2015-09-08 08:05:57 +00002404 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002405 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002406 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2407 }
2408
2409
2410 // Check for OpenMP threadprivate variables.
2411 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2412 return EmitThreadPrivateVarDeclLValue(
2413 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2414 E->getExprLoc());
2415 }
2416
2417 // Drill into block byref variables.
2418 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2419 if (isBlockByref) {
2420 addr = emitBlockByrefAddress(addr, VD);
2421 }
2422
2423 // Drill into reference types.
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002424 LValue LV = VD->getType()->isReferenceType() ?
2425 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2426 MakeAddrLValue(addr, T, AlignmentSource::Decl);
Chris Lattner3f32d692011-07-12 06:52:18 +00002427
John McCallcdda29c2013-03-13 03:10:54 +00002428 bool isLocalStorage = VD->hasLocalStorage();
2429
2430 bool NonGCable = isLocalStorage &&
2431 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002432 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002433 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002434 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002435 LV.setNonGC(true);
2436 }
John McCallcdda29c2013-03-13 03:10:54 +00002437
2438 bool isImpreciseLifetime =
2439 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2440 if (isImpreciseLifetime)
2441 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002442 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002443 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002444 }
John McCallf3a88602011-02-03 08:15:49 +00002445
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002446 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002447 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002448
Richard Smithda383632016-08-15 01:33:41 +00002449 // FIXME: While we're emitting a binding from an enclosing scope, all other
2450 // DeclRefExprs we see should be implicitly treated as if they also refer to
2451 // an enclosing scope.
2452 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2453 return EmitLValue(BD->getBinding());
2454
David Blaikie83d382b2011-09-23 05:06:16 +00002455 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002456}
Chris Lattnere47e4402007-06-01 18:02:12 +00002457
Chris Lattner8394d792007-06-05 20:53:16 +00002458LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2459 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002460 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002461 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002462
Chris Lattner0f398c42008-07-26 22:37:01 +00002463 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002464 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002465 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002466 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002467 QualType T = E->getSubExpr()->getType()->getPointeeType();
2468 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002469
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002470 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00002471 TBAAAccessInfo TBAAInfo;
2472 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2473 &TBAAInfo);
2474 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002475 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002476
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002477 // We should not generate __weak write barrier on indirect reference
2478 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2479 // But, we continue to generate __strong write barrier on indirect write
2480 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002481 if (getLangOpts().ObjC1 &&
2482 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002483 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002484 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002485 return LV;
2486 }
John McCalle3027922010-08-25 11:45:40 +00002487 case UO_Real:
2488 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002489 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002490 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002491
Richard Smith0b6b8e42012-02-18 20:53:32 +00002492 // __real is valid on scalars. This is a faster way of testing that.
2493 // __imag can only produce an rvalue on scalars.
2494 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002495 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002496 assert(E->getSubExpr()->getType()->isArithmeticType());
2497 return LV;
2498 }
2499
Alexey Bataev611b0a12016-11-07 18:15:02 +00002500 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002501
John McCall7f416cc2015-09-08 08:05:57 +00002502 Address Component =
2503 (E->getOpcode() == UO_Real
2504 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2505 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00002506 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
2507 CGM.getTBAAAccessInfo(T));
Alexey Bataev611b0a12016-11-07 18:15:02 +00002508 ElemLV.getQuals().addQualifiers(LV.getQuals());
2509 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002510 }
John McCalle3027922010-08-25 11:45:40 +00002511 case UO_PreInc:
2512 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002513 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002514 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002515
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002516 if (E->getType()->isAnyComplexType())
2517 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2518 else
2519 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2520 return LV;
2521 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002522 }
Chris Lattner8394d792007-06-05 20:53:16 +00002523}
2524
Chris Lattner4347e3692007-06-06 04:54:52 +00002525LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002526 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002527 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002528}
2529
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002530LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002531 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002532 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002533}
2534
Mike Stump4a3999f2009-09-09 13:00:44 +00002535LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002536 auto SL = E->getFunctionName();
2537 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2538 StringRef FnName = CurFn->getName();
2539 if (FnName.startswith("\01"))
2540 FnName = FnName.substr(1);
2541 StringRef NameItems[] = {
2542 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2543 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002544 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2545 std::string Name = SL->getString();
2546 if (!Name.empty()) {
2547 unsigned Discriminator =
2548 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2549 if (Discriminator)
2550 Name += "_" + Twine(Discriminator + 1).str();
2551 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002552 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002553 } else {
2554 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002555 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002556 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002557 }
Alexey Bataevec474782014-10-09 08:45:04 +00002558 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002559 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002560}
2561
Richard Smithe30752c2012-10-09 19:52:38 +00002562/// Emit a type description suitable for use by a runtime sanitizer library. The
2563/// format of a type descriptor is
2564///
2565/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002566/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002567/// \endcode
2568///
Richard Smith683398a2012-10-09 23:55:19 +00002569/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2570/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002571llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002572 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002573 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002574 return C;
2575
Richard Smithe30752c2012-10-09 19:52:38 +00002576 uint16_t TypeKind = -1;
2577 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002578
Richard Smithe30752c2012-10-09 19:52:38 +00002579 if (T->isIntegerType()) {
2580 TypeKind = 0;
2581 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002582 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002583 } else if (T->isFloatingType()) {
2584 TypeKind = 1;
2585 TypeInfo = getContext().getTypeSize(T);
2586 }
2587
2588 // Format the type name as if for a diagnostic, including quotes and
2589 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002590 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002591 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2592 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002593 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002594 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002595
2596 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002597 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2598 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002599 };
2600 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2601
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002602 auto *GV = new llvm::GlobalVariable(
2603 CGM.getModule(), Descriptor->getType(),
2604 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002605 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002606 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002607
2608 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002609 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002610
Richard Smithe30752c2012-10-09 19:52:38 +00002611 return GV;
2612}
2613
2614llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2615 llvm::Type *TargetTy = IntPtrTy;
2616
Vedant Kumar8a715332017-10-03 01:27:24 +00002617 if (V->getType() == TargetTy)
2618 return V;
2619
Richard Smith48366f72013-03-22 00:47:07 +00002620 // Floating-point types which fit into intptr_t are bitcast to integers
2621 // and then passed directly (after zero-extension, if necessary).
2622 if (V->getType()->isFloatingPointTy()) {
2623 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2624 if (Bits <= TargetTy->getIntegerBitWidth())
2625 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2626 Bits));
2627 }
2628
Richard Smithe30752c2012-10-09 19:52:38 +00002629 // Integers which fit in intptr_t are zero-extended and passed directly.
2630 if (V->getType()->isIntegerTy() &&
2631 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2632 return Builder.CreateZExt(V, TargetTy);
2633
2634 // Pointers are passed directly, everything else is passed by address.
2635 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002636 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002637 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002638 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002639 }
2640 return Builder.CreatePtrToInt(V, TargetTy);
2641}
2642
2643/// \brief Emit a representation of a SourceLocation for passing to a handler
2644/// in a sanitizer runtime library. The format for this data is:
2645/// \code
2646/// struct SourceLocation {
2647/// const char *Filename;
2648/// int32_t Line, Column;
2649/// };
2650/// \endcode
2651/// For an invalid SourceLocation, the Filename pointer is null.
2652llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002653 llvm::Constant *Filename;
2654 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002655
Alexey Samsonov6c124142014-07-18 17:50:06 +00002656 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2657 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002658 StringRef FilenameString = PLoc.getFilename();
2659
2660 int PathComponentsToStrip =
2661 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2662 if (PathComponentsToStrip < 0) {
2663 assert(PathComponentsToStrip != INT_MIN);
2664 int PathComponentsToKeep = -PathComponentsToStrip;
2665 auto I = llvm::sys::path::rbegin(FilenameString);
2666 auto E = llvm::sys::path::rend(FilenameString);
2667 while (I != E && --PathComponentsToKeep)
2668 ++I;
2669
2670 FilenameString = FilenameString.substr(I - E);
2671 } else if (PathComponentsToStrip > 0) {
2672 auto I = llvm::sys::path::begin(FilenameString);
2673 auto E = llvm::sys::path::end(FilenameString);
2674 while (I != E && PathComponentsToStrip--)
2675 ++I;
2676
2677 if (I != E)
2678 FilenameString =
2679 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2680 else
2681 FilenameString = llvm::sys::path::filename(FilenameString);
2682 }
2683
2684 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002685 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2686 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2687 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002688 Line = PLoc.getLine();
2689 Column = PLoc.getColumn();
2690 } else {
2691 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2692 Line = Column = 0;
2693 }
2694
2695 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2696 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002697
2698 return llvm::ConstantStruct::getAnon(Data);
2699}
2700
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002701namespace {
2702/// \brief Specify under what conditions this check can be recovered
2703enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002704 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002705 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002706 /// Check supports recovering, runtime has both fatal (noreturn) and
2707 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002708 Recoverable,
2709 /// Runtime conditionally aborts, always need to support recovery.
2710 AlwaysRecoverable
2711};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002712}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002713
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002714static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2715 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002716 switch (Kind) {
2717 case SanitizerKind::Vptr:
2718 return CheckRecoverableKind::AlwaysRecoverable;
2719 case SanitizerKind::Return:
2720 case SanitizerKind::Unreachable:
2721 return CheckRecoverableKind::Unrecoverable;
2722 default:
2723 return CheckRecoverableKind::Recoverable;
2724 }
2725}
2726
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002727namespace {
2728struct SanitizerHandlerInfo {
2729 char const *const Name;
2730 unsigned Version;
2731};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002732}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002733
2734const SanitizerHandlerInfo SanitizerHandlers[] = {
2735#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2736 LIST_SANITIZER_CHECKS
2737#undef SANITIZER_CHECK
2738};
2739
Alexey Samsonov88459522015-01-12 22:39:12 +00002740static void emitCheckHandlerCall(CodeGenFunction &CGF,
2741 llvm::FunctionType *FnType,
2742 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002743 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002744 CheckRecoverableKind RecoverKind, bool IsFatal,
2745 llvm::BasicBlock *ContBB) {
2746 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2747 bool NeedsAbortSuffix =
2748 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002749 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002750 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2751 const StringRef CheckName = CheckInfo.Name;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002752 std::string FnName = "__ubsan_handle_" + CheckName.str();
2753 if (CheckInfo.Version && !MinimalRuntime)
2754 FnName += "_v" + llvm::utostr(CheckInfo.Version);
2755 if (MinimalRuntime)
2756 FnName += "_minimal";
2757 if (NeedsAbortSuffix)
2758 FnName += "_abort";
Alexey Samsonov88459522015-01-12 22:39:12 +00002759 bool MayReturn =
2760 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2761
2762 llvm::AttrBuilder B;
2763 if (!MayReturn) {
2764 B.addAttribute(llvm::Attribute::NoReturn)
2765 .addAttribute(llvm::Attribute::NoUnwind);
2766 }
2767 B.addAttribute(llvm::Attribute::UWTable);
2768
2769 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2770 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002771 llvm::AttributeList::get(CGF.getLLVMContext(),
2772 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002773 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002774 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2775 if (!MayReturn) {
2776 HandlerCall->setDoesNotReturn();
2777 CGF.Builder.CreateUnreachable();
2778 } else {
2779 CGF.Builder.CreateBr(ContBB);
2780 }
2781}
2782
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002783void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002784 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002785 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002786 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002787 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002788 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002789 assert(CheckHandler >= 0 &&
2790 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2791 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002792
2793 llvm::Value *FatalCond = nullptr;
2794 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002795 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002796 for (int i = 0, n = Checked.size(); i < n; ++i) {
2797 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002798 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002799 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002800 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2801 ? TrapCond
2802 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2803 ? RecoverableCond
2804 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002805 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2806 }
2807
Peter Collingbourne9881b782015-06-18 23:59:22 +00002808 if (TrapCond)
2809 EmitTrapCheck(TrapCond);
2810 if (!FatalCond && !RecoverableCond)
2811 return;
2812
Alexey Samsonov88459522015-01-12 22:39:12 +00002813 llvm::Value *JointCond;
2814 if (FatalCond && RecoverableCond)
2815 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2816 else
2817 JointCond = FatalCond ? FatalCond : RecoverableCond;
2818 assert(JointCond);
2819
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002820 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002821 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002822#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002823 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002824 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002825 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002826 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002827 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002828#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002829
Richard Smith4d1458e2012-09-08 02:08:36 +00002830 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002831 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2832 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002833 // Give hint that we very much don't expect to execute the handler
2834 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2835 llvm::MDBuilder MDHelper(getLLVMContext());
2836 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2837 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002838 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002839
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002840 // Handler functions take an i8* pointing to the (handler-specific) static
2841 // information block, followed by a sequence of intptr_t arguments
2842 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002843 SmallVector<llvm::Value *, 4> Args;
2844 SmallVector<llvm::Type *, 4> ArgTypes;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002845 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
2846 Args.reserve(DynamicArgs.size() + 1);
2847 ArgTypes.reserve(DynamicArgs.size() + 1);
Richard Smithe30752c2012-10-09 19:52:38 +00002848
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002849 // Emit handler arguments and create handler function type.
2850 if (!StaticArgs.empty()) {
2851 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2852 auto *InfoPtr =
2853 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2854 llvm::GlobalVariable::PrivateLinkage, Info);
2855 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2856 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2857 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2858 ArgTypes.push_back(Int8PtrTy);
2859 }
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002860
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002861 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2862 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2863 ArgTypes.push_back(IntPtrTy);
2864 }
Richard Smithe30752c2012-10-09 19:52:38 +00002865 }
2866
2867 llvm::FunctionType *FnType =
2868 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002869
Alexey Samsonov88459522015-01-12 22:39:12 +00002870 if (!FatalCond || !RecoverableCond) {
2871 // Simple case: we need to generate a single handler call, either
2872 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002873 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002874 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002875 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002876 // Emit two handler calls: first one for set of unrecoverable checks,
2877 // another one for recoverable.
2878 llvm::BasicBlock *NonFatalHandlerBB =
2879 createBasicBlock("non_fatal." + CheckName);
2880 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2881 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2882 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002883 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002884 NonFatalHandlerBB);
2885 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002886 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002887 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002888 }
Richard Smithe30752c2012-10-09 19:52:38 +00002889
Richard Smith4d1458e2012-09-08 02:08:36 +00002890 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002891}
2892
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002893void CodeGenFunction::EmitCfiSlowPathCheck(
2894 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2895 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002896 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2897
2898 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2899 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2900
2901 llvm::MDBuilder MDHelper(getLLVMContext());
2902 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2903 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2904
2905 EmitBlock(CheckBB);
2906
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002907 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2908
2909 llvm::CallInst *CheckCall;
2910 if (WithDiag) {
2911 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2912 auto *InfoPtr =
2913 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2914 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002915 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002916 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2917
2918 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2919 "__cfi_slowpath_diag",
2920 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2921 false));
2922 CheckCall = Builder.CreateCall(
2923 SlowPathDiagFn,
2924 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2925 } else {
2926 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2927 "__cfi_slowpath",
2928 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2929 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2930 }
2931
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002932 CheckCall->setDoesNotThrow();
2933
2934 EmitBlock(Cont);
2935}
2936
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00002937// Emit a stub for __cfi_check function so that the linker knows about this
2938// symbol in LTO mode.
2939void CodeGenFunction::EmitCfiCheckStub() {
2940 llvm::Module *M = &CGM.getModule();
2941 auto &Ctx = M->getContext();
2942 llvm::Function *F = llvm::Function::Create(
2943 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2944 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2945 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2946 // FIXME: consider emitting an intrinsic call like
2947 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2948 // which can be lowered in CrossDSOCFI pass to the actual contents of
2949 // __cfi_check. This would allow inlining of __cfi_check calls.
2950 llvm::CallInst::Create(
2951 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2952 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2953}
2954
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002955// This function is basically a switch over the CFI failure kind, which is
2956// extracted from CFICheckFailData (1st function argument). Each case is either
2957// llvm.trap or a call to one of the two runtime handlers, based on
2958// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2959// failure kind) traps, but this should really never happen. CFICheckFailData
2960// can be nullptr if the calling module has -fsanitize-trap behavior for this
2961// check kind; in this case __cfi_check_fail traps as well.
2962void CodeGenFunction::EmitCfiCheckFail() {
2963 SanitizerScope SanScope(this);
2964 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002965 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2966 ImplicitParamDecl::Other);
2967 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2968 ImplicitParamDecl::Other);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002969 Args.push_back(&ArgData);
2970 Args.push_back(&ArgAddr);
2971
John McCallc56a8b32016-03-11 04:30:31 +00002972 const CGFunctionInfo &FI =
2973 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002974
2975 llvm::Function *F = llvm::Function::Create(
2976 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2977 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2978 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2979
2980 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2981 SourceLocation());
2982
2983 llvm::Value *Data =
2984 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2985 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2986 llvm::Value *Addr =
2987 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2988 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2989
2990 // Data == nullptr means the calling module has trap behaviour for this check.
2991 llvm::Value *DataIsNotNullPtr =
2992 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2993 EmitTrapCheck(DataIsNotNullPtr);
2994
2995 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002996 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002997 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002998 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002999
3000 llvm::Value *V = Builder.CreateConstGEP2_32(
3001 CfiCheckFailDataTy,
3002 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3003 0);
3004 Address CheckKindAddr(V, getIntAlign());
3005 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3006
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003007 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3008 CGM.getLLVMContext(),
3009 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3010 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00003011 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003012 {Addr, AllVtables}),
3013 IntPtrTy);
3014
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00003015 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003016 {CFITCK_VCall, SanitizerKind::CFIVCall},
3017 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3018 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3019 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3020 {CFITCK_ICall, SanitizerKind::CFIICall}};
3021
3022 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3023 for (auto CheckKindMaskPair : CheckKinds) {
3024 int Kind = CheckKindMaskPair.first;
3025 SanitizerMask Mask = CheckKindMaskPair.second;
3026 llvm::Value *Cond =
3027 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003028 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003029 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003030 {Data, Addr, ValidVtable});
3031 else
3032 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003033 }
3034
3035 FinishFunction();
3036 // The only reference to this function will be created during LTO link.
3037 // Make sure it survives until then.
3038 CGM.addUsedGlobal(F);
3039}
3040
Chad Rosierae229d52013-01-29 23:31:22 +00003041void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00003042 llvm::BasicBlock *Cont = createBasicBlock("cont");
3043
3044 // If we're optimizing, collapse all calls to trap down to just one per
3045 // function to save on code size.
3046 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3047 TrapBB = createBasicBlock("trap");
3048 Builder.CreateCondBr(Checked, Cont, TrapBB);
3049 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003050 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00003051 TrapCall->setDoesNotReturn();
3052 TrapCall->setDoesNotThrow();
3053 Builder.CreateUnreachable();
3054 } else {
3055 Builder.CreateCondBr(Checked, Cont, TrapBB);
3056 }
3057
3058 EmitBlock(Cont);
3059}
3060
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003061llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00003062 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003063
Amaury Sechet21f51b32016-09-09 04:42:49 +00003064 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3065 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3066 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00003067 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00003068 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003069
3070 return TrapCall;
3071}
3072
John McCall7f416cc2015-09-08 08:05:57 +00003073Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003074 LValueBaseInfo *BaseInfo,
3075 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00003076 assert(E->getType()->isArrayType() &&
3077 "Array to pointer decay must have array source type!");
3078
3079 // Expressions of array type can't be bitfields or vector elements.
3080 LValue LV = EmitLValue(E);
3081 Address Addr = LV.getAddress();
John McCall7f416cc2015-09-08 08:05:57 +00003082
3083 // If the array type was an incomplete type, we need to make sure
3084 // the decay ends up being the right type.
3085 llvm::Type *NewTy = ConvertType(E->getType());
3086 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3087
3088 // Note that VLA pointers are always decayed, so we don't need to do
3089 // anything here.
3090 if (!E->getType()->isVariableArrayType()) {
3091 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3092 "Expected pointer to array");
3093 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3094 }
3095
Ivan A. Kosarevf761d0e2017-10-20 12:35:17 +00003096 // The result of this decay conversion points to an array element within the
3097 // base lvalue. However, since TBAA currently does not support representing
3098 // accesses to elements of member arrays, we conservatively represent accesses
3099 // to the pointee object as if it had no any base lvalue specified.
3100 // TODO: Support TBAA for member arrays.
John McCall7f416cc2015-09-08 08:05:57 +00003101 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
Ivan A. Kosarevf761d0e2017-10-20 12:35:17 +00003102 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3103 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3104
John McCall7f416cc2015-09-08 08:05:57 +00003105 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3106}
3107
Chris Lattner6c5abe82010-06-26 23:03:20 +00003108/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3109/// array to pointer, return the array subexpression.
3110static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3111 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003112 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00003113 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00003114 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003115
Chris Lattner6c5abe82010-06-26 23:03:20 +00003116 // If this is a decay from variable width array, bail out.
3117 const Expr *SubExpr = CE->getSubExpr();
3118 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00003119 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003120
Chris Lattner6c5abe82010-06-26 23:03:20 +00003121 return SubExpr;
3122}
3123
John McCall7f416cc2015-09-08 08:05:57 +00003124static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3125 llvm::Value *ptr,
3126 ArrayRef<llvm::Value*> indices,
3127 bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003128 bool signedIndices,
Vedant Kumara125eb52017-06-01 19:22:18 +00003129 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003130 const llvm::Twine &name = "arrayidx") {
3131 if (inbounds) {
Vedant Kumar175b6d12017-07-13 20:55:26 +00003132 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3133 CodeGenFunction::NotSubtraction, loc,
3134 name);
John McCall7f416cc2015-09-08 08:05:57 +00003135 } else {
3136 return CGF.Builder.CreateGEP(ptr, indices, name);
3137 }
3138}
3139
3140static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3141 llvm::Value *idx,
3142 CharUnits eltSize) {
3143 // If we have a constant index, we can use the exact offset of the
3144 // element we're accessing.
3145 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3146 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3147 return arrayAlign.alignmentAtOffset(offset);
3148
3149 // Otherwise, use the worst-case alignment for any element.
3150 } else {
3151 return arrayAlign.alignmentOfArrayElement(eltSize);
3152 }
3153}
3154
3155static QualType getFixedSizeElementType(const ASTContext &ctx,
3156 const VariableArrayType *vla) {
3157 QualType eltType;
3158 do {
3159 eltType = vla->getElementType();
3160 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3161 return eltType;
3162}
3163
3164static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
Vedant Kumara125eb52017-06-01 19:22:18 +00003165 ArrayRef<llvm::Value *> indices,
John McCall7f416cc2015-09-08 08:05:57 +00003166 QualType eltType, bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003167 bool signedIndices, SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003168 const llvm::Twine &name = "arrayidx") {
3169 // All the indices except that last must be zero.
3170#ifndef NDEBUG
3171 for (auto idx : indices.drop_back())
3172 assert(isa<llvm::ConstantInt>(idx) &&
3173 cast<llvm::ConstantInt>(idx)->isZero());
3174#endif
3175
3176 // Determine the element size of the statically-sized base. This is
3177 // the thing that the indices are expressed in terms of.
3178 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3179 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3180 }
3181
3182 // We can use that to compute the best alignment of the element.
3183 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3184 CharUnits eltAlign =
3185 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3186
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003187 llvm::Value *eltPtr = emitArraySubscriptGEP(
3188 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
John McCall7f416cc2015-09-08 08:05:57 +00003189 return Address(eltPtr, eltAlign);
3190}
3191
Richard Smith539e4a72013-02-23 02:53:19 +00003192LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3193 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003194 // The index must always be an integer, which is not an aggregate. Emit it
3195 // in lexical order (this complexity is, sadly, required by C++17).
3196 llvm::Value *IdxPre =
3197 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003198 bool SignedIndices = false;
Richard Smith40885712016-09-27 00:53:24 +00003199 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003200 auto *Idx = IdxPre;
3201 if (E->getLHS() != E->getIdx()) {
3202 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3203 Idx = EmitScalarExpr(E->getIdx());
3204 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003205
Richard Smith9e67b992016-09-26 23:49:47 +00003206 QualType IdxTy = E->getIdx()->getType();
3207 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003208 SignedIndices |= IdxSigned;
Richard Smith9e67b992016-09-26 23:49:47 +00003209
3210 if (SanOpts.has(SanitizerKind::ArrayBounds))
3211 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3212
3213 // Extend or truncate the index type to 32 or 64-bits.
3214 if (Promote && Idx->getType() != IntPtrTy)
3215 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3216
3217 return Idx;
3218 };
3219 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003220
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003221 // If the base is a vector type, then we are forming a vector element lvalue
3222 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003223 if (E->getBase()->getType()->isVectorType() &&
3224 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003225 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003226 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003227 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003228 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003229 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
3230 LHS.getBaseInfo(), TBAAAccessInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003231 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003232
John McCall7f416cc2015-09-08 08:05:57 +00003233 // All the other cases basically behave like simple offsetting.
3234
John McCall7f416cc2015-09-08 08:05:57 +00003235 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003236 if (isa<ExtVectorElementExpr>(E->getBase())) {
3237 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003238 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003239 Address Addr = EmitExtVectorElementLValue(LV);
3240
3241 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
Vedant Kumara125eb52017-06-01 19:22:18 +00003242 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003243 SignedIndices, E->getExprLoc());
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00003244 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3245 CGM.getTBAAAccessInfo(EltType));
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003246 }
John McCall7f416cc2015-09-08 08:05:57 +00003247
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003248 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003249 TBAAAccessInfo TBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003250 Address Addr = Address::invalid();
3251 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003252 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003253 // The base must be a pointer, which is not an aggregate. Emit
3254 // it. It needs to be emitted first in case it's what captures
3255 // the VLA bounds.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003256 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003257 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003258
John McCall23c29fe2011-06-24 21:55:10 +00003259 // The element count here is the total number of non-VLA elements.
3260 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003261
John McCall77527a82011-06-25 01:32:37 +00003262 // Effectively, the multiply by the VLA size is part of the GEP.
3263 // GEP indexes are signed, and scaling an index isn't permitted to
3264 // signed-overflow, so we use the same semantics for our explicit
3265 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003266 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003267 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003268 } else {
3269 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003270 }
John McCall7f416cc2015-09-08 08:05:57 +00003271
3272 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003273 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003274 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003275
Chris Lattner6c5abe82010-06-26 23:03:20 +00003276 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3277 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003278
John McCall7f416cc2015-09-08 08:05:57 +00003279 // Emit the base pointer.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003280 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003281 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3282
3283 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3284 llvm::Value *InterfaceSizeVal =
3285 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3286
3287 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003288
3289 // We don't necessarily build correct LLVM struct types for ObjC
3290 // interfaces, so we can't rely on GEP to do this scaling
3291 // correctly, so we need to cast to i8*. FIXME: is this actually
3292 // true? A lot of other things in the fragile ABI would break...
3293 llvm::Type *OrigBaseTy = Addr.getType();
3294 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3295
3296 // Do the GEP.
3297 CharUnits EltAlign =
3298 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003299 llvm::Value *EltPtr =
3300 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3301 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003302 Addr = Address(EltPtr, EltAlign);
3303
3304 // Cast back.
3305 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003306 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3307 // If this is A[i] where A is an array, the frontend will have decayed the
3308 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3309 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3310 // "gep x, i" here. Emit one "gep A, 0, i".
3311 assert(Array->getType()->isArrayType() &&
3312 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003313 LValue ArrayLV;
3314 // For simple multidimensional array indexing, set the 'accessed' flag for
3315 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003316 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003317 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3318 else
3319 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003320 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003321
Daniel Dunbar82634272011-04-01 00:49:43 +00003322 // Propagate the alignment from the array itself to the result.
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003323 Addr = emitArraySubscriptGEP(
3324 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3325 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3326 E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003327 BaseInfo = ArrayLV.getBaseInfo();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003328 TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003329 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003330 // The base must be a pointer; emit it with an estimate of its alignment.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003331 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003332 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003333 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003334 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003335 SignedIndices, E->getExprLoc());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003336 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003337
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003338 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo, TBAAInfo);
John McCall8ccfcb52009-09-24 19:53:00 +00003339
Richard Smith9c6890a2012-11-01 22:30:59 +00003340 if (getLangOpts().ObjC1 &&
3341 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003342 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003343 setObjCGCLValueClass(getContext(), E, LV);
3344 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003345 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003346}
3347
Alexey Bataev31300ed2016-02-04 11:27:03 +00003348static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003349 LValueBaseInfo &BaseInfo,
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003350 TBAAAccessInfo &TBAAInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003351 QualType BaseTy, QualType ElTy,
3352 bool IsLowerBound) {
3353 LValue BaseLVal;
3354 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3355 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3356 if (BaseTy->isArrayType()) {
3357 Address Addr = BaseLVal.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003358 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003359
3360 // If the array type was an incomplete type, we need to make sure
3361 // the decay ends up being the right type.
3362 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3363 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3364
3365 // Note that VLA pointers are always decayed, so we don't need to do
3366 // anything here.
3367 if (!BaseTy->isVariableArrayType()) {
3368 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3369 "Expected pointer to array");
3370 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3371 "arraydecay");
3372 }
3373
3374 return CGF.Builder.CreateElementBitCast(Addr,
3375 CGF.ConvertTypeForMem(ElTy));
3376 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003377 LValueBaseInfo TypeInfo;
3378 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3379 BaseInfo.mergeForCast(TypeInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003380 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3381 }
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003382 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003383}
3384
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003385LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3386 bool IsLowerBound) {
Alexey Bataev7b0f1f02017-10-12 15:18:41 +00003387 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003388 QualType ResultExprTy;
3389 if (auto *AT = getContext().getAsArrayType(BaseTy))
3390 ResultExprTy = AT->getElementType();
3391 else
3392 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003393 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003394 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003395 // Requesting lower bound or upper bound, but without provided length and
3396 // without ':' symbol for the default length -> length = 1.
3397 // Idx = LowerBound ?: 0;
3398 if (auto *LowerBound = E->getLowerBound()) {
3399 Idx = Builder.CreateIntCast(
3400 EmitScalarExpr(LowerBound), IntPtrTy,
3401 LowerBound->getType()->hasSignedIntegerRepresentation());
3402 } else
3403 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3404 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003405 // Try to emit length or lower bound as constant. If this is possible, 1
3406 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3407 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003408 auto &C = CGM.getContext();
3409 auto *Length = E->getLength();
3410 llvm::APSInt ConstLength;
3411 if (Length) {
3412 // Idx = LowerBound + Length - 1;
3413 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3414 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3415 Length = nullptr;
3416 }
3417 auto *LowerBound = E->getLowerBound();
3418 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3419 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3420 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3421 LowerBound = nullptr;
3422 }
3423 if (!Length)
3424 --ConstLength;
3425 else if (!LowerBound)
3426 --ConstLowerBound;
3427
3428 if (Length || LowerBound) {
3429 auto *LowerBoundVal =
3430 LowerBound
3431 ? Builder.CreateIntCast(
3432 EmitScalarExpr(LowerBound), IntPtrTy,
3433 LowerBound->getType()->hasSignedIntegerRepresentation())
3434 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3435 auto *LengthVal =
3436 Length
3437 ? Builder.CreateIntCast(
3438 EmitScalarExpr(Length), IntPtrTy,
3439 Length->getType()->hasSignedIntegerRepresentation())
3440 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3441 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3442 /*HasNUW=*/false,
3443 !getLangOpts().isSignedOverflowDefined());
3444 if (Length && LowerBound) {
3445 Idx = Builder.CreateSub(
3446 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3447 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3448 }
3449 } else
3450 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3451 } else {
3452 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003453 QualType ArrayTy = BaseTy->isPointerType()
3454 ? E->getBase()->IgnoreParenImpCasts()->getType()
3455 : BaseTy;
3456 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003457 Length = VAT->getSizeExpr();
3458 if (Length->isIntegerConstantExpr(ConstLength, C))
3459 Length = nullptr;
3460 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003461 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003462 ConstLength = CAT->getSize();
3463 }
3464 if (Length) {
3465 auto *LengthVal = Builder.CreateIntCast(
3466 EmitScalarExpr(Length), IntPtrTy,
3467 Length->getType()->hasSignedIntegerRepresentation());
3468 Idx = Builder.CreateSub(
3469 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3470 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3471 } else {
3472 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3473 --ConstLength;
3474 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3475 }
3476 }
3477 }
3478 assert(Idx);
3479
Alexey Bataev31300ed2016-02-04 11:27:03 +00003480 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003481 LValueBaseInfo BaseInfo;
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003482 TBAAAccessInfo TBAAInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003483 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003484 // The base must be a pointer, which is not an aggregate. Emit
3485 // it. It needs to be emitted first in case it's what captures
3486 // the VLA bounds.
3487 Address Base =
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003488 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
3489 BaseTy, VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003490 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003491 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003492
3493 // Effectively, the multiply by the VLA size is part of the GEP.
3494 // GEP indexes are signed, and scaling an index isn't permitted to
3495 // signed-overflow, so we use the same semantics for our explicit
3496 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003497 if (getLangOpts().isSignedOverflowDefined())
3498 Idx = Builder.CreateMul(Idx, NumElements);
3499 else
3500 Idx = Builder.CreateNSWMul(Idx, NumElements);
3501 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003502 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003503 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003504 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3505 // If this is A[i] where A is an array, the frontend will have decayed the
3506 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3507 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3508 // "gep x, i" here. Emit one "gep A, 0, i".
3509 assert(Array->getType()->isArrayType() &&
3510 "Array to pointer decay must have array source type!");
3511 LValue ArrayLV;
3512 // For simple multidimensional array indexing, set the 'accessed' flag for
3513 // better bounds-checking of the base expression.
3514 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3515 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3516 else
3517 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003518
Alexey Bataev31300ed2016-02-04 11:27:03 +00003519 // Propagate the alignment from the array itself to the result.
3520 EltPtr = emitArraySubscriptGEP(
3521 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumara125eb52017-06-01 19:22:18 +00003522 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003523 /*SignedIndices=*/false, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003524 BaseInfo = ArrayLV.getBaseInfo();
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003525 TBAAInfo = CGM.getTBAAAccessInfo(ResultExprTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003526 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003527 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003528 TBAAInfo, BaseTy, ResultExprTy,
3529 IsLowerBound);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003530 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
Vedant Kumara125eb52017-06-01 19:22:18 +00003531 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003532 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003533 }
3534
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003535 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003536}
3537
Chris Lattner9e751ca2007-08-02 23:37:31 +00003538LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003539EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003540 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003541 LValue Base;
3542
3543 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003544 if (E->isArrow()) {
3545 // If it is a pointer to a vector, emit the address and form an lvalue with
3546 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003547 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003548 TBAAAccessInfo TBAAInfo;
3549 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003550 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003551 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003552 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003553 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003554 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3555 // emit the base as an lvalue.
3556 assert(E->getBase()->getType()->isVectorType());
3557 Base = EmitLValue(E->getBase());
3558 } else {
3559 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003560 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003561 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003562 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003563
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003564 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003565 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003566 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003567 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003568 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003569 }
John McCall1553b192011-06-16 04:16:24 +00003570
3571 QualType type =
3572 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003573
Nate Begemand3862152008-05-13 21:03:02 +00003574 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003575 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003576 E->getEncodedElementAccess(Indices);
3577
3578 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003579 llvm::Constant *CV =
3580 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003581 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003582 Base.getBaseInfo(), TBAAAccessInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003583 }
3584 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3585
3586 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003587 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003588
Chris Lattner595ba3a2012-01-30 06:20:36 +00003589 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3590 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003591 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003592 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003593 Base.getBaseInfo(), TBAAAccessInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003594}
3595
Devang Patel30efa2e2007-10-23 20:28:39 +00003596LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00003597 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3598 EmitIgnoredExpr(E->getBase());
3599 return EmitDeclRefLValue(DRE);
3600 }
3601
Devang Pateld68df202007-10-24 22:26:28 +00003602 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003603 // 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 +00003604 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003605 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003606 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003607 TBAAAccessInfo TBAAInfo;
3608 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003609 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003610 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003611 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3612 if (IsBaseCXXThis)
3613 SkippedChecks.set(SanitizerKind::Alignment, true);
3614 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003615 SkippedChecks.set(SanitizerKind::Null, true);
3616 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3617 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003618 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003619 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003620 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003621
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003622 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003623 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003624 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003625 setObjCGCLValueClass(getContext(), E, LV);
3626 return LV;
3627 }
Craig Topper99e79272013-07-26 05:59:26 +00003628
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003629 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003630 return EmitFunctionDeclLValue(*this, E, FD);
3631
David Blaikie83d382b2011-09-23 05:06:16 +00003632 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003633}
Devang Patel30efa2e2007-10-23 20:28:39 +00003634
John McCalldec348f72013-05-03 07:33:41 +00003635/// Given that we are currently emitting a lambda, emit an l-value for
3636/// one of its members.
3637LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3638 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3639 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3640 QualType LambdaTagType =
3641 getContext().getTagDeclType(Field->getParent());
3642 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3643 return EmitLValueForField(LambdaLV, Field);
3644}
3645
John McCall7f416cc2015-09-08 08:05:57 +00003646/// Drill down to the storage of a field without walking into
3647/// reference types.
3648///
3649/// The resulting address doesn't necessarily have the right type.
3650static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3651 const FieldDecl *field) {
3652 const RecordDecl *rec = field->getParent();
3653
3654 unsigned idx =
3655 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3656
3657 CharUnits offset;
3658 // Adjust the alignment down to the given offset.
3659 // As a special case, if the LLVM field index is 0, we know that this
3660 // is zero.
3661 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3662 .getFieldOffset(field->getFieldIndex()) == 0) &&
3663 "LLVM field at index zero had non-zero offset?");
3664 if (idx != 0) {
3665 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3666 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3667 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3668 }
3669
3670 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3671}
3672
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003673static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3674 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3675 if (!RD)
3676 return false;
3677
3678 if (RD->isDynamicClass())
3679 return true;
3680
3681 for (const auto &Base : RD->bases())
3682 if (hasAnyVptr(Base.getType(), Context))
3683 return true;
3684
3685 for (const FieldDecl *Field : RD->fields())
3686 if (hasAnyVptr(Field->getType(), Context))
3687 return true;
3688
3689 return false;
3690}
3691
Eli Friedman7f1ff602012-04-16 03:54:45 +00003692LValue CodeGenFunction::EmitLValueForField(LValue base,
3693 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003694 LValueBaseInfo BaseInfo = base.getBaseInfo();
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003695
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003696 if (field->isBitField()) {
3697 const CGRecordLayout &RL =
3698 CGM.getTypes().getCGRecordLayout(field->getParent());
3699 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003700 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003701 unsigned Idx = RL.getLLVMFieldNo(field);
3702 if (Idx != 0)
3703 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003704 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3705 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003706 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003707 llvm::Type *FieldIntTy =
3708 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3709 if (Addr.getElementType() != FieldIntTy)
3710 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003711
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003712 QualType fieldType =
3713 field->getType().withCVRQualifiers(base.getVRQualifiers());
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003714 // TODO: Support TBAA for bit fields.
3715 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource(), false);
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003716 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
3717 TBAAAccessInfo());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003718 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003719
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003720 // Fields of may-alias structures are may-alias themselves.
3721 // FIXME: this should get propagated down through anonymous structs
3722 // and unions.
3723 QualType FieldType = field->getType();
3724 const RecordDecl *rec = field->getParent();
3725 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
3726 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource), false);
3727 TBAAAccessInfo FieldTBAAInfo;
3728 if (BaseInfo.getMayAlias() || rec->hasAttr<MayAliasAttr>() ||
3729 FieldType->isVectorType()) {
3730 FieldBaseInfo.setMayAlias(true);
3731 FieldTBAAInfo = CGM.getTBAAMayAliasAccessInfo();
3732 } else if (rec->isUnion()) {
3733 // TODO: Support TBAA for unions.
3734 FieldBaseInfo.setMayAlias(true);
3735 FieldTBAAInfo = CGM.getTBAAMayAliasAccessInfo();
3736 } else {
3737 // If no base type been assigned for the base access, then try to generate
3738 // one for this base lvalue.
3739 FieldTBAAInfo = base.getTBAAInfo();
3740 if (!FieldTBAAInfo.BaseType) {
3741 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
3742 assert(!FieldTBAAInfo.Offset &&
3743 "Nonzero offset for an access with no base type!");
3744 }
3745
3746 // Adjust offset to be relative to the base type.
3747 const ASTRecordLayout &Layout =
3748 getContext().getASTRecordLayout(field->getParent());
3749 unsigned CharWidth = getContext().getCharWidth();
3750 if (FieldTBAAInfo.BaseType)
3751 FieldTBAAInfo.Offset +=
3752 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
3753
3754 // Update the final access type.
3755 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
3756 }
3757
John McCall7f416cc2015-09-08 08:05:57 +00003758 Address addr = base.getAddress();
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003759 unsigned RecordCVR = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00003760 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003761 // For unions, there is no pointer adjustment.
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003762 assert(!FieldType->isReferenceType() && "union has reference member");
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003763 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3764 hasAnyVptr(FieldType, getContext()))
3765 // Because unions can easily skip invariant.barriers, we need to add
3766 // a barrier every time CXXRecord field with vptr is referenced.
3767 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3768 addr.getAlignment());
John McCall53fcbd22011-02-26 08:07:02 +00003769 } else {
3770 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003771 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003772
3773 // If this is a reference field, load the reference right now.
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003774 if (FieldType->isReferenceType()) {
3775 LValue RefLVal = MakeAddrLValue(addr, FieldType, FieldBaseInfo,
3776 FieldTBAAInfo);
3777 if (RecordCVR & Qualifiers::Volatile)
3778 RefLVal.getQuals().setVolatile(true);
3779 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003780
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003781 // Qualifiers on the struct don't apply to the referencee.
3782 RecordCVR = 0;
3783 FieldType = FieldType->getPointeeType();
John McCall53fcbd22011-02-26 08:07:02 +00003784 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003785 }
Craig Topper99e79272013-07-26 05:59:26 +00003786
Chris Lattner13ee4f42011-07-10 05:34:54 +00003787 // Make sure that the address is pointing to the right type. This is critical
3788 // for both unions and structs. A union needs a bitcast, a struct element
3789 // will need a bitcast if the LLVM type laid out doesn't match the desired
3790 // type.
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003791 addr = Builder.CreateElementBitCast(
3792 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003793
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003794 if (field->hasAttr<AnnotateAttr>())
3795 addr = EmitFieldAnnotations(field, addr);
3796
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003797 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003798 LV.getQuals().addCVRQualifiers(RecordCVR);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00003799
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003800 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003801 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3802 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003803
Daniel Dunbarf166a522010-08-21 03:44:13 +00003804 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003805}
3806
Craig Topper99e79272013-07-26 05:59:26 +00003807LValue
3808CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003809 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003810 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003811
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003812 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003813 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003814
John McCall7f416cc2015-09-08 08:05:57 +00003815 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003816
John McCall7f416cc2015-09-08 08:05:57 +00003817 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003818 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003819 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003820
John McCall7f416cc2015-09-08 08:05:57 +00003821 // TODO: access-path TBAA?
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003822 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3823 LValueBaseInfo FieldBaseInfo(
3824 getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3825 BaseInfo.getMayAlias());
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00003826 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
3827 CGM.getTBAAAccessInfo(FieldType));
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003828}
3829
Chris Lattnerf53c0962010-09-06 00:11:41 +00003830LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003831 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003832 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003833 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003834 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003835 if (E->getType()->isVariablyModifiedType())
3836 // make sure to emit the VLA size.
3837 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003838
John McCall7f416cc2015-09-08 08:05:57 +00003839 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003840 const Expr *InitExpr = E->getInitializer();
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003841 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003842
Chad Rosier615ed1a2012-03-29 17:37:10 +00003843 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3844 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003845
3846 return Result;
3847}
3848
Richard Smithbb653bd2012-05-14 21:57:21 +00003849LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3850 if (!E->isGLValue())
3851 // Initializing an aggregate temporary in C++11: T{...}.
3852 return EmitAggExprToLValue(E);
3853
3854 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003855 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003856 return EmitLValue(E->getInit(0));
3857}
3858
Richard Smithf3076ff2014-06-20 18:43:47 +00003859/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3860/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3861/// LValue is returned and the current block has been terminated.
3862static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3863 const Expr *Operand) {
3864 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3865 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3866 return None;
3867 }
3868
3869 return CGF.EmitLValue(Operand);
3870}
3871
John McCallc07a0c72011-02-17 10:25:35 +00003872LValue CodeGenFunction::
3873EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3874 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003875 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003876 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003877 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003878 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003879 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003880
Eli Friedman59954892012-01-25 05:04:17 +00003881 OpaqueValueMapping binding(*this, expr);
3882
John McCallc07a0c72011-02-17 10:25:35 +00003883 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003884 bool CondExprBool;
3885 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003886 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003887 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003888
Justin Bogneref512b92014-01-06 22:27:43 +00003889 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003890 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003891 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003892 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003893 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003894 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003895 }
3896
John McCallc07a0c72011-02-17 10:25:35 +00003897 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3898 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3899 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003900
3901 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003902 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003903
John McCall0a6bf2e2011-01-26 19:21:13 +00003904 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003905 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003906 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003907 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003908 Optional<LValue> lhs =
3909 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003910 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003911
Richard Smithf3076ff2014-06-20 18:43:47 +00003912 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003913 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003914
John McCallc07a0c72011-02-17 10:25:35 +00003915 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003916 if (lhs)
3917 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003918
John McCall0a6bf2e2011-01-26 19:21:13 +00003919 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003920 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003921 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003922 Optional<LValue> rhs =
3923 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003924 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003925 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003926 return EmitUnsupportedLValue(expr, "conditional operator");
3927 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003928
John McCallc07a0c72011-02-17 10:25:35 +00003929 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003930
Richard Smithf3076ff2014-06-20 18:43:47 +00003931 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003932 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003933 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003934 phi->addIncoming(lhs->getPointer(), lhsBlock);
3935 phi->addIncoming(rhs->getPointer(), rhsBlock);
3936 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3937 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003938 std::max(lhs->getBaseInfo().getAlignmentSource(),
3939 rhs->getBaseInfo().getAlignmentSource());
3940 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3941 rhs->getBaseInfo().getMayAlias();
3942 return MakeAddrLValue(result, expr->getType(),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00003943 LValueBaseInfo(alignSource, MayAlias),
3944 CGM.getTBAAAccessInfo(expr->getType()));
Richard Smithf3076ff2014-06-20 18:43:47 +00003945 } else {
3946 assert((lhs || rhs) &&
3947 "both operands of glvalue conditional are throw-expressions?");
3948 return lhs ? *lhs : *rhs;
3949 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003950}
3951
Richard Smithbb653bd2012-05-14 21:57:21 +00003952/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3953/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003954/// otherwise if a cast is needed by the code generator in an lvalue context,
3955/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003956/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003957/// are permitted with aggregate result, including noop aggregate casts, and
3958/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003959LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003960 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003961 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003962 case CK_BitCast:
3963 case CK_ArrayToPointerDecay:
3964 case CK_FunctionToPointerDecay:
3965 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003966 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003967 case CK_IntegralToPointer:
3968 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003969 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003970 case CK_VectorSplat:
3971 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003972 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003973 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003974 case CK_IntegralToFloating:
3975 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003976 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003977 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003978 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003979 case CK_FloatingComplexToReal:
3980 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003981 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003982 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003983 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003984 case CK_IntegralComplexToReal:
3985 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003986 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003987 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003988 case CK_DerivedToBaseMemberPointer:
3989 case CK_BaseToDerivedMemberPointer:
3990 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003991 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003992 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003993 case CK_ARCProduceObject:
3994 case CK_ARCConsumeObject:
3995 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003996 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003997 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003998 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003999 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004000 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4001
4002 case CK_Dependent:
4003 llvm_unreachable("dependent cast kind in IR gen!");
4004
4005 case CK_BuiltinFnToFnPtr:
4006 llvm_unreachable("builtin functions are handled elsewhere");
4007
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004008 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004009 case CK_NonAtomicToAtomic:
4010 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004011 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00004012
Anders Carlsson8a01a752011-04-11 02:03:26 +00004013 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00004014 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004015 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004016 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00004017 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00004018 }
4019
John McCalle3027922010-08-25 11:45:40 +00004020 case CK_ConstructorConversion:
4021 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00004022 case CK_CPointerToObjCPointerCast:
4023 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004024 case CK_NoOp:
4025 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004026 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00004027
John McCalle3027922010-08-25 11:45:40 +00004028 case CK_UncheckedDerivedToBase:
4029 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00004030 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00004031 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004032 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004033
Anders Carlssond95f9602009-09-12 16:16:49 +00004034 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004035 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00004036
Anders Carlssond95f9602009-09-12 16:16:49 +00004037 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00004038 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00004039 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4040 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00004041
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004042 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4043 CGM.getTBAAAccessInfo(E->getType()));
Anders Carlssond95f9602009-09-12 16:16:49 +00004044 }
John McCalle3027922010-08-25 11:45:40 +00004045 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00004046 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00004047 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00004048 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004049 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004050
Anders Carlsson8c793172009-11-23 17:57:54 +00004051 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00004052
Anders Carlsson8c793172009-11-23 17:57:54 +00004053 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00004054 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00004055 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00004056 E->path_begin(), E->path_end(),
4057 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00004058
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004059 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4060 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00004061 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004062 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00004063 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004064
Peter Collingbourned2926c92015-03-14 02:42:25 +00004065 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004066 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4067 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004068 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004069
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004070 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4071 CGM.getTBAAAccessInfo(E->getType()));
Eli Friedman8c98dff2009-11-16 05:48:01 +00004072 }
John McCalle3027922010-08-25 11:45:40 +00004073 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00004074 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004075 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00004076
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00004077 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00004078 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004079 Address V = Builder.CreateBitCast(LV.getAddress(),
4080 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00004081
4082 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004083 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4084 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004085 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004086
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004087 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4088 CGM.getTBAAAccessInfo(E->getType()));
Anders Carlsson50cb3212009-11-14 21:21:42 +00004089 }
John McCalle3027922010-08-25 11:45:40 +00004090 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004091 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004092 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4093 ConvertType(E->getType()));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004094 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4095 CGM.getTBAAAccessInfo(E->getType()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004096 }
Egor Churaev89831422016-12-23 14:55:49 +00004097 case CK_ZeroToOCLQueue:
4098 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004099 case CK_ZeroToOCLEvent:
4100 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00004101 }
Craig Topper99e79272013-07-26 05:59:26 +00004102
Douglas Gregorcdb466e2010-07-15 18:58:16 +00004103 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004104}
4105
John McCall1bf58462011-02-16 08:02:54 +00004106LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00004107 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00004108 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00004109}
4110
Eli Friedman7f1ff602012-04-16 03:54:45 +00004111RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004112 const FieldDecl *FD,
4113 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004114 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00004115 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00004116 switch (getEvaluationKind(FT)) {
4117 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004118 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00004119 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00004120 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00004121 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00004122 // This routine is used to load fields one-by-one to perform a copy, so
4123 // don't load reference fields.
4124 if (FD->getType()->isReferenceType())
4125 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00004126 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00004127 }
4128 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004129}
Douglas Gregorfe314812011-06-21 17:03:29 +00004130
Chris Lattnere47e4402007-06-01 18:02:12 +00004131//===--------------------------------------------------------------------===//
4132// Expression Emission
4133//===--------------------------------------------------------------------===//
4134
Craig Topper99e79272013-07-26 05:59:26 +00004135RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00004136 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00004137 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004138 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00004139 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004140
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004141 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004142 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004143
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004144 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00004145 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4146
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004147 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00004148 if (const CXXMethodDecl *MD =
4149 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004150 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004151
John McCallb92ab1a2016-10-26 23:46:34 +00004152 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00004153
John McCallb92ab1a2016-10-26 23:46:34 +00004154 if (callee.isBuiltin()) {
4155 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4156 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004157 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004158
John McCallb92ab1a2016-10-26 23:46:34 +00004159 if (callee.isPseudoDestructor()) {
4160 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4161 }
4162
4163 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4164}
4165
4166/// Emit a CallExpr without considering whether it might be a subclass.
4167RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4168 ReturnValueSlot ReturnValue) {
4169 CGCallee Callee = EmitCallee(E->getCallee());
4170 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4171}
4172
4173static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4174 if (auto builtinID = FD->getBuiltinID()) {
4175 return CGCallee::forBuiltin(builtinID, FD);
4176 }
4177
4178 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4179 return CGCallee::forDirect(calleePtr, FD);
4180}
4181
4182CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4183 E = E->IgnoreParens();
4184
4185 // Look through function-to-pointer decay.
4186 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4187 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4188 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4189 return EmitCallee(ICE->getSubExpr());
4190 }
4191
4192 // Resolve direct calls.
4193 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4194 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4195 return EmitDirectCallee(*this, FD);
4196 }
4197 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4198 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4199 EmitIgnoredExpr(ME->getBase());
4200 return EmitDirectCallee(*this, FD);
4201 }
4202
4203 // Look through template substitutions.
4204 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4205 return EmitCallee(NTTP->getReplacement());
4206
4207 // Treat pseudo-destructor calls differently.
4208 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4209 return CGCallee::forPseudoDestructor(PDE);
4210 }
4211
4212 // Otherwise, we have an indirect reference.
4213 llvm::Value *calleePtr;
4214 QualType functionType;
4215 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4216 calleePtr = EmitScalarExpr(E);
4217 functionType = ptrType->getPointeeType();
4218 } else {
4219 functionType = E->getType();
4220 calleePtr = EmitLValue(E).getPointer();
4221 }
4222 assert(functionType->isFunctionType());
4223 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4224 E->getReferencedDeclOfCallee());
4225 CGCallee callee(calleeInfo, calleePtr);
4226 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004227}
4228
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004229LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004230 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004231 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004232 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004233 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004234 return EmitLValue(E->getRHS());
4235 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004236
John McCalle3027922010-08-25 11:45:40 +00004237 if (E->getOpcode() == BO_PtrMemD ||
4238 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004239 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004240
John McCalla2342eb2010-12-05 02:00:02 +00004241 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004242
4243 // Note that in all of these cases, __block variables need the RHS
4244 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004245
4246 switch (getEvaluationKind(E->getType())) {
4247 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004248 switch (E->getLHS()->getType().getObjCLifetime()) {
4249 case Qualifiers::OCL_Strong:
4250 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4251
4252 case Qualifiers::OCL_Autoreleasing:
4253 return EmitARCStoreAutoreleasing(E).first;
4254
4255 // No reason to do any of these differently.
4256 case Qualifiers::OCL_None:
4257 case Qualifiers::OCL_ExplicitNone:
4258 case Qualifiers::OCL_Weak:
4259 break;
4260 }
4261
John McCalld0a30012010-12-06 06:10:02 +00004262 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004263 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004264 if (RV.isScalar())
4265 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004266 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004267 return LV;
4268 }
John McCall4f29b492010-11-16 23:07:28 +00004269
John McCall47fb9502013-03-07 21:37:08 +00004270 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004271 return EmitComplexAssignmentLValue(E);
4272
John McCall47fb9502013-03-07 21:37:08 +00004273 case TEK_Aggregate:
4274 return EmitAggExprToLValue(E);
4275 }
4276 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004277}
4278
Christopher Lambd91c3d42007-12-29 05:02:41 +00004279LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004280 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004281
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004282 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004283 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004284 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004285
David Majnemerced8bdf2015-02-25 17:36:15 +00004286 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004287 "Can't have a scalar return unless the return type is a "
4288 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004289
John McCall7f416cc2015-09-08 08:05:57 +00004290 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004291}
4292
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004293LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4294 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004295 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004296}
4297
Anders Carlsson3be22e22009-05-30 23:23:33 +00004298LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004299 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4300 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004301 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004302 EmitCXXConstructExpr(E, Slot);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004303 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00004304}
4305
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004306LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004307CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004308 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004309}
4310
John McCall7f416cc2015-09-08 08:05:57 +00004311Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4312 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4313 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004314}
4315
4316LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004317 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004318 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00004319}
4320
Mike Stumpc9b231c2009-11-15 08:09:41 +00004321LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004322CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004323 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004324 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004325 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004326 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004327 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004328}
4329
Eli Friedman5bc17122012-02-08 05:34:55 +00004330LValue
4331CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004332 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004333 EmitLambdaExpr(E, Slot);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004334 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00004335}
4336
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004337LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004338 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004339
Anders Carlsson280e61f12010-06-21 20:59:55 +00004340 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004341 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004342 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004343
Alp Toker314cc812014-01-25 16:55:45 +00004344 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004345 "Can't have a scalar return unless the return type is a "
4346 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004347
John McCall7f416cc2015-09-08 08:05:57 +00004348 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004349}
4350
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004351LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004352 Address V =
4353 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004354 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004355}
4356
Daniel Dunbar722f4242009-04-22 05:08:15 +00004357llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004358 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004359 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004360}
4361
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004362LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4363 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004364 const ObjCIvarDecl *Ivar,
4365 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004366 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004367 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004368}
4369
4370LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004371 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004372 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004373 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004374 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004375 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004376 if (E->isArrow()) {
4377 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004378 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004379 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004380 } else {
4381 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004382 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004383 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004384 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004385 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004386
Craig Topper99e79272013-07-26 05:59:26 +00004387 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004388 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4389 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004390 setObjCGCLValueClass(getContext(), E, LV);
4391 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004392}
4393
Chris Lattnera4185c52009-04-25 19:35:26 +00004394LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004395 // Can only get l-value for message expression returning aggregate type
4396 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004397 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004398 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00004399}
4400
John McCallb92ab1a2016-10-26 23:46:34 +00004401RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004402 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004403 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004404 // Get the actual function type. The callee type will always be a pointer to
4405 // function type or a block pointer type.
4406 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004407 "Call must have function pointer type!");
4408
John McCallb92ab1a2016-10-26 23:46:34 +00004409 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004410
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004411 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004412 // We can only guarantee that a function is called from the correct
4413 // context/function based on the appropriate target attributes,
4414 // so only check in the case where we have both always_inline and target
4415 // since otherwise we could be making a conditional call after a check for
4416 // the proper cpu features (and it won't cause code generation issues due to
4417 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004418 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4419 TargetDecl->hasAttr<TargetAttr>())
4420 checkTargetFeatures(E, FD);
4421
John McCall6fd4c232009-10-23 08:22:42 +00004422 CalleeType = getContext().getCanonicalType(CalleeType);
4423
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004424 const auto *FnType =
4425 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004426
John McCallb92ab1a2016-10-26 23:46:34 +00004427 CGCallee Callee = OrigCallee;
4428
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004429 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004430 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4431 if (llvm::Constant *PrefixSig =
4432 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004433 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004434 llvm::Constant *FTRTTIConst =
4435 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004436 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004437 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4438 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4439
John McCallb92ab1a2016-10-26 23:46:34 +00004440 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4441
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004442 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004443 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004444 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004445 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004446 llvm::Value *CalleeSig =
4447 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004448 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4449
4450 llvm::BasicBlock *Cont = createBasicBlock("cont");
4451 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4452 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4453
4454 EmitBlock(TypeCheck);
4455 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004456 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004457 llvm::Value *CalleeRTTIEncoded =
John McCall7f416cc2015-09-08 08:05:57 +00004458 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004459 llvm::Value *CalleeRTTI =
4460 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004461 llvm::Value *CalleeRTTIMatch =
4462 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4463 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004464 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004465 EmitCheckTypeDescriptor(CalleeType)
4466 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004467 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004468 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004469
4470 Builder.CreateBr(Cont);
4471 EmitBlock(Cont);
4472 }
4473 }
4474
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004475 // If we are checking indirect calls and this call is indirect, check that the
4476 // function pointer is a member of the bit set for the function type.
4477 if (SanOpts.has(SanitizerKind::CFIICall) &&
4478 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4479 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004480 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004481
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004482 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004483 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004484
John McCallb92ab1a2016-10-26 23:46:34 +00004485 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4486 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004487 llvm::Value *TypeTest = Builder.CreateCall(
4488 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004489
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004490 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004491 llvm::Constant *StaticData[] = {
4492 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4493 EmitCheckSourceLocation(E->getLocStart()),
4494 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4495 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004496 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4497 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004498 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004499 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004500 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004501 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004502 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004503 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004504 }
4505
Daniel Dunbarc722b852008-08-30 03:02:31 +00004506 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004507 if (Chain)
4508 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4509 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004510
4511 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004512 // right-to-left, and that we evaluate arguments to certain other operators
4513 // left-to-right. Note that we allow this to override the order dictated by
4514 // the calling convention on the MS ABI, which means that parameter
4515 // destruction order is not necessarily reverse construction order.
4516 // FIXME: Revisit this based on C++ committee response to unimplementability.
4517 EvaluationOrder Order = EvaluationOrder::Default;
4518 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4519 if (OCE->isAssignmentOp())
4520 Order = EvaluationOrder::ForceRightToLeft;
4521 else {
4522 switch (OCE->getOperator()) {
4523 case OO_LessLess:
4524 case OO_GreaterGreater:
4525 case OO_AmpAmp:
4526 case OO_PipePipe:
4527 case OO_Comma:
4528 case OO_ArrowStar:
4529 Order = EvaluationOrder::ForceLeftToRight;
4530 break;
4531 default:
4532 break;
4533 }
4534 }
4535 }
Richard Smith762672a2016-09-28 19:09:10 +00004536
David Blaikief05779e2015-07-21 18:37:18 +00004537 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004538 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004539
Peter Collingbournef7706832014-12-12 23:41:25 +00004540 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4541 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004542
4543 // C99 6.5.2.2p6:
4544 // If the expression that denotes the called function has a type
4545 // that does not include a prototype, [the default argument
4546 // promotions are performed]. If the number of arguments does not
4547 // equal the number of parameters, the behavior is undefined. If
4548 // the function is defined with a type that includes a prototype,
4549 // and either the prototype ends with an ellipsis (, ...) or the
4550 // types of the arguments after promotion are not compatible with
4551 // the types of the parameters, the behavior is undefined. If the
4552 // function is defined with a type that does not include a
4553 // prototype, and the types of the arguments after promotion are
4554 // not compatible with those of the parameters after promotion,
4555 // the behavior is undefined [except in some trivial cases].
4556 // That is, in the general case, we should assume that a call
4557 // through an unprototyped function type works like a *non-variadic*
4558 // call. The way we make this work is to cast to the exact type
4559 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004560 //
4561 // Chain calls use this same code path to add the invisible chain parameter
4562 // to the function type.
4563 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004564 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004565 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004566
4567 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4568 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4569 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004570 }
4571
John McCallb92ab1a2016-10-26 23:46:34 +00004572 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004573}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004574
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004575LValue CodeGenFunction::
4576EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004577 Address BaseAddr = Address::invalid();
4578 if (E->getOpcode() == BO_PtrMemI) {
4579 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4580 } else {
4581 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4582 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004583
John McCallc134eb52010-08-31 21:07:20 +00004584 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4585
4586 const MemberPointerType *MPT
4587 = E->getRHS()->getType()->getAs<MemberPointerType>();
4588
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004589 LValueBaseInfo BaseInfo;
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004590 TBAAAccessInfo TBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00004591 Address MemberAddr =
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004592 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
4593 &TBAAInfo);
John McCallc134eb52010-08-31 21:07:20 +00004594
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004595 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004596}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004597
John McCall47fb9502013-03-07 21:37:08 +00004598/// Given the address of a temporary variable, produce an r-value of
4599/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004600RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004601 QualType type,
4602 SourceLocation loc) {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004603 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004604 switch (getEvaluationKind(type)) {
4605 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004606 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004607 case TEK_Aggregate:
4608 return lvalue.asAggregateRValue();
4609 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004610 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004611 }
4612 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004613}
4614
Duncan Sandse81111c2012-04-10 08:23:07 +00004615void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004616 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004617 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004618 return;
4619
Duncan Sands65229ed2012-04-16 16:29:47 +00004620 llvm::MDBuilder MDHelper(getLLVMContext());
4621 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004622
Duncan Sands6fc46192012-04-14 12:37:26 +00004623 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004624}
John McCallfe96e0b2011-11-06 09:01:30 +00004625
4626namespace {
4627 struct LValueOrRValue {
4628 LValue LV;
4629 RValue RV;
4630 };
4631}
4632
4633static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4634 const PseudoObjectExpr *E,
4635 bool forLValue,
4636 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004637 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004638
4639 // Find the result expression, if any.
4640 const Expr *resultExpr = E->getResultExpr();
4641 LValueOrRValue result;
4642
4643 for (PseudoObjectExpr::const_semantics_iterator
4644 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4645 const Expr *semantic = *i;
4646
4647 // If this semantic expression is an opaque value, bind it
4648 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004649 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004650
4651 // If this is the result expression, we may need to evaluate
4652 // directly into the slot.
4653 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4654 OVMA opaqueData;
4655 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004656 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004657 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
John McCall7f416cc2015-09-08 08:05:57 +00004658 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004659 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004660 opaqueData = OVMA::bind(CGF, ov, LV);
4661 result.RV = slot.asRValue();
4662
4663 // Otherwise, emit as normal.
4664 } else {
4665 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4666
4667 // If this is the result, also evaluate the result now.
4668 if (ov == resultExpr) {
4669 if (forLValue)
4670 result.LV = CGF.EmitLValue(ov);
4671 else
4672 result.RV = CGF.EmitAnyExpr(ov, slot);
4673 }
4674 }
4675
4676 opaques.push_back(opaqueData);
4677
4678 // Otherwise, if the expression is the result, evaluate it
4679 // and remember the result.
4680 } else if (semantic == resultExpr) {
4681 if (forLValue)
4682 result.LV = CGF.EmitLValue(semantic);
4683 else
4684 result.RV = CGF.EmitAnyExpr(semantic, slot);
4685
4686 // Otherwise, evaluate the expression in an ignored context.
4687 } else {
4688 CGF.EmitIgnoredExpr(semantic);
4689 }
4690 }
4691
4692 // Unbind all the opaques now.
4693 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4694 opaques[i].unbind(CGF);
4695
4696 return result;
4697}
4698
4699RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4700 AggValueSlot slot) {
4701 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4702}
4703
4704LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4705 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4706}