blob: b2593ef4675109835f14a7f8771e988789bb1556 [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)) {
111 if (BO->isPtrMemOp()) {
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;
Alexis Hunta8136cc2010-05-05 15:23:54 +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;
Alexis Hunta8136cc2010-05-05 15:23:54 +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 }
Alexis Hunta8136cc2010-05-05 15:23:54 +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();
Alexis Hunta8136cc2010-05-05 15:23:54 +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;
Alexis Hunta8136cc2010-05-05 15:23:54 +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();
Alexis Hunta8136cc2010-05-05 15:23:54 +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 }
Alexis Hunta8136cc2010-05-05 15:23:54 +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();
Alexis Hunta8136cc2010-05-05 15:23:54 +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//
195// See also Stmt.cpp:{getLocStart(),getLocEnd()}.
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) {
212 return static_cast<const E*>(expr)->getLocStart();
213 }
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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +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 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000262
Douglas Gregored6c7442009-11-23 11:41:28 +0000263 // (TD) - a conversion-function-id that specifies a dependent type
Douglas Gregorf144f4f2011-01-19 21:52:31 +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 }
273
274 if (T->isInstantiationDependentType())
275 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000276 }
Douglas Gregor678d76c2011-07-01 01:22:09 +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 }
284
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
Douglas Gregor0e4de762010-05-11 08:41:30 +0000305 // (VD) - FIXME: Missing from the standard:
306 // - a member function or a static data member of the current
307 // instantiation
Richard Smithec8dcd22011-11-08 01:31:09 +0000308 if (Var->isStaticDataMember() &&
309 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 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000316
317 return;
318 }
319
Douglas Gregor0e4de762010-05-11 08:41:30 +0000320 // (VD) - FIXME: Missing from the standard:
321 // - a member function or a static data member of the current
322 // 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),
Chandler Carruth0e439962011-05-01 21:29:53 +0000354 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
355 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000356 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000357 new (getTrailingObjects<NestedNameSpecifierLoc>())
358 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000359 auto *NNS = QualifierLoc.getNestedNameSpecifier();
360 if (NNS->isInstantiationDependent())
361 ExprBits.InstantiationDependent = true;
362 if (NNS->containsUnexpandedParameterPack())
363 ExprBits.ContainsUnexpandedParameterPack = true;
364 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000365 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
366 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000367 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000368 DeclRefExprBits.HasTemplateKWAndArgsInfo
369 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000370 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
371 RefersToEnclosingVariableOrCapture;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000372 if (TemplateArgs) {
373 bool Dependent = false;
374 bool InstantiationDependent = false;
375 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000376 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
377 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
378 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000379 assert(!Dependent && "built a DeclRefExpr with dependent template args");
380 ExprBits.InstantiationDependent |= InstantiationDependent;
381 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000382 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000383 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
384 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000385 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000386 DeclRefExprBits.HadMultipleCandidates = 0;
387
Daniel Dunbar9d355812012-03-09 01:51:51 +0000388 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000389}
390
Craig Topperce7167c2013-08-22 04:58:56 +0000391DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000392 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000393 SourceLocation TemplateKWLoc,
John McCallce546572009-12-08 09:08:17 +0000394 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000395 bool RefersToEnclosingVariableOrCapture,
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000396 SourceLocation NameLoc,
Douglas Gregored6c7442009-11-23 11:41:28 +0000397 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000398 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000399 NamedDecl *FoundD,
Douglas Gregored6c7442009-11-23 11:41:28 +0000400 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000401 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000402 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000403 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000404 T, VK, FoundD, TemplateArgs);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000405}
406
Craig Topperce7167c2013-08-22 04:58:56 +0000407DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000408 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000409 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000410 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000411 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000412 const DeclarationNameInfo &NameInfo,
413 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000414 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000415 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000416 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000417 // Filter out cases where the found Decl is the same as the value refenenced.
418 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000419 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000420
James Y Knighte7d82282015-12-29 18:15:14 +0000421 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
422 std::size_t Size =
423 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
424 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
425 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
426 HasTemplateKWAndArgsInfo ? 1 : 0,
427 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000428
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000429 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000430 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000431 RefersToEnclosingVariableOrCapture,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000432 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000433}
434
Craig Topperce7167c2013-08-22 04:58:56 +0000435DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000436 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000437 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000438 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000439 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000440 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
441 std::size_t Size =
442 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
443 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
444 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
445 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000446 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000447 return new (Mem) DeclRefExpr(EmptyShell());
448}
449
Daniel Dunbarb507f272012-03-09 15:39:15 +0000450SourceLocation DeclRefExpr::getLocStart() const {
451 if (hasQualifier())
452 return getQualifierLoc().getBeginLoc();
453 return getNameInfo().getLocStart();
454}
455SourceLocation DeclRefExpr::getLocEnd() const {
456 if (hasExplicitTemplateArgs())
457 return getRAngleLoc();
458 return getNameInfo().getLocEnd();
459}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000460
Alexey Bataevec474782014-10-09 08:45:04 +0000461PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
462 StringLiteral *SL)
463 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
464 FNTy->isDependentType(), FNTy->isDependentType(),
465 FNTy->isInstantiationDependentType(),
466 /*ContainsUnexpandedParameterPack=*/false),
467 Loc(L), Type(IT), FnName(SL) {}
468
469StringLiteral *PredefinedExpr::getFunctionName() {
Alexey Bataev769562a2014-10-10 18:58:13 +0000470 return cast_or_null<StringLiteral>(FnName);
Alexey Bataevec474782014-10-09 08:45:04 +0000471}
472
473StringRef PredefinedExpr::getIdentTypeName(PredefinedExpr::IdentType IT) {
474 switch (IT) {
475 case Func:
476 return "__func__";
477 case Function:
478 return "__FUNCTION__";
479 case FuncDName:
480 return "__FUNCDNAME__";
481 case LFunction:
482 return "L__FUNCTION__";
483 case PrettyFunction:
484 return "__PRETTY_FUNCTION__";
485 case FuncSig:
486 return "__FUNCSIG__";
487 case PrettyFunctionNoVirtual:
488 break;
489 }
490 llvm_unreachable("Unknown ident type for PredefinedExpr");
491}
492
Anders Carlsson2fb08242009-09-08 18:24:21 +0000493// FIXME: Maybe this should use DeclPrinter with a special "print predefined
494// expr" policy instead.
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000495std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
496 ASTContext &Context = CurrentDecl->getASTContext();
497
David Majnemerbed356a2013-11-06 23:31:56 +0000498 if (IT == PredefinedExpr::FuncDName) {
499 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000500 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000501 MC.reset(Context.createMangleContext());
502
503 if (MC->shouldMangleDeclName(ND)) {
504 SmallString<256> Buffer;
505 llvm::raw_svector_ostream Out(Buffer);
506 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
507 MC->mangleCXXCtor(CD, Ctor_Base, Out);
508 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
509 MC->mangleCXXDtor(DD, Dtor_Base, Out);
510 else
511 MC->mangleName(ND, Out);
512
David Majnemerbed356a2013-11-06 23:31:56 +0000513 if (!Buffer.empty() && Buffer.front() == '\01')
514 return Buffer.substr(1);
515 return Buffer.str();
516 } else
517 return ND->getIdentifier()->getName();
518 }
519 return "";
520 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000521 if (isa<BlockDecl>(CurrentDecl)) {
522 // For blocks we only emit something if it is enclosed in a function
523 // For top-level block we'd like to include the name of variable, but we
524 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000525 auto DC = CurrentDecl->getDeclContext();
526 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000527 return "";
528
529 SmallString<256> Buffer;
530 llvm::raw_svector_ostream Out(Buffer);
531 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
532 // For nested blocks, propagate up to the parent.
533 Out << ComputeName(IT, DCBlock);
534 else if (auto *DCDecl = dyn_cast<Decl>(DC))
535 Out << ComputeName(IT, DCDecl) << "_block_invoke";
Alexey Bataevec474782014-10-09 08:45:04 +0000536 return Out.str();
537 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000538 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000539 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual && IT != FuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000540 return FD->getNameAsString();
541
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000542 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000543 llvm::raw_svector_ostream Out(Name);
544
545 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000546 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000547 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000548 if (MD->isStatic())
549 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000550 }
551
David Blaikiebbafb8a2012-03-11 07:00:24 +0000552 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000553 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000554 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000555
Douglas Gregor11a434a2012-04-10 20:14:15 +0000556 const FunctionDecl *Decl = FD;
557 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
558 Decl = Pattern;
559 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000560 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000561 if (FD->hasWrittenPrototype())
562 FT = dyn_cast<FunctionProtoType>(AFT);
563
Reid Kleckner52eddda2014-04-08 18:13:24 +0000564 if (IT == FuncSig) {
Richard Smith2f63d462017-01-09 21:40:40 +0000565 switch (AFT->getCallConv()) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000566 case CC_C: POut << "__cdecl "; break;
567 case CC_X86StdCall: POut << "__stdcall "; break;
568 case CC_X86FastCall: POut << "__fastcall "; break;
569 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000570 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000571 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000572 // Only bother printing the conventions that MSVC knows about.
573 default: break;
574 }
575 }
576
577 FD->printQualifiedName(POut, Policy);
578
Douglas Gregor11a434a2012-04-10 20:14:15 +0000579 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000580 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000581 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000582 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000583 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000584 }
585
586 if (FT->isVariadic()) {
587 if (FD->getNumParams()) POut << ", ";
588 POut << "...";
Richard Smithcf63b842017-01-09 22:16:16 +0000589 } else if ((IT == FuncSig || !Context.getLangOpts().CPlusPlus) &&
590 !Decl->getNumParams()) {
591 POut << "void";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000592 }
593 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000594 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000595
Sam Weinig4e83bd22009-12-27 01:38:20 +0000596 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Richard Smith2f63d462017-01-09 21:40:40 +0000597 assert(FT && "We must have a written prototype in this case.");
David Blaikief5697e52012-08-10 00:55:35 +0000598 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000599 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000600 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000601 POut << " volatile";
602 RefQualifierKind Ref = MD->getRefQualifier();
603 if (Ref == RQ_LValue)
604 POut << " &";
605 else if (Ref == RQ_RValue)
606 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000607 }
608
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000609 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000610 SpecsTy Specs;
611 const DeclContext *Ctx = FD->getDeclContext();
612 while (Ctx && isa<NamedDecl>(Ctx)) {
613 const ClassTemplateSpecializationDecl *Spec
614 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
615 if (Spec && !Spec->isExplicitSpecialization())
616 Specs.push_back(Spec);
617 Ctx = Ctx->getParent();
618 }
619
620 std::string TemplateParams;
621 llvm::raw_string_ostream TOut(TemplateParams);
622 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
623 I != E; ++I) {
624 const TemplateParameterList *Params
625 = (*I)->getSpecializedTemplate()->getTemplateParameters();
626 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
627 assert(Params->size() == Args.size());
628 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
629 StringRef Param = Params->getParam(i)->getName();
630 if (Param.empty()) continue;
631 TOut << Param << " = ";
632 Args.get(i).print(Policy, TOut);
633 TOut << ", ";
634 }
635 }
636
637 FunctionTemplateSpecializationInfo *FSI
638 = FD->getTemplateSpecializationInfo();
639 if (FSI && !FSI->isExplicitSpecialization()) {
640 const TemplateParameterList* Params
641 = FSI->getTemplate()->getTemplateParameters();
642 const TemplateArgumentList* Args = FSI->TemplateArguments;
643 assert(Params->size() == Args->size());
644 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
645 StringRef Param = Params->getParam(i)->getName();
646 if (Param.empty()) continue;
647 TOut << Param << " = ";
648 Args->get(i).print(Policy, TOut);
649 TOut << ", ";
650 }
651 }
652
653 TOut.flush();
654 if (!TemplateParams.empty()) {
655 // remove the trailing comma and space
656 TemplateParams.resize(TemplateParams.size() - 2);
657 POut << " [" << TemplateParams << "]";
658 }
659
660 POut.flush();
661
Benjamin Kramer90f54222013-08-21 11:45:27 +0000662 // Print "auto" for all deduced return types. This includes C++1y return
663 // type deduction and lambdas. For trailing return types resolve the
664 // decltype expression. Otherwise print the real type when this is
665 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000666 if (isa<CXXMethodDecl>(FD) &&
667 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000668 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000669 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
670 FT->getReturnType()
671 ->getAs<DecltypeType>()
672 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000673 .getAsStringInternal(Proto, Policy);
674 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000675 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000676
677 Out << Proto;
678
Anders Carlsson2fb08242009-09-08 18:24:21 +0000679 return Name.str().str();
680 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000681 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
682 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
683 // Skip to its enclosing function or method, but not its enclosing
684 // CapturedDecl.
685 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
686 const Decl *D = Decl::castFromDeclContext(DC);
687 return ComputeName(IT, D);
688 }
689 llvm_unreachable("CapturedDecl not inside a function or method");
690 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000691 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000692 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000693 llvm::raw_svector_ostream Out(Name);
694 Out << (MD->isInstanceMethod() ? '-' : '+');
695 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000696
697 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
698 // a null check to avoid a crash.
699 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000700 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000701
Anders Carlsson2fb08242009-09-08 18:24:21 +0000702 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000703 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000704 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000705
Anders Carlsson2fb08242009-09-08 18:24:21 +0000706 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000707 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000708 Out << ']';
709
Anders Carlsson2fb08242009-09-08 18:24:21 +0000710 return Name.str().str();
711 }
712 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
713 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
714 return "top level";
715 }
716 return "";
717}
718
Craig Topper37932912013-08-18 10:09:15 +0000719void APNumericStorage::setIntValue(const ASTContext &C,
720 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000721 if (hasAllocation())
722 C.Deallocate(pVal);
723
724 BitWidth = Val.getBitWidth();
725 unsigned NumWords = Val.getNumWords();
726 const uint64_t* Words = Val.getRawData();
727 if (NumWords > 1) {
728 pVal = new (C) uint64_t[NumWords];
729 std::copy(Words, Words + NumWords, pVal);
730 } else if (NumWords == 1)
731 VAL = Words[0];
732 else
733 VAL = 0;
734}
735
Craig Topper37932912013-08-18 10:09:15 +0000736IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000737 QualType type, SourceLocation l)
738 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
739 false, false),
740 Loc(l) {
741 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
742 assert(V.getBitWidth() == C.getIntWidth(type) &&
743 "Integer type is not the correct size for constant.");
744 setValue(C, V);
745}
746
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000747IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000748IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000749 QualType type, SourceLocation l) {
750 return new (C) IntegerLiteral(C, V, type, l);
751}
752
753IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000754IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000755 return new (C) IntegerLiteral(Empty);
756}
757
Craig Topper37932912013-08-18 10:09:15 +0000758FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000759 bool isexact, QualType Type, SourceLocation L)
760 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
761 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000762 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000763 FloatingLiteralBits.IsExact = isexact;
764 setValue(C, V);
765}
766
Craig Topper37932912013-08-18 10:09:15 +0000767FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000768 : Expr(FloatingLiteralClass, Empty) {
Tim Northover178723a2013-01-22 09:46:51 +0000769 setRawSemantics(IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000770 FloatingLiteralBits.IsExact = false;
771}
772
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000773FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000774FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000775 bool isexact, QualType Type, SourceLocation L) {
776 return new (C) FloatingLiteral(C, V, isexact, Type, L);
777}
778
779FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000780FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000781 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000782}
783
Tim Northover178723a2013-01-22 09:46:51 +0000784const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
785 switch(FloatingLiteralBits.Semantics) {
786 case IEEEhalf:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000787 return llvm::APFloat::IEEEhalf();
Tim Northover178723a2013-01-22 09:46:51 +0000788 case IEEEsingle:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000789 return llvm::APFloat::IEEEsingle();
Tim Northover178723a2013-01-22 09:46:51 +0000790 case IEEEdouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000791 return llvm::APFloat::IEEEdouble();
Tim Northover178723a2013-01-22 09:46:51 +0000792 case x87DoubleExtended:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000793 return llvm::APFloat::x87DoubleExtended();
Tim Northover178723a2013-01-22 09:46:51 +0000794 case IEEEquad:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000795 return llvm::APFloat::IEEEquad();
Tim Northover178723a2013-01-22 09:46:51 +0000796 case PPCDoubleDouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000797 return llvm::APFloat::PPCDoubleDouble();
Tim Northover178723a2013-01-22 09:46:51 +0000798 }
799 llvm_unreachable("Unrecognised floating semantics");
800}
801
802void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000803 if (&Sem == &llvm::APFloat::IEEEhalf())
Tim Northover178723a2013-01-22 09:46:51 +0000804 FloatingLiteralBits.Semantics = IEEEhalf;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000805 else if (&Sem == &llvm::APFloat::IEEEsingle())
Tim Northover178723a2013-01-22 09:46:51 +0000806 FloatingLiteralBits.Semantics = IEEEsingle;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000807 else if (&Sem == &llvm::APFloat::IEEEdouble())
Tim Northover178723a2013-01-22 09:46:51 +0000808 FloatingLiteralBits.Semantics = IEEEdouble;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000809 else if (&Sem == &llvm::APFloat::x87DoubleExtended())
Tim Northover178723a2013-01-22 09:46:51 +0000810 FloatingLiteralBits.Semantics = x87DoubleExtended;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000811 else if (&Sem == &llvm::APFloat::IEEEquad())
Tim Northover178723a2013-01-22 09:46:51 +0000812 FloatingLiteralBits.Semantics = IEEEquad;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000813 else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
Tim Northover178723a2013-01-22 09:46:51 +0000814 FloatingLiteralBits.Semantics = PPCDoubleDouble;
815 else
816 llvm_unreachable("Unknown floating semantics");
817}
818
Chris Lattnera0173132008-06-07 22:13:43 +0000819/// getValueAsApproximateDouble - This returns the value as an inaccurate
820/// double. Note that this may cause loss of precision, but is useful for
821/// debugging dumps, etc.
822double FloatingLiteral::getValueAsApproximateDouble() const {
823 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000824 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000825 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
Dale Johannesenc48814b2008-10-09 23:02:32 +0000826 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000827 return V.convertToDouble();
828}
829
Nick Lewycky4ed84042012-02-24 09:07:53 +0000830int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
Eli Friedman381f4312012-02-29 20:59:56 +0000831 int CharByteWidth = 0;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000832 switch(k) {
Eli Friedmanfcec6302011-11-01 02:23:42 +0000833 case Ascii:
834 case UTF8:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000835 CharByteWidth = target.getCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000836 break;
837 case Wide:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000838 CharByteWidth = target.getWCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000839 break;
840 case UTF16:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000841 CharByteWidth = target.getChar16Width();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000842 break;
843 case UTF32:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000844 CharByteWidth = target.getChar32Width();
Eli Friedman381f4312012-02-29 20:59:56 +0000845 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000846 }
847 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
848 CharByteWidth /= 8;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000849 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
Eli Friedmanfcec6302011-11-01 02:23:42 +0000850 && "character byte widths supported are 1, 2, and 4 only");
851 return CharByteWidth;
852}
853
Craig Topper37932912013-08-18 10:09:15 +0000854StringLiteral *StringLiteral::Create(const ASTContext &C, StringRef Str,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000855 StringKind Kind, bool Pascal, QualType Ty,
Mike Stump11289f42009-09-09 15:08:12 +0000856 const SourceLocation *Loc,
Anders Carlssona3905812009-03-15 18:34:13 +0000857 unsigned NumStrs) {
Benjamin Kramercdac7612014-02-25 12:26:20 +0000858 assert(C.getAsConstantArrayType(Ty) &&
859 "StringLiteral must be of constant array type!");
860
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000861 // Allocate enough space for the StringLiteral plus an array of locations for
862 // any concatenated string tokens.
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000863 void *Mem =
864 C.Allocate(sizeof(StringLiteral) + sizeof(SourceLocation) * (NumStrs - 1),
865 alignof(StringLiteral));
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000866 StringLiteral *SL = new (Mem) StringLiteral(Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000867
Steve Naroffdf7855b2007-02-21 23:46:25 +0000868 // OPTIMIZE: could allocate this appended to the StringLiteral.
Eli Friedmanfcec6302011-11-01 02:23:42 +0000869 SL->setString(C,Str,Kind,Pascal);
870
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000871 SL->TokLocs[0] = Loc[0];
872 SL->NumConcatenated = NumStrs;
Chris Lattnerd3e98952006-10-06 05:22:26 +0000873
Chris Lattner630970d2009-02-18 05:49:11 +0000874 if (NumStrs != 1)
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000875 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
876 return SL;
Chris Lattner630970d2009-02-18 05:49:11 +0000877}
878
Craig Topper37932912013-08-18 10:09:15 +0000879StringLiteral *StringLiteral::CreateEmpty(const ASTContext &C,
880 unsigned NumStrs) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000881 void *Mem =
882 C.Allocate(sizeof(StringLiteral) + sizeof(SourceLocation) * (NumStrs - 1),
883 alignof(StringLiteral));
Anastasia Stulova59055b92018-05-09 13:23:26 +0000884 StringLiteral *SL =
885 new (Mem) StringLiteral(C.adjustStringLiteralBaseType(QualType()));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000886 SL->CharByteWidth = 0;
887 SL->Length = 0;
Douglas Gregor958dfc92009-04-15 16:35:07 +0000888 SL->NumConcatenated = NumStrs;
889 return SL;
890}
891
Alexander Kornienko540bacb2013-02-01 12:35:51 +0000892void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +0000893 switch (getKind()) {
894 case Ascii: break; // no prefix.
895 case Wide: OS << 'L'; break;
896 case UTF8: OS << "u8"; break;
897 case UTF16: OS << 'u'; break;
898 case UTF32: OS << 'U'; break;
899 }
900 OS << '"';
901 static const char Hex[] = "0123456789ABCDEF";
902
903 unsigned LastSlashX = getLength();
904 for (unsigned I = 0, N = getLength(); I != N; ++I) {
905 switch (uint32_t Char = getCodeUnit(I)) {
906 default:
907 // FIXME: Convert UTF-8 back to codepoints before rendering.
908
909 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
910 // Leave invalid surrogates alone; we'll use \x for those.
911 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
912 Char <= 0xdbff) {
913 uint32_t Trail = getCodeUnit(I + 1);
914 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
915 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
916 ++I;
917 }
918 }
919
920 if (Char > 0xff) {
921 // If this is a wide string, output characters over 0xff using \x
922 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
923 // codepoint: use \x escapes for invalid codepoints.
924 if (getKind() == Wide ||
925 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
926 // FIXME: Is this the best way to print wchar_t?
927 OS << "\\x";
928 int Shift = 28;
929 while ((Char >> Shift) == 0)
930 Shift -= 4;
931 for (/**/; Shift >= 0; Shift -= 4)
932 OS << Hex[(Char >> Shift) & 15];
933 LastSlashX = I;
934 break;
935 }
936
937 if (Char > 0xffff)
938 OS << "\\U00"
939 << Hex[(Char >> 20) & 15]
940 << Hex[(Char >> 16) & 15];
941 else
942 OS << "\\u";
943 OS << Hex[(Char >> 12) & 15]
944 << Hex[(Char >> 8) & 15]
945 << Hex[(Char >> 4) & 15]
946 << Hex[(Char >> 0) & 15];
947 break;
948 }
949
950 // If we used \x... for the previous character, and this character is a
951 // hexadecimal digit, prevent it being slurped as part of the \x.
952 if (LastSlashX + 1 == I) {
953 switch (Char) {
954 case '0': case '1': case '2': case '3': case '4':
955 case '5': case '6': case '7': case '8': case '9':
956 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
957 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
958 OS << "\"\"";
959 }
960 }
961
962 assert(Char <= 0xff &&
963 "Characters above 0xff should already have been handled.");
964
Jordan Rosea7d03842013-02-08 22:30:41 +0000965 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +0000966 OS << (char)Char;
967 else // Output anything hard as an octal escape.
968 OS << '\\'
969 << (char)('0' + ((Char >> 6) & 7))
970 << (char)('0' + ((Char >> 3) & 7))
971 << (char)('0' + ((Char >> 0) & 7));
972 break;
973 // Handle some common non-printable cases to make dumps prettier.
974 case '\\': OS << "\\\\"; break;
975 case '"': OS << "\\\""; break;
Richard Trieudc355912012-06-13 20:25:24 +0000976 case '\a': OS << "\\a"; break;
977 case '\b': OS << "\\b"; break;
Benjamin Kramer60a53d52016-11-24 09:41:33 +0000978 case '\f': OS << "\\f"; break;
979 case '\n': OS << "\\n"; break;
980 case '\r': OS << "\\r"; break;
981 case '\t': OS << "\\t"; break;
982 case '\v': OS << "\\v"; break;
Richard Trieudc355912012-06-13 20:25:24 +0000983 }
984 }
985 OS << '"';
986}
987
Craig Topper37932912013-08-18 10:09:15 +0000988void StringLiteral::setString(const ASTContext &C, StringRef Str,
Eli Friedmanfcec6302011-11-01 02:23:42 +0000989 StringKind Kind, bool IsPascal) {
990 //FIXME: we assume that the string data comes from a target that uses the same
Simon Pilgrim2c518802017-03-30 14:13:19 +0000991 // code unit size and endianness for the type of string.
Eli Friedmanfcec6302011-11-01 02:23:42 +0000992 this->Kind = Kind;
993 this->IsPascal = IsPascal;
994
Nick Lewycky4ed84042012-02-24 09:07:53 +0000995 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
Eli Friedmanfcec6302011-11-01 02:23:42 +0000996 assert((Str.size()%CharByteWidth == 0)
997 && "size of data must be multiple of CharByteWidth");
998 Length = Str.size()/CharByteWidth;
999
1000 switch(CharByteWidth) {
1001 case 1: {
1002 char *AStrData = new (C) char[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +00001003 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +00001004 StrData.asChar = AStrData;
1005 break;
1006 }
1007 case 2: {
1008 uint16_t *AStrData = new (C) uint16_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +00001009 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +00001010 StrData.asUInt16 = AStrData;
1011 break;
1012 }
1013 case 4: {
1014 uint32_t *AStrData = new (C) uint32_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +00001015 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +00001016 StrData.asUInt32 = AStrData;
1017 break;
1018 }
1019 default:
Davide Italiano04839a52016-01-30 08:03:54 +00001020 llvm_unreachable("unsupported CharByteWidth");
Eli Friedmanfcec6302011-11-01 02:23:42 +00001021 }
Douglas Gregor958dfc92009-04-15 16:35:07 +00001022}
1023
Chris Lattnere925d612010-11-17 07:37:15 +00001024/// getLocationOfByte - Return a source location that points to the specified
1025/// byte of this string literal.
1026///
1027/// Strings are amazingly complex. They can be formed from multiple tokens and
1028/// can have escape sequences in them in addition to the usual trigraph and
1029/// escaped newline business. This routine handles this complexity.
1030///
Richard Smithefb116f2015-12-10 01:11:47 +00001031/// The *StartToken sets the first token to be searched in this function and
1032/// the *StartTokenByteOffset is the byte offset of the first token. Before
1033/// returning, it updates the *StartToken to the TokNo of the token being found
1034/// and sets *StartTokenByteOffset to the byte offset of the token in the
1035/// string.
1036/// Using these two parameters can reduce the time complexity from O(n^2) to
1037/// O(n) if one wants to get the location of byte for all the tokens in a
1038/// string.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001039///
Richard Smithefb116f2015-12-10 01:11:47 +00001040SourceLocation
1041StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1042 const LangOptions &Features,
1043 const TargetInfo &Target, unsigned *StartToken,
1044 unsigned *StartTokenByteOffset) const {
Richard Smith4060f772012-06-13 05:37:23 +00001045 assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
1046 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001047
Chris Lattnere925d612010-11-17 07:37:15 +00001048 // Loop over all of the tokens in this string until we find the one that
1049 // contains the byte we're looking for.
1050 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001051 unsigned StringOffset = 0;
1052 if (StartToken)
1053 TokNo = *StartToken;
1054 if (StartTokenByteOffset) {
1055 StringOffset = *StartTokenByteOffset;
1056 ByteNo -= StringOffset;
1057 }
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001058 while (1) {
Chris Lattnere925d612010-11-17 07:37:15 +00001059 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1060 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1061
1062 // Get the spelling of the string so that we can get the data that makes up
1063 // the string literal, not the identifier for the macro it is potentially
1064 // expanded through.
1065 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001066
Chris Lattnere925d612010-11-17 07:37:15 +00001067 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001068 std::pair<FileID, unsigned> LocInfo =
1069 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001070 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001071 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001072 if (Invalid) {
1073 if (StartTokenByteOffset != nullptr)
1074 *StartTokenByteOffset = StringOffset;
1075 if (StartToken != nullptr)
1076 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001077 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001078 }
1079
Chris Lattnere925d612010-11-17 07:37:15 +00001080 const char *StrData = Buffer.data()+LocInfo.second;
1081
Chris Lattnere925d612010-11-17 07:37:15 +00001082 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001083 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1084 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001085 Token TheTok;
1086 TheLexer.LexFromRawLexer(TheTok);
1087
1088 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001089 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001090 unsigned TokNumBytes = SLP.GetStringLength();
1091
1092 // If the byte is in this token, return the location of the byte.
1093 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001094 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001095 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1096
Chris Lattnere925d612010-11-17 07:37:15 +00001097 // Now that we know the offset of the token in the spelling, use the
1098 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001099 if (StartTokenByteOffset != nullptr)
1100 *StartTokenByteOffset = StringOffset;
1101 if (StartToken != nullptr)
1102 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001103 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1104 }
Richard Smithefb116f2015-12-10 01:11:47 +00001105
Chris Lattnere925d612010-11-17 07:37:15 +00001106 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001107 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001108 ++TokNo;
1109 ByteNo -= TokNumBytes;
1110 }
1111}
1112
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001113
1114
Chris Lattner1b926492006-08-23 06:42:10 +00001115/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1116/// corresponds to, e.g. "sizeof" or "[pre]++".
David Blaikie1d202a62012-10-08 01:11:04 +00001117StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001118 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001119#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1120#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001121 }
David Blaikief47fa302012-01-17 02:30:50 +00001122 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001123}
1124
John McCalle3027922010-08-25 11:45:40 +00001125UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001126UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1127 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001128 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001129 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1130 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1131 case OO_Amp: return UO_AddrOf;
1132 case OO_Star: return UO_Deref;
1133 case OO_Plus: return UO_Plus;
1134 case OO_Minus: return UO_Minus;
1135 case OO_Tilde: return UO_Not;
1136 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001137 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001138 }
1139}
1140
1141OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1142 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001143 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1144 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1145 case UO_AddrOf: return OO_Amp;
1146 case UO_Deref: return OO_Star;
1147 case UO_Plus: return OO_Plus;
1148 case UO_Minus: return OO_Minus;
1149 case UO_Not: return OO_Tilde;
1150 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001151 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001152 default: return OO_None;
1153 }
1154}
1155
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001156
Chris Lattner0eedafe2006-08-24 04:56:27 +00001157//===----------------------------------------------------------------------===//
1158// Postfix Operators.
1159//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001160
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001161CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1162 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
Craig Topper37932912013-08-18 10:09:15 +00001163 ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001164 : Expr(SC, t, VK, OK_Ordinary, fn->isTypeDependent(),
1165 fn->isValueDependent(), fn->isInstantiationDependent(),
1166 fn->containsUnexpandedParameterPack()),
1167 NumArgs(args.size()) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001168
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001169 unsigned NumPreArgs = preargs.size();
1170 SubExprs = new (C) Stmt *[args.size()+PREARGS_START+NumPreArgs];
Douglas Gregor993603d2008-11-14 16:09:21 +00001171 SubExprs[FN] = fn;
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001172 for (unsigned i = 0; i != NumPreArgs; ++i) {
1173 updateDependenciesFromArg(preargs[i]);
1174 SubExprs[i+PREARGS_START] = preargs[i];
1175 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00001176 for (unsigned i = 0; i != args.size(); ++i) {
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001177 updateDependenciesFromArg(args[i]);
Peter Collingbourne3a347252011-02-08 21:18:02 +00001178 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00001179 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001180
Peter Collingbourne3a347252011-02-08 21:18:02 +00001181 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor993603d2008-11-14 16:09:21 +00001182 RParenLoc = rparenloc;
1183}
Nate Begeman1e36a852008-01-17 17:46:27 +00001184
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001185CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1186 ArrayRef<Expr *> args, QualType t, ExprValueKind VK,
1187 SourceLocation rparenloc)
1188 : CallExpr(C, SC, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {}
1189
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001190CallExpr::CallExpr(const ASTContext &C, Expr *fn, ArrayRef<Expr *> args,
John McCall7decc9e2010-11-18 06:31:45 +00001191 QualType t, ExprValueKind VK, SourceLocation rparenloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001192 : CallExpr(C, CallExprClass, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {
1193}
Chris Lattnere165d942006-08-24 04:40:38 +00001194
Craig Topper37932912013-08-18 10:09:15 +00001195CallExpr::CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001196 : CallExpr(C, SC, /*NumPreArgs=*/0, Empty) {}
Peter Collingbourne3a347252011-02-08 21:18:02 +00001197
Craig Topper37932912013-08-18 10:09:15 +00001198CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
Peter Collingbourne3a347252011-02-08 21:18:02 +00001199 EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001200 : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001201 // FIXME: Why do we allocate this?
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001202 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs]();
Peter Collingbourne3a347252011-02-08 21:18:02 +00001203 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregore20a2e52009-04-15 17:43:59 +00001204}
1205
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001206void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1207 if (Arg->isTypeDependent())
1208 ExprBits.TypeDependent = true;
1209 if (Arg->isValueDependent())
1210 ExprBits.ValueDependent = true;
1211 if (Arg->isInstantiationDependent())
1212 ExprBits.InstantiationDependent = true;
1213 if (Arg->containsUnexpandedParameterPack())
1214 ExprBits.ContainsUnexpandedParameterPack = true;
1215}
1216
John McCallb92ab1a2016-10-26 23:46:34 +00001217FunctionDecl *CallExpr::getDirectCallee() {
1218 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
1219}
1220
Nuno Lopes518e3702009-12-20 23:11:08 +00001221Decl *CallExpr::getCalleeDecl() {
John McCallb92ab1a2016-10-26 23:46:34 +00001222 return getCallee()->getReferencedDeclOfCallee();
1223}
1224
1225Decl *Expr::getReferencedDeclOfCallee() {
1226 Expr *CEE = IgnoreParenImpCasts();
Douglas Gregore0e96302011-09-06 21:41:04 +00001227
1228 while (SubstNonTypeTemplateParmExpr *NTTP
1229 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1230 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1231 }
1232
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001233 // If we're calling a dereference, look at the pointer instead.
1234 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1235 if (BO->isPtrMemOp())
1236 CEE = BO->getRHS()->IgnoreParenCasts();
1237 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1238 if (UO->getOpcode() == UO_Deref)
1239 CEE = UO->getSubExpr()->IgnoreParenCasts();
1240 }
Chris Lattner52301912009-07-17 15:46:27 +00001241 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001242 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001243 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1244 return ME->getMemberDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001245
Craig Topper36250ad2014-05-12 05:36:57 +00001246 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001247}
1248
Chris Lattnere4407ed2007-12-28 05:25:02 +00001249/// setNumArgs - This changes the number of arguments present in this call.
1250/// Any orphaned expressions are deleted by this, and any new operands are set
1251/// to null.
Craig Topper37932912013-08-18 10:09:15 +00001252void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001253 // No change, just return.
1254 if (NumArgs == getNumArgs()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001255
Chris Lattnere4407ed2007-12-28 05:25:02 +00001256 // If shrinking # arguments, just delete the extras and forgot them.
1257 if (NumArgs < getNumArgs()) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001258 this->NumArgs = NumArgs;
1259 return;
1260 }
1261
1262 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001263 unsigned NumPreArgs = getNumPreArgs();
1264 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnere4407ed2007-12-28 05:25:02 +00001265 // Copy over args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001266 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnere4407ed2007-12-28 05:25:02 +00001267 NewSubExprs[i] = SubExprs[i];
1268 // Null out new args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001269 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1270 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001271 NewSubExprs[i] = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001272
Douglas Gregorba6e5572009-04-17 21:46:47 +00001273 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnere4407ed2007-12-28 05:25:02 +00001274 SubExprs = NewSubExprs;
1275 this->NumArgs = NumArgs;
1276}
1277
Alp Tokera724cff2013-12-28 21:59:02 +00001278/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001279/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001280unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001281 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001282 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001283 // ImplicitCastExpr.
1284 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1285 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001286 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001287
Steve Narofff6e3b3292008-01-31 01:07:12 +00001288 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1289 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001290 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001291
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001292 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1293 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001294 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001295
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001296 if (!FDecl->getIdentifier())
1297 return 0;
1298
Douglas Gregor15fc9562009-09-12 00:22:50 +00001299 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001300}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001301
Scott Douglass503fc392015-06-10 13:53:15 +00001302bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001303 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001304 return Ctx.BuiltinInfo.isUnevaluated(BI);
1305 return false;
1306}
1307
David Majnemerced8bdf2015-02-25 17:36:15 +00001308QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1309 const Expr *Callee = getCallee();
1310 QualType CalleeType = Callee->getType();
1311 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001312 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001313 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001314 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001315 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1316 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1317 return Ctx.VoidTy;
1318
John McCall0009fcc2011-04-26 20:42:42 +00001319 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001320 CalleeType = Expr::findBoundMemberType(Callee);
1321 }
1322
John McCall0009fcc2011-04-26 20:42:42 +00001323 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001324 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001325}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001326
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001327SourceLocation CallExpr::getLocStart() const {
1328 if (isa<CXXOperatorCallExpr>(this))
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001329 return cast<CXXOperatorCallExpr>(this)->getLocStart();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001330
1331 SourceLocation begin = getCallee()->getLocStart();
Keno Fischer070db172014-08-15 01:39:12 +00001332 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001333 begin = getArg(0)->getLocStart();
1334 return begin;
1335}
1336SourceLocation CallExpr::getLocEnd() const {
1337 if (isa<CXXOperatorCallExpr>(this))
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001338 return cast<CXXOperatorCallExpr>(this)->getLocEnd();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001339
1340 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001341 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001342 end = getArg(getNumArgs() - 1)->getLocEnd();
1343 return end;
1344}
John McCall701417a2011-02-21 06:23:05 +00001345
Craig Topper37932912013-08-18 10:09:15 +00001346OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001347 SourceLocation OperatorLoc,
Alexis Hunta8136cc2010-05-05 15:23:54 +00001348 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001349 ArrayRef<OffsetOfNode> comps,
1350 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001351 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001352 void *Mem = C.Allocate(
1353 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001354
Benjamin Kramerc215e762012-08-24 11:54:20 +00001355 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1356 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001357}
1358
Craig Topper37932912013-08-18 10:09:15 +00001359OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001360 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001361 void *Mem =
1362 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001363 return new (Mem) OffsetOfExpr(numComps, numExprs);
1364}
1365
Craig Topper37932912013-08-18 10:09:15 +00001366OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001367 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001368 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001369 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001370 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1371 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001372 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001373 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001374 tsi->getType()->containsUnexpandedParameterPack()),
Alexis Hunta8136cc2010-05-05 15:23:54 +00001375 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001376 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001377{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001378 for (unsigned i = 0; i != comps.size(); ++i) {
1379 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001380 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001381
Benjamin Kramerc215e762012-08-24 11:54:20 +00001382 for (unsigned i = 0; i != exprs.size(); ++i) {
1383 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001384 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001385 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001386 ExprBits.ContainsUnexpandedParameterPack = true;
1387
Benjamin Kramerc215e762012-08-24 11:54:20 +00001388 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001389 }
1390}
1391
James Y Knight7281c352015-12-29 22:31:18 +00001392IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001393 assert(getKind() == Field || getKind() == Identifier);
1394 if (getKind() == Field)
1395 return getField()->getIdentifier();
Alexis Hunta8136cc2010-05-05 15:23:54 +00001396
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001397 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001398}
1399
David Majnemer10fd83d2015-01-15 10:04:14 +00001400UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1401 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1402 SourceLocation op, SourceLocation rp)
1403 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1404 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1405 // Value-dependent if the argument is type-dependent.
1406 E->isTypeDependent(), E->isInstantiationDependent(),
1407 E->containsUnexpandedParameterPack()),
1408 OpLoc(op), RParenLoc(rp) {
1409 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1410 UnaryExprOrTypeTraitExprBits.IsType = false;
1411 Argument.Ex = E;
1412
1413 // Check to see if we are in the situation where alignof(decl) should be
1414 // dependent because decl's alignment is dependent.
1415 if (ExprKind == UETT_AlignOf) {
1416 if (!isValueDependent() || !isInstantiationDependent()) {
1417 E = E->IgnoreParens();
1418
1419 const ValueDecl *D = nullptr;
1420 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1421 D = DRE->getDecl();
1422 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1423 D = ME->getMemberDecl();
1424
1425 if (D) {
1426 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1427 if (I->isAlignmentDependent()) {
1428 setValueDependent(true);
1429 setInstantiationDependent(true);
1430 break;
1431 }
1432 }
1433 }
1434 }
1435 }
1436}
1437
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001438MemberExpr *MemberExpr::Create(
1439 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1440 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1441 ValueDecl *memberdecl, DeclAccessPair founddecl,
1442 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1443 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001444
Douglas Gregorea972d32011-02-28 21:54:11 +00001445 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001446 founddecl.getDecl() != memberdecl ||
1447 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001448
James Y Knighte7d82282015-12-29 18:15:14 +00001449 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1450 std::size_t Size =
1451 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1452 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1453 HasTemplateKWAndArgsInfo ? 1 : 0,
1454 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001455
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001456 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001457 MemberExpr *E = new (Mem)
1458 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001459
1460 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001461 // FIXME: Wrong. We should be looking at the member declaration we found.
1462 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001463 E->setValueDependent(true);
1464 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001465 E->setInstantiationDependent(true);
1466 }
1467 else if (QualifierLoc &&
1468 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1469 E->setInstantiationDependent(true);
1470
John McCall16df1e52010-03-30 21:47:33 +00001471 E->HasQualifierOrFoundDecl = true;
1472
James Y Knighte7d82282015-12-29 18:15:14 +00001473 MemberExprNameQualifier *NQ =
1474 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001475 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001476 NQ->FoundDecl = founddecl;
1477 }
1478
Abramo Bagnara7945c982012-01-27 09:46:47 +00001479 E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1480
John McCall16df1e52010-03-30 21:47:33 +00001481 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001482 bool Dependent = false;
1483 bool InstantiationDependent = false;
1484 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001485 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1486 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1487 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001488 if (InstantiationDependent)
1489 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001490 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001491 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1492 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001493 }
1494
1495 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001496}
1497
Daniel Dunbarb507f272012-03-09 15:39:15 +00001498SourceLocation MemberExpr::getLocStart() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001499 if (isImplicitAccess()) {
1500 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001501 return getQualifierLoc().getBeginLoc();
1502 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001503 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001504
Daniel Dunbarb507f272012-03-09 15:39:15 +00001505 // FIXME: We don't want this to happen. Rather, we should be able to
1506 // detect all kinds of implicit accesses more cleanly.
1507 SourceLocation BaseStartLoc = getBase()->getLocStart();
1508 if (BaseStartLoc.isValid())
1509 return BaseStartLoc;
1510 return MemberLoc;
1511}
1512SourceLocation MemberExpr::getLocEnd() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001513 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001514 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001515 EndLoc = getRAngleLoc();
1516 else if (EndLoc.isInvalid())
1517 EndLoc = getBase()->getLocEnd();
1518 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001519}
1520
Alp Tokerc1086762013-12-07 13:51:35 +00001521bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001522 switch (getCastKind()) {
1523 case CK_DerivedToBase:
1524 case CK_UncheckedDerivedToBase:
1525 case CK_DerivedToBaseMemberPointer:
1526 case CK_BaseToDerived:
1527 case CK_BaseToDerivedMemberPointer:
1528 assert(!path_empty() && "Cast kind should have a base path!");
1529 break;
1530
1531 case CK_CPointerToObjCPointerCast:
1532 assert(getType()->isObjCObjectPointerType());
1533 assert(getSubExpr()->getType()->isPointerType());
1534 goto CheckNoBasePath;
1535
1536 case CK_BlockPointerToObjCPointerCast:
1537 assert(getType()->isObjCObjectPointerType());
1538 assert(getSubExpr()->getType()->isBlockPointerType());
1539 goto CheckNoBasePath;
1540
John McCallc62bb392012-02-15 01:22:51 +00001541 case CK_ReinterpretMemberPointer:
1542 assert(getType()->isMemberPointerType());
1543 assert(getSubExpr()->getType()->isMemberPointerType());
1544 goto CheckNoBasePath;
1545
John McCall9320b872011-09-09 05:25:32 +00001546 case CK_BitCast:
1547 // Arbitrary casts to C pointer types count as bitcasts.
1548 // Otherwise, we should only have block and ObjC pointer casts
1549 // here if they stay within the type kind.
1550 if (!getType()->isPointerType()) {
1551 assert(getType()->isObjCObjectPointerType() ==
1552 getSubExpr()->getType()->isObjCObjectPointerType());
1553 assert(getType()->isBlockPointerType() ==
1554 getSubExpr()->getType()->isBlockPointerType());
1555 }
1556 goto CheckNoBasePath;
1557
1558 case CK_AnyPointerToBlockPointerCast:
1559 assert(getType()->isBlockPointerType());
1560 assert(getSubExpr()->getType()->isAnyPointerType() &&
1561 !getSubExpr()->getType()->isBlockPointerType());
1562 goto CheckNoBasePath;
1563
Douglas Gregored90df32012-02-22 05:02:47 +00001564 case CK_CopyAndAutoreleaseBlockObject:
1565 assert(getType()->isBlockPointerType());
1566 assert(getSubExpr()->getType()->isBlockPointerType());
1567 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001568
1569 case CK_FunctionToPointerDecay:
1570 assert(getType()->isPointerType());
1571 assert(getSubExpr()->getType()->isFunctionType());
1572 goto CheckNoBasePath;
1573
David Tweede1468322013-12-11 13:39:46 +00001574 case CK_AddressSpaceConversion:
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001575 assert(getType()->isPointerType() || getType()->isBlockPointerType());
1576 assert(getSubExpr()->getType()->isPointerType() ||
1577 getSubExpr()->getType()->isBlockPointerType());
David Tweede1468322013-12-11 13:39:46 +00001578 assert(getType()->getPointeeType().getAddressSpace() !=
1579 getSubExpr()->getType()->getPointeeType().getAddressSpace());
Galina Kistanovaf87496d2017-06-03 06:31:42 +00001580 LLVM_FALLTHROUGH;
John McCall9320b872011-09-09 05:25:32 +00001581 // These should not have an inheritance path.
1582 case CK_Dynamic:
1583 case CK_ToUnion:
1584 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001585 case CK_NullToMemberPointer:
1586 case CK_NullToPointer:
1587 case CK_ConstructorConversion:
1588 case CK_IntegralToPointer:
1589 case CK_PointerToIntegral:
1590 case CK_ToVoid:
1591 case CK_VectorSplat:
1592 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001593 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001594 case CK_IntegralToFloating:
1595 case CK_FloatingToIntegral:
1596 case CK_FloatingCast:
1597 case CK_ObjCObjectLValueCast:
1598 case CK_FloatingRealToComplex:
1599 case CK_FloatingComplexToReal:
1600 case CK_FloatingComplexCast:
1601 case CK_FloatingComplexToIntegralComplex:
1602 case CK_IntegralRealToComplex:
1603 case CK_IntegralComplexToReal:
1604 case CK_IntegralComplexCast:
1605 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001606 case CK_ARCProduceObject:
1607 case CK_ARCConsumeObject:
1608 case CK_ARCReclaimReturnedObject:
1609 case CK_ARCExtendBlockObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001610 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00001611 case CK_ZeroToOCLQueue:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001612 case CK_IntToOCLSampler:
John McCall9320b872011-09-09 05:25:32 +00001613 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1614 goto CheckNoBasePath;
1615
1616 case CK_Dependent:
1617 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001618 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001619 case CK_AtomicToNonAtomic:
1620 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001621 case CK_PointerToBoolean:
1622 case CK_IntegralToBoolean:
1623 case CK_FloatingToBoolean:
1624 case CK_MemberPointerToBoolean:
1625 case CK_FloatingComplexToBoolean:
1626 case CK_IntegralComplexToBoolean:
1627 case CK_LValueBitCast: // -> bool&
1628 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001629 case CK_BuiltinFnToFnPtr:
John McCall9320b872011-09-09 05:25:32 +00001630 CheckNoBasePath:
1631 assert(path_empty() && "Cast kind should not have a base path!");
1632 break;
1633 }
Alp Tokerc1086762013-12-07 13:51:35 +00001634 return true;
John McCall9320b872011-09-09 05:25:32 +00001635}
1636
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001637const char *CastExpr::getCastKindName(CastKind CK) {
1638 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001639#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1640#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001641 }
John McCallc5e62b42010-11-13 09:02:35 +00001642 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001643}
1644
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001645namespace {
1646 Expr *skipImplicitTemporary(Expr *expr) {
1647 // Skip through reference binding to temporary.
1648 if (MaterializeTemporaryExpr *Materialize
1649 = dyn_cast<MaterializeTemporaryExpr>(expr))
1650 expr = Materialize->GetTemporaryExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001651
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001652 // Skip any temporary bindings; they're implicit.
1653 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(expr))
1654 expr = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001655
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001656 return expr;
1657 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001658}
1659
Douglas Gregord196a582009-12-14 19:27:10 +00001660Expr *CastExpr::getSubExprAsWritten() {
Craig Topper36250ad2014-05-12 05:36:57 +00001661 Expr *SubExpr = nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001662 CastExpr *E = this;
1663 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001664 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001665
Douglas Gregord196a582009-12-14 19:27:10 +00001666 // Conversions by constructor and conversion functions have a
1667 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001668 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001669 SubExpr =
1670 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001671 else if (E->getCastKind() == CK_UserDefinedConversion) {
1672 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1673 isa<BlockExpr>(SubExpr)) &&
1674 "Unexpected SubExpr for CK_UserDefinedConversion.");
1675 if (isa<CXXMemberCallExpr>(SubExpr))
1676 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1677 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001678
Douglas Gregord196a582009-12-14 19:27:10 +00001679 // If the subexpression we're left with is an implicit cast, look
1680 // through that, too.
Alexis Hunta8136cc2010-05-05 15:23:54 +00001681 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1682
Douglas Gregord196a582009-12-14 19:27:10 +00001683 return SubExpr;
1684}
1685
John McCallcf142162010-08-07 06:22:56 +00001686CXXBaseSpecifier **CastExpr::path_buffer() {
1687 switch (getStmtClass()) {
1688#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001689#define CASTEXPR(Type, Base) \
1690 case Stmt::Type##Class: \
1691 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001692#define STMT(Type, Base)
1693#include "clang/AST/StmtNodes.inc"
1694 default:
1695 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001696 }
1697}
1698
John McCallf1ef7962017-08-15 21:42:47 +00001699const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1700 QualType opType) {
1701 auto RD = unionType->castAs<RecordType>()->getDecl();
1702 return getTargetFieldForToUnionCast(RD, opType);
1703}
1704
1705const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1706 QualType OpType) {
1707 auto &Ctx = RD->getASTContext();
1708 RecordDecl::field_iterator Field, FieldEnd;
1709 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1710 Field != FieldEnd; ++Field) {
1711 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1712 !Field->isUnnamedBitfield()) {
1713 return *Field;
1714 }
1715 }
1716 return nullptr;
1717}
1718
Craig Topper37932912013-08-18 10:09:15 +00001719ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001720 CastKind Kind, Expr *Operand,
1721 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001722 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001723 unsigned PathSize = (BasePath ? BasePath->size() : 0);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001724 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001725 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001726 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001727 if (PathSize)
1728 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1729 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001730 return E;
1731}
1732
Craig Topper37932912013-08-18 10:09:15 +00001733ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001734 unsigned PathSize) {
James Y Knight1d75c5e2015-12-30 02:27:28 +00001735 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001736 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1737}
1738
1739
Craig Topper37932912013-08-18 10:09:15 +00001740CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001741 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001742 const CXXCastPath *BasePath,
1743 TypeSourceInfo *WrittenTy,
1744 SourceLocation L, SourceLocation R) {
1745 unsigned PathSize = (BasePath ? BasePath->size() : 0);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001746 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001747 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001748 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001749 if (PathSize)
1750 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1751 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001752 return E;
1753}
1754
Craig Topper37932912013-08-18 10:09:15 +00001755CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1756 unsigned PathSize) {
James Y Knight1d75c5e2015-12-30 02:27:28 +00001757 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001758 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1759}
1760
Chris Lattner1b926492006-08-23 06:42:10 +00001761/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1762/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001763StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001764 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001765#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1766#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001767 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001768 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001769}
Steve Naroff47500512007-04-19 23:00:49 +00001770
John McCalle3027922010-08-25 11:45:40 +00001771BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001772BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1773 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001774 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001775 case OO_Plus: return BO_Add;
1776 case OO_Minus: return BO_Sub;
1777 case OO_Star: return BO_Mul;
1778 case OO_Slash: return BO_Div;
1779 case OO_Percent: return BO_Rem;
1780 case OO_Caret: return BO_Xor;
1781 case OO_Amp: return BO_And;
1782 case OO_Pipe: return BO_Or;
1783 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00001784 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00001785 case OO_Less: return BO_LT;
1786 case OO_Greater: return BO_GT;
1787 case OO_PlusEqual: return BO_AddAssign;
1788 case OO_MinusEqual: return BO_SubAssign;
1789 case OO_StarEqual: return BO_MulAssign;
1790 case OO_SlashEqual: return BO_DivAssign;
1791 case OO_PercentEqual: return BO_RemAssign;
1792 case OO_CaretEqual: return BO_XorAssign;
1793 case OO_AmpEqual: return BO_AndAssign;
1794 case OO_PipeEqual: return BO_OrAssign;
1795 case OO_LessLess: return BO_Shl;
1796 case OO_GreaterGreater: return BO_Shr;
1797 case OO_LessLessEqual: return BO_ShlAssign;
1798 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1799 case OO_EqualEqual: return BO_EQ;
1800 case OO_ExclaimEqual: return BO_NE;
1801 case OO_LessEqual: return BO_LE;
1802 case OO_GreaterEqual: return BO_GE;
1803 case OO_AmpAmp: return BO_LAnd;
1804 case OO_PipePipe: return BO_LOr;
1805 case OO_Comma: return BO_Comma;
1806 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001807 }
1808}
1809
1810OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1811 static const OverloadedOperatorKind OverOps[] = {
1812 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1813 OO_Star, OO_Slash, OO_Percent,
1814 OO_Plus, OO_Minus,
1815 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00001816 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001817 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1818 OO_EqualEqual, OO_ExclaimEqual,
1819 OO_Amp,
1820 OO_Caret,
1821 OO_Pipe,
1822 OO_AmpAmp,
1823 OO_PipePipe,
1824 OO_Equal, OO_StarEqual,
1825 OO_SlashEqual, OO_PercentEqual,
1826 OO_PlusEqual, OO_MinusEqual,
1827 OO_LessLessEqual, OO_GreaterGreaterEqual,
1828 OO_AmpEqual, OO_CaretEqual,
1829 OO_PipeEqual,
1830 OO_Comma
1831 };
1832 return OverOps[Opc];
1833}
1834
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001835bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
1836 Opcode Opc,
1837 Expr *LHS, Expr *RHS) {
1838 if (Opc != BO_Add)
1839 return false;
1840
1841 // Check that we have one pointer and one integer operand.
1842 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001843 if (LHS->getType()->isPointerType()) {
1844 if (!RHS->getType()->isIntegerType())
1845 return false;
1846 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001847 } else if (RHS->getType()->isPointerType()) {
1848 if (!LHS->getType()->isIntegerType())
1849 return false;
1850 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001851 } else {
1852 return false;
1853 }
1854
1855 // Check that the pointer is a nullptr.
1856 if (!PExp->IgnoreParenCasts()
1857 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
1858 return false;
1859
1860 // Check that the pointee type is char-sized.
1861 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1862 if (!PTy || !PTy->getPointeeType()->isCharType())
1863 return false;
1864
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001865 return true;
1866}
Craig Topper37932912013-08-18 10:09:15 +00001867InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001868 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001869 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1870 false, false),
1871 InitExprs(C, initExprs.size()),
1872 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
1873{
Sebastian Redlc83ed822012-02-17 08:42:25 +00001874 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00001875 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001876 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00001877 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00001878 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00001879 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00001880 if (initExprs[I]->isInstantiationDependent())
1881 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00001882 if (initExprs[I]->containsUnexpandedParameterPack())
1883 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00001884 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001885
Benjamin Kramerc215e762012-08-24 11:54:20 +00001886 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00001887}
Chris Lattner1ec5f562007-06-27 05:38:08 +00001888
Craig Topper37932912013-08-18 10:09:15 +00001889void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001890 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00001891 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001892}
1893
Craig Topper37932912013-08-18 10:09:15 +00001894void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00001895 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001896}
1897
Craig Topper37932912013-08-18 10:09:15 +00001898Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001899 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001900 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00001901 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00001902 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001903 }
Mike Stump11289f42009-09-09 15:08:12 +00001904
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001905 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00001906 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001907 return Result;
1908}
1909
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001910void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00001911 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001912 ArrayFillerOrUnionFieldInit = filler;
1913 // Fill out any "holes" in the array due to designated initializers.
1914 Expr **inits = getInits();
1915 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001916 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001917 inits[i] = filler;
1918}
1919
Richard Smith9ec1e482012-04-15 02:50:59 +00001920bool InitListExpr::isStringLiteralInit() const {
1921 if (getNumInits() != 1)
1922 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00001923 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
1924 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00001925 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00001926 // It is possible for getInit() to return null.
1927 const Expr *Init = getInit(0);
1928 if (!Init)
1929 return false;
1930 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00001931 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
1932}
1933
Richard Smith122f88d2016-12-06 23:52:28 +00001934bool InitListExpr::isTransparent() const {
1935 assert(isSemanticForm() && "syntactic form never semantically transparent");
1936
1937 // A glvalue InitListExpr is always just sugar.
1938 if (isGLValue()) {
1939 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
1940 return true;
1941 }
1942
1943 // Otherwise, we're sugar if and only if we have exactly one initializer that
1944 // is of the same type.
1945 if (getNumInits() != 1 || !getInit(0))
1946 return false;
1947
Richard Smith382bc512017-02-23 22:41:47 +00001948 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
1949 // transparent struct copy.
1950 if (!getInit(0)->isRValue() && getType()->isRecordType())
1951 return false;
1952
Richard Smith122f88d2016-12-06 23:52:28 +00001953 return getType().getCanonicalType() ==
1954 getInit(0)->getType().getCanonicalType();
1955}
1956
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00001957bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
1958 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
1959
1960 if (LangOpts.CPlusPlus || getNumInits() != 1) {
1961 return false;
1962 }
1963
1964 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
1965 return Lit && Lit->getValue() == 0;
1966}
1967
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001968SourceLocation InitListExpr::getLocStart() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00001969 if (InitListExpr *SyntacticForm = getSyntacticForm())
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001970 return SyntacticForm->getLocStart();
1971 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001972 if (Beg.isInvalid()) {
1973 // Find the first non-null initializer.
1974 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1975 E = InitExprs.end();
1976 I != E; ++I) {
1977 if (Stmt *S = *I) {
1978 Beg = S->getLocStart();
1979 break;
1980 }
1981 }
1982 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001983 return Beg;
1984}
1985
1986SourceLocation InitListExpr::getLocEnd() const {
1987 if (InitListExpr *SyntacticForm = getSyntacticForm())
1988 return SyntacticForm->getLocEnd();
1989 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001990 if (End.isInvalid()) {
1991 // Find the first non-null initializer from the end.
1992 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001993 E = InitExprs.rend();
1994 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001995 if (Stmt *S = *I) {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001996 End = S->getLocEnd();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001997 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001998 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001999 }
2000 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002001 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002002}
2003
Steve Naroff991e99d2008-09-04 15:31:07 +00002004/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002005///
John McCallc833dea2012-02-17 03:32:35 +00002006const FunctionProtoType *BlockExpr::getFunctionType() const {
2007 // The block pointer is never sugared, but the function type might be.
2008 return cast<BlockPointerType>(getType())
2009 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002010}
2011
Mike Stump11289f42009-09-09 15:08:12 +00002012SourceLocation BlockExpr::getCaretLocation() const {
2013 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002014}
Mike Stump11289f42009-09-09 15:08:12 +00002015const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002016 return TheBlock->getBody();
2017}
Mike Stump11289f42009-09-09 15:08:12 +00002018Stmt *BlockExpr::getBody() {
2019 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002020}
Steve Naroff415d3d52008-10-08 17:01:13 +00002021
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002022
Chris Lattner1ec5f562007-06-27 05:38:08 +00002023//===----------------------------------------------------------------------===//
2024// Generic Expression Routines
2025//===----------------------------------------------------------------------===//
2026
Chris Lattner237f2752009-02-14 07:37:35 +00002027/// isUnusedResultAWarning - Return true if this immediate expression should
2028/// be warned about if the result is unused. If so, fill in Loc and Ranges
2029/// with location to warn on and the source range[s] to report with the
2030/// warning.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002031bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2032 SourceRange &R1, SourceRange &R2,
2033 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002034 // Don't warn if the expr is type dependent. The type could end up
2035 // instantiating to void.
2036 if (isTypeDependent())
2037 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002038
Chris Lattner1ec5f562007-06-27 05:38:08 +00002039 switch (getStmtClass()) {
2040 default:
John McCallc493a732010-03-12 07:11:26 +00002041 if (getType()->isVoidType())
2042 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002043 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002044 Loc = getExprLoc();
2045 R1 = getSourceRange();
2046 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002047 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002048 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002049 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002050 case GenericSelectionExprClass:
2051 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002052 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002053 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002054 case CoyieldExprClass:
2055 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002056 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002057 case ChooseExprClass:
2058 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2059 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002060 case UnaryOperatorClass: {
2061 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002062
Chris Lattner1ec5f562007-06-27 05:38:08 +00002063 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002064 case UO_Plus:
2065 case UO_Minus:
2066 case UO_AddrOf:
2067 case UO_Not:
2068 case UO_LNot:
2069 case UO_Deref:
2070 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002071 case UO_Coawait:
2072 // This is just the 'operator co_await' call inside the guts of a
2073 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002074 case UO_PostInc:
2075 case UO_PostDec:
2076 case UO_PreInc:
2077 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002078 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002079 case UO_Real:
2080 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002081 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002082 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2083 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002084 return false;
2085 break;
John McCalle3027922010-08-25 11:45:40 +00002086 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002087 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002088 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002089 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002090 Loc = UO->getOperatorLoc();
2091 R1 = UO->getSubExpr()->getSourceRange();
2092 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002093 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002094 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002095 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002096 switch (BO->getOpcode()) {
2097 default:
2098 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002099 // Consider the RHS of comma for side effects. LHS was checked by
2100 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002101 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002102 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2103 // lvalue-ness) of an assignment written in a macro.
2104 if (IntegerLiteral *IE =
2105 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2106 if (IE->getValue() == 0)
2107 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002108 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002109 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002110 case BO_LAnd:
2111 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002112 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2113 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002114 return false;
2115 break;
John McCall1e3715a2010-02-16 04:10:53 +00002116 }
Chris Lattner237f2752009-02-14 07:37:35 +00002117 if (BO->isAssignmentOp())
2118 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002119 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002120 Loc = BO->getOperatorLoc();
2121 R1 = BO->getLHS()->getSourceRange();
2122 R2 = BO->getRHS()->getSourceRange();
2123 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002124 }
Chris Lattner86928112007-08-25 02:00:02 +00002125 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002126 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002127 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002128 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002129
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002130 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002131 // If only one of the LHS or RHS is a warning, the operator might
2132 // be being used for control flow. Only warn if both the LHS and
2133 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002134 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002135 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00002136 return false;
2137 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00002138 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002139 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002140 }
2141
Chris Lattnera44d1162007-06-27 05:58:59 +00002142 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002143 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002144 Loc = cast<MemberExpr>(this)->getMemberLoc();
2145 R1 = SourceRange(Loc, Loc);
2146 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2147 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002148
Chris Lattner1ec5f562007-06-27 05:38:08 +00002149 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002150 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002151 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2152 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2153 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2154 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002155
Chandler Carruth46339472011-08-17 09:49:44 +00002156 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002157 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002158 // overloads as there is no reasonable way to define these such that they
2159 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002160 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002161 // provides additional value as well. If this list is updated,
2162 // DiagnoseUnusedComparison should be as well.
2163 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002164 switch (Op->getOperator()) {
2165 default:
2166 break;
2167 case OO_EqualEqual:
2168 case OO_ExclaimEqual:
2169 case OO_Less:
2170 case OO_Greater:
2171 case OO_GreaterEqual:
2172 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002173 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2174 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002175 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002176 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002177 Loc = Op->getOperatorLoc();
2178 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002179 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002180 }
Chandler Carruth46339472011-08-17 09:49:44 +00002181
2182 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002183 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002184 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002185 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002186 case CXXMemberCallExprClass:
2187 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002188 // If this is a direct call, get the callee.
2189 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002190 if (const Decl *FD = CE->getCalleeDecl()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002191 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2192 bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2193 : FD->hasAttr<WarnUnusedResultAttr>();
2194
Chris Lattner237f2752009-02-14 07:37:35 +00002195 // If the callee has attribute pure, const, or warn_unused_result, warn
2196 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002197 //
2198 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2199 // updated to match for QoI.
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002200 if (HasWarnUnusedResultAttr ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002201 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002202 WarnE = this;
Chris Lattner1a6babf2009-10-13 04:53:48 +00002203 Loc = CE->getCallee()->getLocStart();
2204 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002205
Chris Lattner1a6babf2009-10-13 04:53:48 +00002206 if (unsigned NumArgs = CE->getNumArgs())
2207 R2 = SourceRange(CE->getArg(0)->getLocStart(),
2208 CE->getArg(NumArgs-1)->getLocEnd());
2209 return true;
2210 }
Chris Lattner237f2752009-02-14 07:37:35 +00002211 }
2212 return false;
2213 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002214
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002215 // If we don't know precisely what we're looking at, let's not warn.
2216 case UnresolvedLookupExprClass:
2217 case CXXUnresolvedConstructExprClass:
2218 return false;
2219
Anders Carlsson6aa50392009-11-17 17:11:23 +00002220 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002221 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002222 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2223 if (Type->hasAttr<WarnUnusedAttr>()) {
2224 WarnE = this;
2225 Loc = getLocStart();
2226 R1 = getSourceRange();
2227 return true;
2228 }
2229 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002230 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002231 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002232
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002233 case ObjCMessageExprClass: {
2234 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002235 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002236 ME->isInstanceMessage() &&
2237 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002238 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002239 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002240 Loc = getExprLoc();
2241 R1 = ME->getSourceRange();
2242 return true;
2243 }
2244
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002245 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002246 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002247 WarnE = this;
2248 Loc = getExprLoc();
2249 return true;
2250 }
2251
Chris Lattner237f2752009-02-14 07:37:35 +00002252 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002253 }
Mike Stump11289f42009-09-09 15:08:12 +00002254
John McCallb7bd14f2010-12-02 01:19:52 +00002255 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002256 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002257 Loc = getExprLoc();
2258 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002259 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002260
John McCallfe96e0b2011-11-06 09:01:30 +00002261 case PseudoObjectExprClass: {
2262 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2263
2264 // Only complain about things that have the form of a getter.
2265 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2266 isa<BinaryOperator>(PO->getSyntacticForm()))
2267 return false;
2268
Eli Friedmanc11535c2012-05-24 00:47:05 +00002269 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002270 Loc = getExprLoc();
2271 R1 = getSourceRange();
2272 return true;
2273 }
2274
Chris Lattner944d3062008-07-26 19:51:01 +00002275 case StmtExprClass: {
2276 // Statement exprs don't logically have side effects themselves, but are
2277 // sometimes used in macros in ways that give them a type that is unused.
2278 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2279 // however, if the result of the stmt expr is dead, we don't want to emit a
2280 // warning.
2281 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002282 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002283 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002284 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002285 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2286 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002287 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002288 }
Mike Stump11289f42009-09-09 15:08:12 +00002289
John McCallc493a732010-03-12 07:11:26 +00002290 if (getType()->isVoidType())
2291 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002292 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002293 Loc = cast<StmtExpr>(this)->getLParenLoc();
2294 R1 = getSourceRange();
2295 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002296 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002297 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002298 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002299 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002300 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002301 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002302 if (CE->getCastKind() == CK_ToVoid) {
2303 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002304 CE->getSubExpr()->getType().isVolatileQualified()) {
2305 const DeclRefExpr *DRE =
2306 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2307 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002308 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2309 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002310 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2311 R1, R2, Ctx);
2312 }
2313 }
Chris Lattner2706a552009-07-28 18:25:28 +00002314 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002315 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002316
Eli Friedmanc11535c2012-05-24 00:47:05 +00002317 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002318 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002319 if (CE->getCastKind() == CK_ConstructorConversion)
2320 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002321
Eli Friedmanc11535c2012-05-24 00:47:05 +00002322 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002323 if (const CXXFunctionalCastExpr *CXXCE =
2324 dyn_cast<CXXFunctionalCastExpr>(this)) {
Eli Friedman89fe0d52013-08-15 22:02:56 +00002325 Loc = CXXCE->getLocStart();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002326 R1 = CXXCE->getSubExpr()->getSourceRange();
2327 } else {
2328 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2329 Loc = CStyleCE->getLParenLoc();
2330 R1 = CStyleCE->getSubExpr()->getSourceRange();
2331 }
Chris Lattner237f2752009-02-14 07:37:35 +00002332 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002333 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002334 case ImplicitCastExprClass: {
2335 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002336
Eli Friedmanc11535c2012-05-24 00:47:05 +00002337 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2338 if (ICE->getCastKind() == CK_LValueToRValue &&
2339 ICE->getSubExpr()->getType().isVolatileQualified())
2340 return false;
2341
2342 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2343 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002344 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002345 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002346 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002347 case CXXDefaultInitExprClass:
2348 return (cast<CXXDefaultInitExpr>(this)
2349 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002350
2351 case CXXNewExprClass:
2352 // FIXME: In theory, there might be new expressions that don't have side
2353 // effects (e.g. a placement new with an uninitialized POD).
2354 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002355 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002356 case MaterializeTemporaryExprClass:
2357 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2358 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002359 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002360 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2361 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002362 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002363 return cast<ExprWithCleanups>(this)->getSubExpr()
2364 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002365 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002366}
2367
Fariborz Jahanian07735332009-02-22 18:40:18 +00002368/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002369/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002370bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002371 const Expr *E = IgnoreParens();
2372 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002373 default:
2374 return false;
2375 case ObjCIvarRefExprClass:
2376 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002377 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002378 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002379 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002380 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002381 case MaterializeTemporaryExprClass:
2382 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2383 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002384 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002385 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002386 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002387 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fariborz Jahanianc367b8f2011-09-23 18:57:30 +00002388
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002389 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2390 if (VD->hasGlobalStorage())
2391 return true;
2392 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002393 // dereferencing to a pointer is always a gc'able candidate,
2394 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002395 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002396 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002397 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002398 return false;
2399 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002400 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002401 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002402 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002403 }
2404 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002405 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002406 }
2407}
Sebastian Redlce354af2010-09-10 20:55:33 +00002408
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002409bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2410 if (isTypeDependent())
2411 return false;
John McCall086a4642010-11-24 05:12:34 +00002412 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002413}
2414
John McCall0009fcc2011-04-26 20:42:42 +00002415QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002416 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002417
2418 // Bound member expressions are always one of these possibilities:
2419 // x->m x.m x->*y x.*y
2420 // (possibly parenthesized)
2421
2422 expr = expr->IgnoreParens();
2423 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2424 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2425 return mem->getMemberDecl()->getType();
2426 }
2427
2428 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2429 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2430 ->getPointeeType();
2431 assert(type->isFunctionType());
2432 return type;
2433 }
2434
David Majnemerced8bdf2015-02-25 17:36:15 +00002435 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002436 return QualType();
2437}
2438
Ted Kremenekfff70962008-01-17 16:57:34 +00002439Expr* Expr::IgnoreParens() {
2440 Expr* E = this;
Abramo Bagnara932e3932010-10-15 07:51:18 +00002441 while (true) {
2442 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2443 E = P->getSubExpr();
2444 continue;
2445 }
2446 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2447 if (P->getOpcode() == UO_Extension) {
2448 E = P->getSubExpr();
2449 continue;
2450 }
2451 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002452 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2453 if (!P->isResultDependent()) {
2454 E = P->getResultExpr();
2455 continue;
2456 }
2457 }
Eli Friedman75807f22013-07-20 00:40:58 +00002458 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2459 if (!P->isConditionDependent()) {
2460 E = P->getChosenSubExpr();
2461 continue;
2462 }
2463 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002464 return E;
2465 }
Ted Kremenekfff70962008-01-17 16:57:34 +00002466}
2467
Chris Lattnerf2660962008-02-13 01:02:39 +00002468/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2469/// or CastExprs or ImplicitCastExprs, returning their operand.
2470Expr *Expr::IgnoreParenCasts() {
2471 Expr *E = this;
2472 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002473 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002474 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002475 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002476 continue;
2477 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002478 if (MaterializeTemporaryExpr *Materialize
2479 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2480 E = Materialize->GetTemporaryExpr();
2481 continue;
2482 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002483 if (SubstNonTypeTemplateParmExpr *NTTP
2484 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2485 E = NTTP->getReplacement();
2486 continue;
2487 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002488 return E;
Chris Lattnerf2660962008-02-13 01:02:39 +00002489 }
2490}
2491
Ted Kremenek6f375e52014-04-16 07:26:09 +00002492Expr *Expr::IgnoreCasts() {
2493 Expr *E = this;
2494 while (true) {
2495 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2496 E = P->getSubExpr();
2497 continue;
2498 }
2499 if (MaterializeTemporaryExpr *Materialize
2500 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2501 E = Materialize->GetTemporaryExpr();
2502 continue;
2503 }
2504 if (SubstNonTypeTemplateParmExpr *NTTP
2505 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2506 E = NTTP->getReplacement();
2507 continue;
2508 }
2509 return E;
2510 }
2511}
2512
John McCall5a4ce8b2010-12-04 08:24:19 +00002513/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2514/// casts. This is intended purely as a temporary workaround for code
2515/// that hasn't yet been rewritten to do the right thing about those
2516/// casts, and may disappear along with the last internal use.
John McCall34376a62010-12-04 03:47:34 +00002517Expr *Expr::IgnoreParenLValueCasts() {
2518 Expr *E = this;
John McCall5a4ce8b2010-12-04 08:24:19 +00002519 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002520 E = E->IgnoreParens();
2521 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00002522 if (P->getCastKind() == CK_LValueToRValue) {
2523 E = P->getSubExpr();
2524 continue;
2525 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002526 } else if (MaterializeTemporaryExpr *Materialize
2527 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2528 E = Materialize->GetTemporaryExpr();
2529 continue;
Douglas Gregor6a40b082011-09-08 17:56:33 +00002530 } else if (SubstNonTypeTemplateParmExpr *NTTP
2531 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2532 E = NTTP->getReplacement();
2533 continue;
John McCall34376a62010-12-04 03:47:34 +00002534 }
2535 break;
2536 }
2537 return E;
2538}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002539
2540Expr *Expr::ignoreParenBaseCasts() {
2541 Expr *E = this;
2542 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002543 E = E->IgnoreParens();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002544 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2545 if (CE->getCastKind() == CK_DerivedToBase ||
2546 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2547 CE->getCastKind() == CK_NoOp) {
2548 E = CE->getSubExpr();
2549 continue;
2550 }
2551 }
2552
2553 return E;
2554 }
2555}
2556
John McCalleebc8322010-05-05 22:59:52 +00002557Expr *Expr::IgnoreParenImpCasts() {
2558 Expr *E = this;
2559 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002560 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002561 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCalleebc8322010-05-05 22:59:52 +00002562 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002563 continue;
2564 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002565 if (MaterializeTemporaryExpr *Materialize
2566 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2567 E = Materialize->GetTemporaryExpr();
2568 continue;
2569 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002570 if (SubstNonTypeTemplateParmExpr *NTTP
2571 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2572 E = NTTP->getReplacement();
2573 continue;
2574 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002575 return E;
John McCalleebc8322010-05-05 22:59:52 +00002576 }
2577}
2578
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002579Expr *Expr::IgnoreConversionOperator() {
2580 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002581 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002582 return MCE->getImplicitObjectArgument();
2583 }
2584 return this;
2585}
2586
Chris Lattneref26c772009-03-13 17:28:01 +00002587/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2588/// value (including ptr->int casts of the same size). Strip off any
2589/// ParenExpr or CastExprs, returning their operand.
2590Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2591 Expr *E = this;
2592 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002593 E = E->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00002594
Chris Lattneref26c772009-03-13 17:28:01 +00002595 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2596 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregorb90df602010-06-16 00:17:44 +00002597 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattneref26c772009-03-13 17:28:01 +00002598 Expr *SE = P->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002599
Chris Lattneref26c772009-03-13 17:28:01 +00002600 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2601 E = SE;
2602 continue;
2603 }
Mike Stump11289f42009-09-09 15:08:12 +00002604
Abramo Bagnara932e3932010-10-15 07:51:18 +00002605 if ((E->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002606 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnara932e3932010-10-15 07:51:18 +00002607 (SE->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002608 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattneref26c772009-03-13 17:28:01 +00002609 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2610 E = SE;
2611 continue;
2612 }
2613 }
Mike Stump11289f42009-09-09 15:08:12 +00002614
Douglas Gregor6a40b082011-09-08 17:56:33 +00002615 if (SubstNonTypeTemplateParmExpr *NTTP
2616 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2617 E = NTTP->getReplacement();
2618 continue;
2619 }
2620
Chris Lattneref26c772009-03-13 17:28:01 +00002621 return E;
2622 }
2623}
2624
Douglas Gregord196a582009-12-14 19:27:10 +00002625bool Expr::isDefaultArgument() const {
2626 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002627 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2628 E = M->GetTemporaryExpr();
2629
Douglas Gregord196a582009-12-14 19:27:10 +00002630 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2631 E = ICE->getSubExprAsWritten();
Alexis Hunta8136cc2010-05-05 15:23:54 +00002632
Douglas Gregord196a582009-12-14 19:27:10 +00002633 return isa<CXXDefaultArgExpr>(E);
2634}
Chris Lattneref26c772009-03-13 17:28:01 +00002635
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002636/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002637/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002638static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002639 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2640 E = M->GetTemporaryExpr();
2641
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002642 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002643 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002644 E = ICE->getSubExpr();
2645 else
2646 break;
2647 }
2648
2649 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2650 E = BE->getSubExpr();
2651
2652 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002653 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002654 E = ICE->getSubExpr();
2655 else
2656 break;
2657 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002658
2659 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002660}
2661
John McCall7a626f62010-09-15 10:14:12 +00002662/// isTemporaryObject - Determines if this expression produces a
2663/// temporary of the given class type.
2664bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2665 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2666 return false;
2667
Anders Carlsson66bbf502010-11-28 16:40:49 +00002668 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002669
John McCall02dc8c72010-09-15 20:59:13 +00002670 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002671 if (!E->Classify(C).isPRValue()) {
2672 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002673 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002674 return false;
2675 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002676
John McCallf4ee1dd2010-09-16 06:57:56 +00002677 // Black-list a few cases which yield pr-values of class type that don't
2678 // refer to temporaries of that type:
2679
2680 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002681 if (isa<ImplicitCastExpr>(E)) {
2682 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2683 case CK_DerivedToBase:
2684 case CK_UncheckedDerivedToBase:
2685 return false;
2686 default:
2687 break;
2688 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002689 }
2690
John McCallf4ee1dd2010-09-16 06:57:56 +00002691 // - member expressions (all)
2692 if (isa<MemberExpr>(E))
2693 return false;
2694
Eli Friedman13ffdd82012-06-15 23:51:06 +00002695 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2696 if (BO->isPtrMemOp())
2697 return false;
2698
John McCallc07a0c72011-02-17 10:25:35 +00002699 // - opaque values (all)
2700 if (isa<OpaqueValueExpr>(E))
2701 return false;
2702
John McCall7a626f62010-09-15 10:14:12 +00002703 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002704}
2705
Douglas Gregor25b7e052011-03-02 21:06:53 +00002706bool Expr::isImplicitCXXThis() const {
2707 const Expr *E = this;
2708
2709 // Strip away parentheses and casts we don't care about.
2710 while (true) {
2711 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2712 E = Paren->getSubExpr();
2713 continue;
2714 }
2715
2716 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2717 if (ICE->getCastKind() == CK_NoOp ||
2718 ICE->getCastKind() == CK_LValueToRValue ||
2719 ICE->getCastKind() == CK_DerivedToBase ||
2720 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2721 E = ICE->getSubExpr();
2722 continue;
2723 }
2724 }
2725
2726 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2727 if (UnOp->getOpcode() == UO_Extension) {
2728 E = UnOp->getSubExpr();
2729 continue;
2730 }
2731 }
2732
Douglas Gregorfe314812011-06-21 17:03:29 +00002733 if (const MaterializeTemporaryExpr *M
2734 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2735 E = M->GetTemporaryExpr();
2736 continue;
2737 }
2738
Douglas Gregor25b7e052011-03-02 21:06:53 +00002739 break;
2740 }
2741
2742 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2743 return This->isImplicit();
2744
2745 return false;
2746}
2747
Douglas Gregor4619e432008-12-05 23:32:09 +00002748/// hasAnyTypeDependentArguments - Determines if any of the expressions
2749/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002750bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002751 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002752 if (Exprs[I]->isTypeDependent())
2753 return true;
2754
2755 return false;
2756}
2757
Abramo Bagnara847c6602014-05-22 19:20:46 +00002758bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2759 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002760 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002761 // which can be evaluated at compile-time. It very closely parallels
2762 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2763 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2764 // to isEvaluatable most of the time.
2765 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002766 // If we ever capture reference-binding directly in the AST, we can
2767 // kill the second parameter.
2768
2769 if (IsForRef) {
2770 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002771 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2772 return true;
2773 if (Culprit)
2774 *Culprit = this;
2775 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002776 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002777
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002778 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002779 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002780 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002781 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002782 return true;
John McCall81c9cea2010-08-01 21:51:45 +00002783 case CXXTemporaryObjectExprClass:
2784 case CXXConstructExprClass: {
2785 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00002786
Eli Friedman4c27ac22013-07-16 22:40:53 +00002787 if (CE->getConstructor()->isTrivial() &&
2788 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2789 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00002790 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00002791
Eli Friedman4c27ac22013-07-16 22:40:53 +00002792 // Trivial copy constructor
2793 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00002794 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00002795 }
2796
Richard Smithd62306a2011-11-10 06:34:14 +00002797 break;
John McCall81c9cea2010-08-01 21:51:45 +00002798 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002799 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002800 // This handles gcc's extension that allows global initializers like
2801 // "struct x {int x;} x = (struct x) {};".
2802 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002803 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002804 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002805 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00002806 case DesignatedInitUpdateExprClass: {
2807 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2808 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2809 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2810 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002811 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002812 const InitListExpr *ILE = cast<InitListExpr>(this);
2813 if (ILE->getType()->isArrayType()) {
2814 unsigned numInits = ILE->getNumInits();
2815 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002816 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002817 return false;
2818 }
2819 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002820 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002821
2822 if (ILE->getType()->isRecordType()) {
2823 unsigned ElementNo = 0;
2824 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00002825 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002826 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00002827 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00002828 continue;
2829
2830 // Don't emit anonymous bitfields, they just affect layout.
2831 if (Field->isUnnamedBitfield())
2832 continue;
2833
2834 if (ElementNo < ILE->getNumInits()) {
2835 const Expr *Elt = ILE->getInit(ElementNo++);
2836 if (Field->isBitField()) {
2837 // Bitfields have to evaluate to an integer.
2838 llvm::APSInt ResultTmp;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002839 if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
2840 if (Culprit)
2841 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00002842 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002843 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002844 } else {
2845 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002846 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002847 return false;
2848 }
2849 }
2850 }
2851 return true;
2852 }
2853
2854 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002855 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00002856 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002857 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00002858 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00002859 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00002860 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002861 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00002862 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002863 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002864 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00002865 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00002866 if (cast<ChooseExpr>(this)->isConditionDependent()) {
2867 if (Culprit)
2868 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00002869 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002870 }
Eli Friedman75807f22013-07-20 00:40:58 +00002871 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002872 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002873 case UnaryOperatorClass: {
2874 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00002875 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002876 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002877 break;
2878 }
John McCall8b0f4ff2010-08-02 21:13:48 +00002879 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00002880 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00002881 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00002882 case CStyleCastExprClass:
2883 case ObjCBridgedCastExprClass:
2884 case CXXDynamicCastExprClass:
2885 case CXXReinterpretCastExprClass:
2886 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00002887 const CastExpr *CE = cast<CastExpr>(this);
2888
Eli Friedman13ec75b2011-12-21 00:43:02 +00002889 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00002890 if (CE->getCastKind() == CK_NoOp ||
2891 CE->getCastKind() == CK_LValueToRValue ||
2892 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00002893 CE->getCastKind() == CK_ConstructorConversion ||
2894 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002895 CE->getCastKind() == CK_AtomicToNonAtomic ||
2896 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002897 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00002898
Eli Friedman384da272009-01-25 03:12:18 +00002899 break;
Richard Smith161f09a2011-12-06 22:44:34 +00002900 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002901 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002902 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002903 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002904
Eli Friedman4c27ac22013-07-16 22:40:53 +00002905 case SubstNonTypeTemplateParmExprClass:
2906 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002907 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002908 case CXXDefaultArgExprClass:
2909 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002910 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002911 case CXXDefaultInitExprClass:
2912 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002913 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002914 }
Richard Smithce8eca52015-12-08 03:21:47 +00002915 // Allow certain forms of UB in constant initializers: signed integer
2916 // overflow and floating-point division by zero. We'll give a warning on
2917 // these, but they're common enough that we have to accept them.
2918 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00002919 return true;
2920 if (Culprit)
2921 *Culprit = this;
2922 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00002923}
2924
Nico Weber758fbac2018-02-13 21:31:47 +00002925bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
2926 const FunctionDecl* FD = getDirectCallee();
2927 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
2928 FD->getBuiltinID() != Builtin::BI__builtin_assume))
2929 return false;
2930
2931 const Expr* Arg = getArg(0);
2932 bool ArgVal;
2933 return !Arg->isValueDependent() &&
2934 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
2935}
2936
Scott Douglasscc013592015-06-10 15:18:23 +00002937namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002938 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00002939 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002940 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00002941 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002942 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00002943
2944 public:
2945 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002946 : Inherited(Context),
2947 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00002948
2949 bool hasSideEffects() const { return HasSideEffects; }
2950
2951 void VisitExpr(const Expr *E) {
2952 if (!HasSideEffects &&
2953 E->HasSideEffects(Context, IncludePossibleEffects))
2954 HasSideEffects = true;
2955 }
2956 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002957}
Scott Douglasscc013592015-06-10 15:18:23 +00002958
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002959bool Expr::HasSideEffects(const ASTContext &Ctx,
2960 bool IncludePossibleEffects) const {
2961 // In circumstances where we care about definite side effects instead of
2962 // potential side effects, we want to ignore expressions that are part of a
2963 // macro expansion as a potential side effect.
2964 if (!IncludePossibleEffects && getExprLoc().isMacroID())
2965 return false;
2966
Richard Smith0421ce72012-08-07 04:16:51 +00002967 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002968 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00002969
2970 switch (getStmtClass()) {
2971 case NoStmtClass:
2972 #define ABSTRACT_STMT(Type)
2973 #define STMT(Type, Base) case Type##Class:
2974 #define EXPR(Type, Base)
2975 #include "clang/AST/StmtNodes.inc"
2976 llvm_unreachable("unexpected Expr kind");
2977
2978 case DependentScopeDeclRefExprClass:
2979 case CXXUnresolvedConstructExprClass:
2980 case CXXDependentScopeMemberExprClass:
2981 case UnresolvedLookupExprClass:
2982 case UnresolvedMemberExprClass:
2983 case PackExpansionExprClass:
2984 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00002985 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002986 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00002987 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002988 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
2989
Richard Smitha33e4fe2012-08-07 05:18:29 +00002990 case DeclRefExprClass:
2991 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002992 case PredefinedExprClass:
2993 case IntegerLiteralClass:
2994 case FloatingLiteralClass:
2995 case ImaginaryLiteralClass:
2996 case StringLiteralClass:
2997 case CharacterLiteralClass:
2998 case OffsetOfExprClass:
2999 case ImplicitValueInitExprClass:
3000 case UnaryExprOrTypeTraitExprClass:
3001 case AddrLabelExprClass:
3002 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003003 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003004 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003005 case CXXBoolLiteralExprClass:
3006 case CXXNullPtrLiteralExprClass:
3007 case CXXThisExprClass:
3008 case CXXScalarValueInitExprClass:
3009 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003010 case ArrayTypeTraitExprClass:
3011 case ExpressionTraitExprClass:
3012 case CXXNoexceptExprClass:
3013 case SizeOfPackExprClass:
3014 case ObjCStringLiteralClass:
3015 case ObjCEncodeExprClass:
3016 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003017 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003018 case CXXUuidofExprClass:
3019 case OpaqueValueExprClass:
3020 // These never have a side-effect.
3021 return false;
3022
3023 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003024 case CXXOperatorCallExprClass:
3025 case CXXMemberCallExprClass:
3026 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003027 case UserDefinedLiteralClass: {
3028 // We don't know a call definitely has side effects, except for calls
3029 // to pure/const functions that definitely don't.
3030 // If the call itself is considered side-effect free, check the operands.
3031 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3032 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3033 if (IsPure || !IncludePossibleEffects)
3034 break;
3035 return true;
3036 }
3037
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003038 case BlockExprClass:
3039 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003040 if (!IncludePossibleEffects)
3041 break;
3042 return true;
3043
John McCall5e77d762013-04-16 07:28:30 +00003044 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003045 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003046 case CompoundAssignOperatorClass:
3047 case VAArgExprClass:
3048 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003049 case CXXThrowExprClass:
3050 case CXXNewExprClass:
3051 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003052 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003053 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003054 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003055 // These always have a side-effect.
3056 return true;
3057
Scott Douglasscc013592015-06-10 15:18:23 +00003058 case StmtExprClass: {
3059 // StmtExprs have a side-effect if any substatement does.
3060 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3061 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3062 return Finder.hasSideEffects();
3063 }
3064
Tim Shen4a05bb82016-06-21 20:29:17 +00003065 case ExprWithCleanupsClass:
3066 if (IncludePossibleEffects)
3067 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3068 return true;
3069 break;
3070
Richard Smith0421ce72012-08-07 04:16:51 +00003071 case ParenExprClass:
3072 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003073 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003074 case MemberExprClass:
3075 case ConditionalOperatorClass:
3076 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003077 case CompoundLiteralExprClass:
3078 case ExtVectorElementExprClass:
3079 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003080 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003081 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003082 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003083 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003084 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003085 case SubstNonTypeTemplateParmExprClass:
3086 case MaterializeTemporaryExprClass:
3087 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003088 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003089 case AsTypeExprClass:
3090 // These have a side-effect if any subexpression does.
3091 break;
3092
Richard Smitha33e4fe2012-08-07 05:18:29 +00003093 case UnaryOperatorClass:
3094 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003095 return true;
3096 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003097
3098 case BinaryOperatorClass:
3099 if (cast<BinaryOperator>(this)->isAssignmentOp())
3100 return true;
3101 break;
3102
Richard Smith0421ce72012-08-07 04:16:51 +00003103 case InitListExprClass:
3104 // FIXME: The children for an InitListExpr doesn't include the array filler.
3105 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003106 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003107 return true;
3108 break;
3109
3110 case GenericSelectionExprClass:
3111 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003112 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003113
3114 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003115 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3116 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003117
3118 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003119 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3120 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003121
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003122 case CXXDefaultInitExprClass: {
3123 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3124 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003125 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003126 // If we've not yet parsed the initializer, assume it has side-effects.
3127 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003128 }
Richard Smith852c9db2013-04-20 22:23:05 +00003129
Richard Smith0421ce72012-08-07 04:16:51 +00003130 case CXXDynamicCastExprClass: {
3131 // A dynamic_cast expression has side-effects if it can throw.
3132 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3133 if (DCE->getTypeAsWritten()->isReferenceType() &&
3134 DCE->getCastKind() == CK_Dynamic)
3135 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003136 }
3137 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003138 case ImplicitCastExprClass:
3139 case CStyleCastExprClass:
3140 case CXXStaticCastExprClass:
3141 case CXXReinterpretCastExprClass:
3142 case CXXConstCastExprClass:
3143 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003144 // While volatile reads are side-effecting in both C and C++, we treat them
3145 // as having possible (not definite) side-effects. This allows idiomatic
3146 // code to behave without warning, such as sizeof(*v) for a volatile-
3147 // qualified pointer.
3148 if (!IncludePossibleEffects)
3149 break;
3150
Richard Smitha33e4fe2012-08-07 05:18:29 +00003151 const CastExpr *CE = cast<CastExpr>(this);
3152 if (CE->getCastKind() == CK_LValueToRValue &&
3153 CE->getSubExpr()->getType().isVolatileQualified())
3154 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003155 break;
3156 }
3157
Richard Smithef8bf432012-08-13 20:08:14 +00003158 case CXXTypeidExprClass:
3159 // typeid might throw if its subexpression is potentially-evaluated, so has
3160 // side-effects in that case whether or not its subexpression does.
3161 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003162
3163 case CXXConstructExprClass:
3164 case CXXTemporaryObjectExprClass: {
3165 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003166 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003167 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003168 // A trivial constructor does not add any side-effects of its own. Just look
3169 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003170 break;
3171 }
3172
Richard Smith5179eb72016-06-28 19:03:57 +00003173 case CXXInheritedCtorInitExprClass: {
3174 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3175 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3176 return true;
3177 break;
3178 }
3179
Richard Smith0421ce72012-08-07 04:16:51 +00003180 case LambdaExprClass: {
3181 const LambdaExpr *LE = cast<LambdaExpr>(this);
3182 for (LambdaExpr::capture_iterator I = LE->capture_begin(),
3183 E = LE->capture_end(); I != E; ++I)
3184 if (I->getCaptureKind() == LCK_ByCopy)
3185 // FIXME: Only has a side-effect if the variable is volatile or if
3186 // the copy would invoke a non-trivial copy constructor.
3187 return true;
3188 return false;
3189 }
3190
3191 case PseudoObjectExprClass: {
3192 // Only look for side-effects in the semantic form, and look past
3193 // OpaqueValueExpr bindings in that form.
3194 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3195 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3196 E = PO->semantics_end();
3197 I != E; ++I) {
3198 const Expr *Subexpr = *I;
3199 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3200 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003201 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003202 return true;
3203 }
3204 return false;
3205 }
3206
3207 case ObjCBoxedExprClass:
3208 case ObjCArrayLiteralClass:
3209 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003210 case ObjCSelectorExprClass:
3211 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003212 case ObjCIsaExprClass:
3213 case ObjCIndirectCopyRestoreExprClass:
3214 case ObjCSubscriptRefExprClass:
3215 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003216 case ObjCMessageExprClass:
3217 case ObjCPropertyRefExprClass:
3218 // FIXME: Classify these cases better.
3219 if (IncludePossibleEffects)
3220 return true;
3221 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003222 }
3223
3224 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003225 for (const Stmt *SubStmt : children())
3226 if (SubStmt &&
3227 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3228 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003229
3230 return false;
3231}
3232
Douglas Gregor1be329d2012-02-23 07:33:15 +00003233namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003234 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003235 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3236 {
3237 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003238
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003239 bool NonTrivial;
Douglas Gregor1be329d2012-02-23 07:33:15 +00003240
3241 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003242 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003243 : Inherited(Context), NonTrivial(false) { }
Douglas Gregor1be329d2012-02-23 07:33:15 +00003244
3245 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003246
3247 void VisitCallExpr(const CallExpr *E) {
3248 if (const CXXMethodDecl *Method
3249 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003250 if (Method->isTrivial()) {
3251 // Recurse to children of the call.
3252 Inherited::VisitStmt(E);
3253 return;
3254 }
3255 }
3256
3257 NonTrivial = true;
3258 }
Scott Douglass503fc392015-06-10 13:53:15 +00003259
3260 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003261 if (E->getConstructor()->isTrivial()) {
3262 // Recurse to children of the call.
3263 Inherited::VisitStmt(E);
3264 return;
3265 }
3266
3267 NonTrivial = true;
3268 }
Scott Douglass503fc392015-06-10 13:53:15 +00003269
3270 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003271 if (E->getTemporary()->getDestructor()->isTrivial()) {
3272 Inherited::VisitStmt(E);
3273 return;
3274 }
3275
3276 NonTrivial = true;
3277 }
3278 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003279}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003280
Scott Douglass503fc392015-06-10 13:53:15 +00003281bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003282 NonTrivialCallFinder Finder(Ctx);
3283 Finder.Visit(this);
3284 return Finder.hasNonTrivialCall();
3285}
3286
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003287/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3288/// pointer constant or not, as well as the specific kind of constant detected.
3289/// Null pointer constants can be integer constant expressions with the
3290/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3291/// (a GNU extension).
3292Expr::NullPointerConstantKind
3293Expr::isNullPointerConstant(ASTContext &Ctx,
3294 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003295 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003296 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003297 switch (NPC) {
3298 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003299 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003300 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003301 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003302 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003303 else
3304 return NPCK_NotNull;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003305
Douglas Gregor56751b52009-09-25 04:25:58 +00003306 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003307 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003308 }
3309 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003310
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003311 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003312 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003313 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003314 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003315 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003316 QualType Pointee = PT->getPointeeType();
Yaxun Liub7318e02017-10-13 03:37:48 +00003317 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3318 // has non-default address space it is not treated as nullptr.
3319 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3320 // since it cannot be assigned to a pointer to constant address space.
3321 bool PointeeHasDefaultAS =
3322 Pointee.getAddressSpace() == LangAS::Default ||
3323 (Ctx.getLangOpts().OpenCLVersion >= 200 &&
3324 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3325 (Ctx.getLangOpts().OpenCL &&
3326 Ctx.getLangOpts().OpenCLVersion < 200 &&
3327 Pointee.getAddressSpace() == LangAS::opencl_private);
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003328
Yaxun Liub7318e02017-10-13 03:37:48 +00003329 if (PointeeHasDefaultAS && Pointee->isVoidType() && // to void*
3330 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Douglas Gregor56751b52009-09-25 04:25:58 +00003331 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003332 }
Steve Naroffada7d422007-05-20 17:54:12 +00003333 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003334 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3335 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003336 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003337 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3338 // Accept ((void*)0) as a null pointer constant, as many other
3339 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003340 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003341 } else if (const GenericSelectionExpr *GE =
3342 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003343 if (GE->isResultDependent())
3344 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003345 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003346 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3347 if (CE->isConditionDependent())
3348 return NPCK_NotNull;
3349 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003350 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003351 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003352 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003353 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003354 } else if (const CXXDefaultInitExpr *DefaultInit
3355 = dyn_cast<CXXDefaultInitExpr>(this)) {
3356 // See through default initializer expressions.
3357 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003358 } else if (isa<GNUNullExpr>(this)) {
3359 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003360 return NPCK_GNUNull;
Douglas Gregorfe314812011-06-21 17:03:29 +00003361 } else if (const MaterializeTemporaryExpr *M
3362 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3363 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003364 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3365 if (const Expr *Source = OVE->getSourceExpr())
3366 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003367 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003368
Richard Smith89645bc2013-01-02 12:01:23 +00003369 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003370 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003371 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003372
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003373 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003374 if (!Ctx.getLangOpts().CPlusPlus11 &&
3375 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003376 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3377 const Expr *InitExpr = CLE->getInitializer();
3378 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3379 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3380 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003381 // This expression must be an integer type.
Alexis Hunta8136cc2010-05-05 15:23:54 +00003382 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003383 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003384 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003385
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003386 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003387 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3388 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003389 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003390 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003391 if (Lit && !Lit->getValue())
3392 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003393 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003394 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003395 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003396 // If we have an integer constant expression, we need to *evaluate* it and
3397 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003398 if (!isIntegerConstantExpr(Ctx))
3399 return NPCK_NotNull;
3400 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003401
David Blaikie1c7c8f72012-08-08 17:33:31 +00003402 if (EvaluateKnownConstInt(Ctx) != 0)
3403 return NPCK_NotNull;
3404
3405 if (isa<IntegerLiteral>(this))
3406 return NPCK_ZeroLiteral;
3407 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003408}
Steve Narofff7a5da12007-07-28 23:10:27 +00003409
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003410/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003411/// property, find the underlying property reference expression.
3412const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3413 const Expr *E = this;
3414 while (true) {
3415 assert((E->getValueKind() == VK_LValue &&
3416 E->getObjectKind() == OK_ObjCProperty) &&
3417 "expression is not a property reference");
3418 E = E->IgnoreParenCasts();
3419 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3420 if (BO->getOpcode() == BO_Comma) {
3421 E = BO->getRHS();
3422 continue;
3423 }
3424 }
3425
3426 break;
3427 }
3428
3429 return cast<ObjCPropertyRefExpr>(E);
3430}
3431
Anna Zaks97c7ce32012-10-01 20:34:04 +00003432bool Expr::isObjCSelfExpr() const {
3433 const Expr *E = IgnoreParenImpCasts();
3434
3435 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3436 if (!DRE)
3437 return false;
3438
3439 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3440 if (!Param)
3441 return false;
3442
3443 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3444 if (!M)
3445 return false;
3446
3447 return M->getSelfDecl() == Param;
3448}
3449
John McCalld25db7e2013-05-06 21:39:12 +00003450FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003451 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003452
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003453 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003454 if (ICE->getCastKind() == CK_LValueToRValue ||
3455 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003456 E = ICE->getSubExpr()->IgnoreParens();
3457 else
3458 break;
3459 }
3460
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003461 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003462 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003463 if (Field->isBitField())
3464 return Field;
3465
George Burgess IV00f70bd2018-03-01 05:43:23 +00003466 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3467 FieldDecl *Ivar = IvarRef->getDecl();
3468 if (Ivar->isBitField())
3469 return Ivar;
3470 }
John McCalld25db7e2013-05-06 21:39:12 +00003471
Richard Smith7873de02016-08-11 22:25:46 +00003472 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003473 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3474 if (Field->isBitField())
3475 return Field;
3476
Richard Smith7873de02016-08-11 22:25:46 +00003477 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3478 if (Expr *E = BD->getBinding())
3479 return E->getSourceBitField();
3480 }
3481
Eli Friedman609ada22011-07-13 02:05:57 +00003482 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003483 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003484 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003485
Eli Friedman609ada22011-07-13 02:05:57 +00003486 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003487 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003488 }
3489
Richard Smith5b571672014-09-24 23:55:00 +00003490 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3491 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3492 return UnOp->getSubExpr()->getSourceBitField();
3493
Craig Topper36250ad2014-05-12 05:36:57 +00003494 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003495}
3496
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003497bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003498 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003499 const Expr *E = this->IgnoreParens();
Alexis Hunta8136cc2010-05-05 15:23:54 +00003500
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003501 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003502 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003503 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003504 E = ICE->getSubExpr()->IgnoreParens();
3505 else
3506 break;
3507 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00003508
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003509 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3510 return ASE->getBase()->getType()->isVectorType();
3511
3512 if (isa<ExtVectorElementExpr>(E))
3513 return true;
3514
Richard Smith7873de02016-08-11 22:25:46 +00003515 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3516 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3517 if (auto *E = BD->getBinding())
3518 return E->refersToVectorElement();
3519
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003520 return false;
3521}
3522
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003523bool Expr::refersToGlobalRegisterVar() const {
3524 const Expr *E = this->IgnoreParenImpCasts();
3525
3526 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3527 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3528 if (VD->getStorageClass() == SC_Register &&
3529 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3530 return true;
3531
3532 return false;
3533}
3534
Chris Lattnerb8211f62009-02-16 22:14:05 +00003535/// isArrow - Return true if the base expression is a pointer to vector,
3536/// return false if the base expression is a vector.
3537bool ExtVectorElementExpr::isArrow() const {
3538 return getBase()->getType()->isPointerType();
3539}
3540
Nate Begemance4d7fc2008-04-18 23:10:10 +00003541unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003542 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003543 return VT->getNumElements();
3544 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003545}
3546
Nate Begemanf322eab2008-05-09 06:41:27 +00003547/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003548bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003549 // FIXME: Refactor this code to an accessor on the AST node which returns the
3550 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003551 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003552
3553 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003554 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003555 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003556
Nate Begeman7e5185b2009-01-18 02:01:21 +00003557 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003558 if (Comp[0] == 's' || Comp[0] == 'S')
3559 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003560
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003561 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003562 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003563 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003564
Steve Naroff0d595ca2007-07-30 03:29:09 +00003565 return false;
3566}
Chris Lattner885b4952007-08-02 23:36:59 +00003567
Nate Begemanf322eab2008-05-09 06:41:27 +00003568/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003569void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003570 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003571 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003572 bool isNumericAccessor = false;
3573 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003574 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003575 isNumericAccessor = true;
3576 }
Mike Stump11289f42009-09-09 15:08:12 +00003577
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003578 bool isHi = Comp == "hi";
3579 bool isLo = Comp == "lo";
3580 bool isEven = Comp == "even";
3581 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003582
Nate Begemanf322eab2008-05-09 06:41:27 +00003583 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3584 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003585
Nate Begemanf322eab2008-05-09 06:41:27 +00003586 if (isHi)
3587 Index = e + i;
3588 else if (isLo)
3589 Index = i;
3590 else if (isEven)
3591 Index = 2 * i;
3592 else if (isOdd)
3593 Index = 2 * i + 1;
3594 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003595 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003596
Nate Begemand3862152008-05-13 21:03:02 +00003597 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003598 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003599}
3600
Craig Topper37932912013-08-18 10:09:15 +00003601ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003602 QualType Type, SourceLocation BLoc,
3603 SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003604 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3605 Type->isDependentType(), Type->isDependentType(),
3606 Type->isInstantiationDependentType(),
3607 Type->containsUnexpandedParameterPack()),
3608 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3609{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003610 SubExprs = new (C) Stmt*[args.size()];
3611 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003612 if (args[i]->isTypeDependent())
3613 ExprBits.TypeDependent = true;
3614 if (args[i]->isValueDependent())
3615 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003616 if (args[i]->isInstantiationDependent())
3617 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003618 if (args[i]->containsUnexpandedParameterPack())
3619 ExprBits.ContainsUnexpandedParameterPack = true;
3620
3621 SubExprs[i] = args[i];
3622 }
3623}
3624
Craig Topper37932912013-08-18 10:09:15 +00003625void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003626 if (SubExprs) C.Deallocate(SubExprs);
3627
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003628 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003629 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003630 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003631}
Nate Begeman48745922009-08-12 02:28:50 +00003632
Craig Topper37932912013-08-18 10:09:15 +00003633GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003634 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003635 ArrayRef<TypeSourceInfo*> AssocTypes,
3636 ArrayRef<Expr*> AssocExprs,
3637 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003638 SourceLocation RParenLoc,
3639 bool ContainsUnexpandedParameterPack,
3640 unsigned ResultIndex)
3641 : Expr(GenericSelectionExprClass,
3642 AssocExprs[ResultIndex]->getType(),
3643 AssocExprs[ResultIndex]->getValueKind(),
3644 AssocExprs[ResultIndex]->getObjectKind(),
3645 AssocExprs[ResultIndex]->isTypeDependent(),
3646 AssocExprs[ResultIndex]->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003647 AssocExprs[ResultIndex]->isInstantiationDependent(),
Peter Collingbourne91147592011-04-15 00:35:48 +00003648 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003649 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3650 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3651 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3652 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003653 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003654 assert(AssocTypes.size() == AssocExprs.size());
3655 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3656 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003657}
3658
Craig Topper37932912013-08-18 10:09:15 +00003659GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003660 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003661 ArrayRef<TypeSourceInfo*> AssocTypes,
3662 ArrayRef<Expr*> AssocExprs,
3663 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003664 SourceLocation RParenLoc,
3665 bool ContainsUnexpandedParameterPack)
3666 : Expr(GenericSelectionExprClass,
3667 Context.DependentTy,
3668 VK_RValue,
3669 OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003670 /*isTypeDependent=*/true,
3671 /*isValueDependent=*/true,
3672 /*isInstantiationDependent=*/true,
Peter Collingbourne91147592011-04-15 00:35:48 +00003673 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003674 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3675 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3676 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3677 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003678 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003679 assert(AssocTypes.size() == AssocExprs.size());
3680 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3681 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003682}
3683
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003684//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003685// DesignatedInitExpr
3686//===----------------------------------------------------------------------===//
3687
Chandler Carruth631abd92011-06-16 06:47:06 +00003688IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003689 assert(Kind == FieldDesignator && "Only valid on a field designator");
3690 if (Field.NameOrField & 0x01)
3691 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3692 else
3693 return getField()->getIdentifier();
3694}
3695
Craig Topper37932912013-08-18 10:09:15 +00003696DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00003697 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003698 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003699 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003700 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003701 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003702 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003703 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003704 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003705 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003706 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003707 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00003708 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003709 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003710
3711 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003712 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003713 *Child++ = Init;
3714
3715 // Copy the designators and their subexpressions, computing
3716 // value-dependence along the way.
3717 unsigned IndexIdx = 0;
3718 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003719 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003720
3721 if (this->Designators[I].isArrayDesignator()) {
3722 // Compute type- and value-dependence.
3723 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003724 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003725 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003726 if (Index->isInstantiationDependent())
3727 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003728 // Propagate unexpanded parameter packs.
3729 if (Index->containsUnexpandedParameterPack())
3730 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003731
3732 // Copy the index expressions into permanent storage.
3733 *Child++ = IndexExprs[IndexIdx++];
3734 } else if (this->Designators[I].isArrayRangeDesignator()) {
3735 // Compute type- and value-dependence.
3736 Expr *Start = IndexExprs[IndexIdx];
3737 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003738 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003739 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00003740 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003741 ExprBits.InstantiationDependent = true;
3742 } else if (Start->isInstantiationDependent() ||
3743 End->isInstantiationDependent()) {
3744 ExprBits.InstantiationDependent = true;
3745 }
3746
Douglas Gregora6e053e2010-12-15 01:34:56 +00003747 // Propagate unexpanded parameter packs.
3748 if (Start->containsUnexpandedParameterPack() ||
3749 End->containsUnexpandedParameterPack())
3750 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003751
3752 // Copy the start/end expressions into permanent storage.
3753 *Child++ = IndexExprs[IndexIdx++];
3754 *Child++ = IndexExprs[IndexIdx++];
3755 }
3756 }
3757
Benjamin Kramerc215e762012-08-24 11:54:20 +00003758 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00003759}
3760
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003761DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00003762DesignatedInitExpr::Create(const ASTContext &C,
3763 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003764 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003765 SourceLocation ColonOrEqualLoc,
3766 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003767 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003768 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00003769 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003770 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003771 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003772}
3773
Craig Topper37932912013-08-18 10:09:15 +00003774DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00003775 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003776 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003777 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00003778 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3779}
3780
Craig Topper37932912013-08-18 10:09:15 +00003781void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003782 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00003783 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003784 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00003785 NumDesignators = NumDesigs;
3786 for (unsigned I = 0; I != NumDesigs; ++I)
3787 Designators[I] = Desigs[I];
3788}
3789
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003790SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3791 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3792 if (size() == 1)
3793 return DIE->getDesignator(0)->getSourceRange();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003794 return SourceRange(DIE->getDesignator(0)->getLocStart(),
3795 DIE->getDesignator(size()-1)->getLocEnd());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003796}
3797
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003798SourceLocation DesignatedInitExpr::getLocStart() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003799 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00003800 auto *DIE = const_cast<DesignatedInitExpr *>(this);
3801 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003802 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00003803 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003804 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3805 else
3806 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3807 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00003808 StartLoc =
3809 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003810 return StartLoc;
3811}
3812
3813SourceLocation DesignatedInitExpr::getLocEnd() const {
3814 return getInit()->getLocEnd();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003815}
3816
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003817Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003818 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003819 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003820}
3821
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003822Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003823 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003824 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003825 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003826}
3827
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003828Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003829 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003830 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003831 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003832}
3833
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003834/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00003835/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00003836void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00003837 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00003838 const Designator *Last) {
3839 unsigned NumNewDesignators = Last - First;
3840 if (NumNewDesignators == 0) {
3841 std::copy_backward(Designators + Idx + 1,
3842 Designators + NumDesignators,
3843 Designators + Idx);
3844 --NumNewDesignators;
3845 return;
3846 } else if (NumNewDesignators == 1) {
3847 Designators[Idx] = *First;
3848 return;
3849 }
3850
Mike Stump11289f42009-09-09 15:08:12 +00003851 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003852 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00003853 std::copy(Designators, Designators + Idx, NewDesignators);
3854 std::copy(First, Last, NewDesignators + Idx);
3855 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3856 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00003857 Designators = NewDesignators;
3858 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3859}
3860
Yunzhong Gaocb779302015-06-10 00:27:52 +00003861DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
3862 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3863 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3864 OK_Ordinary, false, false, false, false) {
3865 BaseAndUpdaterExprs[0] = baseExpr;
3866
3867 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3868 ILE->setType(baseExpr->getType());
3869 BaseAndUpdaterExprs[1] = ILE;
3870}
3871
3872SourceLocation DesignatedInitUpdateExpr::getLocStart() const {
3873 return getBase()->getLocStart();
3874}
3875
3876SourceLocation DesignatedInitUpdateExpr::getLocEnd() const {
3877 return getBase()->getLocEnd();
3878}
3879
Craig Topper37932912013-08-18 10:09:15 +00003880ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003881 ArrayRef<Expr*> exprs,
Sebastian Redla9351792012-02-11 23:51:47 +00003882 SourceLocation rparenloc)
3883 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003884 false, false, false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003885 NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3886 Exprs = new (C) Stmt*[exprs.size()];
3887 for (unsigned i = 0; i != exprs.size(); ++i) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003888 if (exprs[i]->isTypeDependent())
3889 ExprBits.TypeDependent = true;
3890 if (exprs[i]->isValueDependent())
3891 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003892 if (exprs[i]->isInstantiationDependent())
3893 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003894 if (exprs[i]->containsUnexpandedParameterPack())
3895 ExprBits.ContainsUnexpandedParameterPack = true;
3896
Nate Begeman5ec4b312009-08-10 23:49:36 +00003897 Exprs[i] = exprs[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003898 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00003899}
3900
John McCall1bf58462011-02-16 08:02:54 +00003901const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3902 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3903 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00003904 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3905 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00003906 e = cast<CXXConstructExpr>(e)->getArg(0);
3907 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3908 e = ice->getSubExpr();
3909 return cast<OpaqueValueExpr>(e);
3910}
3911
Craig Topper37932912013-08-18 10:09:15 +00003912PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
3913 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00003914 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003915 void *buffer =
3916 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003917 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00003918 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3919}
3920
3921PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3922 : Expr(PseudoObjectExprClass, shell) {
3923 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3924}
3925
Craig Topper37932912013-08-18 10:09:15 +00003926PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00003927 ArrayRef<Expr*> semantics,
3928 unsigned resultIndex) {
3929 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003930 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00003931
3932 QualType type;
3933 ExprValueKind VK;
3934 if (resultIndex == NoResult) {
3935 type = C.VoidTy;
3936 VK = VK_RValue;
3937 } else {
3938 assert(resultIndex < semantics.size());
3939 type = semantics[resultIndex]->getType();
3940 VK = semantics[resultIndex]->getValueKind();
3941 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3942 }
3943
James Y Knighte00a67e2015-12-31 04:18:25 +00003944 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003945 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00003946 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3947 resultIndex);
3948}
3949
3950PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3951 Expr *syntax, ArrayRef<Expr*> semantics,
3952 unsigned resultIndex)
3953 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3954 /*filled in at end of ctor*/ false, false, false, false) {
3955 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3956 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3957
3958 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3959 Expr *E = (i == 0 ? syntax : semantics[i-1]);
3960 getSubExprsBuffer()[i] = E;
3961
3962 if (E->isTypeDependent())
3963 ExprBits.TypeDependent = true;
3964 if (E->isValueDependent())
3965 ExprBits.ValueDependent = true;
3966 if (E->isInstantiationDependent())
3967 ExprBits.InstantiationDependent = true;
3968 if (E->containsUnexpandedParameterPack())
3969 ExprBits.ContainsUnexpandedParameterPack = true;
3970
3971 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00003972 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00003973 "opaque-value semantic expressions for pseudo-object "
3974 "operations must have sources");
3975 }
3976}
3977
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003978//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003979// Child Iterators for iterating over subexpressions/substatements
3980//===----------------------------------------------------------------------===//
3981
Peter Collingbournee190dee2011-03-11 19:24:49 +00003982// UnaryExprOrTypeTraitExpr
3983Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00003984 const_child_range CCR =
3985 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
3986 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
3987}
3988
3989Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00003990 // If this is of a type and the type is a VLA type (and not a typedef), the
3991 // size expression of the VLA needs to be treated as an executable expression.
3992 // Why isn't this weirdness documented better in StmtIterator?
3993 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00003994 if (const VariableArrayType *T =
3995 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
3996 return const_child_range(const_child_iterator(T), const_child_iterator());
3997 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00003998 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00003999 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004000}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004001
Benjamin Kramerc215e762012-08-24 11:54:20 +00004002AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004003 QualType t, AtomicOp op, SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004004 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4005 false, false, false, false),
4006 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4007{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004008 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4009 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004010 if (args[i]->isTypeDependent())
4011 ExprBits.TypeDependent = true;
4012 if (args[i]->isValueDependent())
4013 ExprBits.ValueDependent = true;
4014 if (args[i]->isInstantiationDependent())
4015 ExprBits.InstantiationDependent = true;
4016 if (args[i]->containsUnexpandedParameterPack())
4017 ExprBits.ContainsUnexpandedParameterPack = true;
4018
4019 SubExprs[i] = args[i];
4020 }
4021}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004022
4023unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4024 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004025 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004026 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004027 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004028 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004029 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004030
Yaxun Liu30d652a2017-08-15 16:02:49 +00004031 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004032 case AO__c11_atomic_store:
4033 case AO__c11_atomic_exchange:
4034 case AO__atomic_load:
4035 case AO__atomic_store:
4036 case AO__atomic_store_n:
4037 case AO__atomic_exchange_n:
4038 case AO__c11_atomic_fetch_add:
4039 case AO__c11_atomic_fetch_sub:
4040 case AO__c11_atomic_fetch_and:
4041 case AO__c11_atomic_fetch_or:
4042 case AO__c11_atomic_fetch_xor:
4043 case AO__atomic_fetch_add:
4044 case AO__atomic_fetch_sub:
4045 case AO__atomic_fetch_and:
4046 case AO__atomic_fetch_or:
4047 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004048 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004049 case AO__atomic_add_fetch:
4050 case AO__atomic_sub_fetch:
4051 case AO__atomic_and_fetch:
4052 case AO__atomic_or_fetch:
4053 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004054 case AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004055 case AO__atomic_fetch_min:
4056 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004057 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004058
Yaxun Liu30d652a2017-08-15 16:02:49 +00004059 case AO__opencl_atomic_store:
4060 case AO__opencl_atomic_exchange:
4061 case AO__opencl_atomic_fetch_add:
4062 case AO__opencl_atomic_fetch_sub:
4063 case AO__opencl_atomic_fetch_and:
4064 case AO__opencl_atomic_fetch_or:
4065 case AO__opencl_atomic_fetch_xor:
4066 case AO__opencl_atomic_fetch_min:
4067 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004068 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004069 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004070
4071 case AO__c11_atomic_compare_exchange_strong:
4072 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004073 return 5;
4074
Yaxun Liu39195062017-08-04 18:16:31 +00004075 case AO__opencl_atomic_compare_exchange_strong:
4076 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004077 case AO__atomic_compare_exchange:
4078 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004079 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004080 }
4081 llvm_unreachable("unknown atomic op");
4082}
Alexey Bataeva1764212015-09-30 09:22:36 +00004083
Yaxun Liu39195062017-08-04 18:16:31 +00004084QualType AtomicExpr::getValueType() const {
4085 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4086 if (auto AT = T->getAs<AtomicType>())
4087 return AT->getValueType();
4088 return T;
4089}
4090
Alexey Bataev31300ed2016-02-04 11:27:03 +00004091QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004092 unsigned ArraySectionCount = 0;
4093 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4094 Base = OASE->getBase();
4095 ++ArraySectionCount;
4096 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004097 while (auto *ASE =
4098 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004099 Base = ASE->getBase();
4100 ++ArraySectionCount;
4101 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004102 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004103 auto OriginalTy = Base->getType();
4104 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4105 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4106 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4107
4108 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4109 if (OriginalTy->isAnyPointerType())
4110 OriginalTy = OriginalTy->getPointeeType();
4111 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004112 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004113 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4114 }
4115 }
4116 return OriginalTy;
4117}