blob: d8df83def4b9b1ec6d020b28d09b30ad22494504 [file] [log] [blame]
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
Chris Lattner1b926492006-08-23 06:42:10 +00002//
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 Lattner1b926492006-08-23 06:42:10 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr class and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner5c4664e2007-07-15 23:32:58 +000014#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000015#include "clang/AST/Attr.h"
Douglas Gregor9a657932008-10-21 23:43:52 +000016#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor1be329d2012-02-23 07:33:15 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000020#include "clang/AST/Expr.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/AST/ExprCXX.h"
David Majnemerbed356a2013-11-06 23:31:56 +000022#include "clang/AST/Mangle.h"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000023#include "clang/AST/RecordLayout.h"
24#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000026#include "clang/Basic/CharInfo.h"
Chris Lattnere925d612010-11-17 07:37:15 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnera7944d82007-11-27 18:22:04 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/Lex/Lexer.h"
30#include "clang/Lex/LiteralSupport.h"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000031#include "clang/Sema/SemaDiagnostic.h"
Douglas Gregor0840cc02009-11-01 20:32:48 +000032#include "llvm/Support/ErrorHandling.h"
Anders Carlsson2fb08242009-09-08 18:24:21 +000033#include "llvm/Support/raw_ostream.h"
Douglas Gregord5846a12009-04-15 06:41:24 +000034#include <algorithm>
Eli Friedmanfcec6302011-11-01 02:23:42 +000035#include <cstring>
Chris Lattner1b926492006-08-23 06:42:10 +000036using namespace clang;
37
Richard Smith018ac392016-11-03 18:55:18 +000038const Expr *Expr::getBestDynamicClassTypeExpr() const {
39 const Expr *E = this;
40 while (true) {
41 E = E->ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000042
Richard Smith018ac392016-11-03 18:55:18 +000043 // Follow the RHS of a comma operator.
44 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
45 if (BO->getOpcode() == BO_Comma) {
46 E = BO->getRHS();
47 continue;
48 }
49 }
50
51 // Step into initializer for materialized temporaries.
52 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
53 E = MTE->GetTemporaryExpr();
54 continue;
55 }
56
57 break;
58 }
59
60 return E;
61}
62
63const CXXRecordDecl *Expr::getBestDynamicClassType() const {
64 const Expr *E = getBestDynamicClassTypeExpr();
Rafael Espindola49e860b2012-06-26 17:45:31 +000065 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000066 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
67 DerivedType = PTy->getPointeeType();
68
Rafael Espindola60a2bba2012-07-17 20:24:05 +000069 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000070 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000071
Rafael Espindola49e860b2012-06-26 17:45:31 +000072 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000073 Decl *D = Ty->getDecl();
74 return cast<CXXRecordDecl>(D);
75}
76
Richard Smithf3fabd22013-06-03 00:17:11 +000077const Expr *Expr::skipRValueSubobjectAdjustments(
78 SmallVectorImpl<const Expr *> &CommaLHSs,
79 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000080 const Expr *E = this;
81 while (true) {
82 E = E->IgnoreParens();
83
84 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
85 if ((CE->getCastKind() == CK_DerivedToBase ||
86 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
87 E->getType()->isRecordType()) {
88 E = CE->getSubExpr();
89 CXXRecordDecl *Derived
90 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
91 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
92 continue;
93 }
94
95 if (CE->getCastKind() == CK_NoOp) {
96 E = CE->getSubExpr();
97 continue;
98 }
99 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000100 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +0000101 assert(ME->getBase()->getType()->isRecordType());
102 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000103 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +0000104 E = ME->getBase();
105 Adjustments.push_back(SubobjectAdjustment(Field));
106 continue;
107 }
Rafael Espindola9c006de2012-10-27 01:03:43 +0000108 }
109 }
110 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Richard Smitha3fd1162018-07-24 21:18:30 +0000111 if (BO->getOpcode() == BO_PtrMemD) {
Rafael Espindola973aa202012-11-01 14:32:20 +0000112 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +0000113 E = BO->getLHS();
114 const MemberPointerType *MPT =
115 BO->getRHS()->getType()->getAs<MemberPointerType>();
116 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +0000117 continue;
118 } else if (BO->getOpcode() == BO_Comma) {
119 CommaLHSs.push_back(BO->getLHS());
120 E = BO->getRHS();
121 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000122 }
123 }
124
125 // Nothing changed.
126 break;
127 }
128 return E;
129}
130
Chris Lattner4ebae652010-04-16 23:34:13 +0000131/// isKnownToHaveBooleanValue - Return true if this is an integer expression
132/// that is known to return 0 or 1. This happens for _Bool/bool expressions
133/// but also int expressions which are produced by things like comparisons in
134/// C.
135bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000136 const Expr *E = IgnoreParens();
137
Chris Lattner4ebae652010-04-16 23:34:13 +0000138 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000139 if (E->getType()->isBooleanType()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000140 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000141 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000142
Peter Collingbourne91147592011-04-15 00:35:48 +0000143 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000144 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000145 case UO_Plus:
Chris Lattner4ebae652010-04-16 23:34:13 +0000146 return UO->getSubExpr()->isKnownToHaveBooleanValue();
Richard Trieu0f097742014-04-04 04:13:47 +0000147 case UO_LNot:
148 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000149 default:
150 return false;
151 }
152 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000153
John McCall45d30c32010-06-12 01:56:02 +0000154 // Only look through implicit casts. If the user writes
155 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbourne91147592011-04-15 00:35:48 +0000156 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000157 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000158
Peter Collingbourne91147592011-04-15 00:35:48 +0000159 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000160 switch (BO->getOpcode()) {
161 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000162 case BO_LT: // Relational operators.
163 case BO_GT:
164 case BO_LE:
165 case BO_GE:
166 case BO_EQ: // Equality operators.
167 case BO_NE:
168 case BO_LAnd: // AND operator.
169 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000170 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000171
John McCalle3027922010-08-25 11:45:40 +0000172 case BO_And: // Bitwise AND operator.
173 case BO_Xor: // Bitwise XOR operator.
174 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000175 // Handle things like (x==2)|(y==12).
176 return BO->getLHS()->isKnownToHaveBooleanValue() &&
177 BO->getRHS()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000178
John McCalle3027922010-08-25 11:45:40 +0000179 case BO_Comma:
180 case BO_Assign:
Chris Lattner4ebae652010-04-16 23:34:13 +0000181 return BO->getRHS()->isKnownToHaveBooleanValue();
182 }
183 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000184
Peter Collingbourne91147592011-04-15 00:35:48 +0000185 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000186 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
187 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000188
Chris Lattner4ebae652010-04-16 23:34:13 +0000189 return false;
190}
191
John McCallbd066782011-02-09 08:16:59 +0000192// Amusing macro metaprogramming hack: check whether a class provides
193// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000194//
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000195// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000196namespace {
197 /// This implementation is used when a class provides a custom
198 /// implementation of getExprLoc.
199 template <class E, class T>
200 SourceLocation getExprLocImpl(const Expr *expr,
201 SourceLocation (T::*v)() const) {
202 return static_cast<const E*>(expr)->getExprLoc();
203 }
John McCallbd066782011-02-09 08:16:59 +0000204
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000205 /// This implementation is used when a class doesn't provide
206 /// a custom implementation of getExprLoc. Overload resolution
207 /// should pick it over the implementation above because it's
208 /// more specialized according to function template partial ordering.
209 template <class E>
210 SourceLocation getExprLocImpl(const Expr *expr,
211 SourceLocation (Expr::*v)() const) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000212 return static_cast<const E *>(expr)->getBeginLoc();
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000213 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000214}
John McCallbd066782011-02-09 08:16:59 +0000215
216SourceLocation Expr::getExprLoc() const {
217 switch (getStmtClass()) {
218 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
219#define ABSTRACT_STMT(type)
220#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000221 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000222#define EXPR(type, base) \
223 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
224#include "clang/AST/StmtNodes.inc"
225 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000226 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000227}
228
Chris Lattner0eedafe2006-08-24 04:56:27 +0000229//===----------------------------------------------------------------------===//
230// Primary Expressions.
231//===----------------------------------------------------------------------===//
232
Fangrui Song6907ce22018-07-30 19:24:48 +0000233/// Compute the type-, value-, and instantiation-dependence of a
Douglas Gregor678d76c2011-07-01 01:22:09 +0000234/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000235/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000236static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
237 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000238 bool &ValueDependent,
239 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000240 TypeDependent = false;
241 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000242 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000243
244 // (TD) C++ [temp.dep.expr]p3:
245 // An id-expression is type-dependent if it contains:
246 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000247 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000248 //
249 // (VD) C++ [temp.dep.constexpr]p2:
250 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000251
Douglas Gregored6c7442009-11-23 11:41:28 +0000252 // (TD) - an identifier that was declared with dependent type
253 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000254 if (T->isDependentType()) {
255 TypeDependent = true;
256 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000257 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000258 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000259 } else if (T->isInstantiationDependentType()) {
260 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000261 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000262
Douglas Gregored6c7442009-11-23 11:41:28 +0000263 // (TD) - a conversion-function-id that specifies a dependent type
Fangrui Song6907ce22018-07-30 19:24:48 +0000264 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000265 == DeclarationName::CXXConversionFunctionName) {
266 QualType T = D->getDeclName().getCXXNameType();
267 if (T->isDependentType()) {
268 TypeDependent = true;
269 ValueDependent = true;
270 InstantiationDependent = true;
271 return;
272 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000273
Douglas Gregor678d76c2011-07-01 01:22:09 +0000274 if (T->isInstantiationDependentType())
275 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000276 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000277
Douglas Gregored6c7442009-11-23 11:41:28 +0000278 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000279 if (isa<NonTypeTemplateParmDecl>(D)) {
280 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000281 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000282 return;
283 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000284
Douglas Gregored6c7442009-11-23 11:41:28 +0000285 // (VD) - a constant with integral or enumeration type and is
286 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000287 // (VD) - a constant with literal type and is initialized with an
288 // expression that is value-dependent [C++11].
289 // (VD) - FIXME: Missing from the standard:
290 // - an entity with reference type and is initialized with an
291 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000292 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000293 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000294 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000295 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000296 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000297 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000298 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000299 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000300 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000301 InstantiationDependent = true;
302 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000303 }
304
Fangrui Song6907ce22018-07-30 19:24:48 +0000305 // (VD) - FIXME: Missing from the standard:
306 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000307 // instantiation
Fangrui Song6907ce22018-07-30 19:24:48 +0000308 if (Var->isStaticDataMember() &&
Richard Smithec8dcd22011-11-08 01:31:09 +0000309 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000310 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000311 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000312 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
313 if (TInfo->getType()->isIncompleteArrayType())
314 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000315 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000316
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000317 return;
318 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000319
320 // (VD) - FIXME: Missing from the standard:
321 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000322 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000323 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
324 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000325 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000326 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000327}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000328
Craig Topperce7167c2013-08-22 04:58:56 +0000329void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000330 bool TypeDependent = false;
331 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000332 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000333 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
334 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000335
336 ExprBits.TypeDependent |= TypeDependent;
337 ExprBits.ValueDependent |= ValueDependent;
338 ExprBits.InstantiationDependent |= InstantiationDependent;
339
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000340 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000341 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000342 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000343}
344
Craig Topperce7167c2013-08-22 04:58:56 +0000345DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000346 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000347 SourceLocation TemplateKWLoc,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000348 ValueDecl *D, bool RefersToEnclosingVariableOrCapture,
John McCall113bee02012-03-10 09:33:50 +0000349 const DeclarationNameInfo &NameInfo,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000350 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000351 const TemplateArgumentListInfo *TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +0000352 QualType T, ExprValueKind VK)
Douglas Gregor678d76c2011-07-01 01:22:09 +0000353 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
Bruno Riccia795e802018-11-13 17:56:44 +0000354 D(D), DNLoc(NameInfo.getInfo()) {
355 DeclRefExprBits.Loc = NameInfo.getLoc();
Chandler Carruth0e439962011-05-01 21:29:53 +0000356 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000357 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000358 new (getTrailingObjects<NestedNameSpecifierLoc>())
359 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000360 auto *NNS = QualifierLoc.getNestedNameSpecifier();
361 if (NNS->isInstantiationDependent())
362 ExprBits.InstantiationDependent = true;
363 if (NNS->containsUnexpandedParameterPack())
364 ExprBits.ContainsUnexpandedParameterPack = true;
365 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000366 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
367 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000368 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000369 DeclRefExprBits.HasTemplateKWAndArgsInfo
370 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000371 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
372 RefersToEnclosingVariableOrCapture;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000373 if (TemplateArgs) {
374 bool Dependent = false;
375 bool InstantiationDependent = false;
376 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000377 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
378 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
379 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000380 assert(!Dependent && "built a DeclRefExpr with dependent template args");
381 ExprBits.InstantiationDependent |= InstantiationDependent;
382 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000383 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000384 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
385 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000386 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000387 DeclRefExprBits.HadMultipleCandidates = 0;
388
Daniel Dunbar9d355812012-03-09 01:51:51 +0000389 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000390}
391
Craig Topperce7167c2013-08-22 04:58:56 +0000392DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000393 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000394 SourceLocation TemplateKWLoc,
John McCallce546572009-12-08 09:08:17 +0000395 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000396 bool RefersToEnclosingVariableOrCapture,
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000397 SourceLocation NameLoc,
Douglas Gregored6c7442009-11-23 11:41:28 +0000398 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000399 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000400 NamedDecl *FoundD,
Douglas Gregored6c7442009-11-23 11:41:28 +0000401 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000402 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000403 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000404 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000405 T, VK, FoundD, TemplateArgs);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000406}
407
Craig Topperce7167c2013-08-22 04:58:56 +0000408DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000409 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000410 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000411 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000412 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000413 const DeclarationNameInfo &NameInfo,
414 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000415 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000416 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000417 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000418 // Filter out cases where the found Decl is the same as the value refenenced.
419 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000420 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000421
James Y Knighte7d82282015-12-29 18:15:14 +0000422 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
423 std::size_t Size =
424 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
425 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
426 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
427 HasTemplateKWAndArgsInfo ? 1 : 0,
428 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000429
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000430 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000431 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000432 RefersToEnclosingVariableOrCapture,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000433 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000434}
435
Craig Topperce7167c2013-08-22 04:58:56 +0000436DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000437 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000438 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000439 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000440 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000441 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
442 std::size_t Size =
443 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
444 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
445 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
446 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000447 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000448 return new (Mem) DeclRefExpr(EmptyShell());
449}
450
Stephen Kelly724e9e52018-08-09 20:05:03 +0000451SourceLocation DeclRefExpr::getBeginLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000452 if (hasQualifier())
453 return getQualifierLoc().getBeginLoc();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000454 return getNameInfo().getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000455}
Stephen Kelly02a67ba2018-08-09 20:05:47 +0000456SourceLocation DeclRefExpr::getEndLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000457 if (hasExplicitTemplateArgs())
458 return getRAngleLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000459 return getNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000460}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000461
Bruno Ricci17ff0262018-10-27 19:21:19 +0000462PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
Alexey Bataevec474782014-10-09 08:45:04 +0000463 StringLiteral *SL)
464 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
465 FNTy->isDependentType(), FNTy->isDependentType(),
466 FNTy->isInstantiationDependentType(),
Bruno Ricci17ff0262018-10-27 19:21:19 +0000467 /*ContainsUnexpandedParameterPack=*/false) {
468 PredefinedExprBits.Kind = IK;
469 assert((getIdentKind() == IK) &&
470 "IdentKind do not fit in PredefinedExprBitfields!");
471 bool HasFunctionName = SL != nullptr;
472 PredefinedExprBits.HasFunctionName = HasFunctionName;
473 PredefinedExprBits.Loc = L;
474 if (HasFunctionName)
475 setFunctionName(SL);
Alexey Bataevec474782014-10-09 08:45:04 +0000476}
477
Bruno Ricci17ff0262018-10-27 19:21:19 +0000478PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
479 : Expr(PredefinedExprClass, Empty) {
480 PredefinedExprBits.HasFunctionName = HasFunctionName;
481}
482
483PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
484 QualType FNTy, IdentKind IK,
485 StringLiteral *SL) {
486 bool HasFunctionName = SL != nullptr;
487 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
488 alignof(PredefinedExpr));
489 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
490}
491
492PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
493 bool HasFunctionName) {
494 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
495 alignof(PredefinedExpr));
496 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
497}
498
499StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
500 switch (IK) {
Alexey Bataevec474782014-10-09 08:45:04 +0000501 case Func:
502 return "__func__";
503 case Function:
504 return "__FUNCTION__";
505 case FuncDName:
506 return "__FUNCDNAME__";
507 case LFunction:
508 return "L__FUNCTION__";
509 case PrettyFunction:
510 return "__PRETTY_FUNCTION__";
511 case FuncSig:
512 return "__FUNCSIG__";
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000513 case LFuncSig:
514 return "L__FUNCSIG__";
Alexey Bataevec474782014-10-09 08:45:04 +0000515 case PrettyFunctionNoVirtual:
516 break;
517 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000518 llvm_unreachable("Unknown ident kind for PredefinedExpr");
Alexey Bataevec474782014-10-09 08:45:04 +0000519}
520
Anders Carlsson2fb08242009-09-08 18:24:21 +0000521// FIXME: Maybe this should use DeclPrinter with a special "print predefined
522// expr" policy instead.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000523std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000524 ASTContext &Context = CurrentDecl->getASTContext();
525
Bruno Ricci17ff0262018-10-27 19:21:19 +0000526 if (IK == PredefinedExpr::FuncDName) {
David Majnemerbed356a2013-11-06 23:31:56 +0000527 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000528 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000529 MC.reset(Context.createMangleContext());
530
531 if (MC->shouldMangleDeclName(ND)) {
532 SmallString<256> Buffer;
533 llvm::raw_svector_ostream Out(Buffer);
534 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
535 MC->mangleCXXCtor(CD, Ctor_Base, Out);
536 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
537 MC->mangleCXXDtor(DD, Dtor_Base, Out);
538 else
539 MC->mangleName(ND, Out);
540
David Majnemerbed356a2013-11-06 23:31:56 +0000541 if (!Buffer.empty() && Buffer.front() == '\01')
542 return Buffer.substr(1);
543 return Buffer.str();
544 } else
545 return ND->getIdentifier()->getName();
546 }
547 return "";
548 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000549 if (isa<BlockDecl>(CurrentDecl)) {
550 // For blocks we only emit something if it is enclosed in a function
551 // For top-level block we'd like to include the name of variable, but we
552 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000553 auto DC = CurrentDecl->getDeclContext();
554 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000555 return "";
556
557 SmallString<256> Buffer;
558 llvm::raw_svector_ostream Out(Buffer);
559 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
560 // For nested blocks, propagate up to the parent.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000561 Out << ComputeName(IK, DCBlock);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000562 else if (auto *DCDecl = dyn_cast<Decl>(DC))
Bruno Ricci17ff0262018-10-27 19:21:19 +0000563 Out << ComputeName(IK, DCDecl) << "_block_invoke";
Alexey Bataevec474782014-10-09 08:45:04 +0000564 return Out.str();
565 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000566 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000567 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
568 IK != FuncSig && IK != LFuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000569 return FD->getNameAsString();
570
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000571 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000572 llvm::raw_svector_ostream Out(Name);
573
574 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000575 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000576 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000577 if (MD->isStatic())
578 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000579 }
580
David Blaikiebbafb8a2012-03-11 07:00:24 +0000581 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000582 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000583 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000584
Douglas Gregor11a434a2012-04-10 20:14:15 +0000585 const FunctionDecl *Decl = FD;
586 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
587 Decl = Pattern;
588 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000589 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000590 if (FD->hasWrittenPrototype())
591 FT = dyn_cast<FunctionProtoType>(AFT);
592
Bruno Ricci17ff0262018-10-27 19:21:19 +0000593 if (IK == FuncSig || IK == LFuncSig) {
Richard Smith2f63d462017-01-09 21:40:40 +0000594 switch (AFT->getCallConv()) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000595 case CC_C: POut << "__cdecl "; break;
596 case CC_X86StdCall: POut << "__stdcall "; break;
597 case CC_X86FastCall: POut << "__fastcall "; break;
598 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000599 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000600 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000601 // Only bother printing the conventions that MSVC knows about.
602 default: break;
603 }
604 }
605
606 FD->printQualifiedName(POut, Policy);
607
Douglas Gregor11a434a2012-04-10 20:14:15 +0000608 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000609 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000610 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000611 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000612 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000613 }
614
615 if (FT->isVariadic()) {
616 if (FD->getNumParams()) POut << ", ";
617 POut << "...";
Bruno Ricci17ff0262018-10-27 19:21:19 +0000618 } else if ((IK == FuncSig || IK == LFuncSig ||
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000619 !Context.getLangOpts().CPlusPlus) &&
Richard Smithcf63b842017-01-09 22:16:16 +0000620 !Decl->getNumParams()) {
621 POut << "void";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000622 }
623 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000624 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000625
Sam Weinig4e83bd22009-12-27 01:38:20 +0000626 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Richard Smith2f63d462017-01-09 21:40:40 +0000627 assert(FT && "We must have a written prototype in this case.");
David Blaikief5697e52012-08-10 00:55:35 +0000628 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000629 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000630 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000631 POut << " volatile";
632 RefQualifierKind Ref = MD->getRefQualifier();
633 if (Ref == RQ_LValue)
634 POut << " &";
635 else if (Ref == RQ_RValue)
636 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000637 }
638
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000639 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000640 SpecsTy Specs;
641 const DeclContext *Ctx = FD->getDeclContext();
642 while (Ctx && isa<NamedDecl>(Ctx)) {
643 const ClassTemplateSpecializationDecl *Spec
644 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
645 if (Spec && !Spec->isExplicitSpecialization())
646 Specs.push_back(Spec);
647 Ctx = Ctx->getParent();
648 }
649
650 std::string TemplateParams;
651 llvm::raw_string_ostream TOut(TemplateParams);
652 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
653 I != E; ++I) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000654 const TemplateParameterList *Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000655 = (*I)->getSpecializedTemplate()->getTemplateParameters();
656 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
657 assert(Params->size() == Args.size());
658 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
659 StringRef Param = Params->getParam(i)->getName();
660 if (Param.empty()) continue;
661 TOut << Param << " = ";
662 Args.get(i).print(Policy, TOut);
663 TOut << ", ";
664 }
665 }
666
Fangrui Song6907ce22018-07-30 19:24:48 +0000667 FunctionTemplateSpecializationInfo *FSI
Douglas Gregor11a434a2012-04-10 20:14:15 +0000668 = FD->getTemplateSpecializationInfo();
669 if (FSI && !FSI->isExplicitSpecialization()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000670 const TemplateParameterList* Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000671 = FSI->getTemplate()->getTemplateParameters();
672 const TemplateArgumentList* Args = FSI->TemplateArguments;
673 assert(Params->size() == Args->size());
674 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
675 StringRef Param = Params->getParam(i)->getName();
676 if (Param.empty()) continue;
677 TOut << Param << " = ";
678 Args->get(i).print(Policy, TOut);
679 TOut << ", ";
680 }
681 }
682
683 TOut.flush();
684 if (!TemplateParams.empty()) {
685 // remove the trailing comma and space
686 TemplateParams.resize(TemplateParams.size() - 2);
687 POut << " [" << TemplateParams << "]";
688 }
689
690 POut.flush();
691
Benjamin Kramer90f54222013-08-21 11:45:27 +0000692 // Print "auto" for all deduced return types. This includes C++1y return
693 // type deduction and lambdas. For trailing return types resolve the
694 // decltype expression. Otherwise print the real type when this is
695 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000696 if (isa<CXXMethodDecl>(FD) &&
697 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000698 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000699 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
700 FT->getReturnType()
701 ->getAs<DecltypeType>()
702 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000703 .getAsStringInternal(Proto, Policy);
704 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000705 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000706
707 Out << Proto;
708
Anders Carlsson2fb08242009-09-08 18:24:21 +0000709 return Name.str().str();
710 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000711 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
712 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
713 // Skip to its enclosing function or method, but not its enclosing
714 // CapturedDecl.
715 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
716 const Decl *D = Decl::castFromDeclContext(DC);
Bruno Ricci17ff0262018-10-27 19:21:19 +0000717 return ComputeName(IK, D);
Wei Pan8d6b19a2013-08-26 14:27:34 +0000718 }
719 llvm_unreachable("CapturedDecl not inside a function or method");
720 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000721 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000722 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000723 llvm::raw_svector_ostream Out(Name);
724 Out << (MD->isInstanceMethod() ? '-' : '+');
725 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000726
727 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
728 // a null check to avoid a crash.
729 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000730 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000731
Anders Carlsson2fb08242009-09-08 18:24:21 +0000732 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000733 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000734 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000735
Anders Carlsson2fb08242009-09-08 18:24:21 +0000736 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000737 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000738 Out << ']';
739
Anders Carlsson2fb08242009-09-08 18:24:21 +0000740 return Name.str().str();
741 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000742 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000743 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
744 return "top level";
745 }
746 return "";
747}
748
Craig Topper37932912013-08-18 10:09:15 +0000749void APNumericStorage::setIntValue(const ASTContext &C,
750 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000751 if (hasAllocation())
752 C.Deallocate(pVal);
753
754 BitWidth = Val.getBitWidth();
755 unsigned NumWords = Val.getNumWords();
756 const uint64_t* Words = Val.getRawData();
757 if (NumWords > 1) {
758 pVal = new (C) uint64_t[NumWords];
759 std::copy(Words, Words + NumWords, pVal);
760 } else if (NumWords == 1)
761 VAL = Words[0];
762 else
763 VAL = 0;
764}
765
Craig Topper37932912013-08-18 10:09:15 +0000766IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000767 QualType type, SourceLocation l)
768 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
769 false, false),
770 Loc(l) {
771 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
772 assert(V.getBitWidth() == C.getIntWidth(type) &&
773 "Integer type is not the correct size for constant.");
774 setValue(C, V);
775}
776
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000777IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000778IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000779 QualType type, SourceLocation l) {
780 return new (C) IntegerLiteral(C, V, type, l);
781}
782
783IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000784IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000785 return new (C) IntegerLiteral(Empty);
786}
787
Leonard Chandb01c3a2018-06-20 17:19:40 +0000788FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
789 QualType type, SourceLocation l,
790 unsigned Scale)
791 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
792 false, false),
793 Loc(l), Scale(Scale) {
794 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
795 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
796 "Fixed point type is not the correct size for constant.");
797 setValue(C, V);
798}
799
800FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
801 const llvm::APInt &V,
802 QualType type,
803 SourceLocation l,
804 unsigned Scale) {
805 return new (C) FixedPointLiteral(C, V, type, l, Scale);
806}
807
808std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
809 // Currently the longest decimal number that can be printed is the max for an
810 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
811 // which is 43 characters.
812 SmallString<64> S;
813 FixedPointValueToString(
Leonard Chanc03642e2018-08-06 16:05:08 +0000814 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
Leonard Chandb01c3a2018-06-20 17:19:40 +0000815 return S.str();
816}
817
Craig Topper37932912013-08-18 10:09:15 +0000818FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000819 bool isexact, QualType Type, SourceLocation L)
820 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
821 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000822 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000823 FloatingLiteralBits.IsExact = isexact;
824 setValue(C, V);
825}
826
Craig Topper37932912013-08-18 10:09:15 +0000827FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000828 : Expr(FloatingLiteralClass, Empty) {
Tim Northover178723a2013-01-22 09:46:51 +0000829 setRawSemantics(IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000830 FloatingLiteralBits.IsExact = false;
831}
832
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000833FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000834FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000835 bool isexact, QualType Type, SourceLocation L) {
836 return new (C) FloatingLiteral(C, V, isexact, Type, L);
837}
838
839FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000840FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000841 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000842}
843
Tim Northover178723a2013-01-22 09:46:51 +0000844const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
845 switch(FloatingLiteralBits.Semantics) {
846 case IEEEhalf:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000847 return llvm::APFloat::IEEEhalf();
Tim Northover178723a2013-01-22 09:46:51 +0000848 case IEEEsingle:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000849 return llvm::APFloat::IEEEsingle();
Tim Northover178723a2013-01-22 09:46:51 +0000850 case IEEEdouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000851 return llvm::APFloat::IEEEdouble();
Tim Northover178723a2013-01-22 09:46:51 +0000852 case x87DoubleExtended:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000853 return llvm::APFloat::x87DoubleExtended();
Tim Northover178723a2013-01-22 09:46:51 +0000854 case IEEEquad:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000855 return llvm::APFloat::IEEEquad();
Tim Northover178723a2013-01-22 09:46:51 +0000856 case PPCDoubleDouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000857 return llvm::APFloat::PPCDoubleDouble();
Tim Northover178723a2013-01-22 09:46:51 +0000858 }
859 llvm_unreachable("Unrecognised floating semantics");
860}
861
862void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000863 if (&Sem == &llvm::APFloat::IEEEhalf())
Tim Northover178723a2013-01-22 09:46:51 +0000864 FloatingLiteralBits.Semantics = IEEEhalf;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000865 else if (&Sem == &llvm::APFloat::IEEEsingle())
Tim Northover178723a2013-01-22 09:46:51 +0000866 FloatingLiteralBits.Semantics = IEEEsingle;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000867 else if (&Sem == &llvm::APFloat::IEEEdouble())
Tim Northover178723a2013-01-22 09:46:51 +0000868 FloatingLiteralBits.Semantics = IEEEdouble;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000869 else if (&Sem == &llvm::APFloat::x87DoubleExtended())
Tim Northover178723a2013-01-22 09:46:51 +0000870 FloatingLiteralBits.Semantics = x87DoubleExtended;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000871 else if (&Sem == &llvm::APFloat::IEEEquad())
Tim Northover178723a2013-01-22 09:46:51 +0000872 FloatingLiteralBits.Semantics = IEEEquad;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000873 else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
Tim Northover178723a2013-01-22 09:46:51 +0000874 FloatingLiteralBits.Semantics = PPCDoubleDouble;
875 else
876 llvm_unreachable("Unknown floating semantics");
877}
878
Chris Lattnera0173132008-06-07 22:13:43 +0000879/// getValueAsApproximateDouble - This returns the value as an inaccurate
880/// double. Note that this may cause loss of precision, but is useful for
881/// debugging dumps, etc.
882double FloatingLiteral::getValueAsApproximateDouble() const {
883 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000884 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000885 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
Dale Johannesenc48814b2008-10-09 23:02:32 +0000886 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000887 return V.convertToDouble();
888}
889
Bruno Ricciaf214882018-11-15 16:42:14 +0000890unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
891 StringKind SK) {
892 unsigned CharByteWidth = 0;
893 switch (SK) {
894 case Ascii:
895 case UTF8:
896 CharByteWidth = Target.getCharWidth();
897 break;
898 case Wide:
899 CharByteWidth = Target.getWCharWidth();
900 break;
901 case UTF16:
902 CharByteWidth = Target.getChar16Width();
903 break;
904 case UTF32:
905 CharByteWidth = Target.getChar32Width();
906 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000907 }
908 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
909 CharByteWidth /= 8;
Bruno Ricciaf214882018-11-15 16:42:14 +0000910 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
911 "The only supported character byte widths are 1,2 and 4!");
Eli Friedmanfcec6302011-11-01 02:23:42 +0000912 return CharByteWidth;
913}
914
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000915StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
916 StringKind Kind, bool Pascal, QualType Ty,
917 const SourceLocation *Loc,
918 unsigned NumConcatenated)
919 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
920 false) {
921 assert(Ctx.getAsConstantArrayType(Ty) &&
Benjamin Kramercdac7612014-02-25 12:26:20 +0000922 "StringLiteral must be of constant array type!");
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000923 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
924 unsigned ByteLength = Str.size();
925 assert((ByteLength % CharByteWidth == 0) &&
926 "The size of the data must be a multiple of CharByteWidth!");
Benjamin Kramercdac7612014-02-25 12:26:20 +0000927
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000928 // Avoid the expensive division. The compiler should be able to figure it
929 // out by itself. However as of clang 7, even with the appropriate
930 // llvm_unreachable added just here, it is not able to do so.
931 unsigned Length;
932 switch (CharByteWidth) {
933 case 1:
934 Length = ByteLength;
935 break;
936 case 2:
937 Length = ByteLength / 2;
938 break;
939 case 4:
940 Length = ByteLength / 4;
941 break;
942 default:
943 llvm_unreachable("Unsupported character width!");
944 }
Mike Stump11289f42009-09-09 15:08:12 +0000945
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000946 StringLiteralBits.Kind = Kind;
947 StringLiteralBits.CharByteWidth = CharByteWidth;
948 StringLiteralBits.IsPascal = Pascal;
949 StringLiteralBits.NumConcatenated = NumConcatenated;
950 *getTrailingObjects<unsigned>() = Length;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000951
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000952 // Initialize the trailing array of SourceLocation.
953 // This is safe since SourceLocation is POD-like.
954 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
955 NumConcatenated * sizeof(SourceLocation));
Chris Lattnerd3e98952006-10-06 05:22:26 +0000956
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000957 // Initialize the trailing array of char holding the string data.
958 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
Chris Lattner630970d2009-02-18 05:49:11 +0000959}
960
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000961StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
962 unsigned Length, unsigned CharByteWidth)
963 : Expr(StringLiteralClass, Empty) {
964 StringLiteralBits.CharByteWidth = CharByteWidth;
965 StringLiteralBits.NumConcatenated = NumConcatenated;
966 *getTrailingObjects<unsigned>() = Length;
967}
968
969StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
970 StringKind Kind, bool Pascal, QualType Ty,
971 const SourceLocation *Loc,
972 unsigned NumConcatenated) {
973 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
974 1, NumConcatenated, Str.size()),
975 alignof(StringLiteral));
976 return new (Mem)
977 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
978}
979
980StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
981 unsigned NumConcatenated,
982 unsigned Length,
983 unsigned CharByteWidth) {
984 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
985 1, NumConcatenated, Length * CharByteWidth),
986 alignof(StringLiteral));
987 return new (Mem)
988 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
Douglas Gregor958dfc92009-04-15 16:35:07 +0000989}
990
Alexander Kornienko540bacb2013-02-01 12:35:51 +0000991void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +0000992 switch (getKind()) {
993 case Ascii: break; // no prefix.
994 case Wide: OS << 'L'; break;
995 case UTF8: OS << "u8"; break;
996 case UTF16: OS << 'u'; break;
997 case UTF32: OS << 'U'; break;
998 }
999 OS << '"';
1000 static const char Hex[] = "0123456789ABCDEF";
1001
1002 unsigned LastSlashX = getLength();
1003 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1004 switch (uint32_t Char = getCodeUnit(I)) {
1005 default:
1006 // FIXME: Convert UTF-8 back to codepoints before rendering.
1007
1008 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1009 // Leave invalid surrogates alone; we'll use \x for those.
Fangrui Song6907ce22018-07-30 19:24:48 +00001010 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
Richard Trieudc355912012-06-13 20:25:24 +00001011 Char <= 0xdbff) {
1012 uint32_t Trail = getCodeUnit(I + 1);
1013 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1014 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1015 ++I;
1016 }
1017 }
1018
1019 if (Char > 0xff) {
1020 // If this is a wide string, output characters over 0xff using \x
1021 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1022 // codepoint: use \x escapes for invalid codepoints.
1023 if (getKind() == Wide ||
1024 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1025 // FIXME: Is this the best way to print wchar_t?
1026 OS << "\\x";
1027 int Shift = 28;
1028 while ((Char >> Shift) == 0)
1029 Shift -= 4;
1030 for (/**/; Shift >= 0; Shift -= 4)
1031 OS << Hex[(Char >> Shift) & 15];
1032 LastSlashX = I;
1033 break;
1034 }
1035
1036 if (Char > 0xffff)
1037 OS << "\\U00"
1038 << Hex[(Char >> 20) & 15]
1039 << Hex[(Char >> 16) & 15];
1040 else
1041 OS << "\\u";
1042 OS << Hex[(Char >> 12) & 15]
1043 << Hex[(Char >> 8) & 15]
1044 << Hex[(Char >> 4) & 15]
1045 << Hex[(Char >> 0) & 15];
1046 break;
1047 }
1048
1049 // If we used \x... for the previous character, and this character is a
1050 // hexadecimal digit, prevent it being slurped as part of the \x.
1051 if (LastSlashX + 1 == I) {
1052 switch (Char) {
1053 case '0': case '1': case '2': case '3': case '4':
1054 case '5': case '6': case '7': case '8': case '9':
1055 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1056 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1057 OS << "\"\"";
1058 }
1059 }
1060
1061 assert(Char <= 0xff &&
1062 "Characters above 0xff should already have been handled.");
1063
Jordan Rosea7d03842013-02-08 22:30:41 +00001064 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +00001065 OS << (char)Char;
1066 else // Output anything hard as an octal escape.
1067 OS << '\\'
1068 << (char)('0' + ((Char >> 6) & 7))
1069 << (char)('0' + ((Char >> 3) & 7))
1070 << (char)('0' + ((Char >> 0) & 7));
1071 break;
1072 // Handle some common non-printable cases to make dumps prettier.
1073 case '\\': OS << "\\\\"; break;
1074 case '"': OS << "\\\""; break;
Richard Trieudc355912012-06-13 20:25:24 +00001075 case '\a': OS << "\\a"; break;
1076 case '\b': OS << "\\b"; break;
Benjamin Kramer60a53d52016-11-24 09:41:33 +00001077 case '\f': OS << "\\f"; break;
1078 case '\n': OS << "\\n"; break;
1079 case '\r': OS << "\\r"; break;
1080 case '\t': OS << "\\t"; break;
1081 case '\v': OS << "\\v"; break;
Richard Trieudc355912012-06-13 20:25:24 +00001082 }
1083 }
1084 OS << '"';
1085}
1086
Chris Lattnere925d612010-11-17 07:37:15 +00001087/// getLocationOfByte - Return a source location that points to the specified
1088/// byte of this string literal.
1089///
1090/// Strings are amazingly complex. They can be formed from multiple tokens and
1091/// can have escape sequences in them in addition to the usual trigraph and
1092/// escaped newline business. This routine handles this complexity.
1093///
Richard Smithefb116f2015-12-10 01:11:47 +00001094/// The *StartToken sets the first token to be searched in this function and
1095/// the *StartTokenByteOffset is the byte offset of the first token. Before
1096/// returning, it updates the *StartToken to the TokNo of the token being found
1097/// and sets *StartTokenByteOffset to the byte offset of the token in the
1098/// string.
1099/// Using these two parameters can reduce the time complexity from O(n^2) to
1100/// O(n) if one wants to get the location of byte for all the tokens in a
1101/// string.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001102///
Richard Smithefb116f2015-12-10 01:11:47 +00001103SourceLocation
1104StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1105 const LangOptions &Features,
1106 const TargetInfo &Target, unsigned *StartToken,
1107 unsigned *StartTokenByteOffset) const {
Bruno Ricciaf214882018-11-15 16:42:14 +00001108 assert((getKind() == StringLiteral::Ascii ||
1109 getKind() == StringLiteral::UTF8) &&
Richard Smith4060f772012-06-13 05:37:23 +00001110 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001111
Chris Lattnere925d612010-11-17 07:37:15 +00001112 // Loop over all of the tokens in this string until we find the one that
1113 // contains the byte we're looking for.
1114 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001115 unsigned StringOffset = 0;
1116 if (StartToken)
1117 TokNo = *StartToken;
1118 if (StartTokenByteOffset) {
1119 StringOffset = *StartTokenByteOffset;
1120 ByteNo -= StringOffset;
1121 }
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001122 while (1) {
Chris Lattnere925d612010-11-17 07:37:15 +00001123 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1124 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
Fangrui Song6907ce22018-07-30 19:24:48 +00001125
Chris Lattnere925d612010-11-17 07:37:15 +00001126 // Get the spelling of the string so that we can get the data that makes up
1127 // the string literal, not the identifier for the macro it is potentially
1128 // expanded through.
1129 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001130
Chris Lattnere925d612010-11-17 07:37:15 +00001131 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001132 std::pair<FileID, unsigned> LocInfo =
1133 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001134 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001135 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001136 if (Invalid) {
1137 if (StartTokenByteOffset != nullptr)
1138 *StartTokenByteOffset = StringOffset;
1139 if (StartToken != nullptr)
1140 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001141 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001142 }
1143
Chris Lattnere925d612010-11-17 07:37:15 +00001144 const char *StrData = Buffer.data()+LocInfo.second;
Fangrui Song6907ce22018-07-30 19:24:48 +00001145
Chris Lattnere925d612010-11-17 07:37:15 +00001146 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001147 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1148 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001149 Token TheTok;
1150 TheLexer.LexFromRawLexer(TheTok);
Fangrui Song6907ce22018-07-30 19:24:48 +00001151
Chris Lattnere925d612010-11-17 07:37:15 +00001152 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001153 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001154 unsigned TokNumBytes = SLP.GetStringLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00001155
Chris Lattnere925d612010-11-17 07:37:15 +00001156 // If the byte is in this token, return the location of the byte.
1157 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001158 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001159 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1160
Chris Lattnere925d612010-11-17 07:37:15 +00001161 // Now that we know the offset of the token in the spelling, use the
1162 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001163 if (StartTokenByteOffset != nullptr)
1164 *StartTokenByteOffset = StringOffset;
1165 if (StartToken != nullptr)
1166 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001167 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1168 }
Richard Smithefb116f2015-12-10 01:11:47 +00001169
Chris Lattnere925d612010-11-17 07:37:15 +00001170 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001171 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001172 ++TokNo;
1173 ByteNo -= TokNumBytes;
1174 }
1175}
1176
Chris Lattner1b926492006-08-23 06:42:10 +00001177/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1178/// corresponds to, e.g. "sizeof" or "[pre]++".
Bruno Ricci3dfcb842018-11-13 21:33:22 +00001179StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1180 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001181#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1182#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001183 }
David Blaikief47fa302012-01-17 02:30:50 +00001184 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001185}
1186
John McCalle3027922010-08-25 11:45:40 +00001187UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001188UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1189 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001190 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001191 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1192 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1193 case OO_Amp: return UO_AddrOf;
1194 case OO_Star: return UO_Deref;
1195 case OO_Plus: return UO_Plus;
1196 case OO_Minus: return UO_Minus;
1197 case OO_Tilde: return UO_Not;
1198 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001199 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001200 }
1201}
1202
1203OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1204 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001205 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1206 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1207 case UO_AddrOf: return OO_Amp;
1208 case UO_Deref: return OO_Star;
1209 case UO_Plus: return OO_Plus;
1210 case UO_Minus: return OO_Minus;
1211 case UO_Not: return OO_Tilde;
1212 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001213 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001214 default: return OO_None;
1215 }
1216}
1217
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001218
Chris Lattner0eedafe2006-08-24 04:56:27 +00001219//===----------------------------------------------------------------------===//
1220// Postfix Operators.
1221//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001222
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001223CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1224 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
Craig Topper37932912013-08-18 10:09:15 +00001225 ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001226 : Expr(SC, t, VK, OK_Ordinary, fn->isTypeDependent(),
1227 fn->isValueDependent(), fn->isInstantiationDependent(),
1228 fn->containsUnexpandedParameterPack()),
1229 NumArgs(args.size()) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001230
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001231 unsigned NumPreArgs = preargs.size();
1232 SubExprs = new (C) Stmt *[args.size()+PREARGS_START+NumPreArgs];
Douglas Gregor993603d2008-11-14 16:09:21 +00001233 SubExprs[FN] = fn;
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001234 for (unsigned i = 0; i != NumPreArgs; ++i) {
1235 updateDependenciesFromArg(preargs[i]);
1236 SubExprs[i+PREARGS_START] = preargs[i];
1237 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00001238 for (unsigned i = 0; i != args.size(); ++i) {
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001239 updateDependenciesFromArg(args[i]);
Peter Collingbourne3a347252011-02-08 21:18:02 +00001240 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00001241 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001242
Peter Collingbourne3a347252011-02-08 21:18:02 +00001243 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor993603d2008-11-14 16:09:21 +00001244 RParenLoc = rparenloc;
1245}
Nate Begeman1e36a852008-01-17 17:46:27 +00001246
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001247CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1248 ArrayRef<Expr *> args, QualType t, ExprValueKind VK,
1249 SourceLocation rparenloc)
1250 : CallExpr(C, SC, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {}
1251
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001252CallExpr::CallExpr(const ASTContext &C, Expr *fn, ArrayRef<Expr *> args,
John McCall7decc9e2010-11-18 06:31:45 +00001253 QualType t, ExprValueKind VK, SourceLocation rparenloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001254 : CallExpr(C, CallExprClass, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {
1255}
Chris Lattnere165d942006-08-24 04:40:38 +00001256
Craig Topper37932912013-08-18 10:09:15 +00001257CallExpr::CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001258 : CallExpr(C, SC, /*NumPreArgs=*/0, Empty) {}
Peter Collingbourne3a347252011-02-08 21:18:02 +00001259
Craig Topper37932912013-08-18 10:09:15 +00001260CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
Peter Collingbourne3a347252011-02-08 21:18:02 +00001261 EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001262 : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001263 // FIXME: Why do we allocate this?
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001264 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs]();
Peter Collingbourne3a347252011-02-08 21:18:02 +00001265 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregore20a2e52009-04-15 17:43:59 +00001266}
1267
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001268void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1269 if (Arg->isTypeDependent())
1270 ExprBits.TypeDependent = true;
1271 if (Arg->isValueDependent())
1272 ExprBits.ValueDependent = true;
1273 if (Arg->isInstantiationDependent())
1274 ExprBits.InstantiationDependent = true;
1275 if (Arg->containsUnexpandedParameterPack())
1276 ExprBits.ContainsUnexpandedParameterPack = true;
1277}
1278
John McCallb92ab1a2016-10-26 23:46:34 +00001279FunctionDecl *CallExpr::getDirectCallee() {
1280 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
1281}
1282
Nuno Lopes518e3702009-12-20 23:11:08 +00001283Decl *CallExpr::getCalleeDecl() {
John McCallb92ab1a2016-10-26 23:46:34 +00001284 return getCallee()->getReferencedDeclOfCallee();
1285}
1286
1287Decl *Expr::getReferencedDeclOfCallee() {
1288 Expr *CEE = IgnoreParenImpCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00001289
Douglas Gregore0e96302011-09-06 21:41:04 +00001290 while (SubstNonTypeTemplateParmExpr *NTTP
1291 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1292 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1293 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001294
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001295 // If we're calling a dereference, look at the pointer instead.
1296 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1297 if (BO->isPtrMemOp())
1298 CEE = BO->getRHS()->IgnoreParenCasts();
1299 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1300 if (UO->getOpcode() == UO_Deref)
1301 CEE = UO->getSubExpr()->IgnoreParenCasts();
1302 }
Chris Lattner52301912009-07-17 15:46:27 +00001303 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001304 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001305 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1306 return ME->getMemberDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001307
Craig Topper36250ad2014-05-12 05:36:57 +00001308 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001309}
1310
Chris Lattnere4407ed2007-12-28 05:25:02 +00001311/// setNumArgs - This changes the number of arguments present in this call.
1312/// Any orphaned expressions are deleted by this, and any new operands are set
1313/// to null.
Craig Topper37932912013-08-18 10:09:15 +00001314void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001315 // No change, just return.
1316 if (NumArgs == getNumArgs()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001317
Chris Lattnere4407ed2007-12-28 05:25:02 +00001318 // If shrinking # arguments, just delete the extras and forgot them.
1319 if (NumArgs < getNumArgs()) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001320 this->NumArgs = NumArgs;
1321 return;
1322 }
1323
1324 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001325 unsigned NumPreArgs = getNumPreArgs();
1326 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnere4407ed2007-12-28 05:25:02 +00001327 // Copy over args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001328 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnere4407ed2007-12-28 05:25:02 +00001329 NewSubExprs[i] = SubExprs[i];
1330 // Null out new args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001331 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1332 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001333 NewSubExprs[i] = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001334
Douglas Gregorba6e5572009-04-17 21:46:47 +00001335 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnere4407ed2007-12-28 05:25:02 +00001336 SubExprs = NewSubExprs;
1337 this->NumArgs = NumArgs;
1338}
1339
Alp Tokera724cff2013-12-28 21:59:02 +00001340/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001341/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001342unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001343 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001344 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001345 // ImplicitCastExpr.
1346 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1347 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001348 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001349
Steve Narofff6e3b3292008-01-31 01:07:12 +00001350 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1351 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001352 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001353
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001354 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1355 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001356 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001357
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001358 if (!FDecl->getIdentifier())
1359 return 0;
1360
Douglas Gregor15fc9562009-09-12 00:22:50 +00001361 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001362}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001363
Scott Douglass503fc392015-06-10 13:53:15 +00001364bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001365 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001366 return Ctx.BuiltinInfo.isUnevaluated(BI);
1367 return false;
1368}
1369
David Majnemerced8bdf2015-02-25 17:36:15 +00001370QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1371 const Expr *Callee = getCallee();
1372 QualType CalleeType = Callee->getType();
1373 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001374 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001375 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001376 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001377 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1378 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1379 return Ctx.VoidTy;
1380
John McCall0009fcc2011-04-26 20:42:42 +00001381 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001382 CalleeType = Expr::findBoundMemberType(Callee);
1383 }
1384
John McCall0009fcc2011-04-26 20:42:42 +00001385 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001386 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001387}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001388
Stephen Kelly724e9e52018-08-09 20:05:03 +00001389SourceLocation CallExpr::getBeginLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001390 if (isa<CXXOperatorCallExpr>(this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001391 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001392
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001393 SourceLocation begin = getCallee()->getBeginLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001394 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001395 begin = getArg(0)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001396 return begin;
1397}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001398SourceLocation CallExpr::getEndLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001399 if (isa<CXXOperatorCallExpr>(this))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001400 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001401
1402 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001403 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001404 end = getArg(getNumArgs() - 1)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001405 return end;
1406}
John McCall701417a2011-02-21 06:23:05 +00001407
Craig Topper37932912013-08-18 10:09:15 +00001408OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001409 SourceLocation OperatorLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001410 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001411 ArrayRef<OffsetOfNode> comps,
1412 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001413 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001414 void *Mem = C.Allocate(
1415 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001416
Benjamin Kramerc215e762012-08-24 11:54:20 +00001417 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1418 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001419}
1420
Craig Topper37932912013-08-18 10:09:15 +00001421OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001422 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001423 void *Mem =
1424 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001425 return new (Mem) OffsetOfExpr(numComps, numExprs);
1426}
1427
Craig Topper37932912013-08-18 10:09:15 +00001428OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001429 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001430 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001431 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001432 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
Fangrui Song6907ce22018-07-30 19:24:48 +00001433 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001434 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001435 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001436 tsi->getType()->containsUnexpandedParameterPack()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001437 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001438 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001439{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001440 for (unsigned i = 0; i != comps.size(); ++i) {
1441 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001442 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001443
Benjamin Kramerc215e762012-08-24 11:54:20 +00001444 for (unsigned i = 0; i != exprs.size(); ++i) {
1445 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001446 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001447 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001448 ExprBits.ContainsUnexpandedParameterPack = true;
1449
Benjamin Kramerc215e762012-08-24 11:54:20 +00001450 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001451 }
1452}
1453
James Y Knight7281c352015-12-29 22:31:18 +00001454IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001455 assert(getKind() == Field || getKind() == Identifier);
1456 if (getKind() == Field)
1457 return getField()->getIdentifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00001458
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001459 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001460}
1461
David Majnemer10fd83d2015-01-15 10:04:14 +00001462UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1463 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1464 SourceLocation op, SourceLocation rp)
1465 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1466 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1467 // Value-dependent if the argument is type-dependent.
1468 E->isTypeDependent(), E->isInstantiationDependent(),
1469 E->containsUnexpandedParameterPack()),
1470 OpLoc(op), RParenLoc(rp) {
1471 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1472 UnaryExprOrTypeTraitExprBits.IsType = false;
1473 Argument.Ex = E;
1474
1475 // Check to see if we are in the situation where alignof(decl) should be
1476 // dependent because decl's alignment is dependent.
Richard Smith6822bd72018-10-26 19:26:45 +00001477 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
David Majnemer10fd83d2015-01-15 10:04:14 +00001478 if (!isValueDependent() || !isInstantiationDependent()) {
1479 E = E->IgnoreParens();
1480
1481 const ValueDecl *D = nullptr;
1482 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1483 D = DRE->getDecl();
1484 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1485 D = ME->getMemberDecl();
1486
1487 if (D) {
1488 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1489 if (I->isAlignmentDependent()) {
1490 setValueDependent(true);
1491 setInstantiationDependent(true);
1492 break;
1493 }
1494 }
1495 }
1496 }
1497 }
1498}
1499
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001500MemberExpr *MemberExpr::Create(
1501 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1502 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1503 ValueDecl *memberdecl, DeclAccessPair founddecl,
1504 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1505 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001506
Douglas Gregorea972d32011-02-28 21:54:11 +00001507 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001508 founddecl.getDecl() != memberdecl ||
1509 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001510
James Y Knighte7d82282015-12-29 18:15:14 +00001511 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1512 std::size_t Size =
1513 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1514 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1515 HasTemplateKWAndArgsInfo ? 1 : 0,
1516 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001517
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001518 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001519 MemberExpr *E = new (Mem)
1520 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001521
1522 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001523 // FIXME: Wrong. We should be looking at the member declaration we found.
1524 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001525 E->setValueDependent(true);
1526 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001527 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001528 }
1529 else if (QualifierLoc &&
1530 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001531 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001532
Bruno Ricci4c742532018-11-15 13:56:22 +00001533 E->MemberExprBits.HasQualifierOrFoundDecl = true;
John McCall16df1e52010-03-30 21:47:33 +00001534
James Y Knighte7d82282015-12-29 18:15:14 +00001535 MemberExprNameQualifier *NQ =
1536 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001537 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001538 NQ->FoundDecl = founddecl;
1539 }
1540
Bruno Ricci4c742532018-11-15 13:56:22 +00001541 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1542 (targs || TemplateKWLoc.isValid());
Abramo Bagnara7945c982012-01-27 09:46:47 +00001543
John McCall16df1e52010-03-30 21:47:33 +00001544 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001545 bool Dependent = false;
1546 bool InstantiationDependent = false;
1547 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001548 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1549 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1550 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001551 if (InstantiationDependent)
1552 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001553 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001554 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1555 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001556 }
1557
1558 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001559}
1560
Stephen Kelly724e9e52018-08-09 20:05:03 +00001561SourceLocation MemberExpr::getBeginLoc() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001562 if (isImplicitAccess()) {
1563 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001564 return getQualifierLoc().getBeginLoc();
1565 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001566 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001567
Daniel Dunbarb507f272012-03-09 15:39:15 +00001568 // FIXME: We don't want this to happen. Rather, we should be able to
1569 // detect all kinds of implicit accesses more cleanly.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001570 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001571 if (BaseStartLoc.isValid())
1572 return BaseStartLoc;
1573 return MemberLoc;
1574}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001575SourceLocation MemberExpr::getEndLoc() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001576 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001577 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001578 EndLoc = getRAngleLoc();
1579 else if (EndLoc.isInvalid())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001580 EndLoc = getBase()->getEndLoc();
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001581 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001582}
1583
Alp Tokerc1086762013-12-07 13:51:35 +00001584bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001585 switch (getCastKind()) {
1586 case CK_DerivedToBase:
1587 case CK_UncheckedDerivedToBase:
1588 case CK_DerivedToBaseMemberPointer:
1589 case CK_BaseToDerived:
1590 case CK_BaseToDerivedMemberPointer:
1591 assert(!path_empty() && "Cast kind should have a base path!");
1592 break;
1593
1594 case CK_CPointerToObjCPointerCast:
1595 assert(getType()->isObjCObjectPointerType());
1596 assert(getSubExpr()->getType()->isPointerType());
1597 goto CheckNoBasePath;
1598
1599 case CK_BlockPointerToObjCPointerCast:
1600 assert(getType()->isObjCObjectPointerType());
1601 assert(getSubExpr()->getType()->isBlockPointerType());
1602 goto CheckNoBasePath;
1603
John McCallc62bb392012-02-15 01:22:51 +00001604 case CK_ReinterpretMemberPointer:
1605 assert(getType()->isMemberPointerType());
1606 assert(getSubExpr()->getType()->isMemberPointerType());
1607 goto CheckNoBasePath;
1608
John McCall9320b872011-09-09 05:25:32 +00001609 case CK_BitCast:
1610 // Arbitrary casts to C pointer types count as bitcasts.
1611 // Otherwise, we should only have block and ObjC pointer casts
1612 // here if they stay within the type kind.
1613 if (!getType()->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001614 assert(getType()->isObjCObjectPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001615 getSubExpr()->getType()->isObjCObjectPointerType());
Fangrui Song6907ce22018-07-30 19:24:48 +00001616 assert(getType()->isBlockPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001617 getSubExpr()->getType()->isBlockPointerType());
1618 }
1619 goto CheckNoBasePath;
1620
1621 case CK_AnyPointerToBlockPointerCast:
1622 assert(getType()->isBlockPointerType());
1623 assert(getSubExpr()->getType()->isAnyPointerType() &&
1624 !getSubExpr()->getType()->isBlockPointerType());
1625 goto CheckNoBasePath;
1626
Douglas Gregored90df32012-02-22 05:02:47 +00001627 case CK_CopyAndAutoreleaseBlockObject:
1628 assert(getType()->isBlockPointerType());
1629 assert(getSubExpr()->getType()->isBlockPointerType());
1630 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001631
1632 case CK_FunctionToPointerDecay:
1633 assert(getType()->isPointerType());
1634 assert(getSubExpr()->getType()->isFunctionType());
1635 goto CheckNoBasePath;
1636
Anastasia Stulova04307942018-11-16 16:22:56 +00001637 case CK_AddressSpaceConversion: {
1638 auto Ty = getType();
1639 auto SETy = getSubExpr()->getType();
1640 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1641 if (!isGLValue())
1642 Ty = Ty->getPointeeType();
1643 if (!isGLValue())
1644 SETy = SETy->getPointeeType();
1645 assert(!Ty.isNull() && !SETy.isNull() &&
1646 Ty.getAddressSpace() != SETy.getAddressSpace());
1647 goto CheckNoBasePath;
1648 }
John McCall9320b872011-09-09 05:25:32 +00001649 // These should not have an inheritance path.
1650 case CK_Dynamic:
1651 case CK_ToUnion:
1652 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001653 case CK_NullToMemberPointer:
1654 case CK_NullToPointer:
1655 case CK_ConstructorConversion:
1656 case CK_IntegralToPointer:
1657 case CK_PointerToIntegral:
1658 case CK_ToVoid:
1659 case CK_VectorSplat:
1660 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001661 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001662 case CK_IntegralToFloating:
1663 case CK_FloatingToIntegral:
1664 case CK_FloatingCast:
1665 case CK_ObjCObjectLValueCast:
1666 case CK_FloatingRealToComplex:
1667 case CK_FloatingComplexToReal:
1668 case CK_FloatingComplexCast:
1669 case CK_FloatingComplexToIntegralComplex:
1670 case CK_IntegralRealToComplex:
1671 case CK_IntegralComplexToReal:
1672 case CK_IntegralComplexCast:
1673 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001674 case CK_ARCProduceObject:
1675 case CK_ARCConsumeObject:
1676 case CK_ARCReclaimReturnedObject:
1677 case CK_ARCExtendBlockObject:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001678 case CK_ZeroToOCLOpaqueType:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001679 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00001680 case CK_FixedPointCast:
John McCall9320b872011-09-09 05:25:32 +00001681 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1682 goto CheckNoBasePath;
1683
1684 case CK_Dependent:
1685 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001686 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001687 case CK_AtomicToNonAtomic:
1688 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001689 case CK_PointerToBoolean:
1690 case CK_IntegralToBoolean:
1691 case CK_FloatingToBoolean:
1692 case CK_MemberPointerToBoolean:
1693 case CK_FloatingComplexToBoolean:
1694 case CK_IntegralComplexToBoolean:
1695 case CK_LValueBitCast: // -> bool&
1696 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001697 case CK_BuiltinFnToFnPtr:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001698 case CK_FixedPointToBoolean:
John McCall9320b872011-09-09 05:25:32 +00001699 CheckNoBasePath:
1700 assert(path_empty() && "Cast kind should not have a base path!");
1701 break;
1702 }
Alp Tokerc1086762013-12-07 13:51:35 +00001703 return true;
John McCall9320b872011-09-09 05:25:32 +00001704}
1705
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001706const char *CastExpr::getCastKindName(CastKind CK) {
1707 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001708#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1709#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001710 }
John McCallc5e62b42010-11-13 09:02:35 +00001711 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001712}
1713
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001714namespace {
Richard Smith1ef75542018-06-27 20:30:34 +00001715 const Expr *skipImplicitTemporary(const Expr *E) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001716 // Skip through reference binding to temporary.
Richard Smith1ef75542018-06-27 20:30:34 +00001717 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1718 E = Materialize->GetTemporaryExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001719
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001720 // Skip any temporary bindings; they're implicit.
Richard Smith1ef75542018-06-27 20:30:34 +00001721 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1722 E = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001723
Richard Smith1ef75542018-06-27 20:30:34 +00001724 return E;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001725 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001726}
1727
Douglas Gregord196a582009-12-14 19:27:10 +00001728Expr *CastExpr::getSubExprAsWritten() {
Richard Smith1ef75542018-06-27 20:30:34 +00001729 const Expr *SubExpr = nullptr;
1730 const CastExpr *E = this;
Douglas Gregord196a582009-12-14 19:27:10 +00001731 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001732 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001733
Douglas Gregord196a582009-12-14 19:27:10 +00001734 // Conversions by constructor and conversion functions have a
1735 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001736 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001737 SubExpr =
1738 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001739 else if (E->getCastKind() == CK_UserDefinedConversion) {
1740 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1741 isa<BlockExpr>(SubExpr)) &&
1742 "Unexpected SubExpr for CK_UserDefinedConversion.");
Richard Smith1ef75542018-06-27 20:30:34 +00001743 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1744 SubExpr = MCE->getImplicitObjectArgument();
Manman Ren8abc2e52016-02-02 22:23:03 +00001745 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001746
Douglas Gregord196a582009-12-14 19:27:10 +00001747 // If the subexpression we're left with is an implicit cast, look
1748 // through that, too.
Fangrui Song6907ce22018-07-30 19:24:48 +00001749 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1750
Richard Smith1ef75542018-06-27 20:30:34 +00001751 return const_cast<Expr*>(SubExpr);
1752}
1753
1754NamedDecl *CastExpr::getConversionFunction() const {
1755 const Expr *SubExpr = nullptr;
1756
1757 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1758 SubExpr = skipImplicitTemporary(E->getSubExpr());
1759
1760 if (E->getCastKind() == CK_ConstructorConversion)
1761 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1762
1763 if (E->getCastKind() == CK_UserDefinedConversion) {
1764 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1765 return MCE->getMethodDecl();
1766 }
1767 }
1768
1769 return nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001770}
1771
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001772CastExpr::BasePathSizeTy *CastExpr::BasePathSize() {
1773 assert(!path_empty());
1774 switch (getStmtClass()) {
1775#define ABSTRACT_STMT(x)
1776#define CASTEXPR(Type, Base) \
1777 case Stmt::Type##Class: \
1778 return static_cast<Type *>(this) \
1779 ->getTrailingObjects<CastExpr::BasePathSizeTy>();
1780#define STMT(Type, Base)
1781#include "clang/AST/StmtNodes.inc"
1782 default:
1783 llvm_unreachable("non-cast expressions not possible here");
1784 }
1785}
1786
John McCallcf142162010-08-07 06:22:56 +00001787CXXBaseSpecifier **CastExpr::path_buffer() {
1788 switch (getStmtClass()) {
1789#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001790#define CASTEXPR(Type, Base) \
1791 case Stmt::Type##Class: \
1792 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001793#define STMT(Type, Base)
1794#include "clang/AST/StmtNodes.inc"
1795 default:
1796 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001797 }
1798}
1799
John McCallf1ef7962017-08-15 21:42:47 +00001800const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1801 QualType opType) {
1802 auto RD = unionType->castAs<RecordType>()->getDecl();
1803 return getTargetFieldForToUnionCast(RD, opType);
1804}
1805
1806const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1807 QualType OpType) {
1808 auto &Ctx = RD->getASTContext();
1809 RecordDecl::field_iterator Field, FieldEnd;
1810 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1811 Field != FieldEnd; ++Field) {
1812 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1813 !Field->isUnnamedBitfield()) {
1814 return *Field;
1815 }
1816 }
1817 return nullptr;
1818}
1819
Craig Topper37932912013-08-18 10:09:15 +00001820ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001821 CastKind Kind, Expr *Operand,
1822 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001823 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001824 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001825 void *Buffer =
1826 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1827 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001828 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001829 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001830 if (PathSize)
1831 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1832 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001833 return E;
1834}
1835
Craig Topper37932912013-08-18 10:09:15 +00001836ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001837 unsigned PathSize) {
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001838 void *Buffer =
1839 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1840 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001841 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1842}
1843
1844
Craig Topper37932912013-08-18 10:09:15 +00001845CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001846 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001847 const CXXCastPath *BasePath,
1848 TypeSourceInfo *WrittenTy,
1849 SourceLocation L, SourceLocation R) {
1850 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001851 void *Buffer =
1852 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1853 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001854 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001855 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001856 if (PathSize)
1857 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1858 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001859 return E;
1860}
1861
Craig Topper37932912013-08-18 10:09:15 +00001862CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1863 unsigned PathSize) {
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001864 void *Buffer =
1865 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1866 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001867 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1868}
1869
Chris Lattner1b926492006-08-23 06:42:10 +00001870/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1871/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001872StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001873 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001874#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1875#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001876 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001877 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001878}
Steve Naroff47500512007-04-19 23:00:49 +00001879
John McCalle3027922010-08-25 11:45:40 +00001880BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001881BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1882 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001883 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001884 case OO_Plus: return BO_Add;
1885 case OO_Minus: return BO_Sub;
1886 case OO_Star: return BO_Mul;
1887 case OO_Slash: return BO_Div;
1888 case OO_Percent: return BO_Rem;
1889 case OO_Caret: return BO_Xor;
1890 case OO_Amp: return BO_And;
1891 case OO_Pipe: return BO_Or;
1892 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00001893 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00001894 case OO_Less: return BO_LT;
1895 case OO_Greater: return BO_GT;
1896 case OO_PlusEqual: return BO_AddAssign;
1897 case OO_MinusEqual: return BO_SubAssign;
1898 case OO_StarEqual: return BO_MulAssign;
1899 case OO_SlashEqual: return BO_DivAssign;
1900 case OO_PercentEqual: return BO_RemAssign;
1901 case OO_CaretEqual: return BO_XorAssign;
1902 case OO_AmpEqual: return BO_AndAssign;
1903 case OO_PipeEqual: return BO_OrAssign;
1904 case OO_LessLess: return BO_Shl;
1905 case OO_GreaterGreater: return BO_Shr;
1906 case OO_LessLessEqual: return BO_ShlAssign;
1907 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1908 case OO_EqualEqual: return BO_EQ;
1909 case OO_ExclaimEqual: return BO_NE;
1910 case OO_LessEqual: return BO_LE;
1911 case OO_GreaterEqual: return BO_GE;
1912 case OO_AmpAmp: return BO_LAnd;
1913 case OO_PipePipe: return BO_LOr;
1914 case OO_Comma: return BO_Comma;
1915 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001916 }
1917}
1918
1919OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1920 static const OverloadedOperatorKind OverOps[] = {
1921 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1922 OO_Star, OO_Slash, OO_Percent,
1923 OO_Plus, OO_Minus,
1924 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00001925 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001926 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1927 OO_EqualEqual, OO_ExclaimEqual,
1928 OO_Amp,
1929 OO_Caret,
1930 OO_Pipe,
1931 OO_AmpAmp,
1932 OO_PipePipe,
1933 OO_Equal, OO_StarEqual,
1934 OO_SlashEqual, OO_PercentEqual,
1935 OO_PlusEqual, OO_MinusEqual,
1936 OO_LessLessEqual, OO_GreaterGreaterEqual,
1937 OO_AmpEqual, OO_CaretEqual,
1938 OO_PipeEqual,
1939 OO_Comma
1940 };
1941 return OverOps[Opc];
1942}
1943
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001944bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
1945 Opcode Opc,
1946 Expr *LHS, Expr *RHS) {
1947 if (Opc != BO_Add)
1948 return false;
1949
1950 // Check that we have one pointer and one integer operand.
1951 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001952 if (LHS->getType()->isPointerType()) {
1953 if (!RHS->getType()->isIntegerType())
1954 return false;
1955 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001956 } else if (RHS->getType()->isPointerType()) {
1957 if (!LHS->getType()->isIntegerType())
1958 return false;
1959 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001960 } else {
1961 return false;
1962 }
1963
1964 // Check that the pointer is a nullptr.
1965 if (!PExp->IgnoreParenCasts()
1966 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
1967 return false;
1968
1969 // Check that the pointee type is char-sized.
1970 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1971 if (!PTy || !PTy->getPointeeType()->isCharType())
1972 return false;
1973
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001974 return true;
1975}
Craig Topper37932912013-08-18 10:09:15 +00001976InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001977 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001978 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1979 false, false),
1980 InitExprs(C, initExprs.size()),
1981 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
1982{
Sebastian Redlc83ed822012-02-17 08:42:25 +00001983 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00001984 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001985 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00001986 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00001987 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00001988 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00001989 if (initExprs[I]->isInstantiationDependent())
1990 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00001991 if (initExprs[I]->containsUnexpandedParameterPack())
1992 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00001993 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001994
Benjamin Kramerc215e762012-08-24 11:54:20 +00001995 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00001996}
Chris Lattner1ec5f562007-06-27 05:38:08 +00001997
Craig Topper37932912013-08-18 10:09:15 +00001998void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001999 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00002000 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002001}
2002
Craig Topper37932912013-08-18 10:09:15 +00002003void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00002004 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002005}
2006
Craig Topper37932912013-08-18 10:09:15 +00002007Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002008 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00002009 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00002010 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00002011 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002012 }
Mike Stump11289f42009-09-09 15:08:12 +00002013
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002014 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00002015 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002016 return Result;
2017}
2018
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002019void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00002020 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002021 ArrayFillerOrUnionFieldInit = filler;
2022 // Fill out any "holes" in the array due to designated initializers.
2023 Expr **inits = getInits();
2024 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00002025 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002026 inits[i] = filler;
2027}
2028
Richard Smith9ec1e482012-04-15 02:50:59 +00002029bool InitListExpr::isStringLiteralInit() const {
2030 if (getNumInits() != 1)
2031 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00002032 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2033 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00002034 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00002035 // It is possible for getInit() to return null.
2036 const Expr *Init = getInit(0);
2037 if (!Init)
2038 return false;
2039 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00002040 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2041}
2042
Richard Smith122f88d2016-12-06 23:52:28 +00002043bool InitListExpr::isTransparent() const {
2044 assert(isSemanticForm() && "syntactic form never semantically transparent");
2045
2046 // A glvalue InitListExpr is always just sugar.
2047 if (isGLValue()) {
2048 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2049 return true;
2050 }
2051
2052 // Otherwise, we're sugar if and only if we have exactly one initializer that
2053 // is of the same type.
2054 if (getNumInits() != 1 || !getInit(0))
2055 return false;
2056
Richard Smith382bc512017-02-23 22:41:47 +00002057 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2058 // transparent struct copy.
2059 if (!getInit(0)->isRValue() && getType()->isRecordType())
2060 return false;
2061
Richard Smith122f88d2016-12-06 23:52:28 +00002062 return getType().getCanonicalType() ==
2063 getInit(0)->getType().getCanonicalType();
2064}
2065
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002066bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2067 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2068
2069 if (LangOpts.CPlusPlus || getNumInits() != 1) {
2070 return false;
2071 }
2072
2073 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
2074 return Lit && Lit->getValue() == 0;
2075}
2076
Stephen Kelly724e9e52018-08-09 20:05:03 +00002077SourceLocation InitListExpr::getBeginLoc() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00002078 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002079 return SyntacticForm->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002080 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002081 if (Beg.isInvalid()) {
2082 // Find the first non-null initializer.
2083 for (InitExprsTy::const_iterator I = InitExprs.begin(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002084 E = InitExprs.end();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002085 I != E; ++I) {
2086 if (Stmt *S = *I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002087 Beg = S->getBeginLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002088 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002089 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002090 }
2091 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002092 return Beg;
2093}
2094
Stephen Kelly02a67ba2018-08-09 20:05:47 +00002095SourceLocation InitListExpr::getEndLoc() const {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002096 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002097 return SyntacticForm->getEndLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002098 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002099 if (End.isInvalid()) {
2100 // Find the first non-null initializer from the end.
2101 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002102 E = InitExprs.rend();
2103 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002104 if (Stmt *S = *I) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002105 End = S->getEndLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002106 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002107 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002108 }
2109 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002110 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002111}
2112
Steve Naroff991e99d2008-09-04 15:31:07 +00002113/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002114///
John McCallc833dea2012-02-17 03:32:35 +00002115const FunctionProtoType *BlockExpr::getFunctionType() const {
2116 // The block pointer is never sugared, but the function type might be.
2117 return cast<BlockPointerType>(getType())
2118 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002119}
2120
Mike Stump11289f42009-09-09 15:08:12 +00002121SourceLocation BlockExpr::getCaretLocation() const {
2122 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002123}
Mike Stump11289f42009-09-09 15:08:12 +00002124const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002125 return TheBlock->getBody();
2126}
Mike Stump11289f42009-09-09 15:08:12 +00002127Stmt *BlockExpr::getBody() {
2128 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002129}
Steve Naroff415d3d52008-10-08 17:01:13 +00002130
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002131
Chris Lattner1ec5f562007-06-27 05:38:08 +00002132//===----------------------------------------------------------------------===//
2133// Generic Expression Routines
2134//===----------------------------------------------------------------------===//
2135
Chris Lattner237f2752009-02-14 07:37:35 +00002136/// isUnusedResultAWarning - Return true if this immediate expression should
2137/// be warned about if the result is unused. If so, fill in Loc and Ranges
2138/// with location to warn on and the source range[s] to report with the
2139/// warning.
Fangrui Song6907ce22018-07-30 19:24:48 +00002140bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
Eli Friedmanc11535c2012-05-24 00:47:05 +00002141 SourceRange &R1, SourceRange &R2,
2142 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002143 // Don't warn if the expr is type dependent. The type could end up
2144 // instantiating to void.
2145 if (isTypeDependent())
2146 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002147
Chris Lattner1ec5f562007-06-27 05:38:08 +00002148 switch (getStmtClass()) {
2149 default:
John McCallc493a732010-03-12 07:11:26 +00002150 if (getType()->isVoidType())
2151 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002152 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002153 Loc = getExprLoc();
2154 R1 = getSourceRange();
2155 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002156 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002157 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002158 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002159 case GenericSelectionExprClass:
2160 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002161 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002162 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002163 case CoyieldExprClass:
2164 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002165 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002166 case ChooseExprClass:
2167 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2168 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002169 case UnaryOperatorClass: {
2170 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002171
Chris Lattner1ec5f562007-06-27 05:38:08 +00002172 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002173 case UO_Plus:
2174 case UO_Minus:
2175 case UO_AddrOf:
2176 case UO_Not:
2177 case UO_LNot:
2178 case UO_Deref:
2179 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002180 case UO_Coawait:
2181 // This is just the 'operator co_await' call inside the guts of a
2182 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002183 case UO_PostInc:
2184 case UO_PostDec:
2185 case UO_PreInc:
2186 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002187 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002188 case UO_Real:
2189 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002190 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002191 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2192 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002193 return false;
2194 break;
John McCalle3027922010-08-25 11:45:40 +00002195 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002196 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002197 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002198 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002199 Loc = UO->getOperatorLoc();
2200 R1 = UO->getSubExpr()->getSourceRange();
2201 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002202 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002203 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002204 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002205 switch (BO->getOpcode()) {
2206 default:
2207 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002208 // Consider the RHS of comma for side effects. LHS was checked by
2209 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002210 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002211 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2212 // lvalue-ness) of an assignment written in a macro.
2213 if (IntegerLiteral *IE =
2214 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2215 if (IE->getValue() == 0)
2216 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002217 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002218 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002219 case BO_LAnd:
2220 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002221 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2222 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002223 return false;
2224 break;
John McCall1e3715a2010-02-16 04:10:53 +00002225 }
Chris Lattner237f2752009-02-14 07:37:35 +00002226 if (BO->isAssignmentOp())
2227 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002228 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002229 Loc = BO->getOperatorLoc();
2230 R1 = BO->getLHS()->getSourceRange();
2231 R2 = BO->getRHS()->getSourceRange();
2232 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002233 }
Chris Lattner86928112007-08-25 02:00:02 +00002234 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002235 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002236 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002237 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002238
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002239 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002240 // If only one of the LHS or RHS is a warning, the operator might
2241 // be being used for control flow. Only warn if both the LHS and
2242 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002243 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002244 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00002245 return false;
2246 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00002247 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002248 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002249 }
2250
Chris Lattnera44d1162007-06-27 05:58:59 +00002251 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002252 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002253 Loc = cast<MemberExpr>(this)->getMemberLoc();
2254 R1 = SourceRange(Loc, Loc);
2255 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2256 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002257
Chris Lattner1ec5f562007-06-27 05:38:08 +00002258 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002259 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002260 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2261 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2262 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2263 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002264
Chandler Carruth46339472011-08-17 09:49:44 +00002265 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002266 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002267 // overloads as there is no reasonable way to define these such that they
2268 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002269 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002270 // provides additional value as well. If this list is updated,
2271 // DiagnoseUnusedComparison should be as well.
2272 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002273 switch (Op->getOperator()) {
2274 default:
2275 break;
2276 case OO_EqualEqual:
2277 case OO_ExclaimEqual:
2278 case OO_Less:
2279 case OO_Greater:
2280 case OO_GreaterEqual:
2281 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002282 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2283 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002284 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002285 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002286 Loc = Op->getOperatorLoc();
2287 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002288 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002289 }
Chandler Carruth46339472011-08-17 09:49:44 +00002290
2291 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002292 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002293 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002294 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002295 case CXXMemberCallExprClass:
2296 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002297 // If this is a direct call, get the callee.
2298 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002299 if (const Decl *FD = CE->getCalleeDecl()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002300 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2301 bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2302 : FD->hasAttr<WarnUnusedResultAttr>();
2303
Chris Lattner237f2752009-02-14 07:37:35 +00002304 // If the callee has attribute pure, const, or warn_unused_result, warn
2305 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002306 //
2307 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2308 // updated to match for QoI.
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002309 if (HasWarnUnusedResultAttr ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002310 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002311 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002312 Loc = CE->getCallee()->getBeginLoc();
Chris Lattner1a6babf2009-10-13 04:53:48 +00002313 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002314
Chris Lattner1a6babf2009-10-13 04:53:48 +00002315 if (unsigned NumArgs = CE->getNumArgs())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002316 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002317 CE->getArg(NumArgs - 1)->getEndLoc());
Chris Lattner1a6babf2009-10-13 04:53:48 +00002318 return true;
2319 }
Chris Lattner237f2752009-02-14 07:37:35 +00002320 }
2321 return false;
2322 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002323
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002324 // If we don't know precisely what we're looking at, let's not warn.
2325 case UnresolvedLookupExprClass:
2326 case CXXUnresolvedConstructExprClass:
2327 return false;
2328
Anders Carlsson6aa50392009-11-17 17:11:23 +00002329 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002330 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002331 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2332 if (Type->hasAttr<WarnUnusedAttr>()) {
2333 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002334 Loc = getBeginLoc();
Lubos Lunak1f490f32013-07-21 13:15:58 +00002335 R1 = getSourceRange();
2336 return true;
2337 }
2338 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002339 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002340 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002341
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002342 case ObjCMessageExprClass: {
2343 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002344 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002345 ME->isInstanceMessage() &&
2346 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002347 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002348 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002349 Loc = getExprLoc();
2350 R1 = ME->getSourceRange();
2351 return true;
2352 }
2353
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002354 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002355 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002356 WarnE = this;
2357 Loc = getExprLoc();
2358 return true;
2359 }
2360
Chris Lattner237f2752009-02-14 07:37:35 +00002361 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002362 }
Mike Stump11289f42009-09-09 15:08:12 +00002363
John McCallb7bd14f2010-12-02 01:19:52 +00002364 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002365 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002366 Loc = getExprLoc();
2367 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002368 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002369
John McCallfe96e0b2011-11-06 09:01:30 +00002370 case PseudoObjectExprClass: {
2371 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2372
2373 // Only complain about things that have the form of a getter.
2374 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2375 isa<BinaryOperator>(PO->getSyntacticForm()))
2376 return false;
2377
Eli Friedmanc11535c2012-05-24 00:47:05 +00002378 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002379 Loc = getExprLoc();
2380 R1 = getSourceRange();
2381 return true;
2382 }
2383
Chris Lattner944d3062008-07-26 19:51:01 +00002384 case StmtExprClass: {
2385 // Statement exprs don't logically have side effects themselves, but are
2386 // sometimes used in macros in ways that give them a type that is unused.
2387 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2388 // however, if the result of the stmt expr is dead, we don't want to emit a
2389 // warning.
2390 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002391 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002392 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002393 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002394 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2395 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002396 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002397 }
Mike Stump11289f42009-09-09 15:08:12 +00002398
John McCallc493a732010-03-12 07:11:26 +00002399 if (getType()->isVoidType())
2400 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002401 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002402 Loc = cast<StmtExpr>(this)->getLParenLoc();
2403 R1 = getSourceRange();
2404 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002405 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002406 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002407 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002408 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002409 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002410 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002411 if (CE->getCastKind() == CK_ToVoid) {
2412 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002413 CE->getSubExpr()->getType().isVolatileQualified()) {
2414 const DeclRefExpr *DRE =
2415 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2416 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002417 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2418 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002419 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2420 R1, R2, Ctx);
2421 }
2422 }
Chris Lattner2706a552009-07-28 18:25:28 +00002423 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002424 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002425
Eli Friedmanc11535c2012-05-24 00:47:05 +00002426 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002427 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002428 if (CE->getCastKind() == CK_ConstructorConversion)
2429 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002430
Eli Friedmanc11535c2012-05-24 00:47:05 +00002431 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002432 if (const CXXFunctionalCastExpr *CXXCE =
2433 dyn_cast<CXXFunctionalCastExpr>(this)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002434 Loc = CXXCE->getBeginLoc();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002435 R1 = CXXCE->getSubExpr()->getSourceRange();
2436 } else {
2437 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2438 Loc = CStyleCE->getLParenLoc();
2439 R1 = CStyleCE->getSubExpr()->getSourceRange();
2440 }
Chris Lattner237f2752009-02-14 07:37:35 +00002441 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002442 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002443 case ImplicitCastExprClass: {
2444 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002445
Eli Friedmanc11535c2012-05-24 00:47:05 +00002446 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2447 if (ICE->getCastKind() == CK_LValueToRValue &&
2448 ICE->getSubExpr()->getType().isVolatileQualified())
2449 return false;
2450
2451 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2452 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002453 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002454 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002455 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002456 case CXXDefaultInitExprClass:
2457 return (cast<CXXDefaultInitExpr>(this)
2458 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002459
2460 case CXXNewExprClass:
2461 // FIXME: In theory, there might be new expressions that don't have side
2462 // effects (e.g. a placement new with an uninitialized POD).
2463 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002464 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002465 case MaterializeTemporaryExprClass:
2466 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2467 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002468 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002469 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2470 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002471 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002472 return cast<ExprWithCleanups>(this)->getSubExpr()
2473 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002474 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002475}
2476
Fariborz Jahanian07735332009-02-22 18:40:18 +00002477/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002478/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002479bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002480 const Expr *E = IgnoreParens();
2481 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002482 default:
2483 return false;
2484 case ObjCIvarRefExprClass:
2485 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002486 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002487 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002488 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002489 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002490 case MaterializeTemporaryExprClass:
2491 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2492 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002493 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002494 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002495 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002496 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002497
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002498 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2499 if (VD->hasGlobalStorage())
2500 return true;
2501 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002502 // dereferencing to a pointer is always a gc'able candidate,
2503 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002504 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002505 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002506 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002507 return false;
2508 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002509 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002510 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002511 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002512 }
2513 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002514 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002515 }
2516}
Sebastian Redlce354af2010-09-10 20:55:33 +00002517
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002518bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2519 if (isTypeDependent())
2520 return false;
John McCall086a4642010-11-24 05:12:34 +00002521 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002522}
2523
John McCall0009fcc2011-04-26 20:42:42 +00002524QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002525 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002526
2527 // Bound member expressions are always one of these possibilities:
2528 // x->m x.m x->*y x.*y
2529 // (possibly parenthesized)
2530
2531 expr = expr->IgnoreParens();
2532 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2533 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2534 return mem->getMemberDecl()->getType();
2535 }
2536
2537 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2538 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2539 ->getPointeeType();
2540 assert(type->isFunctionType());
2541 return type;
2542 }
2543
David Majnemerced8bdf2015-02-25 17:36:15 +00002544 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002545 return QualType();
2546}
2547
Ted Kremenekfff70962008-01-17 16:57:34 +00002548Expr* Expr::IgnoreParens() {
2549 Expr* E = this;
Abramo Bagnara932e3932010-10-15 07:51:18 +00002550 while (true) {
2551 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2552 E = P->getSubExpr();
2553 continue;
2554 }
2555 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2556 if (P->getOpcode() == UO_Extension) {
2557 E = P->getSubExpr();
2558 continue;
2559 }
2560 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002561 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2562 if (!P->isResultDependent()) {
2563 E = P->getResultExpr();
2564 continue;
2565 }
2566 }
Eli Friedman75807f22013-07-20 00:40:58 +00002567 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2568 if (!P->isConditionDependent()) {
2569 E = P->getChosenSubExpr();
2570 continue;
2571 }
2572 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002573 return E;
2574 }
Ted Kremenekfff70962008-01-17 16:57:34 +00002575}
2576
Chris Lattnerf2660962008-02-13 01:02:39 +00002577/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2578/// or CastExprs or ImplicitCastExprs, returning their operand.
2579Expr *Expr::IgnoreParenCasts() {
2580 Expr *E = this;
2581 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002582 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002583 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002584 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002585 continue;
2586 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002587 if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002588 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2589 E = Materialize->GetTemporaryExpr();
2590 continue;
2591 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002592 if (SubstNonTypeTemplateParmExpr *NTTP
2593 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2594 E = NTTP->getReplacement();
2595 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002596 }
Hans Wennborg8c79706e2018-11-27 14:01:40 +00002597 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E)) {
2598 E = CE->getSubExpr();
Bill Wendling8003edc2018-11-09 00:41:36 +00002599 continue;
2600 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002601 return E;
Chris Lattnerf2660962008-02-13 01:02:39 +00002602 }
2603}
2604
Ted Kremenek6f375e52014-04-16 07:26:09 +00002605Expr *Expr::IgnoreCasts() {
2606 Expr *E = this;
2607 while (true) {
2608 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2609 E = P->getSubExpr();
2610 continue;
2611 }
2612 if (MaterializeTemporaryExpr *Materialize
2613 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2614 E = Materialize->GetTemporaryExpr();
2615 continue;
2616 }
2617 if (SubstNonTypeTemplateParmExpr *NTTP
2618 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2619 E = NTTP->getReplacement();
2620 continue;
2621 }
Hans Wennborg8c79706e2018-11-27 14:01:40 +00002622 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E)) {
2623 E = CE->getSubExpr();
Bill Wendling8003edc2018-11-09 00:41:36 +00002624 continue;
2625 }
Ted Kremenek6f375e52014-04-16 07:26:09 +00002626 return E;
2627 }
2628}
2629
John McCall5a4ce8b2010-12-04 08:24:19 +00002630/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2631/// casts. This is intended purely as a temporary workaround for code
2632/// that hasn't yet been rewritten to do the right thing about those
2633/// casts, and may disappear along with the last internal use.
John McCall34376a62010-12-04 03:47:34 +00002634Expr *Expr::IgnoreParenLValueCasts() {
2635 Expr *E = this;
John McCall5a4ce8b2010-12-04 08:24:19 +00002636 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002637 E = E->IgnoreParens();
2638 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00002639 if (P->getCastKind() == CK_LValueToRValue) {
2640 E = P->getSubExpr();
2641 continue;
2642 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002643 } else if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002644 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2645 E = Materialize->GetTemporaryExpr();
2646 continue;
Douglas Gregor6a40b082011-09-08 17:56:33 +00002647 } else if (SubstNonTypeTemplateParmExpr *NTTP
2648 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2649 E = NTTP->getReplacement();
2650 continue;
Hans Wennborg8c79706e2018-11-27 14:01:40 +00002651 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E)) {
2652 E = CE->getSubExpr();
Bill Wendling8003edc2018-11-09 00:41:36 +00002653 continue;
John McCall34376a62010-12-04 03:47:34 +00002654 }
2655 break;
2656 }
2657 return E;
2658}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002659
2660Expr *Expr::ignoreParenBaseCasts() {
2661 Expr *E = this;
2662 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002663 E = E->IgnoreParens();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002664 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2665 if (CE->getCastKind() == CK_DerivedToBase ||
2666 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2667 CE->getCastKind() == CK_NoOp) {
2668 E = CE->getSubExpr();
2669 continue;
2670 }
2671 }
2672
2673 return E;
2674 }
2675}
2676
John McCalleebc8322010-05-05 22:59:52 +00002677Expr *Expr::IgnoreParenImpCasts() {
2678 Expr *E = this;
2679 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002680 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002681 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCalleebc8322010-05-05 22:59:52 +00002682 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002683 continue;
2684 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002685 if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002686 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2687 E = Materialize->GetTemporaryExpr();
2688 continue;
2689 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002690 if (SubstNonTypeTemplateParmExpr *NTTP
2691 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2692 E = NTTP->getReplacement();
2693 continue;
2694 }
Bill Wendling8003edc2018-11-09 00:41:36 +00002695 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E)) {
2696 E = CE->getSubExpr();
2697 continue;
2698 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002699 return E;
John McCalleebc8322010-05-05 22:59:52 +00002700 }
2701}
2702
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002703Expr *Expr::IgnoreConversionOperator() {
2704 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002705 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002706 return MCE->getImplicitObjectArgument();
2707 }
2708 return this;
2709}
2710
Chris Lattneref26c772009-03-13 17:28:01 +00002711/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2712/// value (including ptr->int casts of the same size). Strip off any
2713/// ParenExpr or CastExprs, returning their operand.
2714Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2715 Expr *E = this;
2716 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002717 E = E->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00002718
Chris Lattneref26c772009-03-13 17:28:01 +00002719 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2720 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregorb90df602010-06-16 00:17:44 +00002721 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattneref26c772009-03-13 17:28:01 +00002722 Expr *SE = P->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002723
Chris Lattneref26c772009-03-13 17:28:01 +00002724 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2725 E = SE;
2726 continue;
2727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
Abramo Bagnara932e3932010-10-15 07:51:18 +00002729 if ((E->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002730 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnara932e3932010-10-15 07:51:18 +00002731 (SE->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002732 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattneref26c772009-03-13 17:28:01 +00002733 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2734 E = SE;
2735 continue;
2736 }
2737 }
Mike Stump11289f42009-09-09 15:08:12 +00002738
Douglas Gregor6a40b082011-09-08 17:56:33 +00002739 if (SubstNonTypeTemplateParmExpr *NTTP
2740 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2741 E = NTTP->getReplacement();
2742 continue;
2743 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002744
Chris Lattneref26c772009-03-13 17:28:01 +00002745 return E;
2746 }
2747}
2748
Douglas Gregord196a582009-12-14 19:27:10 +00002749bool Expr::isDefaultArgument() const {
2750 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002751 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2752 E = M->GetTemporaryExpr();
2753
Douglas Gregord196a582009-12-14 19:27:10 +00002754 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2755 E = ICE->getSubExprAsWritten();
Fangrui Song6907ce22018-07-30 19:24:48 +00002756
Douglas Gregord196a582009-12-14 19:27:10 +00002757 return isa<CXXDefaultArgExpr>(E);
2758}
Chris Lattneref26c772009-03-13 17:28:01 +00002759
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002760/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002761/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002762static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002763 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2764 E = M->GetTemporaryExpr();
2765
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002766 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002767 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002768 E = ICE->getSubExpr();
2769 else
2770 break;
2771 }
2772
2773 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2774 E = BE->getSubExpr();
2775
2776 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002777 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002778 E = ICE->getSubExpr();
2779 else
2780 break;
2781 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002782
2783 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002784}
2785
John McCall7a626f62010-09-15 10:14:12 +00002786/// isTemporaryObject - Determines if this expression produces a
2787/// temporary of the given class type.
2788bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2789 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2790 return false;
2791
Anders Carlsson66bbf502010-11-28 16:40:49 +00002792 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002793
John McCall02dc8c72010-09-15 20:59:13 +00002794 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002795 if (!E->Classify(C).isPRValue()) {
2796 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002797 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002798 return false;
2799 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002800
John McCallf4ee1dd2010-09-16 06:57:56 +00002801 // Black-list a few cases which yield pr-values of class type that don't
2802 // refer to temporaries of that type:
2803
2804 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002805 if (isa<ImplicitCastExpr>(E)) {
2806 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2807 case CK_DerivedToBase:
2808 case CK_UncheckedDerivedToBase:
2809 return false;
2810 default:
2811 break;
2812 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002813 }
2814
John McCallf4ee1dd2010-09-16 06:57:56 +00002815 // - member expressions (all)
2816 if (isa<MemberExpr>(E))
2817 return false;
2818
Eli Friedman13ffdd82012-06-15 23:51:06 +00002819 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2820 if (BO->isPtrMemOp())
2821 return false;
2822
John McCallc07a0c72011-02-17 10:25:35 +00002823 // - opaque values (all)
2824 if (isa<OpaqueValueExpr>(E))
2825 return false;
2826
John McCall7a626f62010-09-15 10:14:12 +00002827 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002828}
2829
Douglas Gregor25b7e052011-03-02 21:06:53 +00002830bool Expr::isImplicitCXXThis() const {
2831 const Expr *E = this;
Fangrui Song6907ce22018-07-30 19:24:48 +00002832
Douglas Gregor25b7e052011-03-02 21:06:53 +00002833 // Strip away parentheses and casts we don't care about.
2834 while (true) {
2835 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2836 E = Paren->getSubExpr();
2837 continue;
2838 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002839
Douglas Gregor25b7e052011-03-02 21:06:53 +00002840 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2841 if (ICE->getCastKind() == CK_NoOp ||
2842 ICE->getCastKind() == CK_LValueToRValue ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002843 ICE->getCastKind() == CK_DerivedToBase ||
Douglas Gregor25b7e052011-03-02 21:06:53 +00002844 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2845 E = ICE->getSubExpr();
2846 continue;
2847 }
2848 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002849
Douglas Gregor25b7e052011-03-02 21:06:53 +00002850 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2851 if (UnOp->getOpcode() == UO_Extension) {
2852 E = UnOp->getSubExpr();
2853 continue;
2854 }
2855 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002856
Douglas Gregorfe314812011-06-21 17:03:29 +00002857 if (const MaterializeTemporaryExpr *M
2858 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2859 E = M->GetTemporaryExpr();
2860 continue;
2861 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002862
Douglas Gregor25b7e052011-03-02 21:06:53 +00002863 break;
2864 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002865
Douglas Gregor25b7e052011-03-02 21:06:53 +00002866 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2867 return This->isImplicit();
Fangrui Song6907ce22018-07-30 19:24:48 +00002868
Douglas Gregor25b7e052011-03-02 21:06:53 +00002869 return false;
2870}
2871
Douglas Gregor4619e432008-12-05 23:32:09 +00002872/// hasAnyTypeDependentArguments - Determines if any of the expressions
2873/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002874bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002875 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002876 if (Exprs[I]->isTypeDependent())
2877 return true;
2878
2879 return false;
2880}
2881
Abramo Bagnara847c6602014-05-22 19:20:46 +00002882bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2883 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002884 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002885 // which can be evaluated at compile-time. It very closely parallels
2886 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2887 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2888 // to isEvaluatable most of the time.
2889 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002890 // If we ever capture reference-binding directly in the AST, we can
2891 // kill the second parameter.
2892
2893 if (IsForRef) {
2894 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002895 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2896 return true;
2897 if (Culprit)
2898 *Culprit = this;
2899 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002900 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002901
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002902 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002903 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002904 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002905 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002906 return true;
John McCall81c9cea2010-08-01 21:51:45 +00002907 case CXXTemporaryObjectExprClass:
2908 case CXXConstructExprClass: {
2909 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00002910
Eli Friedman4c27ac22013-07-16 22:40:53 +00002911 if (CE->getConstructor()->isTrivial() &&
2912 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2913 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00002914 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00002915
Eli Friedman4c27ac22013-07-16 22:40:53 +00002916 // Trivial copy constructor
2917 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00002918 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00002919 }
2920
Richard Smithd62306a2011-11-10 06:34:14 +00002921 break;
John McCall81c9cea2010-08-01 21:51:45 +00002922 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002923 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002924 // This handles gcc's extension that allows global initializers like
2925 // "struct x {int x;} x = (struct x) {};".
2926 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002927 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002928 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002929 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00002930 case DesignatedInitUpdateExprClass: {
2931 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2932 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2933 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2934 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002935 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002936 const InitListExpr *ILE = cast<InitListExpr>(this);
2937 if (ILE->getType()->isArrayType()) {
2938 unsigned numInits = ILE->getNumInits();
2939 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002940 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002941 return false;
2942 }
2943 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002944 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002945
2946 if (ILE->getType()->isRecordType()) {
2947 unsigned ElementNo = 0;
2948 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00002949 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002950 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00002951 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00002952 continue;
2953
2954 // Don't emit anonymous bitfields, they just affect layout.
2955 if (Field->isUnnamedBitfield())
2956 continue;
2957
2958 if (ElementNo < ILE->getNumInits()) {
2959 const Expr *Elt = ILE->getInit(ElementNo++);
2960 if (Field->isBitField()) {
2961 // Bitfields have to evaluate to an integer.
Hans Wennborg8c79706e2018-11-27 14:01:40 +00002962 llvm::APSInt ResultTmp;
2963 if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002964 if (Culprit)
2965 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00002966 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002967 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002968 } else {
2969 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002970 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002971 return false;
2972 }
2973 }
2974 }
2975 return true;
2976 }
2977
2978 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002979 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00002980 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002981 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00002982 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00002983 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00002984 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002985 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00002986 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002987 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002988 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00002989 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00002990 if (cast<ChooseExpr>(this)->isConditionDependent()) {
2991 if (Culprit)
2992 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00002993 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002994 }
Eli Friedman75807f22013-07-20 00:40:58 +00002995 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002996 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002997 case UnaryOperatorClass: {
2998 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00002999 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003000 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003001 break;
3002 }
John McCall8b0f4ff2010-08-02 21:13:48 +00003003 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00003004 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00003005 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00003006 case CStyleCastExprClass:
3007 case ObjCBridgedCastExprClass:
3008 case CXXDynamicCastExprClass:
3009 case CXXReinterpretCastExprClass:
3010 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00003011 const CastExpr *CE = cast<CastExpr>(this);
3012
Eli Friedman13ec75b2011-12-21 00:43:02 +00003013 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00003014 if (CE->getCastKind() == CK_NoOp ||
3015 CE->getCastKind() == CK_LValueToRValue ||
3016 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00003017 CE->getCastKind() == CK_ConstructorConversion ||
3018 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003019 CE->getCastKind() == CK_AtomicToNonAtomic ||
3020 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003021 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00003022
Eli Friedman384da272009-01-25 03:12:18 +00003023 break;
Richard Smith161f09a2011-12-06 22:44:34 +00003024 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003025 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003026 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003027 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003028
Eli Friedman4c27ac22013-07-16 22:40:53 +00003029 case SubstNonTypeTemplateParmExprClass:
3030 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003031 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003032 case CXXDefaultArgExprClass:
3033 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003034 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003035 case CXXDefaultInitExprClass:
3036 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003037 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003038 }
Richard Smithce8eca52015-12-08 03:21:47 +00003039 // Allow certain forms of UB in constant initializers: signed integer
3040 // overflow and floating-point division by zero. We'll give a warning on
3041 // these, but they're common enough that we have to accept them.
3042 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00003043 return true;
3044 if (Culprit)
3045 *Culprit = this;
3046 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00003047}
3048
Nico Weber758fbac2018-02-13 21:31:47 +00003049bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3050 const FunctionDecl* FD = getDirectCallee();
3051 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3052 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3053 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003054
Nico Weber758fbac2018-02-13 21:31:47 +00003055 const Expr* Arg = getArg(0);
3056 bool ArgVal;
3057 return !Arg->isValueDependent() &&
3058 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3059}
3060
Scott Douglasscc013592015-06-10 15:18:23 +00003061namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003062 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00003063 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003064 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00003065 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003066 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00003067
3068 public:
3069 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003070 : Inherited(Context),
3071 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00003072
3073 bool hasSideEffects() const { return HasSideEffects; }
3074
3075 void VisitExpr(const Expr *E) {
3076 if (!HasSideEffects &&
3077 E->HasSideEffects(Context, IncludePossibleEffects))
3078 HasSideEffects = true;
3079 }
3080 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003081}
Scott Douglasscc013592015-06-10 15:18:23 +00003082
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003083bool Expr::HasSideEffects(const ASTContext &Ctx,
3084 bool IncludePossibleEffects) const {
3085 // In circumstances where we care about definite side effects instead of
3086 // potential side effects, we want to ignore expressions that are part of a
3087 // macro expansion as a potential side effect.
3088 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3089 return false;
3090
Richard Smith0421ce72012-08-07 04:16:51 +00003091 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003092 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00003093
3094 switch (getStmtClass()) {
3095 case NoStmtClass:
3096 #define ABSTRACT_STMT(Type)
3097 #define STMT(Type, Base) case Type##Class:
3098 #define EXPR(Type, Base)
3099 #include "clang/AST/StmtNodes.inc"
3100 llvm_unreachable("unexpected Expr kind");
3101
3102 case DependentScopeDeclRefExprClass:
3103 case CXXUnresolvedConstructExprClass:
3104 case CXXDependentScopeMemberExprClass:
3105 case UnresolvedLookupExprClass:
3106 case UnresolvedMemberExprClass:
3107 case PackExpansionExprClass:
3108 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00003109 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003110 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00003111 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003112 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3113
Richard Smitha33e4fe2012-08-07 05:18:29 +00003114 case DeclRefExprClass:
3115 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003116 case PredefinedExprClass:
3117 case IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003118 case FixedPointLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003119 case FloatingLiteralClass:
3120 case ImaginaryLiteralClass:
3121 case StringLiteralClass:
3122 case CharacterLiteralClass:
3123 case OffsetOfExprClass:
3124 case ImplicitValueInitExprClass:
3125 case UnaryExprOrTypeTraitExprClass:
3126 case AddrLabelExprClass:
3127 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003128 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003129 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003130 case CXXBoolLiteralExprClass:
3131 case CXXNullPtrLiteralExprClass:
3132 case CXXThisExprClass:
3133 case CXXScalarValueInitExprClass:
3134 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003135 case ArrayTypeTraitExprClass:
3136 case ExpressionTraitExprClass:
3137 case CXXNoexceptExprClass:
3138 case SizeOfPackExprClass:
3139 case ObjCStringLiteralClass:
3140 case ObjCEncodeExprClass:
3141 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003142 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003143 case CXXUuidofExprClass:
3144 case OpaqueValueExprClass:
3145 // These never have a side-effect.
3146 return false;
3147
Bill Wendling7c44da22018-10-31 03:48:47 +00003148 case ConstantExprClass:
3149 // FIXME: Move this into the "return false;" block above.
3150 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3151 Ctx, IncludePossibleEffects);
3152
Richard Smith0421ce72012-08-07 04:16:51 +00003153 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003154 case CXXOperatorCallExprClass:
3155 case CXXMemberCallExprClass:
3156 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003157 case UserDefinedLiteralClass: {
3158 // We don't know a call definitely has side effects, except for calls
3159 // to pure/const functions that definitely don't.
3160 // If the call itself is considered side-effect free, check the operands.
3161 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3162 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3163 if (IsPure || !IncludePossibleEffects)
3164 break;
3165 return true;
3166 }
3167
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003168 case BlockExprClass:
3169 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003170 if (!IncludePossibleEffects)
3171 break;
3172 return true;
3173
John McCall5e77d762013-04-16 07:28:30 +00003174 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003175 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003176 case CompoundAssignOperatorClass:
3177 case VAArgExprClass:
3178 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003179 case CXXThrowExprClass:
3180 case CXXNewExprClass:
3181 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003182 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003183 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003184 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003185 // These always have a side-effect.
3186 return true;
3187
Scott Douglasscc013592015-06-10 15:18:23 +00003188 case StmtExprClass: {
3189 // StmtExprs have a side-effect if any substatement does.
3190 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3191 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3192 return Finder.hasSideEffects();
3193 }
3194
Tim Shen4a05bb82016-06-21 20:29:17 +00003195 case ExprWithCleanupsClass:
3196 if (IncludePossibleEffects)
3197 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3198 return true;
3199 break;
3200
Richard Smith0421ce72012-08-07 04:16:51 +00003201 case ParenExprClass:
3202 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003203 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003204 case MemberExprClass:
3205 case ConditionalOperatorClass:
3206 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003207 case CompoundLiteralExprClass:
3208 case ExtVectorElementExprClass:
3209 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003210 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003211 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003212 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003213 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003214 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003215 case SubstNonTypeTemplateParmExprClass:
3216 case MaterializeTemporaryExprClass:
3217 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003218 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003219 case AsTypeExprClass:
3220 // These have a side-effect if any subexpression does.
3221 break;
3222
Richard Smitha33e4fe2012-08-07 05:18:29 +00003223 case UnaryOperatorClass:
3224 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003225 return true;
3226 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003227
3228 case BinaryOperatorClass:
3229 if (cast<BinaryOperator>(this)->isAssignmentOp())
3230 return true;
3231 break;
3232
Richard Smith0421ce72012-08-07 04:16:51 +00003233 case InitListExprClass:
3234 // FIXME: The children for an InitListExpr doesn't include the array filler.
3235 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003236 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003237 return true;
3238 break;
3239
3240 case GenericSelectionExprClass:
3241 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003242 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003243
3244 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003245 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3246 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003247
3248 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003249 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3250 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003251
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003252 case CXXDefaultInitExprClass: {
3253 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3254 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003255 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003256 // If we've not yet parsed the initializer, assume it has side-effects.
3257 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003258 }
Richard Smith852c9db2013-04-20 22:23:05 +00003259
Richard Smith0421ce72012-08-07 04:16:51 +00003260 case CXXDynamicCastExprClass: {
3261 // A dynamic_cast expression has side-effects if it can throw.
3262 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3263 if (DCE->getTypeAsWritten()->isReferenceType() &&
3264 DCE->getCastKind() == CK_Dynamic)
3265 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003266 }
3267 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003268 case ImplicitCastExprClass:
3269 case CStyleCastExprClass:
3270 case CXXStaticCastExprClass:
3271 case CXXReinterpretCastExprClass:
3272 case CXXConstCastExprClass:
3273 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003274 // While volatile reads are side-effecting in both C and C++, we treat them
3275 // as having possible (not definite) side-effects. This allows idiomatic
3276 // code to behave without warning, such as sizeof(*v) for a volatile-
3277 // qualified pointer.
3278 if (!IncludePossibleEffects)
3279 break;
3280
Richard Smitha33e4fe2012-08-07 05:18:29 +00003281 const CastExpr *CE = cast<CastExpr>(this);
3282 if (CE->getCastKind() == CK_LValueToRValue &&
3283 CE->getSubExpr()->getType().isVolatileQualified())
3284 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003285 break;
3286 }
3287
Richard Smithef8bf432012-08-13 20:08:14 +00003288 case CXXTypeidExprClass:
3289 // typeid might throw if its subexpression is potentially-evaluated, so has
3290 // side-effects in that case whether or not its subexpression does.
3291 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003292
3293 case CXXConstructExprClass:
3294 case CXXTemporaryObjectExprClass: {
3295 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003296 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003297 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003298 // A trivial constructor does not add any side-effects of its own. Just look
3299 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003300 break;
3301 }
3302
Richard Smith5179eb72016-06-28 19:03:57 +00003303 case CXXInheritedCtorInitExprClass: {
3304 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3305 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3306 return true;
3307 break;
3308 }
3309
Richard Smith0421ce72012-08-07 04:16:51 +00003310 case LambdaExprClass: {
3311 const LambdaExpr *LE = cast<LambdaExpr>(this);
Richard Smithb3d203f2018-10-19 19:01:34 +00003312 for (Expr *E : LE->capture_inits())
3313 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003314 return true;
3315 return false;
3316 }
3317
3318 case PseudoObjectExprClass: {
3319 // Only look for side-effects in the semantic form, and look past
3320 // OpaqueValueExpr bindings in that form.
3321 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3322 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3323 E = PO->semantics_end();
3324 I != E; ++I) {
3325 const Expr *Subexpr = *I;
3326 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3327 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003328 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003329 return true;
3330 }
3331 return false;
3332 }
3333
3334 case ObjCBoxedExprClass:
3335 case ObjCArrayLiteralClass:
3336 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003337 case ObjCSelectorExprClass:
3338 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003339 case ObjCIsaExprClass:
3340 case ObjCIndirectCopyRestoreExprClass:
3341 case ObjCSubscriptRefExprClass:
3342 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003343 case ObjCMessageExprClass:
3344 case ObjCPropertyRefExprClass:
3345 // FIXME: Classify these cases better.
3346 if (IncludePossibleEffects)
3347 return true;
3348 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003349 }
3350
3351 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003352 for (const Stmt *SubStmt : children())
3353 if (SubStmt &&
3354 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3355 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003356
3357 return false;
3358}
3359
Douglas Gregor1be329d2012-02-23 07:33:15 +00003360namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003361 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003362 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3363 {
3364 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003365
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003366 bool NonTrivial;
Fangrui Song6907ce22018-07-30 19:24:48 +00003367
Douglas Gregor1be329d2012-02-23 07:33:15 +00003368 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003369 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003370 : Inherited(Context), NonTrivial(false) { }
Fangrui Song6907ce22018-07-30 19:24:48 +00003371
Douglas Gregor1be329d2012-02-23 07:33:15 +00003372 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003373
3374 void VisitCallExpr(const CallExpr *E) {
3375 if (const CXXMethodDecl *Method
3376 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003377 if (Method->isTrivial()) {
3378 // Recurse to children of the call.
3379 Inherited::VisitStmt(E);
3380 return;
3381 }
3382 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003383
Douglas Gregor1be329d2012-02-23 07:33:15 +00003384 NonTrivial = true;
3385 }
Scott Douglass503fc392015-06-10 13:53:15 +00003386
3387 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003388 if (E->getConstructor()->isTrivial()) {
3389 // Recurse to children of the call.
3390 Inherited::VisitStmt(E);
3391 return;
3392 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003393
Douglas Gregor1be329d2012-02-23 07:33:15 +00003394 NonTrivial = true;
3395 }
Scott Douglass503fc392015-06-10 13:53:15 +00003396
3397 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003398 if (E->getTemporary()->getDestructor()->isTrivial()) {
3399 Inherited::VisitStmt(E);
3400 return;
3401 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003402
Douglas Gregor1be329d2012-02-23 07:33:15 +00003403 NonTrivial = true;
3404 }
3405 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003406}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003407
Scott Douglass503fc392015-06-10 13:53:15 +00003408bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003409 NonTrivialCallFinder Finder(Ctx);
3410 Finder.Visit(this);
Fangrui Song6907ce22018-07-30 19:24:48 +00003411 return Finder.hasNonTrivialCall();
Douglas Gregor1be329d2012-02-23 07:33:15 +00003412}
3413
Fangrui Song6907ce22018-07-30 19:24:48 +00003414/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003415/// pointer constant or not, as well as the specific kind of constant detected.
3416/// Null pointer constants can be integer constant expressions with the
3417/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3418/// (a GNU extension).
3419Expr::NullPointerConstantKind
3420Expr::isNullPointerConstant(ASTContext &Ctx,
3421 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003422 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003423 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003424 switch (NPC) {
3425 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003426 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003427 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003428 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003429 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003430 else
3431 return NPCK_NotNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003432
Douglas Gregor56751b52009-09-25 04:25:58 +00003433 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003434 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003435 }
3436 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003437
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003438 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003439 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003440 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003441 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003442 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003443 QualType Pointee = PT->getPointeeType();
Richard Smithdab73ce2018-11-28 06:25:06 +00003444 Qualifiers Qs = Pointee.getQualifiers();
Yaxun Liub7318e02017-10-13 03:37:48 +00003445 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3446 // has non-default address space it is not treated as nullptr.
3447 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3448 // since it cannot be assigned to a pointer to constant address space.
Richard Smithdab73ce2018-11-28 06:25:06 +00003449 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
Yaxun Liub7318e02017-10-13 03:37:48 +00003450 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3451 (Ctx.getLangOpts().OpenCL &&
3452 Ctx.getLangOpts().OpenCLVersion < 200 &&
Richard Smithdab73ce2018-11-28 06:25:06 +00003453 Pointee.getAddressSpace() == LangAS::opencl_private))
3454 Qs.removeAddressSpace();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003455
Richard Smithdab73ce2018-11-28 06:25:06 +00003456 if (Pointee->isVoidType() && Qs.empty() && // to void*
3457 CE->getSubExpr()->getType()->isIntegerType()) // from int
Douglas Gregor56751b52009-09-25 04:25:58 +00003458 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003459 }
Steve Naroffada7d422007-05-20 17:54:12 +00003460 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003461 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3462 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003463 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003464 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3465 // Accept ((void*)0) as a null pointer constant, as many other
3466 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003467 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003468 } else if (const GenericSelectionExpr *GE =
3469 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003470 if (GE->isResultDependent())
3471 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003472 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003473 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3474 if (CE->isConditionDependent())
3475 return NPCK_NotNull;
3476 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003477 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003478 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003479 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003480 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003481 } else if (const CXXDefaultInitExpr *DefaultInit
3482 = dyn_cast<CXXDefaultInitExpr>(this)) {
3483 // See through default initializer expressions.
3484 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003485 } else if (isa<GNUNullExpr>(this)) {
3486 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003487 return NPCK_GNUNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003488 } else if (const MaterializeTemporaryExpr *M
Douglas Gregorfe314812011-06-21 17:03:29 +00003489 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3490 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003491 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3492 if (const Expr *Source = OVE->getSourceExpr())
3493 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003494 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003495
Richard Smith89645bc2013-01-02 12:01:23 +00003496 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003497 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003498 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003499
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003500 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003501 if (!Ctx.getLangOpts().CPlusPlus11 &&
3502 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003503 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3504 const Expr *InitExpr = CLE->getInitializer();
3505 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3506 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3507 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003508 // This expression must be an integer type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003509 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003510 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003511 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003512
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003513 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003514 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3515 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003516 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003517 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003518 if (Lit && !Lit->getValue())
3519 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003520 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003521 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003522 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003523 // If we have an integer constant expression, we need to *evaluate* it and
3524 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003525 if (!isIntegerConstantExpr(Ctx))
3526 return NPCK_NotNull;
3527 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003528
David Blaikie1c7c8f72012-08-08 17:33:31 +00003529 if (EvaluateKnownConstInt(Ctx) != 0)
3530 return NPCK_NotNull;
3531
3532 if (isa<IntegerLiteral>(this))
3533 return NPCK_ZeroLiteral;
3534 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003535}
Steve Narofff7a5da12007-07-28 23:10:27 +00003536
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003537/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003538/// property, find the underlying property reference expression.
3539const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3540 const Expr *E = this;
3541 while (true) {
3542 assert((E->getValueKind() == VK_LValue &&
3543 E->getObjectKind() == OK_ObjCProperty) &&
3544 "expression is not a property reference");
3545 E = E->IgnoreParenCasts();
3546 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3547 if (BO->getOpcode() == BO_Comma) {
3548 E = BO->getRHS();
3549 continue;
3550 }
3551 }
3552
3553 break;
3554 }
3555
3556 return cast<ObjCPropertyRefExpr>(E);
3557}
3558
Anna Zaks97c7ce32012-10-01 20:34:04 +00003559bool Expr::isObjCSelfExpr() const {
3560 const Expr *E = IgnoreParenImpCasts();
3561
3562 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3563 if (!DRE)
3564 return false;
3565
3566 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3567 if (!Param)
3568 return false;
3569
3570 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3571 if (!M)
3572 return false;
3573
3574 return M->getSelfDecl() == Param;
3575}
3576
John McCalld25db7e2013-05-06 21:39:12 +00003577FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003578 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003579
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003580 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003581 if (ICE->getCastKind() == CK_LValueToRValue ||
3582 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003583 E = ICE->getSubExpr()->IgnoreParens();
3584 else
3585 break;
3586 }
3587
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003588 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003589 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003590 if (Field->isBitField())
3591 return Field;
3592
George Burgess IV00f70bd2018-03-01 05:43:23 +00003593 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3594 FieldDecl *Ivar = IvarRef->getDecl();
3595 if (Ivar->isBitField())
3596 return Ivar;
3597 }
John McCalld25db7e2013-05-06 21:39:12 +00003598
Richard Smith7873de02016-08-11 22:25:46 +00003599 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003600 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3601 if (Field->isBitField())
3602 return Field;
3603
Richard Smith7873de02016-08-11 22:25:46 +00003604 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3605 if (Expr *E = BD->getBinding())
3606 return E->getSourceBitField();
3607 }
3608
Eli Friedman609ada22011-07-13 02:05:57 +00003609 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003610 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003611 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003612
Eli Friedman609ada22011-07-13 02:05:57 +00003613 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003614 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003615 }
3616
Richard Smith5b571672014-09-24 23:55:00 +00003617 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3618 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3619 return UnOp->getSubExpr()->getSourceBitField();
3620
Craig Topper36250ad2014-05-12 05:36:57 +00003621 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003622}
3623
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003624bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003625 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003626 const Expr *E = this->IgnoreParens();
Fangrui Song6907ce22018-07-30 19:24:48 +00003627
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003628 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003629 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003630 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003631 E = ICE->getSubExpr()->IgnoreParens();
3632 else
3633 break;
3634 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003635
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003636 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3637 return ASE->getBase()->getType()->isVectorType();
3638
3639 if (isa<ExtVectorElementExpr>(E))
3640 return true;
3641
Richard Smith7873de02016-08-11 22:25:46 +00003642 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3643 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3644 if (auto *E = BD->getBinding())
3645 return E->refersToVectorElement();
3646
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003647 return false;
3648}
3649
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003650bool Expr::refersToGlobalRegisterVar() const {
3651 const Expr *E = this->IgnoreParenImpCasts();
3652
3653 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3654 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3655 if (VD->getStorageClass() == SC_Register &&
3656 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3657 return true;
3658
3659 return false;
3660}
3661
Chris Lattnerb8211f62009-02-16 22:14:05 +00003662/// isArrow - Return true if the base expression is a pointer to vector,
3663/// return false if the base expression is a vector.
3664bool ExtVectorElementExpr::isArrow() const {
3665 return getBase()->getType()->isPointerType();
3666}
3667
Nate Begemance4d7fc2008-04-18 23:10:10 +00003668unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003669 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003670 return VT->getNumElements();
3671 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003672}
3673
Nate Begemanf322eab2008-05-09 06:41:27 +00003674/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003675bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003676 // FIXME: Refactor this code to an accessor on the AST node which returns the
3677 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003678 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003679
3680 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003681 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003682 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003683
Nate Begeman7e5185b2009-01-18 02:01:21 +00003684 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003685 if (Comp[0] == 's' || Comp[0] == 'S')
3686 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003687
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003688 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003689 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003690 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003691
Steve Naroff0d595ca2007-07-30 03:29:09 +00003692 return false;
3693}
Chris Lattner885b4952007-08-02 23:36:59 +00003694
Nate Begemanf322eab2008-05-09 06:41:27 +00003695/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003696void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003697 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003698 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003699 bool isNumericAccessor = false;
3700 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003701 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003702 isNumericAccessor = true;
3703 }
Mike Stump11289f42009-09-09 15:08:12 +00003704
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003705 bool isHi = Comp == "hi";
3706 bool isLo = Comp == "lo";
3707 bool isEven = Comp == "even";
3708 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003709
Nate Begemanf322eab2008-05-09 06:41:27 +00003710 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3711 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003712
Nate Begemanf322eab2008-05-09 06:41:27 +00003713 if (isHi)
3714 Index = e + i;
3715 else if (isLo)
3716 Index = i;
3717 else if (isEven)
3718 Index = 2 * i;
3719 else if (isOdd)
3720 Index = 2 * i + 1;
3721 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003722 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003723
Nate Begemand3862152008-05-13 21:03:02 +00003724 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003725 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003726}
3727
Craig Topper37932912013-08-18 10:09:15 +00003728ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003729 QualType Type, SourceLocation BLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00003730 SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003731 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3732 Type->isDependentType(), Type->isDependentType(),
3733 Type->isInstantiationDependentType(),
3734 Type->containsUnexpandedParameterPack()),
3735 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3736{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003737 SubExprs = new (C) Stmt*[args.size()];
3738 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003739 if (args[i]->isTypeDependent())
3740 ExprBits.TypeDependent = true;
3741 if (args[i]->isValueDependent())
3742 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003743 if (args[i]->isInstantiationDependent())
3744 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003745 if (args[i]->containsUnexpandedParameterPack())
3746 ExprBits.ContainsUnexpandedParameterPack = true;
3747
3748 SubExprs[i] = args[i];
3749 }
3750}
3751
Craig Topper37932912013-08-18 10:09:15 +00003752void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003753 if (SubExprs) C.Deallocate(SubExprs);
3754
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003755 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003756 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003757 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003758}
Nate Begeman48745922009-08-12 02:28:50 +00003759
Craig Topper37932912013-08-18 10:09:15 +00003760GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003761 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003762 ArrayRef<TypeSourceInfo*> AssocTypes,
3763 ArrayRef<Expr*> AssocExprs,
3764 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003765 SourceLocation RParenLoc,
3766 bool ContainsUnexpandedParameterPack,
3767 unsigned ResultIndex)
3768 : Expr(GenericSelectionExprClass,
3769 AssocExprs[ResultIndex]->getType(),
3770 AssocExprs[ResultIndex]->getValueKind(),
3771 AssocExprs[ResultIndex]->getObjectKind(),
3772 AssocExprs[ResultIndex]->isTypeDependent(),
3773 AssocExprs[ResultIndex]->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003774 AssocExprs[ResultIndex]->isInstantiationDependent(),
Peter Collingbourne91147592011-04-15 00:35:48 +00003775 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003776 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3777 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3778 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3779 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003780 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003781 assert(AssocTypes.size() == AssocExprs.size());
3782 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3783 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003784}
3785
Craig Topper37932912013-08-18 10:09:15 +00003786GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003787 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003788 ArrayRef<TypeSourceInfo*> AssocTypes,
3789 ArrayRef<Expr*> AssocExprs,
3790 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003791 SourceLocation RParenLoc,
3792 bool ContainsUnexpandedParameterPack)
3793 : Expr(GenericSelectionExprClass,
3794 Context.DependentTy,
3795 VK_RValue,
3796 OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003797 /*isTypeDependent=*/true,
3798 /*isValueDependent=*/true,
3799 /*isInstantiationDependent=*/true,
Peter Collingbourne91147592011-04-15 00:35:48 +00003800 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003801 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3802 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3803 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3804 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003805 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003806 assert(AssocTypes.size() == AssocExprs.size());
3807 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3808 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003809}
3810
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003811//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003812// DesignatedInitExpr
3813//===----------------------------------------------------------------------===//
3814
Chandler Carruth631abd92011-06-16 06:47:06 +00003815IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003816 assert(Kind == FieldDesignator && "Only valid on a field designator");
3817 if (Field.NameOrField & 0x01)
3818 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3819 else
3820 return getField()->getIdentifier();
3821}
3822
Craig Topper37932912013-08-18 10:09:15 +00003823DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00003824 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003825 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003826 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003827 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003828 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003829 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003830 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003831 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003832 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003833 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003834 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00003835 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003836 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003837
3838 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003839 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003840 *Child++ = Init;
3841
3842 // Copy the designators and their subexpressions, computing
3843 // value-dependence along the way.
3844 unsigned IndexIdx = 0;
3845 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003846 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003847
3848 if (this->Designators[I].isArrayDesignator()) {
3849 // Compute type- and value-dependence.
3850 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003851 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003852 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003853 if (Index->isInstantiationDependent())
3854 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003855 // Propagate unexpanded parameter packs.
3856 if (Index->containsUnexpandedParameterPack())
3857 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003858
3859 // Copy the index expressions into permanent storage.
3860 *Child++ = IndexExprs[IndexIdx++];
3861 } else if (this->Designators[I].isArrayRangeDesignator()) {
3862 // Compute type- and value-dependence.
3863 Expr *Start = IndexExprs[IndexIdx];
3864 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003865 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003866 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00003867 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003868 ExprBits.InstantiationDependent = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003869 } else if (Start->isInstantiationDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003870 End->isInstantiationDependent()) {
3871 ExprBits.InstantiationDependent = true;
3872 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003873
Douglas Gregora6e053e2010-12-15 01:34:56 +00003874 // Propagate unexpanded parameter packs.
3875 if (Start->containsUnexpandedParameterPack() ||
3876 End->containsUnexpandedParameterPack())
3877 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003878
3879 // Copy the start/end expressions into permanent storage.
3880 *Child++ = IndexExprs[IndexIdx++];
3881 *Child++ = IndexExprs[IndexIdx++];
3882 }
3883 }
3884
Benjamin Kramerc215e762012-08-24 11:54:20 +00003885 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00003886}
3887
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003888DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00003889DesignatedInitExpr::Create(const ASTContext &C,
3890 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003891 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003892 SourceLocation ColonOrEqualLoc,
3893 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003894 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003895 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00003896 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003897 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003898 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003899}
3900
Craig Topper37932912013-08-18 10:09:15 +00003901DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00003902 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003903 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003904 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00003905 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3906}
3907
Craig Topper37932912013-08-18 10:09:15 +00003908void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003909 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00003910 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003911 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00003912 NumDesignators = NumDesigs;
3913 for (unsigned I = 0; I != NumDesigs; ++I)
3914 Designators[I] = Desigs[I];
3915}
3916
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003917SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3918 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3919 if (size() == 1)
3920 return DIE->getDesignator(0)->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003921 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003922 DIE->getDesignator(size() - 1)->getEndLoc());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003923}
3924
Stephen Kelly724e9e52018-08-09 20:05:03 +00003925SourceLocation DesignatedInitExpr::getBeginLoc() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003926 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00003927 auto *DIE = const_cast<DesignatedInitExpr *>(this);
3928 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003929 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00003930 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003931 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3932 else
3933 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3934 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00003935 StartLoc =
3936 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003937 return StartLoc;
3938}
3939
Stephen Kelly02a67ba2018-08-09 20:05:47 +00003940SourceLocation DesignatedInitExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003941 return getInit()->getEndLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003942}
3943
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003944Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003945 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003946 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003947}
3948
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003949Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003950 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003951 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003952 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003953}
3954
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003955Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003956 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003957 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003958 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003959}
3960
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003961/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00003962/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00003963void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00003964 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00003965 const Designator *Last) {
3966 unsigned NumNewDesignators = Last - First;
3967 if (NumNewDesignators == 0) {
3968 std::copy_backward(Designators + Idx + 1,
3969 Designators + NumDesignators,
3970 Designators + Idx);
3971 --NumNewDesignators;
3972 return;
3973 } else if (NumNewDesignators == 1) {
3974 Designators[Idx] = *First;
3975 return;
3976 }
3977
Mike Stump11289f42009-09-09 15:08:12 +00003978 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003979 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00003980 std::copy(Designators, Designators + Idx, NewDesignators);
3981 std::copy(First, Last, NewDesignators + Idx);
3982 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3983 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00003984 Designators = NewDesignators;
3985 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3986}
3987
Yunzhong Gaocb779302015-06-10 00:27:52 +00003988DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
3989 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3990 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3991 OK_Ordinary, false, false, false, false) {
3992 BaseAndUpdaterExprs[0] = baseExpr;
3993
3994 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3995 ILE->setType(baseExpr->getType());
3996 BaseAndUpdaterExprs[1] = ILE;
3997}
3998
Stephen Kelly724e9e52018-08-09 20:05:03 +00003999SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004000 return getBase()->getBeginLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004001}
4002
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004003SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004004 return getBase()->getEndLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004005}
4006
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004007ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4008 SourceLocation RParenLoc)
4009 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4010 false, false),
4011 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4012 ParenListExprBits.NumExprs = Exprs.size();
4013
4014 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4015 if (Exprs[I]->isTypeDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004016 ExprBits.TypeDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004017 if (Exprs[I]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004018 ExprBits.ValueDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004019 if (Exprs[I]->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00004020 ExprBits.InstantiationDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004021 if (Exprs[I]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004022 ExprBits.ContainsUnexpandedParameterPack = true;
4023
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004024 getTrailingObjects<Stmt *>()[I] = Exprs[I];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004025 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004026}
4027
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004028ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4029 : Expr(ParenListExprClass, Empty) {
4030 ParenListExprBits.NumExprs = NumExprs;
4031}
4032
4033ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4034 SourceLocation LParenLoc,
4035 ArrayRef<Expr *> Exprs,
4036 SourceLocation RParenLoc) {
4037 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4038 alignof(ParenListExpr));
4039 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4040}
4041
4042ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4043 unsigned NumExprs) {
4044 void *Mem =
4045 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4046 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4047}
4048
John McCall1bf58462011-02-16 08:02:54 +00004049const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4050 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4051 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00004052 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4053 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00004054 e = cast<CXXConstructExpr>(e)->getArg(0);
4055 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4056 e = ice->getSubExpr();
4057 return cast<OpaqueValueExpr>(e);
4058}
4059
Craig Topper37932912013-08-18 10:09:15 +00004060PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4061 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00004062 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004063 void *buffer =
4064 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004065 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004066 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4067}
4068
4069PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4070 : Expr(PseudoObjectExprClass, shell) {
4071 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4072}
4073
Craig Topper37932912013-08-18 10:09:15 +00004074PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00004075 ArrayRef<Expr*> semantics,
4076 unsigned resultIndex) {
4077 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004078 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00004079
4080 QualType type;
4081 ExprValueKind VK;
4082 if (resultIndex == NoResult) {
4083 type = C.VoidTy;
4084 VK = VK_RValue;
4085 } else {
4086 assert(resultIndex < semantics.size());
4087 type = semantics[resultIndex]->getType();
4088 VK = semantics[resultIndex]->getValueKind();
4089 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4090 }
4091
James Y Knighte00a67e2015-12-31 04:18:25 +00004092 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004093 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004094 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4095 resultIndex);
4096}
4097
4098PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4099 Expr *syntax, ArrayRef<Expr*> semantics,
4100 unsigned resultIndex)
4101 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4102 /*filled in at end of ctor*/ false, false, false, false) {
4103 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4104 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4105
4106 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4107 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4108 getSubExprsBuffer()[i] = E;
4109
4110 if (E->isTypeDependent())
4111 ExprBits.TypeDependent = true;
4112 if (E->isValueDependent())
4113 ExprBits.ValueDependent = true;
4114 if (E->isInstantiationDependent())
4115 ExprBits.InstantiationDependent = true;
4116 if (E->containsUnexpandedParameterPack())
4117 ExprBits.ContainsUnexpandedParameterPack = true;
4118
4119 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00004120 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00004121 "opaque-value semantic expressions for pseudo-object "
4122 "operations must have sources");
4123 }
4124}
4125
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004126//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004127// Child Iterators for iterating over subexpressions/substatements
4128//===----------------------------------------------------------------------===//
4129
Peter Collingbournee190dee2011-03-11 19:24:49 +00004130// UnaryExprOrTypeTraitExpr
4131Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004132 const_child_range CCR =
4133 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4134 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4135}
4136
4137Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00004138 // If this is of a type and the type is a VLA type (and not a typedef), the
4139 // size expression of the VLA needs to be treated as an executable expression.
4140 // Why isn't this weirdness documented better in StmtIterator?
4141 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004142 if (const VariableArrayType *T =
4143 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4144 return const_child_range(const_child_iterator(T), const_child_iterator());
4145 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00004146 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004147 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004148}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004149
Benjamin Kramerc215e762012-08-24 11:54:20 +00004150AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004151 QualType t, AtomicOp op, SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004152 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4153 false, false, false, false),
4154 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4155{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004156 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4157 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004158 if (args[i]->isTypeDependent())
4159 ExprBits.TypeDependent = true;
4160 if (args[i]->isValueDependent())
4161 ExprBits.ValueDependent = true;
4162 if (args[i]->isInstantiationDependent())
4163 ExprBits.InstantiationDependent = true;
4164 if (args[i]->containsUnexpandedParameterPack())
4165 ExprBits.ContainsUnexpandedParameterPack = true;
4166
4167 SubExprs[i] = args[i];
4168 }
4169}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004170
4171unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4172 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004173 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004174 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004175 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004176 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004177 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004178
Yaxun Liu30d652a2017-08-15 16:02:49 +00004179 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004180 case AO__c11_atomic_store:
4181 case AO__c11_atomic_exchange:
4182 case AO__atomic_load:
4183 case AO__atomic_store:
4184 case AO__atomic_store_n:
4185 case AO__atomic_exchange_n:
4186 case AO__c11_atomic_fetch_add:
4187 case AO__c11_atomic_fetch_sub:
4188 case AO__c11_atomic_fetch_and:
4189 case AO__c11_atomic_fetch_or:
4190 case AO__c11_atomic_fetch_xor:
4191 case AO__atomic_fetch_add:
4192 case AO__atomic_fetch_sub:
4193 case AO__atomic_fetch_and:
4194 case AO__atomic_fetch_or:
4195 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004196 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004197 case AO__atomic_add_fetch:
4198 case AO__atomic_sub_fetch:
4199 case AO__atomic_and_fetch:
4200 case AO__atomic_or_fetch:
4201 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004202 case AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004203 case AO__atomic_fetch_min:
4204 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004205 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004206
Yaxun Liu30d652a2017-08-15 16:02:49 +00004207 case AO__opencl_atomic_store:
4208 case AO__opencl_atomic_exchange:
4209 case AO__opencl_atomic_fetch_add:
4210 case AO__opencl_atomic_fetch_sub:
4211 case AO__opencl_atomic_fetch_and:
4212 case AO__opencl_atomic_fetch_or:
4213 case AO__opencl_atomic_fetch_xor:
4214 case AO__opencl_atomic_fetch_min:
4215 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004216 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004217 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004218
4219 case AO__c11_atomic_compare_exchange_strong:
4220 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004221 return 5;
4222
Yaxun Liu39195062017-08-04 18:16:31 +00004223 case AO__opencl_atomic_compare_exchange_strong:
4224 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004225 case AO__atomic_compare_exchange:
4226 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004227 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004228 }
4229 llvm_unreachable("unknown atomic op");
4230}
Alexey Bataeva1764212015-09-30 09:22:36 +00004231
Yaxun Liu39195062017-08-04 18:16:31 +00004232QualType AtomicExpr::getValueType() const {
4233 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4234 if (auto AT = T->getAs<AtomicType>())
4235 return AT->getValueType();
4236 return T;
4237}
4238
Alexey Bataev31300ed2016-02-04 11:27:03 +00004239QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004240 unsigned ArraySectionCount = 0;
4241 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4242 Base = OASE->getBase();
4243 ++ArraySectionCount;
4244 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004245 while (auto *ASE =
4246 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004247 Base = ASE->getBase();
4248 ++ArraySectionCount;
4249 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004250 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004251 auto OriginalTy = Base->getType();
4252 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4253 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4254 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4255
4256 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4257 if (OriginalTy->isAnyPointerType())
4258 OriginalTy = OriginalTy->getPointeeType();
4259 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004260 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004261 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4262 }
4263 }
4264 return OriginalTy;
4265}