blob: e835686a1a9368d2fef786b53c746e2e7b2db5d2 [file] [log] [blame]
Chris Lattner1b926492006-08-23 06:42:10 +00001//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris 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"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
David Majnemerbed356a2013-11-06 23:31:56 +000022#include "clang/AST/Mangle.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner5e9a8782006-11-04 06:21:51 +000024#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"
31#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
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000038const CXXRecordDecl *Expr::getBestDynamicClassType() const {
Rafael Espindolaecbe2e92012-06-28 01:56:38 +000039 const Expr *E = ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000040
41 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000042 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
43 DerivedType = PTy->getPointeeType();
44
Rafael Espindola60a2bba2012-07-17 20:24:05 +000045 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000046 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000047
Rafael Espindola49e860b2012-06-26 17:45:31 +000048 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000049 Decl *D = Ty->getDecl();
50 return cast<CXXRecordDecl>(D);
51}
52
Richard Smithf3fabd22013-06-03 00:17:11 +000053const Expr *Expr::skipRValueSubobjectAdjustments(
54 SmallVectorImpl<const Expr *> &CommaLHSs,
55 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000056 const Expr *E = this;
57 while (true) {
58 E = E->IgnoreParens();
59
60 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
61 if ((CE->getCastKind() == CK_DerivedToBase ||
62 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
63 E->getType()->isRecordType()) {
64 E = CE->getSubExpr();
65 CXXRecordDecl *Derived
66 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
67 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
68 continue;
69 }
70
71 if (CE->getCastKind() == CK_NoOp) {
72 E = CE->getSubExpr();
73 continue;
74 }
75 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +000076 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +000077 assert(ME->getBase()->getType()->isRecordType());
78 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +000079 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +000080 E = ME->getBase();
81 Adjustments.push_back(SubobjectAdjustment(Field));
82 continue;
83 }
Rafael Espindola9c006de2012-10-27 01:03:43 +000084 }
85 }
86 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
87 if (BO->isPtrMemOp()) {
Rafael Espindola973aa202012-11-01 14:32:20 +000088 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +000089 E = BO->getLHS();
90 const MemberPointerType *MPT =
91 BO->getRHS()->getType()->getAs<MemberPointerType>();
92 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +000093 continue;
94 } else if (BO->getOpcode() == BO_Comma) {
95 CommaLHSs.push_back(BO->getLHS());
96 E = BO->getRHS();
97 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +000098 }
99 }
100
101 // Nothing changed.
102 break;
103 }
104 return E;
105}
106
Chris Lattner4ebae652010-04-16 23:34:13 +0000107/// isKnownToHaveBooleanValue - Return true if this is an integer expression
108/// that is known to return 0 or 1. This happens for _Bool/bool expressions
109/// but also int expressions which are produced by things like comparisons in
110/// C.
111bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000112 const Expr *E = IgnoreParens();
113
Chris Lattner4ebae652010-04-16 23:34:13 +0000114 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000115 if (E->getType()->isBooleanType()) return true;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000116 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000117 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000118
Peter Collingbourne91147592011-04-15 00:35:48 +0000119 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000120 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000121 case UO_Plus:
Chris Lattner4ebae652010-04-16 23:34:13 +0000122 return UO->getSubExpr()->isKnownToHaveBooleanValue();
Richard Trieu0f097742014-04-04 04:13:47 +0000123 case UO_LNot:
124 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000125 default:
126 return false;
127 }
128 }
Alexis Hunta8136cc2010-05-05 15:23:54 +0000129
John McCall45d30c32010-06-12 01:56:02 +0000130 // Only look through implicit casts. If the user writes
131 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbourne91147592011-04-15 00:35:48 +0000132 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000133 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000134
Peter Collingbourne91147592011-04-15 00:35:48 +0000135 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000136 switch (BO->getOpcode()) {
137 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000138 case BO_LT: // Relational operators.
139 case BO_GT:
140 case BO_LE:
141 case BO_GE:
142 case BO_EQ: // Equality operators.
143 case BO_NE:
144 case BO_LAnd: // AND operator.
145 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000146 return true;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000147
John McCalle3027922010-08-25 11:45:40 +0000148 case BO_And: // Bitwise AND operator.
149 case BO_Xor: // Bitwise XOR operator.
150 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000151 // Handle things like (x==2)|(y==12).
152 return BO->getLHS()->isKnownToHaveBooleanValue() &&
153 BO->getRHS()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000154
John McCalle3027922010-08-25 11:45:40 +0000155 case BO_Comma:
156 case BO_Assign:
Chris Lattner4ebae652010-04-16 23:34:13 +0000157 return BO->getRHS()->isKnownToHaveBooleanValue();
158 }
159 }
Alexis Hunta8136cc2010-05-05 15:23:54 +0000160
Peter Collingbourne91147592011-04-15 00:35:48 +0000161 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000162 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
163 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000164
Chris Lattner4ebae652010-04-16 23:34:13 +0000165 return false;
166}
167
John McCallbd066782011-02-09 08:16:59 +0000168// Amusing macro metaprogramming hack: check whether a class provides
169// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000170//
171// See also Stmt.cpp:{getLocStart(),getLocEnd()}.
John McCallbd066782011-02-09 08:16:59 +0000172namespace {
173 /// This implementation is used when a class provides a custom
174 /// implementation of getExprLoc.
175 template <class E, class T>
176 SourceLocation getExprLocImpl(const Expr *expr,
177 SourceLocation (T::*v)() const) {
178 return static_cast<const E*>(expr)->getExprLoc();
179 }
180
181 /// This implementation is used when a class doesn't provide
182 /// a custom implementation of getExprLoc. Overload resolution
183 /// should pick it over the implementation above because it's
184 /// more specialized according to function template partial ordering.
185 template <class E>
186 SourceLocation getExprLocImpl(const Expr *expr,
187 SourceLocation (Expr::*v)() const) {
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000188 return static_cast<const E*>(expr)->getLocStart();
John McCallbd066782011-02-09 08:16:59 +0000189 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000190}
John McCallbd066782011-02-09 08:16:59 +0000191
192SourceLocation Expr::getExprLoc() const {
193 switch (getStmtClass()) {
194 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
195#define ABSTRACT_STMT(type)
196#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000197 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000198#define EXPR(type, base) \
199 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
200#include "clang/AST/StmtNodes.inc"
201 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000202 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000203}
204
Chris Lattner0eedafe2006-08-24 04:56:27 +0000205//===----------------------------------------------------------------------===//
206// Primary Expressions.
207//===----------------------------------------------------------------------===//
208
Douglas Gregor678d76c2011-07-01 01:22:09 +0000209/// \brief Compute the type-, value-, and instantiation-dependence of a
210/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000211/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000212static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
213 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000214 bool &ValueDependent,
215 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000216 TypeDependent = false;
217 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000218 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000219
220 // (TD) C++ [temp.dep.expr]p3:
221 // An id-expression is type-dependent if it contains:
222 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000223 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000224 //
225 // (VD) C++ [temp.dep.constexpr]p2:
226 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000227
Douglas Gregored6c7442009-11-23 11:41:28 +0000228 // (TD) - an identifier that was declared with dependent type
229 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000230 if (T->isDependentType()) {
231 TypeDependent = true;
232 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000233 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000234 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000235 } else if (T->isInstantiationDependentType()) {
236 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000237 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000238
Douglas Gregored6c7442009-11-23 11:41:28 +0000239 // (TD) - a conversion-function-id that specifies a dependent type
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000240 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000241 == DeclarationName::CXXConversionFunctionName) {
242 QualType T = D->getDeclName().getCXXNameType();
243 if (T->isDependentType()) {
244 TypeDependent = true;
245 ValueDependent = true;
246 InstantiationDependent = true;
247 return;
248 }
249
250 if (T->isInstantiationDependentType())
251 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000252 }
Douglas Gregor678d76c2011-07-01 01:22:09 +0000253
Douglas Gregored6c7442009-11-23 11:41:28 +0000254 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000255 if (isa<NonTypeTemplateParmDecl>(D)) {
256 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000257 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000258 return;
259 }
260
Douglas Gregored6c7442009-11-23 11:41:28 +0000261 // (VD) - a constant with integral or enumeration type and is
262 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000263 // (VD) - a constant with literal type and is initialized with an
264 // expression that is value-dependent [C++11].
265 // (VD) - FIXME: Missing from the standard:
266 // - an entity with reference type and is initialized with an
267 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000268 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000269 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000270 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000271 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000272 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000273 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000274 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000275 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000276 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000277 InstantiationDependent = true;
278 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000279 }
280
Douglas Gregor0e4de762010-05-11 08:41:30 +0000281 // (VD) - FIXME: Missing from the standard:
282 // - a member function or a static data member of the current
283 // instantiation
Richard Smithec8dcd22011-11-08 01:31:09 +0000284 if (Var->isStaticDataMember() &&
285 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000286 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000287 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000288 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
289 if (TInfo->getType()->isIncompleteArrayType())
290 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000291 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000292
293 return;
294 }
295
Douglas Gregor0e4de762010-05-11 08:41:30 +0000296 // (VD) - FIXME: Missing from the standard:
297 // - a member function or a static data member of the current
298 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000299 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
300 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000301 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000302 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000303}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000304
Craig Topperce7167c2013-08-22 04:58:56 +0000305void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000306 bool TypeDependent = false;
307 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000308 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000309 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
310 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000311
312 ExprBits.TypeDependent |= TypeDependent;
313 ExprBits.ValueDependent |= ValueDependent;
314 ExprBits.InstantiationDependent |= InstantiationDependent;
315
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000316 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000317 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000318 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000319}
320
Craig Topperce7167c2013-08-22 04:58:56 +0000321DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000322 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000323 SourceLocation TemplateKWLoc,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000324 ValueDecl *D, bool RefersToEnclosingVariableOrCapture,
John McCall113bee02012-03-10 09:33:50 +0000325 const DeclarationNameInfo &NameInfo,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000326 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000327 const TemplateArgumentListInfo *TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +0000328 QualType T, ExprValueKind VK)
Douglas Gregor678d76c2011-07-01 01:22:09 +0000329 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
Chandler Carruth0e439962011-05-01 21:29:53 +0000330 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
331 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000332 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000333 new (getTrailingObjects<NestedNameSpecifierLoc>())
334 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000335 auto *NNS = QualifierLoc.getNestedNameSpecifier();
336 if (NNS->isInstantiationDependent())
337 ExprBits.InstantiationDependent = true;
338 if (NNS->containsUnexpandedParameterPack())
339 ExprBits.ContainsUnexpandedParameterPack = true;
340 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000341 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
342 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000343 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000344 DeclRefExprBits.HasTemplateKWAndArgsInfo
345 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000346 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
347 RefersToEnclosingVariableOrCapture;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000348 if (TemplateArgs) {
349 bool Dependent = false;
350 bool InstantiationDependent = false;
351 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000352 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
353 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
354 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000355 assert(!Dependent && "built a DeclRefExpr with dependent template args");
356 ExprBits.InstantiationDependent |= InstantiationDependent;
357 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000358 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000359 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
360 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000361 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000362 DeclRefExprBits.HadMultipleCandidates = 0;
363
Daniel Dunbar9d355812012-03-09 01:51:51 +0000364 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000365}
366
Craig Topperce7167c2013-08-22 04:58:56 +0000367DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000368 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000369 SourceLocation TemplateKWLoc,
John McCallce546572009-12-08 09:08:17 +0000370 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000371 bool RefersToEnclosingVariableOrCapture,
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000372 SourceLocation NameLoc,
Douglas Gregored6c7442009-11-23 11:41:28 +0000373 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000374 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000375 NamedDecl *FoundD,
Douglas Gregored6c7442009-11-23 11:41:28 +0000376 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000377 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000378 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000379 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000380 T, VK, FoundD, TemplateArgs);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000381}
382
Craig Topperce7167c2013-08-22 04:58:56 +0000383DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000384 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000385 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000386 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000387 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000388 const DeclarationNameInfo &NameInfo,
389 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000390 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000391 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000392 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000393 // Filter out cases where the found Decl is the same as the value refenenced.
394 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000395 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000396
James Y Knighte7d82282015-12-29 18:15:14 +0000397 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
398 std::size_t Size =
399 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
400 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
401 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
402 HasTemplateKWAndArgsInfo ? 1 : 0,
403 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000404
Chris Lattner5c0b4052010-10-30 05:14:06 +0000405 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Daniel Dunbar9d355812012-03-09 01:51:51 +0000406 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000407 RefersToEnclosingVariableOrCapture,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000408 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000409}
410
Craig Topperce7167c2013-08-22 04:58:56 +0000411DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000412 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000413 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000414 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000415 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000416 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
417 std::size_t Size =
418 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
419 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
420 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
421 NumTemplateArgs);
Chris Lattner5c0b4052010-10-30 05:14:06 +0000422 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000423 return new (Mem) DeclRefExpr(EmptyShell());
424}
425
Daniel Dunbarb507f272012-03-09 15:39:15 +0000426SourceLocation DeclRefExpr::getLocStart() const {
427 if (hasQualifier())
428 return getQualifierLoc().getBeginLoc();
429 return getNameInfo().getLocStart();
430}
431SourceLocation DeclRefExpr::getLocEnd() const {
432 if (hasExplicitTemplateArgs())
433 return getRAngleLoc();
434 return getNameInfo().getLocEnd();
435}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000436
Alexey Bataevec474782014-10-09 08:45:04 +0000437PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
438 StringLiteral *SL)
439 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
440 FNTy->isDependentType(), FNTy->isDependentType(),
441 FNTy->isInstantiationDependentType(),
442 /*ContainsUnexpandedParameterPack=*/false),
443 Loc(L), Type(IT), FnName(SL) {}
444
445StringLiteral *PredefinedExpr::getFunctionName() {
Alexey Bataev769562a2014-10-10 18:58:13 +0000446 return cast_or_null<StringLiteral>(FnName);
Alexey Bataevec474782014-10-09 08:45:04 +0000447}
448
449StringRef PredefinedExpr::getIdentTypeName(PredefinedExpr::IdentType IT) {
450 switch (IT) {
451 case Func:
452 return "__func__";
453 case Function:
454 return "__FUNCTION__";
455 case FuncDName:
456 return "__FUNCDNAME__";
457 case LFunction:
458 return "L__FUNCTION__";
459 case PrettyFunction:
460 return "__PRETTY_FUNCTION__";
461 case FuncSig:
462 return "__FUNCSIG__";
463 case PrettyFunctionNoVirtual:
464 break;
465 }
466 llvm_unreachable("Unknown ident type for PredefinedExpr");
467}
468
Anders Carlsson2fb08242009-09-08 18:24:21 +0000469// FIXME: Maybe this should use DeclPrinter with a special "print predefined
470// expr" policy instead.
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000471std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
472 ASTContext &Context = CurrentDecl->getASTContext();
473
David Majnemerbed356a2013-11-06 23:31:56 +0000474 if (IT == PredefinedExpr::FuncDName) {
475 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000476 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000477 MC.reset(Context.createMangleContext());
478
479 if (MC->shouldMangleDeclName(ND)) {
480 SmallString<256> Buffer;
481 llvm::raw_svector_ostream Out(Buffer);
482 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
483 MC->mangleCXXCtor(CD, Ctor_Base, Out);
484 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
485 MC->mangleCXXDtor(DD, Dtor_Base, Out);
486 else
487 MC->mangleName(ND, Out);
488
David Majnemerbed356a2013-11-06 23:31:56 +0000489 if (!Buffer.empty() && Buffer.front() == '\01')
490 return Buffer.substr(1);
491 return Buffer.str();
492 } else
493 return ND->getIdentifier()->getName();
494 }
495 return "";
496 }
Alexey Bataevec474782014-10-09 08:45:04 +0000497 if (auto *BD = dyn_cast<BlockDecl>(CurrentDecl)) {
498 std::unique_ptr<MangleContext> MC;
499 MC.reset(Context.createMangleContext());
500 SmallString<256> Buffer;
501 llvm::raw_svector_ostream Out(Buffer);
502 auto DC = CurrentDecl->getDeclContext();
503 if (DC->isFileContext())
504 MC->mangleGlobalBlock(BD, /*ID*/ nullptr, Out);
505 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
506 MC->mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, Out);
507 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
508 MC->mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, Out);
509 else
510 MC->mangleBlock(DC, BD, Out);
511 return Out.str();
512 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000513 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000514 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual && IT != FuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000515 return FD->getNameAsString();
516
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000517 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000518 llvm::raw_svector_ostream Out(Name);
519
520 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000521 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000522 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000523 if (MD->isStatic())
524 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000525 }
526
David Blaikiebbafb8a2012-03-11 07:00:24 +0000527 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000528 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000529 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000530
Douglas Gregor11a434a2012-04-10 20:14:15 +0000531 const FunctionDecl *Decl = FD;
532 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
533 Decl = Pattern;
534 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000535 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000536 if (FD->hasWrittenPrototype())
537 FT = dyn_cast<FunctionProtoType>(AFT);
538
Reid Kleckner52eddda2014-04-08 18:13:24 +0000539 if (IT == FuncSig) {
540 switch (FT->getCallConv()) {
541 case CC_C: POut << "__cdecl "; break;
542 case CC_X86StdCall: POut << "__stdcall "; break;
543 case CC_X86FastCall: POut << "__fastcall "; break;
544 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000545 case CC_X86VectorCall: POut << "__vectorcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000546 // Only bother printing the conventions that MSVC knows about.
547 default: break;
548 }
549 }
550
551 FD->printQualifiedName(POut, Policy);
552
Douglas Gregor11a434a2012-04-10 20:14:15 +0000553 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000554 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000555 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000556 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000557 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000558 }
559
560 if (FT->isVariadic()) {
561 if (FD->getNumParams()) POut << ", ";
562 POut << "...";
563 }
564 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000565 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000566
Sam Weinig4e83bd22009-12-27 01:38:20 +0000567 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Argyrios Kyrtzidis53e3d6d2012-12-14 19:44:11 +0000568 const FunctionType *FT = MD->getType()->castAs<FunctionType>();
David Blaikief5697e52012-08-10 00:55:35 +0000569 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000570 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000571 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000572 POut << " volatile";
573 RefQualifierKind Ref = MD->getRefQualifier();
574 if (Ref == RQ_LValue)
575 POut << " &";
576 else if (Ref == RQ_RValue)
577 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000578 }
579
Douglas Gregor11a434a2012-04-10 20:14:15 +0000580 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
581 SpecsTy Specs;
582 const DeclContext *Ctx = FD->getDeclContext();
583 while (Ctx && isa<NamedDecl>(Ctx)) {
584 const ClassTemplateSpecializationDecl *Spec
585 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
586 if (Spec && !Spec->isExplicitSpecialization())
587 Specs.push_back(Spec);
588 Ctx = Ctx->getParent();
589 }
590
591 std::string TemplateParams;
592 llvm::raw_string_ostream TOut(TemplateParams);
593 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
594 I != E; ++I) {
595 const TemplateParameterList *Params
596 = (*I)->getSpecializedTemplate()->getTemplateParameters();
597 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
598 assert(Params->size() == Args.size());
599 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
600 StringRef Param = Params->getParam(i)->getName();
601 if (Param.empty()) continue;
602 TOut << Param << " = ";
603 Args.get(i).print(Policy, TOut);
604 TOut << ", ";
605 }
606 }
607
608 FunctionTemplateSpecializationInfo *FSI
609 = FD->getTemplateSpecializationInfo();
610 if (FSI && !FSI->isExplicitSpecialization()) {
611 const TemplateParameterList* Params
612 = FSI->getTemplate()->getTemplateParameters();
613 const TemplateArgumentList* Args = FSI->TemplateArguments;
614 assert(Params->size() == Args->size());
615 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
616 StringRef Param = Params->getParam(i)->getName();
617 if (Param.empty()) continue;
618 TOut << Param << " = ";
619 Args->get(i).print(Policy, TOut);
620 TOut << ", ";
621 }
622 }
623
624 TOut.flush();
625 if (!TemplateParams.empty()) {
626 // remove the trailing comma and space
627 TemplateParams.resize(TemplateParams.size() - 2);
628 POut << " [" << TemplateParams << "]";
629 }
630
631 POut.flush();
632
Benjamin Kramer90f54222013-08-21 11:45:27 +0000633 // Print "auto" for all deduced return types. This includes C++1y return
634 // type deduction and lambdas. For trailing return types resolve the
635 // decltype expression. Otherwise print the real type when this is
636 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000637 if (isa<CXXMethodDecl>(FD) &&
638 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000639 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000640 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
641 FT->getReturnType()
642 ->getAs<DecltypeType>()
643 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000644 .getAsStringInternal(Proto, Policy);
645 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000646 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000647
648 Out << Proto;
649
Anders Carlsson2fb08242009-09-08 18:24:21 +0000650 return Name.str().str();
651 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000652 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
653 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
654 // Skip to its enclosing function or method, but not its enclosing
655 // CapturedDecl.
656 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
657 const Decl *D = Decl::castFromDeclContext(DC);
658 return ComputeName(IT, D);
659 }
660 llvm_unreachable("CapturedDecl not inside a function or method");
661 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000662 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000663 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000664 llvm::raw_svector_ostream Out(Name);
665 Out << (MD->isInstanceMethod() ? '-' : '+');
666 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000667
668 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
669 // a null check to avoid a crash.
670 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000671 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000672
Anders Carlsson2fb08242009-09-08 18:24:21 +0000673 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000674 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000675 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000676
Anders Carlsson2fb08242009-09-08 18:24:21 +0000677 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000678 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000679 Out << ']';
680
Anders Carlsson2fb08242009-09-08 18:24:21 +0000681 return Name.str().str();
682 }
683 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
684 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
685 return "top level";
686 }
687 return "";
688}
689
Craig Topper37932912013-08-18 10:09:15 +0000690void APNumericStorage::setIntValue(const ASTContext &C,
691 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000692 if (hasAllocation())
693 C.Deallocate(pVal);
694
695 BitWidth = Val.getBitWidth();
696 unsigned NumWords = Val.getNumWords();
697 const uint64_t* Words = Val.getRawData();
698 if (NumWords > 1) {
699 pVal = new (C) uint64_t[NumWords];
700 std::copy(Words, Words + NumWords, pVal);
701 } else if (NumWords == 1)
702 VAL = Words[0];
703 else
704 VAL = 0;
705}
706
Craig Topper37932912013-08-18 10:09:15 +0000707IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000708 QualType type, SourceLocation l)
709 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
710 false, false),
711 Loc(l) {
712 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
713 assert(V.getBitWidth() == C.getIntWidth(type) &&
714 "Integer type is not the correct size for constant.");
715 setValue(C, V);
716}
717
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000718IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000719IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000720 QualType type, SourceLocation l) {
721 return new (C) IntegerLiteral(C, V, type, l);
722}
723
724IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000725IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000726 return new (C) IntegerLiteral(Empty);
727}
728
Craig Topper37932912013-08-18 10:09:15 +0000729FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000730 bool isexact, QualType Type, SourceLocation L)
731 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
732 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000733 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000734 FloatingLiteralBits.IsExact = isexact;
735 setValue(C, V);
736}
737
Craig Topper37932912013-08-18 10:09:15 +0000738FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000739 : Expr(FloatingLiteralClass, Empty) {
Tim Northover178723a2013-01-22 09:46:51 +0000740 setRawSemantics(IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000741 FloatingLiteralBits.IsExact = false;
742}
743
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000744FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000745FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000746 bool isexact, QualType Type, SourceLocation L) {
747 return new (C) FloatingLiteral(C, V, isexact, Type, L);
748}
749
750FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000751FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000752 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000753}
754
Tim Northover178723a2013-01-22 09:46:51 +0000755const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
756 switch(FloatingLiteralBits.Semantics) {
757 case IEEEhalf:
758 return llvm::APFloat::IEEEhalf;
759 case IEEEsingle:
760 return llvm::APFloat::IEEEsingle;
761 case IEEEdouble:
762 return llvm::APFloat::IEEEdouble;
763 case x87DoubleExtended:
764 return llvm::APFloat::x87DoubleExtended;
765 case IEEEquad:
766 return llvm::APFloat::IEEEquad;
767 case PPCDoubleDouble:
768 return llvm::APFloat::PPCDoubleDouble;
769 }
770 llvm_unreachable("Unrecognised floating semantics");
771}
772
773void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
774 if (&Sem == &llvm::APFloat::IEEEhalf)
775 FloatingLiteralBits.Semantics = IEEEhalf;
776 else if (&Sem == &llvm::APFloat::IEEEsingle)
777 FloatingLiteralBits.Semantics = IEEEsingle;
778 else if (&Sem == &llvm::APFloat::IEEEdouble)
779 FloatingLiteralBits.Semantics = IEEEdouble;
780 else if (&Sem == &llvm::APFloat::x87DoubleExtended)
781 FloatingLiteralBits.Semantics = x87DoubleExtended;
782 else if (&Sem == &llvm::APFloat::IEEEquad)
783 FloatingLiteralBits.Semantics = IEEEquad;
784 else if (&Sem == &llvm::APFloat::PPCDoubleDouble)
785 FloatingLiteralBits.Semantics = PPCDoubleDouble;
786 else
787 llvm_unreachable("Unknown floating semantics");
788}
789
Chris Lattnera0173132008-06-07 22:13:43 +0000790/// getValueAsApproximateDouble - This returns the value as an inaccurate
791/// double. Note that this may cause loss of precision, but is useful for
792/// debugging dumps, etc.
793double FloatingLiteral::getValueAsApproximateDouble() const {
794 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000795 bool ignored;
796 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
797 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000798 return V.convertToDouble();
799}
800
Nick Lewycky4ed84042012-02-24 09:07:53 +0000801int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
Eli Friedman381f4312012-02-29 20:59:56 +0000802 int CharByteWidth = 0;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000803 switch(k) {
Eli Friedmanfcec6302011-11-01 02:23:42 +0000804 case Ascii:
805 case UTF8:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000806 CharByteWidth = target.getCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000807 break;
808 case Wide:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000809 CharByteWidth = target.getWCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000810 break;
811 case UTF16:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000812 CharByteWidth = target.getChar16Width();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000813 break;
814 case UTF32:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000815 CharByteWidth = target.getChar32Width();
Eli Friedman381f4312012-02-29 20:59:56 +0000816 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000817 }
818 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
819 CharByteWidth /= 8;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000820 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
Eli Friedmanfcec6302011-11-01 02:23:42 +0000821 && "character byte widths supported are 1, 2, and 4 only");
822 return CharByteWidth;
823}
824
Craig Topper37932912013-08-18 10:09:15 +0000825StringLiteral *StringLiteral::Create(const ASTContext &C, StringRef Str,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000826 StringKind Kind, bool Pascal, QualType Ty,
Mike Stump11289f42009-09-09 15:08:12 +0000827 const SourceLocation *Loc,
Anders Carlssona3905812009-03-15 18:34:13 +0000828 unsigned NumStrs) {
Benjamin Kramercdac7612014-02-25 12:26:20 +0000829 assert(C.getAsConstantArrayType(Ty) &&
830 "StringLiteral must be of constant array type!");
831
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000832 // Allocate enough space for the StringLiteral plus an array of locations for
833 // any concatenated string tokens.
834 void *Mem = C.Allocate(sizeof(StringLiteral)+
835 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner5c0b4052010-10-30 05:14:06 +0000836 llvm::alignOf<StringLiteral>());
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000837 StringLiteral *SL = new (Mem) StringLiteral(Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000838
Steve Naroffdf7855b2007-02-21 23:46:25 +0000839 // OPTIMIZE: could allocate this appended to the StringLiteral.
Eli Friedmanfcec6302011-11-01 02:23:42 +0000840 SL->setString(C,Str,Kind,Pascal);
841
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000842 SL->TokLocs[0] = Loc[0];
843 SL->NumConcatenated = NumStrs;
Chris Lattnerd3e98952006-10-06 05:22:26 +0000844
Chris Lattner630970d2009-02-18 05:49:11 +0000845 if (NumStrs != 1)
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000846 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
847 return SL;
Chris Lattner630970d2009-02-18 05:49:11 +0000848}
849
Craig Topper37932912013-08-18 10:09:15 +0000850StringLiteral *StringLiteral::CreateEmpty(const ASTContext &C,
851 unsigned NumStrs) {
Douglas Gregor958dfc92009-04-15 16:35:07 +0000852 void *Mem = C.Allocate(sizeof(StringLiteral)+
853 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner5c0b4052010-10-30 05:14:06 +0000854 llvm::alignOf<StringLiteral>());
Douglas Gregor958dfc92009-04-15 16:35:07 +0000855 StringLiteral *SL = new (Mem) StringLiteral(QualType());
Eli Friedmanfcec6302011-11-01 02:23:42 +0000856 SL->CharByteWidth = 0;
857 SL->Length = 0;
Douglas Gregor958dfc92009-04-15 16:35:07 +0000858 SL->NumConcatenated = NumStrs;
859 return SL;
860}
861
Alexander Kornienko540bacb2013-02-01 12:35:51 +0000862void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +0000863 switch (getKind()) {
864 case Ascii: break; // no prefix.
865 case Wide: OS << 'L'; break;
866 case UTF8: OS << "u8"; break;
867 case UTF16: OS << 'u'; break;
868 case UTF32: OS << 'U'; break;
869 }
870 OS << '"';
871 static const char Hex[] = "0123456789ABCDEF";
872
873 unsigned LastSlashX = getLength();
874 for (unsigned I = 0, N = getLength(); I != N; ++I) {
875 switch (uint32_t Char = getCodeUnit(I)) {
876 default:
877 // FIXME: Convert UTF-8 back to codepoints before rendering.
878
879 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
880 // Leave invalid surrogates alone; we'll use \x for those.
881 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
882 Char <= 0xdbff) {
883 uint32_t Trail = getCodeUnit(I + 1);
884 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
885 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
886 ++I;
887 }
888 }
889
890 if (Char > 0xff) {
891 // If this is a wide string, output characters over 0xff using \x
892 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
893 // codepoint: use \x escapes for invalid codepoints.
894 if (getKind() == Wide ||
895 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
896 // FIXME: Is this the best way to print wchar_t?
897 OS << "\\x";
898 int Shift = 28;
899 while ((Char >> Shift) == 0)
900 Shift -= 4;
901 for (/**/; Shift >= 0; Shift -= 4)
902 OS << Hex[(Char >> Shift) & 15];
903 LastSlashX = I;
904 break;
905 }
906
907 if (Char > 0xffff)
908 OS << "\\U00"
909 << Hex[(Char >> 20) & 15]
910 << Hex[(Char >> 16) & 15];
911 else
912 OS << "\\u";
913 OS << Hex[(Char >> 12) & 15]
914 << Hex[(Char >> 8) & 15]
915 << Hex[(Char >> 4) & 15]
916 << Hex[(Char >> 0) & 15];
917 break;
918 }
919
920 // If we used \x... for the previous character, and this character is a
921 // hexadecimal digit, prevent it being slurped as part of the \x.
922 if (LastSlashX + 1 == I) {
923 switch (Char) {
924 case '0': case '1': case '2': case '3': case '4':
925 case '5': case '6': case '7': case '8': case '9':
926 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
927 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
928 OS << "\"\"";
929 }
930 }
931
932 assert(Char <= 0xff &&
933 "Characters above 0xff should already have been handled.");
934
Jordan Rosea7d03842013-02-08 22:30:41 +0000935 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +0000936 OS << (char)Char;
937 else // Output anything hard as an octal escape.
938 OS << '\\'
939 << (char)('0' + ((Char >> 6) & 7))
940 << (char)('0' + ((Char >> 3) & 7))
941 << (char)('0' + ((Char >> 0) & 7));
942 break;
943 // Handle some common non-printable cases to make dumps prettier.
944 case '\\': OS << "\\\\"; break;
945 case '"': OS << "\\\""; break;
946 case '\n': OS << "\\n"; break;
947 case '\t': OS << "\\t"; break;
948 case '\a': OS << "\\a"; break;
949 case '\b': OS << "\\b"; break;
950 }
951 }
952 OS << '"';
953}
954
Craig Topper37932912013-08-18 10:09:15 +0000955void StringLiteral::setString(const ASTContext &C, StringRef Str,
Eli Friedmanfcec6302011-11-01 02:23:42 +0000956 StringKind Kind, bool IsPascal) {
957 //FIXME: we assume that the string data comes from a target that uses the same
958 // code unit size and endianess for the type of string.
959 this->Kind = Kind;
960 this->IsPascal = IsPascal;
961
Nick Lewycky4ed84042012-02-24 09:07:53 +0000962 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
Eli Friedmanfcec6302011-11-01 02:23:42 +0000963 assert((Str.size()%CharByteWidth == 0)
964 && "size of data must be multiple of CharByteWidth");
965 Length = Str.size()/CharByteWidth;
966
967 switch(CharByteWidth) {
968 case 1: {
969 char *AStrData = new (C) char[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +0000970 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000971 StrData.asChar = AStrData;
972 break;
973 }
974 case 2: {
975 uint16_t *AStrData = new (C) uint16_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +0000976 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000977 StrData.asUInt16 = AStrData;
978 break;
979 }
980 case 4: {
981 uint32_t *AStrData = new (C) uint32_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +0000982 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000983 StrData.asUInt32 = AStrData;
984 break;
985 }
986 default:
Davide Italiano04839a52016-01-30 08:03:54 +0000987 llvm_unreachable("unsupported CharByteWidth");
Eli Friedmanfcec6302011-11-01 02:23:42 +0000988 }
Douglas Gregor958dfc92009-04-15 16:35:07 +0000989}
990
Chris Lattnere925d612010-11-17 07:37:15 +0000991/// getLocationOfByte - Return a source location that points to the specified
992/// byte of this string literal.
993///
994/// Strings are amazingly complex. They can be formed from multiple tokens and
995/// can have escape sequences in them in addition to the usual trigraph and
996/// escaped newline business. This routine handles this complexity.
997///
Richard Smithefb116f2015-12-10 01:11:47 +0000998/// The *StartToken sets the first token to be searched in this function and
999/// the *StartTokenByteOffset is the byte offset of the first token. Before
1000/// returning, it updates the *StartToken to the TokNo of the token being found
1001/// and sets *StartTokenByteOffset to the byte offset of the token in the
1002/// string.
1003/// Using these two parameters can reduce the time complexity from O(n^2) to
1004/// O(n) if one wants to get the location of byte for all the tokens in a
1005/// string.
1006///
1007SourceLocation
1008StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1009 const LangOptions &Features,
1010 const TargetInfo &Target, unsigned *StartToken,
1011 unsigned *StartTokenByteOffset) const {
Richard Smith4060f772012-06-13 05:37:23 +00001012 assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
1013 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001014
Chris Lattnere925d612010-11-17 07:37:15 +00001015 // Loop over all of the tokens in this string until we find the one that
1016 // contains the byte we're looking for.
1017 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001018 unsigned StringOffset = 0;
1019 if (StartToken)
1020 TokNo = *StartToken;
1021 if (StartTokenByteOffset) {
1022 StringOffset = *StartTokenByteOffset;
1023 ByteNo -= StringOffset;
1024 }
Chris Lattnere925d612010-11-17 07:37:15 +00001025 while (1) {
1026 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1027 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1028
1029 // Get the spelling of the string so that we can get the data that makes up
1030 // the string literal, not the identifier for the macro it is potentially
1031 // expanded through.
1032 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001033
Chris Lattnere925d612010-11-17 07:37:15 +00001034 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001035 std::pair<FileID, unsigned> LocInfo =
1036 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001037 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001038 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001039 if (Invalid) {
1040 if (StartTokenByteOffset != nullptr)
1041 *StartTokenByteOffset = StringOffset;
1042 if (StartToken != nullptr)
1043 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001044 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001045 }
1046
Chris Lattnere925d612010-11-17 07:37:15 +00001047 const char *StrData = Buffer.data()+LocInfo.second;
1048
Chris Lattnere925d612010-11-17 07:37:15 +00001049 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001050 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1051 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001052 Token TheTok;
1053 TheLexer.LexFromRawLexer(TheTok);
1054
1055 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001056 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001057 unsigned TokNumBytes = SLP.GetStringLength();
1058
1059 // If the byte is in this token, return the location of the byte.
1060 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001061 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001062 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1063
Chris Lattnere925d612010-11-17 07:37:15 +00001064 // Now that we know the offset of the token in the spelling, use the
1065 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001066 if (StartTokenByteOffset != nullptr)
1067 *StartTokenByteOffset = StringOffset;
1068 if (StartToken != nullptr)
1069 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001070 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1071 }
Richard Smithefb116f2015-12-10 01:11:47 +00001072
Chris Lattnere925d612010-11-17 07:37:15 +00001073 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001074 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001075 ++TokNo;
1076 ByteNo -= TokNumBytes;
1077 }
1078}
1079
1080
1081
Chris Lattner1b926492006-08-23 06:42:10 +00001082/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1083/// corresponds to, e.g. "sizeof" or "[pre]++".
David Blaikie1d202a62012-10-08 01:11:04 +00001084StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001085 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001086#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1087#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001088 }
David Blaikief47fa302012-01-17 02:30:50 +00001089 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001090}
1091
John McCalle3027922010-08-25 11:45:40 +00001092UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001093UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1094 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001095 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001096 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1097 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1098 case OO_Amp: return UO_AddrOf;
1099 case OO_Star: return UO_Deref;
1100 case OO_Plus: return UO_Plus;
1101 case OO_Minus: return UO_Minus;
1102 case OO_Tilde: return UO_Not;
1103 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001104 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001105 }
1106}
1107
1108OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1109 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001110 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1111 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1112 case UO_AddrOf: return OO_Amp;
1113 case UO_Deref: return OO_Star;
1114 case UO_Plus: return OO_Plus;
1115 case UO_Minus: return OO_Minus;
1116 case UO_Not: return OO_Tilde;
1117 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001118 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001119 default: return OO_None;
1120 }
1121}
1122
1123
Chris Lattner0eedafe2006-08-24 04:56:27 +00001124//===----------------------------------------------------------------------===//
1125// Postfix Operators.
1126//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001127
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001128CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1129 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
Craig Topper37932912013-08-18 10:09:15 +00001130 ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001131 : Expr(SC, t, VK, OK_Ordinary, fn->isTypeDependent(),
1132 fn->isValueDependent(), fn->isInstantiationDependent(),
1133 fn->containsUnexpandedParameterPack()),
1134 NumArgs(args.size()) {
Mike Stump11289f42009-09-09 15:08:12 +00001135
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001136 unsigned NumPreArgs = preargs.size();
1137 SubExprs = new (C) Stmt *[args.size()+PREARGS_START+NumPreArgs];
Douglas Gregor993603d2008-11-14 16:09:21 +00001138 SubExprs[FN] = fn;
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001139 for (unsigned i = 0; i != NumPreArgs; ++i) {
1140 updateDependenciesFromArg(preargs[i]);
1141 SubExprs[i+PREARGS_START] = preargs[i];
1142 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00001143 for (unsigned i = 0; i != args.size(); ++i) {
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001144 updateDependenciesFromArg(args[i]);
Peter Collingbourne3a347252011-02-08 21:18:02 +00001145 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00001146 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001147
Peter Collingbourne3a347252011-02-08 21:18:02 +00001148 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor993603d2008-11-14 16:09:21 +00001149 RParenLoc = rparenloc;
1150}
Nate Begeman1e36a852008-01-17 17:46:27 +00001151
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001152CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1153 ArrayRef<Expr *> args, QualType t, ExprValueKind VK,
1154 SourceLocation rparenloc)
1155 : CallExpr(C, SC, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {}
1156
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001157CallExpr::CallExpr(const ASTContext &C, Expr *fn, ArrayRef<Expr *> args,
John McCall7decc9e2010-11-18 06:31:45 +00001158 QualType t, ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001159 : CallExpr(C, CallExprClass, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {
Chris Lattnere165d942006-08-24 04:40:38 +00001160}
1161
Craig Topper37932912013-08-18 10:09:15 +00001162CallExpr::CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001163 : CallExpr(C, SC, /*NumPreArgs=*/0, Empty) {}
Peter Collingbourne3a347252011-02-08 21:18:02 +00001164
Craig Topper37932912013-08-18 10:09:15 +00001165CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
Peter Collingbourne3a347252011-02-08 21:18:02 +00001166 EmptyShell Empty)
Craig Topper36250ad2014-05-12 05:36:57 +00001167 : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001168 // FIXME: Why do we allocate this?
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001169 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs]();
Peter Collingbourne3a347252011-02-08 21:18:02 +00001170 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregore20a2e52009-04-15 17:43:59 +00001171}
1172
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001173void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1174 if (Arg->isTypeDependent())
1175 ExprBits.TypeDependent = true;
1176 if (Arg->isValueDependent())
1177 ExprBits.ValueDependent = true;
1178 if (Arg->isInstantiationDependent())
1179 ExprBits.InstantiationDependent = true;
1180 if (Arg->containsUnexpandedParameterPack())
1181 ExprBits.ContainsUnexpandedParameterPack = true;
1182}
1183
Nuno Lopes518e3702009-12-20 23:11:08 +00001184Decl *CallExpr::getCalleeDecl() {
John McCalle3ca8eb2011-09-13 23:08:34 +00001185 Expr *CEE = getCallee()->IgnoreParenImpCasts();
Douglas Gregore0e96302011-09-06 21:41:04 +00001186
1187 while (SubstNonTypeTemplateParmExpr *NTTP
1188 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1189 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1190 }
1191
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001192 // If we're calling a dereference, look at the pointer instead.
1193 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1194 if (BO->isPtrMemOp())
1195 CEE = BO->getRHS()->IgnoreParenCasts();
1196 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1197 if (UO->getOpcode() == UO_Deref)
1198 CEE = UO->getSubExpr()->IgnoreParenCasts();
1199 }
Chris Lattner52301912009-07-17 15:46:27 +00001200 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001201 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001202 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1203 return ME->getMemberDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001204
Craig Topper36250ad2014-05-12 05:36:57 +00001205 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001206}
1207
Nuno Lopes518e3702009-12-20 23:11:08 +00001208FunctionDecl *CallExpr::getDirectCallee() {
Chris Lattner3a6af3d2009-12-21 01:10:56 +00001209 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
Nuno Lopes518e3702009-12-20 23:11:08 +00001210}
1211
Chris Lattnere4407ed2007-12-28 05:25:02 +00001212/// setNumArgs - This changes the number of arguments present in this call.
1213/// Any orphaned expressions are deleted by this, and any new operands are set
1214/// to null.
Craig Topper37932912013-08-18 10:09:15 +00001215void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001216 // No change, just return.
1217 if (NumArgs == getNumArgs()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001218
Chris Lattnere4407ed2007-12-28 05:25:02 +00001219 // If shrinking # arguments, just delete the extras and forgot them.
1220 if (NumArgs < getNumArgs()) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001221 this->NumArgs = NumArgs;
1222 return;
1223 }
1224
1225 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001226 unsigned NumPreArgs = getNumPreArgs();
1227 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnere4407ed2007-12-28 05:25:02 +00001228 // Copy over args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001229 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnere4407ed2007-12-28 05:25:02 +00001230 NewSubExprs[i] = SubExprs[i];
1231 // Null out new args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001232 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1233 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001234 NewSubExprs[i] = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001235
Douglas Gregorba6e5572009-04-17 21:46:47 +00001236 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnere4407ed2007-12-28 05:25:02 +00001237 SubExprs = NewSubExprs;
1238 this->NumArgs = NumArgs;
1239}
1240
Alp Tokera724cff2013-12-28 21:59:02 +00001241/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001242/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001243unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001244 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001245 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001246 // ImplicitCastExpr.
1247 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1248 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001249 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001250
Steve Narofff6e3b3292008-01-31 01:07:12 +00001251 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1252 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001253 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001254
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001255 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1256 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001257 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001258
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001259 if (!FDecl->getIdentifier())
1260 return 0;
1261
Douglas Gregor15fc9562009-09-12 00:22:50 +00001262 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001263}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001264
Scott Douglass503fc392015-06-10 13:53:15 +00001265bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001266 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001267 return Ctx.BuiltinInfo.isUnevaluated(BI);
1268 return false;
1269}
1270
David Majnemerced8bdf2015-02-25 17:36:15 +00001271QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1272 const Expr *Callee = getCallee();
1273 QualType CalleeType = Callee->getType();
1274 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001275 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001276 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001277 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001278 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1279 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1280 return Ctx.VoidTy;
1281
John McCall0009fcc2011-04-26 20:42:42 +00001282 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001283 CalleeType = Expr::findBoundMemberType(Callee);
1284 }
1285
John McCall0009fcc2011-04-26 20:42:42 +00001286 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001287 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001288}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001289
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001290SourceLocation CallExpr::getLocStart() const {
1291 if (isa<CXXOperatorCallExpr>(this))
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001292 return cast<CXXOperatorCallExpr>(this)->getLocStart();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001293
1294 SourceLocation begin = getCallee()->getLocStart();
Keno Fischer070db172014-08-15 01:39:12 +00001295 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001296 begin = getArg(0)->getLocStart();
1297 return begin;
1298}
1299SourceLocation CallExpr::getLocEnd() const {
1300 if (isa<CXXOperatorCallExpr>(this))
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001301 return cast<CXXOperatorCallExpr>(this)->getLocEnd();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001302
1303 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001304 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001305 end = getArg(getNumArgs() - 1)->getLocEnd();
1306 return end;
1307}
John McCall701417a2011-02-21 06:23:05 +00001308
Craig Topper37932912013-08-18 10:09:15 +00001309OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001310 SourceLocation OperatorLoc,
Alexis Hunta8136cc2010-05-05 15:23:54 +00001311 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001312 ArrayRef<OffsetOfNode> comps,
1313 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001314 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001315 void *Mem = C.Allocate(
1316 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001317
Benjamin Kramerc215e762012-08-24 11:54:20 +00001318 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1319 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001320}
1321
Craig Topper37932912013-08-18 10:09:15 +00001322OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001323 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001324 void *Mem =
1325 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001326 return new (Mem) OffsetOfExpr(numComps, numExprs);
1327}
1328
Craig Topper37932912013-08-18 10:09:15 +00001329OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001330 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001331 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001332 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001333 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1334 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001335 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001336 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001337 tsi->getType()->containsUnexpandedParameterPack()),
Alexis Hunta8136cc2010-05-05 15:23:54 +00001338 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001339 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001340{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001341 for (unsigned i = 0; i != comps.size(); ++i) {
1342 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001343 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001344
Benjamin Kramerc215e762012-08-24 11:54:20 +00001345 for (unsigned i = 0; i != exprs.size(); ++i) {
1346 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001347 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001348 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001349 ExprBits.ContainsUnexpandedParameterPack = true;
1350
Benjamin Kramerc215e762012-08-24 11:54:20 +00001351 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001352 }
1353}
1354
James Y Knight7281c352015-12-29 22:31:18 +00001355IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001356 assert(getKind() == Field || getKind() == Identifier);
1357 if (getKind() == Field)
1358 return getField()->getIdentifier();
Alexis Hunta8136cc2010-05-05 15:23:54 +00001359
Douglas Gregor882211c2010-04-28 22:16:22 +00001360 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1361}
1362
David Majnemer10fd83d2015-01-15 10:04:14 +00001363UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1364 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1365 SourceLocation op, SourceLocation rp)
1366 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1367 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1368 // Value-dependent if the argument is type-dependent.
1369 E->isTypeDependent(), E->isInstantiationDependent(),
1370 E->containsUnexpandedParameterPack()),
1371 OpLoc(op), RParenLoc(rp) {
1372 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1373 UnaryExprOrTypeTraitExprBits.IsType = false;
1374 Argument.Ex = E;
1375
1376 // Check to see if we are in the situation where alignof(decl) should be
1377 // dependent because decl's alignment is dependent.
1378 if (ExprKind == UETT_AlignOf) {
1379 if (!isValueDependent() || !isInstantiationDependent()) {
1380 E = E->IgnoreParens();
1381
1382 const ValueDecl *D = nullptr;
1383 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1384 D = DRE->getDecl();
1385 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1386 D = ME->getMemberDecl();
1387
1388 if (D) {
1389 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1390 if (I->isAlignmentDependent()) {
1391 setValueDependent(true);
1392 setInstantiationDependent(true);
1393 break;
1394 }
1395 }
1396 }
1397 }
1398 }
1399}
1400
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001401MemberExpr *MemberExpr::Create(
1402 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1403 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1404 ValueDecl *memberdecl, DeclAccessPair founddecl,
1405 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1406 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
John McCall16df1e52010-03-30 21:47:33 +00001407
Douglas Gregorea972d32011-02-28 21:54:11 +00001408 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001409 founddecl.getDecl() != memberdecl ||
1410 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001411
James Y Knighte7d82282015-12-29 18:15:14 +00001412 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1413 std::size_t Size =
1414 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1415 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1416 HasTemplateKWAndArgsInfo ? 1 : 0,
1417 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001418
Chris Lattner5c0b4052010-10-30 05:14:06 +00001419 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001420 MemberExpr *E = new (Mem)
1421 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001422
1423 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001424 // FIXME: Wrong. We should be looking at the member declaration we found.
1425 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001426 E->setValueDependent(true);
1427 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001428 E->setInstantiationDependent(true);
1429 }
1430 else if (QualifierLoc &&
1431 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1432 E->setInstantiationDependent(true);
1433
John McCall16df1e52010-03-30 21:47:33 +00001434 E->HasQualifierOrFoundDecl = true;
1435
James Y Knighte7d82282015-12-29 18:15:14 +00001436 MemberExprNameQualifier *NQ =
1437 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001438 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001439 NQ->FoundDecl = founddecl;
1440 }
1441
Abramo Bagnara7945c982012-01-27 09:46:47 +00001442 E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1443
John McCall16df1e52010-03-30 21:47:33 +00001444 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001445 bool Dependent = false;
1446 bool InstantiationDependent = false;
1447 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001448 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1449 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1450 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001451 if (InstantiationDependent)
1452 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001453 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001454 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1455 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001456 }
1457
1458 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001459}
1460
Daniel Dunbarb507f272012-03-09 15:39:15 +00001461SourceLocation MemberExpr::getLocStart() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001462 if (isImplicitAccess()) {
1463 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001464 return getQualifierLoc().getBeginLoc();
1465 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001466 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001467
Daniel Dunbarb507f272012-03-09 15:39:15 +00001468 // FIXME: We don't want this to happen. Rather, we should be able to
1469 // detect all kinds of implicit accesses more cleanly.
1470 SourceLocation BaseStartLoc = getBase()->getLocStart();
1471 if (BaseStartLoc.isValid())
1472 return BaseStartLoc;
1473 return MemberLoc;
1474}
1475SourceLocation MemberExpr::getLocEnd() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001476 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001477 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001478 EndLoc = getRAngleLoc();
1479 else if (EndLoc.isInvalid())
1480 EndLoc = getBase()->getLocEnd();
1481 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001482}
1483
Alp Tokerc1086762013-12-07 13:51:35 +00001484bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001485 switch (getCastKind()) {
1486 case CK_DerivedToBase:
1487 case CK_UncheckedDerivedToBase:
1488 case CK_DerivedToBaseMemberPointer:
1489 case CK_BaseToDerived:
1490 case CK_BaseToDerivedMemberPointer:
1491 assert(!path_empty() && "Cast kind should have a base path!");
1492 break;
1493
1494 case CK_CPointerToObjCPointerCast:
1495 assert(getType()->isObjCObjectPointerType());
1496 assert(getSubExpr()->getType()->isPointerType());
1497 goto CheckNoBasePath;
1498
1499 case CK_BlockPointerToObjCPointerCast:
1500 assert(getType()->isObjCObjectPointerType());
1501 assert(getSubExpr()->getType()->isBlockPointerType());
1502 goto CheckNoBasePath;
1503
John McCallc62bb392012-02-15 01:22:51 +00001504 case CK_ReinterpretMemberPointer:
1505 assert(getType()->isMemberPointerType());
1506 assert(getSubExpr()->getType()->isMemberPointerType());
1507 goto CheckNoBasePath;
1508
John McCall9320b872011-09-09 05:25:32 +00001509 case CK_BitCast:
1510 // Arbitrary casts to C pointer types count as bitcasts.
1511 // Otherwise, we should only have block and ObjC pointer casts
1512 // here if they stay within the type kind.
1513 if (!getType()->isPointerType()) {
1514 assert(getType()->isObjCObjectPointerType() ==
1515 getSubExpr()->getType()->isObjCObjectPointerType());
1516 assert(getType()->isBlockPointerType() ==
1517 getSubExpr()->getType()->isBlockPointerType());
1518 }
1519 goto CheckNoBasePath;
1520
1521 case CK_AnyPointerToBlockPointerCast:
1522 assert(getType()->isBlockPointerType());
1523 assert(getSubExpr()->getType()->isAnyPointerType() &&
1524 !getSubExpr()->getType()->isBlockPointerType());
1525 goto CheckNoBasePath;
1526
Douglas Gregored90df32012-02-22 05:02:47 +00001527 case CK_CopyAndAutoreleaseBlockObject:
1528 assert(getType()->isBlockPointerType());
1529 assert(getSubExpr()->getType()->isBlockPointerType());
1530 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001531
1532 case CK_FunctionToPointerDecay:
1533 assert(getType()->isPointerType());
1534 assert(getSubExpr()->getType()->isFunctionType());
1535 goto CheckNoBasePath;
1536
David Tweede1468322013-12-11 13:39:46 +00001537 case CK_AddressSpaceConversion:
1538 assert(getType()->isPointerType());
1539 assert(getSubExpr()->getType()->isPointerType());
1540 assert(getType()->getPointeeType().getAddressSpace() !=
1541 getSubExpr()->getType()->getPointeeType().getAddressSpace());
John McCall9320b872011-09-09 05:25:32 +00001542 // These should not have an inheritance path.
1543 case CK_Dynamic:
1544 case CK_ToUnion:
1545 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001546 case CK_NullToMemberPointer:
1547 case CK_NullToPointer:
1548 case CK_ConstructorConversion:
1549 case CK_IntegralToPointer:
1550 case CK_PointerToIntegral:
1551 case CK_ToVoid:
1552 case CK_VectorSplat:
1553 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001554 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001555 case CK_IntegralToFloating:
1556 case CK_FloatingToIntegral:
1557 case CK_FloatingCast:
1558 case CK_ObjCObjectLValueCast:
1559 case CK_FloatingRealToComplex:
1560 case CK_FloatingComplexToReal:
1561 case CK_FloatingComplexCast:
1562 case CK_FloatingComplexToIntegralComplex:
1563 case CK_IntegralRealToComplex:
1564 case CK_IntegralComplexToReal:
1565 case CK_IntegralComplexCast:
1566 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001567 case CK_ARCProduceObject:
1568 case CK_ARCConsumeObject:
1569 case CK_ARCReclaimReturnedObject:
1570 case CK_ARCExtendBlockObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001571 case CK_ZeroToOCLEvent:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001572 case CK_IntToOCLSampler:
John McCall9320b872011-09-09 05:25:32 +00001573 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1574 goto CheckNoBasePath;
1575
1576 case CK_Dependent:
1577 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001578 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001579 case CK_AtomicToNonAtomic:
1580 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001581 case CK_PointerToBoolean:
1582 case CK_IntegralToBoolean:
1583 case CK_FloatingToBoolean:
1584 case CK_MemberPointerToBoolean:
1585 case CK_FloatingComplexToBoolean:
1586 case CK_IntegralComplexToBoolean:
1587 case CK_LValueBitCast: // -> bool&
1588 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001589 case CK_BuiltinFnToFnPtr:
John McCall9320b872011-09-09 05:25:32 +00001590 CheckNoBasePath:
1591 assert(path_empty() && "Cast kind should not have a base path!");
1592 break;
1593 }
Alp Tokerc1086762013-12-07 13:51:35 +00001594 return true;
John McCall9320b872011-09-09 05:25:32 +00001595}
1596
Anders Carlsson496335e2009-09-03 00:59:21 +00001597const char *CastExpr::getCastKindName() const {
1598 switch (getCastKind()) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001599#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1600#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001601 }
John McCallc5e62b42010-11-13 09:02:35 +00001602 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001603}
1604
Douglas Gregord196a582009-12-14 19:27:10 +00001605Expr *CastExpr::getSubExprAsWritten() {
Craig Topper36250ad2014-05-12 05:36:57 +00001606 Expr *SubExpr = nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001607 CastExpr *E = this;
1608 do {
1609 SubExpr = E->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00001610
1611 // Skip through reference binding to temporary.
1612 if (MaterializeTemporaryExpr *Materialize
1613 = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1614 SubExpr = Materialize->GetTemporaryExpr();
1615
Douglas Gregord196a582009-12-14 19:27:10 +00001616 // Skip any temporary bindings; they're implicit.
1617 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1618 SubExpr = Binder->getSubExpr();
Alexis Hunta8136cc2010-05-05 15:23:54 +00001619
Douglas Gregord196a582009-12-14 19:27:10 +00001620 // Conversions by constructor and conversion functions have a
1621 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001622 if (E->getCastKind() == CK_ConstructorConversion)
Douglas Gregord196a582009-12-14 19:27:10 +00001623 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
Manman Ren8abc2e52016-02-02 22:23:03 +00001624 else if (E->getCastKind() == CK_UserDefinedConversion) {
1625 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1626 isa<BlockExpr>(SubExpr)) &&
1627 "Unexpected SubExpr for CK_UserDefinedConversion.");
1628 if (isa<CXXMemberCallExpr>(SubExpr))
1629 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1630 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001631
Douglas Gregord196a582009-12-14 19:27:10 +00001632 // If the subexpression we're left with is an implicit cast, look
1633 // through that, too.
Alexis Hunta8136cc2010-05-05 15:23:54 +00001634 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1635
Douglas Gregord196a582009-12-14 19:27:10 +00001636 return SubExpr;
1637}
1638
John McCallcf142162010-08-07 06:22:56 +00001639CXXBaseSpecifier **CastExpr::path_buffer() {
1640 switch (getStmtClass()) {
1641#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001642#define CASTEXPR(Type, Base) \
1643 case Stmt::Type##Class: \
1644 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001645#define STMT(Type, Base)
1646#include "clang/AST/StmtNodes.inc"
1647 default:
1648 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001649 }
1650}
1651
Craig Topper37932912013-08-18 10:09:15 +00001652ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001653 CastKind Kind, Expr *Operand,
1654 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001655 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001656 unsigned PathSize = (BasePath ? BasePath->size() : 0);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001657 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001658 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001659 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001660 if (PathSize)
1661 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1662 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001663 return E;
1664}
1665
Craig Topper37932912013-08-18 10:09:15 +00001666ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001667 unsigned PathSize) {
James Y Knight1d75c5e2015-12-30 02:27:28 +00001668 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001669 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1670}
1671
1672
Craig Topper37932912013-08-18 10:09:15 +00001673CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001674 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001675 const CXXCastPath *BasePath,
1676 TypeSourceInfo *WrittenTy,
1677 SourceLocation L, SourceLocation R) {
1678 unsigned PathSize = (BasePath ? BasePath->size() : 0);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001679 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001680 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001681 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001682 if (PathSize)
1683 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1684 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001685 return E;
1686}
1687
Craig Topper37932912013-08-18 10:09:15 +00001688CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1689 unsigned PathSize) {
James Y Knight1d75c5e2015-12-30 02:27:28 +00001690 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001691 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1692}
1693
Chris Lattner1b926492006-08-23 06:42:10 +00001694/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1695/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001696StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001697 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001698#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1699#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001700 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001701 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001702}
Steve Naroff47500512007-04-19 23:00:49 +00001703
John McCalle3027922010-08-25 11:45:40 +00001704BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001705BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1706 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001707 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001708 case OO_Plus: return BO_Add;
1709 case OO_Minus: return BO_Sub;
1710 case OO_Star: return BO_Mul;
1711 case OO_Slash: return BO_Div;
1712 case OO_Percent: return BO_Rem;
1713 case OO_Caret: return BO_Xor;
1714 case OO_Amp: return BO_And;
1715 case OO_Pipe: return BO_Or;
1716 case OO_Equal: return BO_Assign;
1717 case OO_Less: return BO_LT;
1718 case OO_Greater: return BO_GT;
1719 case OO_PlusEqual: return BO_AddAssign;
1720 case OO_MinusEqual: return BO_SubAssign;
1721 case OO_StarEqual: return BO_MulAssign;
1722 case OO_SlashEqual: return BO_DivAssign;
1723 case OO_PercentEqual: return BO_RemAssign;
1724 case OO_CaretEqual: return BO_XorAssign;
1725 case OO_AmpEqual: return BO_AndAssign;
1726 case OO_PipeEqual: return BO_OrAssign;
1727 case OO_LessLess: return BO_Shl;
1728 case OO_GreaterGreater: return BO_Shr;
1729 case OO_LessLessEqual: return BO_ShlAssign;
1730 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1731 case OO_EqualEqual: return BO_EQ;
1732 case OO_ExclaimEqual: return BO_NE;
1733 case OO_LessEqual: return BO_LE;
1734 case OO_GreaterEqual: return BO_GE;
1735 case OO_AmpAmp: return BO_LAnd;
1736 case OO_PipePipe: return BO_LOr;
1737 case OO_Comma: return BO_Comma;
1738 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001739 }
1740}
1741
1742OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1743 static const OverloadedOperatorKind OverOps[] = {
1744 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1745 OO_Star, OO_Slash, OO_Percent,
1746 OO_Plus, OO_Minus,
1747 OO_LessLess, OO_GreaterGreater,
1748 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1749 OO_EqualEqual, OO_ExclaimEqual,
1750 OO_Amp,
1751 OO_Caret,
1752 OO_Pipe,
1753 OO_AmpAmp,
1754 OO_PipePipe,
1755 OO_Equal, OO_StarEqual,
1756 OO_SlashEqual, OO_PercentEqual,
1757 OO_PlusEqual, OO_MinusEqual,
1758 OO_LessLessEqual, OO_GreaterGreaterEqual,
1759 OO_AmpEqual, OO_CaretEqual,
1760 OO_PipeEqual,
1761 OO_Comma
1762 };
1763 return OverOps[Opc];
1764}
1765
Craig Topper37932912013-08-18 10:09:15 +00001766InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001767 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Douglas Gregora6e053e2010-12-15 01:34:56 +00001768 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
Douglas Gregor678d76c2011-07-01 01:22:09 +00001769 false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001770 InitExprs(C, initExprs.size()),
Craig Topper36250ad2014-05-12 05:36:57 +00001771 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
Sebastian Redlc83ed822012-02-17 08:42:25 +00001772{
1773 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00001774 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001775 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00001776 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00001777 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00001778 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00001779 if (initExprs[I]->isInstantiationDependent())
1780 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00001781 if (initExprs[I]->containsUnexpandedParameterPack())
1782 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00001783 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001784
Benjamin Kramerc215e762012-08-24 11:54:20 +00001785 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00001786}
Chris Lattner1ec5f562007-06-27 05:38:08 +00001787
Craig Topper37932912013-08-18 10:09:15 +00001788void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001789 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00001790 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001791}
1792
Craig Topper37932912013-08-18 10:09:15 +00001793void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00001794 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001795}
1796
Craig Topper37932912013-08-18 10:09:15 +00001797Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001798 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001799 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00001800 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00001801 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001802 }
Mike Stump11289f42009-09-09 15:08:12 +00001803
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001804 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00001805 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001806 return Result;
1807}
1808
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001809void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00001810 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001811 ArrayFillerOrUnionFieldInit = filler;
1812 // Fill out any "holes" in the array due to designated initializers.
1813 Expr **inits = getInits();
1814 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001815 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001816 inits[i] = filler;
1817}
1818
Richard Smith9ec1e482012-04-15 02:50:59 +00001819bool InitListExpr::isStringLiteralInit() const {
1820 if (getNumInits() != 1)
1821 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00001822 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
1823 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00001824 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00001825 // It is possible for getInit() to return null.
1826 const Expr *Init = getInit(0);
1827 if (!Init)
1828 return false;
1829 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00001830 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
1831}
1832
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001833SourceLocation InitListExpr::getLocStart() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00001834 if (InitListExpr *SyntacticForm = getSyntacticForm())
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001835 return SyntacticForm->getLocStart();
1836 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001837 if (Beg.isInvalid()) {
1838 // Find the first non-null initializer.
1839 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1840 E = InitExprs.end();
1841 I != E; ++I) {
1842 if (Stmt *S = *I) {
1843 Beg = S->getLocStart();
1844 break;
1845 }
1846 }
1847 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001848 return Beg;
1849}
1850
1851SourceLocation InitListExpr::getLocEnd() const {
1852 if (InitListExpr *SyntacticForm = getSyntacticForm())
1853 return SyntacticForm->getLocEnd();
1854 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001855 if (End.isInvalid()) {
1856 // Find the first non-null initializer from the end.
1857 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001858 E = InitExprs.rend();
1859 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001860 if (Stmt *S = *I) {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001861 End = S->getLocEnd();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001862 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001863 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001864 }
1865 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001866 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001867}
1868
Steve Naroff991e99d2008-09-04 15:31:07 +00001869/// getFunctionType - Return the underlying function type for this block.
Steve Naroffc540d662008-09-03 18:15:37 +00001870///
John McCallc833dea2012-02-17 03:32:35 +00001871const FunctionProtoType *BlockExpr::getFunctionType() const {
1872 // The block pointer is never sugared, but the function type might be.
1873 return cast<BlockPointerType>(getType())
1874 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00001875}
1876
Mike Stump11289f42009-09-09 15:08:12 +00001877SourceLocation BlockExpr::getCaretLocation() const {
1878 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00001879}
Mike Stump11289f42009-09-09 15:08:12 +00001880const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00001881 return TheBlock->getBody();
1882}
Mike Stump11289f42009-09-09 15:08:12 +00001883Stmt *BlockExpr::getBody() {
1884 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00001885}
Steve Naroff415d3d52008-10-08 17:01:13 +00001886
1887
Chris Lattner1ec5f562007-06-27 05:38:08 +00001888//===----------------------------------------------------------------------===//
1889// Generic Expression Routines
1890//===----------------------------------------------------------------------===//
1891
Chris Lattner237f2752009-02-14 07:37:35 +00001892/// isUnusedResultAWarning - Return true if this immediate expression should
1893/// be warned about if the result is unused. If so, fill in Loc and Ranges
1894/// with location to warn on and the source range[s] to report with the
1895/// warning.
Eli Friedmanc11535c2012-05-24 00:47:05 +00001896bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
1897 SourceRange &R1, SourceRange &R2,
1898 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00001899 // Don't warn if the expr is type dependent. The type could end up
1900 // instantiating to void.
1901 if (isTypeDependent())
1902 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001903
Chris Lattner1ec5f562007-06-27 05:38:08 +00001904 switch (getStmtClass()) {
1905 default:
John McCallc493a732010-03-12 07:11:26 +00001906 if (getType()->isVoidType())
1907 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00001908 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00001909 Loc = getExprLoc();
1910 R1 = getSourceRange();
1911 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00001912 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00001913 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00001914 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00001915 case GenericSelectionExprClass:
1916 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00001917 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00001918 case ChooseExprClass:
1919 return cast<ChooseExpr>(this)->getChosenSubExpr()->
1920 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00001921 case UnaryOperatorClass: {
1922 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00001923
Chris Lattner1ec5f562007-06-27 05:38:08 +00001924 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00001925 case UO_Plus:
1926 case UO_Minus:
1927 case UO_AddrOf:
1928 case UO_Not:
1929 case UO_LNot:
1930 case UO_Deref:
1931 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00001932 case UO_Coawait:
1933 // This is just the 'operator co_await' call inside the guts of a
1934 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00001935 case UO_PostInc:
1936 case UO_PostDec:
1937 case UO_PreInc:
1938 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00001939 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00001940 case UO_Real:
1941 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00001942 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00001943 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1944 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00001945 return false;
1946 break;
John McCalle3027922010-08-25 11:45:40 +00001947 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00001948 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00001949 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00001950 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00001951 Loc = UO->getOperatorLoc();
1952 R1 = UO->getSubExpr()->getSourceRange();
1953 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00001954 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00001955 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00001956 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00001957 switch (BO->getOpcode()) {
1958 default:
1959 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00001960 // Consider the RHS of comma for side effects. LHS was checked by
1961 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00001962 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00001963 // ((foo = <blah>), 0) is an idiom for hiding the result (and
1964 // lvalue-ness) of an assignment written in a macro.
1965 if (IntegerLiteral *IE =
1966 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1967 if (IE->getValue() == 0)
1968 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00001969 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00001970 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00001971 case BO_LAnd:
1972 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00001973 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
1974 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00001975 return false;
1976 break;
John McCall1e3715a2010-02-16 04:10:53 +00001977 }
Chris Lattner237f2752009-02-14 07:37:35 +00001978 if (BO->isAssignmentOp())
1979 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00001980 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00001981 Loc = BO->getOperatorLoc();
1982 R1 = BO->getLHS()->getSourceRange();
1983 R2 = BO->getRHS()->getSourceRange();
1984 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00001985 }
Chris Lattner86928112007-08-25 02:00:02 +00001986 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00001987 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001988 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00001989 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00001990
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00001991 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00001992 // If only one of the LHS or RHS is a warning, the operator might
1993 // be being used for control flow. Only warn if both the LHS and
1994 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00001995 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00001996 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00001997 return false;
1998 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00001999 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002000 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002001 }
2002
Chris Lattnera44d1162007-06-27 05:58:59 +00002003 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002004 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002005 Loc = cast<MemberExpr>(this)->getMemberLoc();
2006 R1 = SourceRange(Loc, Loc);
2007 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2008 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002009
Chris Lattner1ec5f562007-06-27 05:38:08 +00002010 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002011 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002012 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2013 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2014 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2015 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002016
Chandler Carruth46339472011-08-17 09:49:44 +00002017 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002018 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002019 // overloads as there is no reasonable way to define these such that they
2020 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002021 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002022 // provides additional value as well. If this list is updated,
2023 // DiagnoseUnusedComparison should be as well.
2024 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002025 switch (Op->getOperator()) {
2026 default:
2027 break;
2028 case OO_EqualEqual:
2029 case OO_ExclaimEqual:
2030 case OO_Less:
2031 case OO_Greater:
2032 case OO_GreaterEqual:
2033 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002034 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2035 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002036 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002037 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002038 Loc = Op->getOperatorLoc();
2039 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002040 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002041 }
Chandler Carruth46339472011-08-17 09:49:44 +00002042
2043 // Fallthrough for generic call handling.
2044 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002045 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002046 case CXXMemberCallExprClass:
2047 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002048 // If this is a direct call, get the callee.
2049 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002050 if (const Decl *FD = CE->getCalleeDecl()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002051 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2052 bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2053 : FD->hasAttr<WarnUnusedResultAttr>();
2054
Chris Lattner237f2752009-02-14 07:37:35 +00002055 // If the callee has attribute pure, const, or warn_unused_result, warn
2056 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002057 //
2058 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2059 // updated to match for QoI.
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002060 if (HasWarnUnusedResultAttr ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002061 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002062 WarnE = this;
Chris Lattner1a6babf2009-10-13 04:53:48 +00002063 Loc = CE->getCallee()->getLocStart();
2064 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002065
Chris Lattner1a6babf2009-10-13 04:53:48 +00002066 if (unsigned NumArgs = CE->getNumArgs())
2067 R2 = SourceRange(CE->getArg(0)->getLocStart(),
2068 CE->getArg(NumArgs-1)->getLocEnd());
2069 return true;
2070 }
Chris Lattner237f2752009-02-14 07:37:35 +00002071 }
2072 return false;
2073 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002074
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002075 // If we don't know precisely what we're looking at, let's not warn.
2076 case UnresolvedLookupExprClass:
2077 case CXXUnresolvedConstructExprClass:
2078 return false;
2079
Anders Carlsson6aa50392009-11-17 17:11:23 +00002080 case CXXTemporaryObjectExprClass:
Lubos Lunak1f490f32013-07-21 13:15:58 +00002081 case CXXConstructExprClass: {
2082 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2083 if (Type->hasAttr<WarnUnusedAttr>()) {
2084 WarnE = this;
2085 Loc = getLocStart();
2086 R1 = getSourceRange();
2087 return true;
2088 }
2089 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002090 return false;
Lubos Lunak1f490f32013-07-21 13:15:58 +00002091 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002092
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002093 case ObjCMessageExprClass: {
2094 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002095 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002096 ME->isInstanceMessage() &&
2097 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002098 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002099 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002100 Loc = getExprLoc();
2101 R1 = ME->getSourceRange();
2102 return true;
2103 }
2104
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002105 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002106 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002107 WarnE = this;
2108 Loc = getExprLoc();
2109 return true;
2110 }
2111
Chris Lattner237f2752009-02-14 07:37:35 +00002112 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002113 }
Mike Stump11289f42009-09-09 15:08:12 +00002114
John McCallb7bd14f2010-12-02 01:19:52 +00002115 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002116 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002117 Loc = getExprLoc();
2118 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002119 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002120
John McCallfe96e0b2011-11-06 09:01:30 +00002121 case PseudoObjectExprClass: {
2122 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2123
2124 // Only complain about things that have the form of a getter.
2125 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2126 isa<BinaryOperator>(PO->getSyntacticForm()))
2127 return false;
2128
Eli Friedmanc11535c2012-05-24 00:47:05 +00002129 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002130 Loc = getExprLoc();
2131 R1 = getSourceRange();
2132 return true;
2133 }
2134
Chris Lattner944d3062008-07-26 19:51:01 +00002135 case StmtExprClass: {
2136 // Statement exprs don't logically have side effects themselves, but are
2137 // sometimes used in macros in ways that give them a type that is unused.
2138 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2139 // however, if the result of the stmt expr is dead, we don't want to emit a
2140 // warning.
2141 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002142 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002143 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002144 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002145 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2146 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002147 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
John McCallc493a732010-03-12 07:11:26 +00002150 if (getType()->isVoidType())
2151 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002152 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002153 Loc = cast<StmtExpr>(this)->getLParenLoc();
2154 R1 = getSourceRange();
2155 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002156 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002157 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002158 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002159 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002160 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002161 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002162 if (CE->getCastKind() == CK_ToVoid) {
2163 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002164 CE->getSubExpr()->getType().isVolatileQualified()) {
2165 const DeclRefExpr *DRE =
2166 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2167 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2168 cast<VarDecl>(DRE->getDecl())->hasLocalStorage())) {
2169 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2170 R1, R2, Ctx);
2171 }
2172 }
Chris Lattner2706a552009-07-28 18:25:28 +00002173 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002174 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002175
Eli Friedmanc11535c2012-05-24 00:47:05 +00002176 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002177 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002178 if (CE->getCastKind() == CK_ConstructorConversion)
2179 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002180
Eli Friedmanc11535c2012-05-24 00:47:05 +00002181 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002182 if (const CXXFunctionalCastExpr *CXXCE =
2183 dyn_cast<CXXFunctionalCastExpr>(this)) {
Eli Friedman89fe0d52013-08-15 22:02:56 +00002184 Loc = CXXCE->getLocStart();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002185 R1 = CXXCE->getSubExpr()->getSourceRange();
2186 } else {
2187 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2188 Loc = CStyleCE->getLParenLoc();
2189 R1 = CStyleCE->getSubExpr()->getSourceRange();
2190 }
Chris Lattner237f2752009-02-14 07:37:35 +00002191 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002192 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002193 case ImplicitCastExprClass: {
2194 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002195
Eli Friedmanc11535c2012-05-24 00:47:05 +00002196 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2197 if (ICE->getCastKind() == CK_LValueToRValue &&
2198 ICE->getSubExpr()->getType().isVolatileQualified())
2199 return false;
2200
2201 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2202 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002203 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002204 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002205 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002206 case CXXDefaultInitExprClass:
2207 return (cast<CXXDefaultInitExpr>(this)
2208 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002209
2210 case CXXNewExprClass:
2211 // FIXME: In theory, there might be new expressions that don't have side
2212 // effects (e.g. a placement new with an uninitialized POD).
2213 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002214 return false;
Anders Carlssone80ccac2009-08-16 04:11:06 +00002215 case CXXBindTemporaryExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002216 return (cast<CXXBindTemporaryExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002217 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
John McCall5d413782010-12-06 08:20:24 +00002218 case ExprWithCleanupsClass:
2219 return (cast<ExprWithCleanups>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002220 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002221 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002222}
2223
Fariborz Jahanian07735332009-02-22 18:40:18 +00002224/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002225/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002226bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002227 const Expr *E = IgnoreParens();
2228 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002229 default:
2230 return false;
2231 case ObjCIvarRefExprClass:
2232 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002233 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002234 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002235 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002236 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002237 case MaterializeTemporaryExprClass:
2238 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2239 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002240 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002241 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002242 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002243 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fariborz Jahanianc367b8f2011-09-23 18:57:30 +00002244
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002245 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2246 if (VD->hasGlobalStorage())
2247 return true;
2248 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002249 // dereferencing to a pointer is always a gc'able candidate,
2250 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002251 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002252 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002253 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002254 return false;
2255 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002256 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002257 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002258 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002259 }
2260 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002261 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002262 }
2263}
Sebastian Redlce354af2010-09-10 20:55:33 +00002264
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002265bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2266 if (isTypeDependent())
2267 return false;
John McCall086a4642010-11-24 05:12:34 +00002268 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002269}
2270
John McCall0009fcc2011-04-26 20:42:42 +00002271QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002272 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002273
2274 // Bound member expressions are always one of these possibilities:
2275 // x->m x.m x->*y x.*y
2276 // (possibly parenthesized)
2277
2278 expr = expr->IgnoreParens();
2279 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2280 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2281 return mem->getMemberDecl()->getType();
2282 }
2283
2284 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2285 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2286 ->getPointeeType();
2287 assert(type->isFunctionType());
2288 return type;
2289 }
2290
David Majnemerced8bdf2015-02-25 17:36:15 +00002291 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002292 return QualType();
2293}
2294
Ted Kremenekfff70962008-01-17 16:57:34 +00002295Expr* Expr::IgnoreParens() {
2296 Expr* E = this;
Abramo Bagnara932e3932010-10-15 07:51:18 +00002297 while (true) {
2298 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2299 E = P->getSubExpr();
2300 continue;
2301 }
2302 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2303 if (P->getOpcode() == UO_Extension) {
2304 E = P->getSubExpr();
2305 continue;
2306 }
2307 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002308 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2309 if (!P->isResultDependent()) {
2310 E = P->getResultExpr();
2311 continue;
2312 }
2313 }
Eli Friedman75807f22013-07-20 00:40:58 +00002314 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2315 if (!P->isConditionDependent()) {
2316 E = P->getChosenSubExpr();
2317 continue;
2318 }
2319 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002320 return E;
2321 }
Ted Kremenekfff70962008-01-17 16:57:34 +00002322}
2323
Chris Lattnerf2660962008-02-13 01:02:39 +00002324/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2325/// or CastExprs or ImplicitCastExprs, returning their operand.
2326Expr *Expr::IgnoreParenCasts() {
2327 Expr *E = this;
2328 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002329 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002330 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002331 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002332 continue;
2333 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002334 if (MaterializeTemporaryExpr *Materialize
2335 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2336 E = Materialize->GetTemporaryExpr();
2337 continue;
2338 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002339 if (SubstNonTypeTemplateParmExpr *NTTP
2340 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2341 E = NTTP->getReplacement();
2342 continue;
2343 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002344 return E;
Chris Lattnerf2660962008-02-13 01:02:39 +00002345 }
2346}
2347
Ted Kremenek6f375e52014-04-16 07:26:09 +00002348Expr *Expr::IgnoreCasts() {
2349 Expr *E = this;
2350 while (true) {
2351 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2352 E = P->getSubExpr();
2353 continue;
2354 }
2355 if (MaterializeTemporaryExpr *Materialize
2356 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2357 E = Materialize->GetTemporaryExpr();
2358 continue;
2359 }
2360 if (SubstNonTypeTemplateParmExpr *NTTP
2361 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2362 E = NTTP->getReplacement();
2363 continue;
2364 }
2365 return E;
2366 }
2367}
2368
John McCall5a4ce8b2010-12-04 08:24:19 +00002369/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2370/// casts. This is intended purely as a temporary workaround for code
2371/// that hasn't yet been rewritten to do the right thing about those
2372/// casts, and may disappear along with the last internal use.
John McCall34376a62010-12-04 03:47:34 +00002373Expr *Expr::IgnoreParenLValueCasts() {
2374 Expr *E = this;
John McCall5a4ce8b2010-12-04 08:24:19 +00002375 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002376 E = E->IgnoreParens();
2377 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00002378 if (P->getCastKind() == CK_LValueToRValue) {
2379 E = P->getSubExpr();
2380 continue;
2381 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002382 } else if (MaterializeTemporaryExpr *Materialize
2383 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2384 E = Materialize->GetTemporaryExpr();
2385 continue;
Douglas Gregor6a40b082011-09-08 17:56:33 +00002386 } else if (SubstNonTypeTemplateParmExpr *NTTP
2387 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2388 E = NTTP->getReplacement();
2389 continue;
John McCall34376a62010-12-04 03:47:34 +00002390 }
2391 break;
2392 }
2393 return E;
2394}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002395
2396Expr *Expr::ignoreParenBaseCasts() {
2397 Expr *E = this;
2398 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002399 E = E->IgnoreParens();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002400 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2401 if (CE->getCastKind() == CK_DerivedToBase ||
2402 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2403 CE->getCastKind() == CK_NoOp) {
2404 E = CE->getSubExpr();
2405 continue;
2406 }
2407 }
2408
2409 return E;
2410 }
2411}
2412
John McCalleebc8322010-05-05 22:59:52 +00002413Expr *Expr::IgnoreParenImpCasts() {
2414 Expr *E = this;
2415 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002416 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002417 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCalleebc8322010-05-05 22:59:52 +00002418 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002419 continue;
2420 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002421 if (MaterializeTemporaryExpr *Materialize
2422 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2423 E = Materialize->GetTemporaryExpr();
2424 continue;
2425 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002426 if (SubstNonTypeTemplateParmExpr *NTTP
2427 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2428 E = NTTP->getReplacement();
2429 continue;
2430 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002431 return E;
John McCalleebc8322010-05-05 22:59:52 +00002432 }
2433}
2434
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002435Expr *Expr::IgnoreConversionOperator() {
2436 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002437 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002438 return MCE->getImplicitObjectArgument();
2439 }
2440 return this;
2441}
2442
Chris Lattneref26c772009-03-13 17:28:01 +00002443/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2444/// value (including ptr->int casts of the same size). Strip off any
2445/// ParenExpr or CastExprs, returning their operand.
2446Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2447 Expr *E = this;
2448 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002449 E = E->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00002450
Chris Lattneref26c772009-03-13 17:28:01 +00002451 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2452 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregorb90df602010-06-16 00:17:44 +00002453 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattneref26c772009-03-13 17:28:01 +00002454 Expr *SE = P->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002455
Chris Lattneref26c772009-03-13 17:28:01 +00002456 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2457 E = SE;
2458 continue;
2459 }
Mike Stump11289f42009-09-09 15:08:12 +00002460
Abramo Bagnara932e3932010-10-15 07:51:18 +00002461 if ((E->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002462 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnara932e3932010-10-15 07:51:18 +00002463 (SE->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002464 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattneref26c772009-03-13 17:28:01 +00002465 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2466 E = SE;
2467 continue;
2468 }
2469 }
Mike Stump11289f42009-09-09 15:08:12 +00002470
Douglas Gregor6a40b082011-09-08 17:56:33 +00002471 if (SubstNonTypeTemplateParmExpr *NTTP
2472 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2473 E = NTTP->getReplacement();
2474 continue;
2475 }
2476
Chris Lattneref26c772009-03-13 17:28:01 +00002477 return E;
2478 }
2479}
2480
Douglas Gregord196a582009-12-14 19:27:10 +00002481bool Expr::isDefaultArgument() const {
2482 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002483 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2484 E = M->GetTemporaryExpr();
2485
Douglas Gregord196a582009-12-14 19:27:10 +00002486 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2487 E = ICE->getSubExprAsWritten();
Alexis Hunta8136cc2010-05-05 15:23:54 +00002488
Douglas Gregord196a582009-12-14 19:27:10 +00002489 return isa<CXXDefaultArgExpr>(E);
2490}
Chris Lattneref26c772009-03-13 17:28:01 +00002491
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002492/// \brief Skip over any no-op casts and any temporary-binding
2493/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002494static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002495 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2496 E = M->GetTemporaryExpr();
2497
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002498 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002499 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002500 E = ICE->getSubExpr();
2501 else
2502 break;
2503 }
2504
2505 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2506 E = BE->getSubExpr();
2507
2508 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002509 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002510 E = ICE->getSubExpr();
2511 else
2512 break;
2513 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002514
2515 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002516}
2517
John McCall7a626f62010-09-15 10:14:12 +00002518/// isTemporaryObject - Determines if this expression produces a
2519/// temporary of the given class type.
2520bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2521 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2522 return false;
2523
Anders Carlsson66bbf502010-11-28 16:40:49 +00002524 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002525
John McCall02dc8c72010-09-15 20:59:13 +00002526 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002527 if (!E->Classify(C).isPRValue()) {
2528 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002529 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002530 return false;
2531 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002532
John McCallf4ee1dd2010-09-16 06:57:56 +00002533 // Black-list a few cases which yield pr-values of class type that don't
2534 // refer to temporaries of that type:
2535
2536 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002537 if (isa<ImplicitCastExpr>(E)) {
2538 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2539 case CK_DerivedToBase:
2540 case CK_UncheckedDerivedToBase:
2541 return false;
2542 default:
2543 break;
2544 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002545 }
2546
John McCallf4ee1dd2010-09-16 06:57:56 +00002547 // - member expressions (all)
2548 if (isa<MemberExpr>(E))
2549 return false;
2550
Eli Friedman13ffdd82012-06-15 23:51:06 +00002551 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2552 if (BO->isPtrMemOp())
2553 return false;
2554
John McCallc07a0c72011-02-17 10:25:35 +00002555 // - opaque values (all)
2556 if (isa<OpaqueValueExpr>(E))
2557 return false;
2558
John McCall7a626f62010-09-15 10:14:12 +00002559 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002560}
2561
Douglas Gregor25b7e052011-03-02 21:06:53 +00002562bool Expr::isImplicitCXXThis() const {
2563 const Expr *E = this;
2564
2565 // Strip away parentheses and casts we don't care about.
2566 while (true) {
2567 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2568 E = Paren->getSubExpr();
2569 continue;
2570 }
2571
2572 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2573 if (ICE->getCastKind() == CK_NoOp ||
2574 ICE->getCastKind() == CK_LValueToRValue ||
2575 ICE->getCastKind() == CK_DerivedToBase ||
2576 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2577 E = ICE->getSubExpr();
2578 continue;
2579 }
2580 }
2581
2582 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2583 if (UnOp->getOpcode() == UO_Extension) {
2584 E = UnOp->getSubExpr();
2585 continue;
2586 }
2587 }
2588
Douglas Gregorfe314812011-06-21 17:03:29 +00002589 if (const MaterializeTemporaryExpr *M
2590 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2591 E = M->GetTemporaryExpr();
2592 continue;
2593 }
2594
Douglas Gregor25b7e052011-03-02 21:06:53 +00002595 break;
2596 }
2597
2598 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2599 return This->isImplicit();
2600
2601 return false;
2602}
2603
Douglas Gregor4619e432008-12-05 23:32:09 +00002604/// hasAnyTypeDependentArguments - Determines if any of the expressions
2605/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002606bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002607 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002608 if (Exprs[I]->isTypeDependent())
2609 return true;
2610
2611 return false;
2612}
2613
Abramo Bagnara847c6602014-05-22 19:20:46 +00002614bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2615 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002616 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002617 // which can be evaluated at compile-time. It very closely parallels
2618 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2619 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2620 // to isEvaluatable most of the time.
2621 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002622 // If we ever capture reference-binding directly in the AST, we can
2623 // kill the second parameter.
2624
2625 if (IsForRef) {
2626 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002627 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2628 return true;
2629 if (Culprit)
2630 *Culprit = this;
2631 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002632 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002633
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002634 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002635 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002636 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002637 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002638 return true;
John McCall81c9cea2010-08-01 21:51:45 +00002639 case CXXTemporaryObjectExprClass:
2640 case CXXConstructExprClass: {
2641 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00002642
Eli Friedman4c27ac22013-07-16 22:40:53 +00002643 if (CE->getConstructor()->isTrivial() &&
2644 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2645 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00002646 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00002647
Eli Friedman4c27ac22013-07-16 22:40:53 +00002648 // Trivial copy constructor
2649 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00002650 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00002651 }
2652
Richard Smithd62306a2011-11-10 06:34:14 +00002653 break;
John McCall81c9cea2010-08-01 21:51:45 +00002654 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002655 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002656 // This handles gcc's extension that allows global initializers like
2657 // "struct x {int x;} x = (struct x) {};".
2658 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002659 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002660 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002661 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00002662 case DesignatedInitUpdateExprClass: {
2663 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2664 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2665 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2666 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002667 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002668 const InitListExpr *ILE = cast<InitListExpr>(this);
2669 if (ILE->getType()->isArrayType()) {
2670 unsigned numInits = ILE->getNumInits();
2671 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002672 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002673 return false;
2674 }
2675 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002676 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002677
2678 if (ILE->getType()->isRecordType()) {
2679 unsigned ElementNo = 0;
2680 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00002681 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002682 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00002683 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00002684 continue;
2685
2686 // Don't emit anonymous bitfields, they just affect layout.
2687 if (Field->isUnnamedBitfield())
2688 continue;
2689
2690 if (ElementNo < ILE->getNumInits()) {
2691 const Expr *Elt = ILE->getInit(ElementNo++);
2692 if (Field->isBitField()) {
2693 // Bitfields have to evaluate to an integer.
2694 llvm::APSInt ResultTmp;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002695 if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
2696 if (Culprit)
2697 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00002698 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002699 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002700 } else {
2701 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002702 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002703 return false;
2704 }
2705 }
2706 }
2707 return true;
2708 }
2709
2710 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002711 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00002712 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002713 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00002714 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00002715 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00002716 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002717 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00002718 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002719 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002720 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00002721 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00002722 if (cast<ChooseExpr>(this)->isConditionDependent()) {
2723 if (Culprit)
2724 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00002725 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002726 }
Eli Friedman75807f22013-07-20 00:40:58 +00002727 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002728 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002729 case UnaryOperatorClass: {
2730 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00002731 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002732 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002733 break;
2734 }
John McCall8b0f4ff2010-08-02 21:13:48 +00002735 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00002736 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00002737 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00002738 case CStyleCastExprClass:
2739 case ObjCBridgedCastExprClass:
2740 case CXXDynamicCastExprClass:
2741 case CXXReinterpretCastExprClass:
2742 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00002743 const CastExpr *CE = cast<CastExpr>(this);
2744
Eli Friedman13ec75b2011-12-21 00:43:02 +00002745 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00002746 if (CE->getCastKind() == CK_NoOp ||
2747 CE->getCastKind() == CK_LValueToRValue ||
2748 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00002749 CE->getCastKind() == CK_ConstructorConversion ||
2750 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002751 CE->getCastKind() == CK_AtomicToNonAtomic ||
2752 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002753 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00002754
Eli Friedman384da272009-01-25 03:12:18 +00002755 break;
Richard Smith161f09a2011-12-06 22:44:34 +00002756 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002757 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002758 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002759 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002760
2761 case SubstNonTypeTemplateParmExprClass:
2762 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002763 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002764 case CXXDefaultArgExprClass:
2765 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002766 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002767 case CXXDefaultInitExprClass:
2768 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002769 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002770 }
Richard Smithce8eca52015-12-08 03:21:47 +00002771 // Allow certain forms of UB in constant initializers: signed integer
2772 // overflow and floating-point division by zero. We'll give a warning on
2773 // these, but they're common enough that we have to accept them.
2774 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00002775 return true;
2776 if (Culprit)
2777 *Culprit = this;
2778 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00002779}
2780
Scott Douglasscc013592015-06-10 15:18:23 +00002781namespace {
2782 /// \brief Look for any side effects within a Stmt.
2783 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
2784 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
2785 const bool IncludePossibleEffects;
2786 bool HasSideEffects;
2787
2788 public:
2789 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
2790 : Inherited(Context),
2791 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
2792
2793 bool hasSideEffects() const { return HasSideEffects; }
2794
2795 void VisitExpr(const Expr *E) {
2796 if (!HasSideEffects &&
2797 E->HasSideEffects(Context, IncludePossibleEffects))
2798 HasSideEffects = true;
2799 }
2800 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002801}
Scott Douglasscc013592015-06-10 15:18:23 +00002802
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002803bool Expr::HasSideEffects(const ASTContext &Ctx,
2804 bool IncludePossibleEffects) const {
2805 // In circumstances where we care about definite side effects instead of
2806 // potential side effects, we want to ignore expressions that are part of a
2807 // macro expansion as a potential side effect.
2808 if (!IncludePossibleEffects && getExprLoc().isMacroID())
2809 return false;
2810
Richard Smith0421ce72012-08-07 04:16:51 +00002811 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002812 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00002813
2814 switch (getStmtClass()) {
2815 case NoStmtClass:
2816 #define ABSTRACT_STMT(Type)
2817 #define STMT(Type, Base) case Type##Class:
2818 #define EXPR(Type, Base)
2819 #include "clang/AST/StmtNodes.inc"
2820 llvm_unreachable("unexpected Expr kind");
2821
2822 case DependentScopeDeclRefExprClass:
2823 case CXXUnresolvedConstructExprClass:
2824 case CXXDependentScopeMemberExprClass:
2825 case UnresolvedLookupExprClass:
2826 case UnresolvedMemberExprClass:
2827 case PackExpansionExprClass:
2828 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00002829 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002830 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00002831 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002832 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
2833
Richard Smitha33e4fe2012-08-07 05:18:29 +00002834 case DeclRefExprClass:
2835 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002836 case PredefinedExprClass:
2837 case IntegerLiteralClass:
2838 case FloatingLiteralClass:
2839 case ImaginaryLiteralClass:
2840 case StringLiteralClass:
2841 case CharacterLiteralClass:
2842 case OffsetOfExprClass:
2843 case ImplicitValueInitExprClass:
2844 case UnaryExprOrTypeTraitExprClass:
2845 case AddrLabelExprClass:
2846 case GNUNullExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002847 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002848 case CXXBoolLiteralExprClass:
2849 case CXXNullPtrLiteralExprClass:
2850 case CXXThisExprClass:
2851 case CXXScalarValueInitExprClass:
2852 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002853 case ArrayTypeTraitExprClass:
2854 case ExpressionTraitExprClass:
2855 case CXXNoexceptExprClass:
2856 case SizeOfPackExprClass:
2857 case ObjCStringLiteralClass:
2858 case ObjCEncodeExprClass:
2859 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00002860 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002861 case CXXUuidofExprClass:
2862 case OpaqueValueExprClass:
2863 // These never have a side-effect.
2864 return false;
2865
2866 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002867 case CXXOperatorCallExprClass:
2868 case CXXMemberCallExprClass:
2869 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00002870 case UserDefinedLiteralClass: {
2871 // We don't know a call definitely has side effects, except for calls
2872 // to pure/const functions that definitely don't.
2873 // If the call itself is considered side-effect free, check the operands.
2874 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
2875 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
2876 if (IsPure || !IncludePossibleEffects)
2877 break;
2878 return true;
2879 }
2880
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002881 case BlockExprClass:
2882 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002883 if (!IncludePossibleEffects)
2884 break;
2885 return true;
2886
John McCall5e77d762013-04-16 07:28:30 +00002887 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00002888 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002889 case CompoundAssignOperatorClass:
2890 case VAArgExprClass:
2891 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002892 case CXXThrowExprClass:
2893 case CXXNewExprClass:
2894 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00002895 case CoawaitExprClass:
2896 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002897 // These always have a side-effect.
2898 return true;
2899
Scott Douglasscc013592015-06-10 15:18:23 +00002900 case StmtExprClass: {
2901 // StmtExprs have a side-effect if any substatement does.
2902 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
2903 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
2904 return Finder.hasSideEffects();
2905 }
2906
Tim Shen4a05bb82016-06-21 20:29:17 +00002907 case ExprWithCleanupsClass:
2908 if (IncludePossibleEffects)
2909 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
2910 return true;
2911 break;
2912
Richard Smith0421ce72012-08-07 04:16:51 +00002913 case ParenExprClass:
2914 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00002915 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002916 case MemberExprClass:
2917 case ConditionalOperatorClass:
2918 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002919 case CompoundLiteralExprClass:
2920 case ExtVectorElementExprClass:
2921 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002922 case DesignatedInitUpdateExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002923 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002924 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00002925 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002926 case SubstNonTypeTemplateParmExprClass:
2927 case MaterializeTemporaryExprClass:
2928 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002929 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002930 case AsTypeExprClass:
2931 // These have a side-effect if any subexpression does.
2932 break;
2933
Richard Smitha33e4fe2012-08-07 05:18:29 +00002934 case UnaryOperatorClass:
2935 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00002936 return true;
2937 break;
Richard Smith0421ce72012-08-07 04:16:51 +00002938
2939 case BinaryOperatorClass:
2940 if (cast<BinaryOperator>(this)->isAssignmentOp())
2941 return true;
2942 break;
2943
Richard Smith0421ce72012-08-07 04:16:51 +00002944 case InitListExprClass:
2945 // FIXME: The children for an InitListExpr doesn't include the array filler.
2946 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002947 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00002948 return true;
2949 break;
2950
2951 case GenericSelectionExprClass:
2952 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002953 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00002954
2955 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002956 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
2957 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00002958
2959 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002960 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
2961 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00002962
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002963 case CXXDefaultInitExprClass: {
2964 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
2965 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002966 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00002967 // If we've not yet parsed the initializer, assume it has side-effects.
2968 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002969 }
Richard Smith852c9db2013-04-20 22:23:05 +00002970
Richard Smith0421ce72012-08-07 04:16:51 +00002971 case CXXDynamicCastExprClass: {
2972 // A dynamic_cast expression has side-effects if it can throw.
2973 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
2974 if (DCE->getTypeAsWritten()->isReferenceType() &&
2975 DCE->getCastKind() == CK_Dynamic)
2976 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00002977 } // Fall through.
2978 case ImplicitCastExprClass:
2979 case CStyleCastExprClass:
2980 case CXXStaticCastExprClass:
2981 case CXXReinterpretCastExprClass:
2982 case CXXConstCastExprClass:
2983 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00002984 // While volatile reads are side-effecting in both C and C++, we treat them
2985 // as having possible (not definite) side-effects. This allows idiomatic
2986 // code to behave without warning, such as sizeof(*v) for a volatile-
2987 // qualified pointer.
2988 if (!IncludePossibleEffects)
2989 break;
2990
Richard Smitha33e4fe2012-08-07 05:18:29 +00002991 const CastExpr *CE = cast<CastExpr>(this);
2992 if (CE->getCastKind() == CK_LValueToRValue &&
2993 CE->getSubExpr()->getType().isVolatileQualified())
2994 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00002995 break;
2996 }
2997
Richard Smithef8bf432012-08-13 20:08:14 +00002998 case CXXTypeidExprClass:
2999 // typeid might throw if its subexpression is potentially-evaluated, so has
3000 // side-effects in that case whether or not its subexpression does.
3001 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003002
3003 case CXXConstructExprClass:
3004 case CXXTemporaryObjectExprClass: {
3005 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003006 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003007 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003008 // A trivial constructor does not add any side-effects of its own. Just look
3009 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003010 break;
3011 }
3012
Richard Smith5179eb72016-06-28 19:03:57 +00003013 case CXXInheritedCtorInitExprClass: {
3014 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3015 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3016 return true;
3017 break;
3018 }
3019
Richard Smith0421ce72012-08-07 04:16:51 +00003020 case LambdaExprClass: {
3021 const LambdaExpr *LE = cast<LambdaExpr>(this);
3022 for (LambdaExpr::capture_iterator I = LE->capture_begin(),
3023 E = LE->capture_end(); I != E; ++I)
3024 if (I->getCaptureKind() == LCK_ByCopy)
3025 // FIXME: Only has a side-effect if the variable is volatile or if
3026 // the copy would invoke a non-trivial copy constructor.
3027 return true;
3028 return false;
3029 }
3030
3031 case PseudoObjectExprClass: {
3032 // Only look for side-effects in the semantic form, and look past
3033 // OpaqueValueExpr bindings in that form.
3034 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3035 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3036 E = PO->semantics_end();
3037 I != E; ++I) {
3038 const Expr *Subexpr = *I;
3039 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3040 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003041 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003042 return true;
3043 }
3044 return false;
3045 }
3046
3047 case ObjCBoxedExprClass:
3048 case ObjCArrayLiteralClass:
3049 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003050 case ObjCSelectorExprClass:
3051 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003052 case ObjCIsaExprClass:
3053 case ObjCIndirectCopyRestoreExprClass:
3054 case ObjCSubscriptRefExprClass:
3055 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003056 case ObjCMessageExprClass:
3057 case ObjCPropertyRefExprClass:
3058 // FIXME: Classify these cases better.
3059 if (IncludePossibleEffects)
3060 return true;
3061 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003062 }
3063
3064 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003065 for (const Stmt *SubStmt : children())
3066 if (SubStmt &&
3067 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3068 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003069
3070 return false;
3071}
3072
Douglas Gregor1be329d2012-02-23 07:33:15 +00003073namespace {
3074 /// \brief Look for a call to a non-trivial function within an expression.
Scott Douglass503fc392015-06-10 13:53:15 +00003075 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
Douglas Gregor1be329d2012-02-23 07:33:15 +00003076 {
Scott Douglass503fc392015-06-10 13:53:15 +00003077 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3078
Douglas Gregor1be329d2012-02-23 07:33:15 +00003079 bool NonTrivial;
3080
3081 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003082 explicit NonTrivialCallFinder(const ASTContext &Context)
Douglas Gregor6427a5e2012-02-23 07:44:18 +00003083 : Inherited(Context), NonTrivial(false) { }
Douglas Gregor1be329d2012-02-23 07:33:15 +00003084
3085 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003086
3087 void VisitCallExpr(const CallExpr *E) {
3088 if (const CXXMethodDecl *Method
3089 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003090 if (Method->isTrivial()) {
3091 // Recurse to children of the call.
3092 Inherited::VisitStmt(E);
3093 return;
3094 }
3095 }
3096
3097 NonTrivial = true;
3098 }
Scott Douglass503fc392015-06-10 13:53:15 +00003099
3100 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003101 if (E->getConstructor()->isTrivial()) {
3102 // Recurse to children of the call.
3103 Inherited::VisitStmt(E);
3104 return;
3105 }
3106
3107 NonTrivial = true;
3108 }
Scott Douglass503fc392015-06-10 13:53:15 +00003109
3110 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003111 if (E->getTemporary()->getDestructor()->isTrivial()) {
3112 Inherited::VisitStmt(E);
3113 return;
3114 }
3115
3116 NonTrivial = true;
3117 }
3118 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003119}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003120
Scott Douglass503fc392015-06-10 13:53:15 +00003121bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003122 NonTrivialCallFinder Finder(Ctx);
3123 Finder.Visit(this);
3124 return Finder.hasNonTrivialCall();
3125}
3126
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003127/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3128/// pointer constant or not, as well as the specific kind of constant detected.
3129/// Null pointer constants can be integer constant expressions with the
3130/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3131/// (a GNU extension).
3132Expr::NullPointerConstantKind
3133Expr::isNullPointerConstant(ASTContext &Ctx,
3134 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003135 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003136 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003137 switch (NPC) {
3138 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003139 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003140 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003141 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003142 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003143 else
3144 return NPCK_NotNull;
Alexis Hunta8136cc2010-05-05 15:23:54 +00003145
Douglas Gregor56751b52009-09-25 04:25:58 +00003146 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003147 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003148 }
3149 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003150
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003151 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003152 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003153 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003154 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003155 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003156 QualType Pointee = PT->getPointeeType();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003157 Qualifiers Q = Pointee.getQualifiers();
3158 // In OpenCL v2.0 generic address space acts as a placeholder
3159 // and should be ignored.
3160 bool IsASValid = true;
3161 if (Ctx.getLangOpts().OpenCLVersion >= 200) {
3162 if (Pointee.getAddressSpace() == LangAS::opencl_generic)
3163 Q.removeAddressSpace();
3164 else
3165 IsASValid = false;
3166 }
3167
3168 if (IsASValid && !Q.hasQualifiers() &&
3169 Pointee->isVoidType() && // to void*
3170 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Douglas Gregor56751b52009-09-25 04:25:58 +00003171 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003172 }
Steve Naroffada7d422007-05-20 17:54:12 +00003173 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003174 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3175 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003176 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003177 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3178 // Accept ((void*)0) as a null pointer constant, as many other
3179 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003180 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003181 } else if (const GenericSelectionExpr *GE =
3182 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003183 if (GE->isResultDependent())
3184 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003185 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003186 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3187 if (CE->isConditionDependent())
3188 return NPCK_NotNull;
3189 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003190 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003191 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003192 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003193 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003194 } else if (const CXXDefaultInitExpr *DefaultInit
3195 = dyn_cast<CXXDefaultInitExpr>(this)) {
3196 // See through default initializer expressions.
3197 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003198 } else if (isa<GNUNullExpr>(this)) {
3199 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003200 return NPCK_GNUNull;
Douglas Gregorfe314812011-06-21 17:03:29 +00003201 } else if (const MaterializeTemporaryExpr *M
3202 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3203 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003204 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3205 if (const Expr *Source = OVE->getSourceExpr())
3206 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003207 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003208
Richard Smith89645bc2013-01-02 12:01:23 +00003209 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003210 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003211 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003212
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003213 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003214 if (!Ctx.getLangOpts().CPlusPlus11 &&
3215 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003216 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3217 const Expr *InitExpr = CLE->getInitializer();
3218 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3219 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3220 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003221 // This expression must be an integer type.
Alexis Hunta8136cc2010-05-05 15:23:54 +00003222 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003223 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003224 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003225
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003226 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003227 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3228 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003229 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003230 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003231 if (Lit && !Lit->getValue())
3232 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003233 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003234 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003235 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003236 // If we have an integer constant expression, we need to *evaluate* it and
3237 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003238 if (!isIntegerConstantExpr(Ctx))
3239 return NPCK_NotNull;
3240 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003241
David Blaikie1c7c8f72012-08-08 17:33:31 +00003242 if (EvaluateKnownConstInt(Ctx) != 0)
3243 return NPCK_NotNull;
3244
3245 if (isa<IntegerLiteral>(this))
3246 return NPCK_ZeroLiteral;
3247 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003248}
Steve Narofff7a5da12007-07-28 23:10:27 +00003249
John McCall34376a62010-12-04 03:47:34 +00003250/// \brief If this expression is an l-value for an Objective C
3251/// property, find the underlying property reference expression.
3252const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3253 const Expr *E = this;
3254 while (true) {
3255 assert((E->getValueKind() == VK_LValue &&
3256 E->getObjectKind() == OK_ObjCProperty) &&
3257 "expression is not a property reference");
3258 E = E->IgnoreParenCasts();
3259 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3260 if (BO->getOpcode() == BO_Comma) {
3261 E = BO->getRHS();
3262 continue;
3263 }
3264 }
3265
3266 break;
3267 }
3268
3269 return cast<ObjCPropertyRefExpr>(E);
3270}
3271
Anna Zaks97c7ce32012-10-01 20:34:04 +00003272bool Expr::isObjCSelfExpr() const {
3273 const Expr *E = IgnoreParenImpCasts();
3274
3275 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3276 if (!DRE)
3277 return false;
3278
3279 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3280 if (!Param)
3281 return false;
3282
3283 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3284 if (!M)
3285 return false;
3286
3287 return M->getSelfDecl() == Param;
3288}
3289
John McCalld25db7e2013-05-06 21:39:12 +00003290FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003291 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003292
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003293 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003294 if (ICE->getCastKind() == CK_LValueToRValue ||
3295 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003296 E = ICE->getSubExpr()->IgnoreParens();
3297 else
3298 break;
3299 }
3300
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003301 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003302 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003303 if (Field->isBitField())
3304 return Field;
3305
John McCalld25db7e2013-05-06 21:39:12 +00003306 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E))
3307 if (FieldDecl *Ivar = dyn_cast<FieldDecl>(IvarRef->getDecl()))
3308 if (Ivar->isBitField())
3309 return Ivar;
3310
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003311 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
3312 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3313 if (Field->isBitField())
3314 return Field;
3315
Eli Friedman609ada22011-07-13 02:05:57 +00003316 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003317 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003318 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003319
Eli Friedman609ada22011-07-13 02:05:57 +00003320 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003321 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003322 }
3323
Richard Smith5b571672014-09-24 23:55:00 +00003324 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3325 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3326 return UnOp->getSubExpr()->getSourceBitField();
3327
Craig Topper36250ad2014-05-12 05:36:57 +00003328 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003329}
3330
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003331bool Expr::refersToVectorElement() const {
3332 const Expr *E = this->IgnoreParens();
Alexis Hunta8136cc2010-05-05 15:23:54 +00003333
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003334 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003335 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003336 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003337 E = ICE->getSubExpr()->IgnoreParens();
3338 else
3339 break;
3340 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00003341
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003342 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3343 return ASE->getBase()->getType()->isVectorType();
3344
3345 if (isa<ExtVectorElementExpr>(E))
3346 return true;
3347
3348 return false;
3349}
3350
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003351bool Expr::refersToGlobalRegisterVar() const {
3352 const Expr *E = this->IgnoreParenImpCasts();
3353
3354 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3355 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3356 if (VD->getStorageClass() == SC_Register &&
3357 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3358 return true;
3359
3360 return false;
3361}
3362
Chris Lattnerb8211f62009-02-16 22:14:05 +00003363/// isArrow - Return true if the base expression is a pointer to vector,
3364/// return false if the base expression is a vector.
3365bool ExtVectorElementExpr::isArrow() const {
3366 return getBase()->getType()->isPointerType();
3367}
3368
Nate Begemance4d7fc2008-04-18 23:10:10 +00003369unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003370 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003371 return VT->getNumElements();
3372 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003373}
3374
Nate Begemanf322eab2008-05-09 06:41:27 +00003375/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003376bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003377 // FIXME: Refactor this code to an accessor on the AST node which returns the
3378 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003379 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003380
3381 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003382 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003383 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003384
Nate Begeman7e5185b2009-01-18 02:01:21 +00003385 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003386 if (Comp[0] == 's' || Comp[0] == 'S')
3387 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003388
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003389 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003390 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003391 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003392
Steve Naroff0d595ca2007-07-30 03:29:09 +00003393 return false;
3394}
Chris Lattner885b4952007-08-02 23:36:59 +00003395
Nate Begemanf322eab2008-05-09 06:41:27 +00003396/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003397void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003398 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003399 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003400 bool isNumericAccessor = false;
3401 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003402 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003403 isNumericAccessor = true;
3404 }
Mike Stump11289f42009-09-09 15:08:12 +00003405
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003406 bool isHi = Comp == "hi";
3407 bool isLo = Comp == "lo";
3408 bool isEven = Comp == "even";
3409 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003410
Nate Begemanf322eab2008-05-09 06:41:27 +00003411 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3412 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003413
Nate Begemanf322eab2008-05-09 06:41:27 +00003414 if (isHi)
3415 Index = e + i;
3416 else if (isLo)
3417 Index = i;
3418 else if (isEven)
3419 Index = 2 * i;
3420 else if (isOdd)
3421 Index = 2 * i + 1;
3422 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003423 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003424
Nate Begemand3862152008-05-13 21:03:02 +00003425 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003426 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003427}
3428
Craig Topper37932912013-08-18 10:09:15 +00003429ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003430 QualType Type, SourceLocation BLoc,
3431 SourceLocation RP)
3432 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3433 Type->isDependentType(), Type->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003434 Type->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003435 Type->containsUnexpandedParameterPack()),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003436 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
Douglas Gregora6e053e2010-12-15 01:34:56 +00003437{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003438 SubExprs = new (C) Stmt*[args.size()];
3439 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003440 if (args[i]->isTypeDependent())
3441 ExprBits.TypeDependent = true;
3442 if (args[i]->isValueDependent())
3443 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003444 if (args[i]->isInstantiationDependent())
3445 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003446 if (args[i]->containsUnexpandedParameterPack())
3447 ExprBits.ContainsUnexpandedParameterPack = true;
3448
3449 SubExprs[i] = args[i];
3450 }
3451}
3452
Craig Topper37932912013-08-18 10:09:15 +00003453void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003454 if (SubExprs) C.Deallocate(SubExprs);
3455
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003456 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003457 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003458 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003459}
Nate Begeman48745922009-08-12 02:28:50 +00003460
Craig Topper37932912013-08-18 10:09:15 +00003461GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003462 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003463 ArrayRef<TypeSourceInfo*> AssocTypes,
3464 ArrayRef<Expr*> AssocExprs,
3465 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003466 SourceLocation RParenLoc,
3467 bool ContainsUnexpandedParameterPack,
3468 unsigned ResultIndex)
3469 : Expr(GenericSelectionExprClass,
3470 AssocExprs[ResultIndex]->getType(),
3471 AssocExprs[ResultIndex]->getValueKind(),
3472 AssocExprs[ResultIndex]->getObjectKind(),
3473 AssocExprs[ResultIndex]->isTypeDependent(),
3474 AssocExprs[ResultIndex]->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003475 AssocExprs[ResultIndex]->isInstantiationDependent(),
Peter Collingbourne91147592011-04-15 00:35:48 +00003476 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003477 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3478 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3479 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3480 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003481 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003482 assert(AssocTypes.size() == AssocExprs.size());
3483 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3484 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003485}
3486
Craig Topper37932912013-08-18 10:09:15 +00003487GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003488 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003489 ArrayRef<TypeSourceInfo*> AssocTypes,
3490 ArrayRef<Expr*> AssocExprs,
3491 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003492 SourceLocation RParenLoc,
3493 bool ContainsUnexpandedParameterPack)
3494 : Expr(GenericSelectionExprClass,
3495 Context.DependentTy,
3496 VK_RValue,
3497 OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003498 /*isTypeDependent=*/true,
3499 /*isValueDependent=*/true,
3500 /*isInstantiationDependent=*/true,
Peter Collingbourne91147592011-04-15 00:35:48 +00003501 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003502 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3503 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3504 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3505 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003506 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003507 assert(AssocTypes.size() == AssocExprs.size());
3508 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3509 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003510}
3511
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003512//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003513// DesignatedInitExpr
3514//===----------------------------------------------------------------------===//
3515
Chandler Carruth631abd92011-06-16 06:47:06 +00003516IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003517 assert(Kind == FieldDesignator && "Only valid on a field designator");
3518 if (Field.NameOrField & 0x01)
3519 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3520 else
3521 return getField()->getIdentifier();
3522}
3523
Craig Topper37932912013-08-18 10:09:15 +00003524DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00003525 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003526 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003527 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003528 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003529 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003530 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003531 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003532 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003533 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003534 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003535 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00003536 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003537 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003538
3539 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003540 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003541 *Child++ = Init;
3542
3543 // Copy the designators and their subexpressions, computing
3544 // value-dependence along the way.
3545 unsigned IndexIdx = 0;
3546 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003547 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003548
3549 if (this->Designators[I].isArrayDesignator()) {
3550 // Compute type- and value-dependence.
3551 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003552 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003553 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003554 if (Index->isInstantiationDependent())
3555 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003556 // Propagate unexpanded parameter packs.
3557 if (Index->containsUnexpandedParameterPack())
3558 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003559
3560 // Copy the index expressions into permanent storage.
3561 *Child++ = IndexExprs[IndexIdx++];
3562 } else if (this->Designators[I].isArrayRangeDesignator()) {
3563 // Compute type- and value-dependence.
3564 Expr *Start = IndexExprs[IndexIdx];
3565 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003566 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003567 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00003568 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003569 ExprBits.InstantiationDependent = true;
3570 } else if (Start->isInstantiationDependent() ||
3571 End->isInstantiationDependent()) {
3572 ExprBits.InstantiationDependent = true;
3573 }
3574
Douglas Gregora6e053e2010-12-15 01:34:56 +00003575 // Propagate unexpanded parameter packs.
3576 if (Start->containsUnexpandedParameterPack() ||
3577 End->containsUnexpandedParameterPack())
3578 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003579
3580 // Copy the start/end expressions into permanent storage.
3581 *Child++ = IndexExprs[IndexIdx++];
3582 *Child++ = IndexExprs[IndexIdx++];
3583 }
3584 }
3585
Benjamin Kramerc215e762012-08-24 11:54:20 +00003586 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00003587}
3588
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003589DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00003590DesignatedInitExpr::Create(const ASTContext &C,
3591 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003592 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003593 SourceLocation ColonOrEqualLoc,
3594 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003595 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
James Y Knight53c76162015-07-17 18:21:37 +00003596 llvm::alignOf<DesignatedInitExpr>());
David Majnemerf7e36092016-06-23 00:15:04 +00003597 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003598 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003599 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003600}
3601
Craig Topper37932912013-08-18 10:09:15 +00003602DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00003603 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003604 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
3605 llvm::alignOf<DesignatedInitExpr>());
Douglas Gregor38676d52009-04-16 00:55:48 +00003606 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3607}
3608
Craig Topper37932912013-08-18 10:09:15 +00003609void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003610 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00003611 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003612 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00003613 NumDesignators = NumDesigs;
3614 for (unsigned I = 0; I != NumDesigs; ++I)
3615 Designators[I] = Desigs[I];
3616}
3617
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003618SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3619 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3620 if (size() == 1)
3621 return DIE->getDesignator(0)->getSourceRange();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003622 return SourceRange(DIE->getDesignator(0)->getLocStart(),
3623 DIE->getDesignator(size()-1)->getLocEnd());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003624}
3625
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003626SourceLocation DesignatedInitExpr::getLocStart() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003627 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00003628 auto *DIE = const_cast<DesignatedInitExpr *>(this);
3629 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003630 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00003631 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003632 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3633 else
3634 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3635 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00003636 StartLoc =
3637 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003638 return StartLoc;
3639}
3640
3641SourceLocation DesignatedInitExpr::getLocEnd() const {
3642 return getInit()->getLocEnd();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003643}
3644
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003645Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003646 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003647 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003648}
3649
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003650Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003651 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003652 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003653 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003654}
3655
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003656Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003657 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003658 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003659 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003660}
3661
Douglas Gregord5846a12009-04-15 06:41:24 +00003662/// \brief Replaces the designator at index @p Idx with the series
3663/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00003664void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00003665 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00003666 const Designator *Last) {
3667 unsigned NumNewDesignators = Last - First;
3668 if (NumNewDesignators == 0) {
3669 std::copy_backward(Designators + Idx + 1,
3670 Designators + NumDesignators,
3671 Designators + Idx);
3672 --NumNewDesignators;
3673 return;
3674 } else if (NumNewDesignators == 1) {
3675 Designators[Idx] = *First;
3676 return;
3677 }
3678
Mike Stump11289f42009-09-09 15:08:12 +00003679 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003680 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00003681 std::copy(Designators, Designators + Idx, NewDesignators);
3682 std::copy(First, Last, NewDesignators + Idx);
3683 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3684 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00003685 Designators = NewDesignators;
3686 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3687}
3688
Yunzhong Gaocb779302015-06-10 00:27:52 +00003689DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
3690 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3691 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3692 OK_Ordinary, false, false, false, false) {
3693 BaseAndUpdaterExprs[0] = baseExpr;
3694
3695 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3696 ILE->setType(baseExpr->getType());
3697 BaseAndUpdaterExprs[1] = ILE;
3698}
3699
3700SourceLocation DesignatedInitUpdateExpr::getLocStart() const {
3701 return getBase()->getLocStart();
3702}
3703
3704SourceLocation DesignatedInitUpdateExpr::getLocEnd() const {
3705 return getBase()->getLocEnd();
3706}
3707
Craig Topper37932912013-08-18 10:09:15 +00003708ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003709 ArrayRef<Expr*> exprs,
Sebastian Redla9351792012-02-11 23:51:47 +00003710 SourceLocation rparenloc)
3711 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003712 false, false, false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003713 NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3714 Exprs = new (C) Stmt*[exprs.size()];
3715 for (unsigned i = 0; i != exprs.size(); ++i) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003716 if (exprs[i]->isTypeDependent())
3717 ExprBits.TypeDependent = true;
3718 if (exprs[i]->isValueDependent())
3719 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003720 if (exprs[i]->isInstantiationDependent())
3721 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003722 if (exprs[i]->containsUnexpandedParameterPack())
3723 ExprBits.ContainsUnexpandedParameterPack = true;
3724
Nate Begeman5ec4b312009-08-10 23:49:36 +00003725 Exprs[i] = exprs[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003726 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00003727}
3728
John McCall1bf58462011-02-16 08:02:54 +00003729const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3730 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3731 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00003732 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3733 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00003734 e = cast<CXXConstructExpr>(e)->getArg(0);
3735 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3736 e = ice->getSubExpr();
3737 return cast<OpaqueValueExpr>(e);
3738}
3739
Craig Topper37932912013-08-18 10:09:15 +00003740PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
3741 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00003742 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003743 void *buffer =
3744 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
3745 llvm::alignOf<PseudoObjectExpr>());
John McCallfe96e0b2011-11-06 09:01:30 +00003746 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3747}
3748
3749PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3750 : Expr(PseudoObjectExprClass, shell) {
3751 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3752}
3753
Craig Topper37932912013-08-18 10:09:15 +00003754PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00003755 ArrayRef<Expr*> semantics,
3756 unsigned resultIndex) {
3757 assert(syntax && "no syntactic expression!");
3758 assert(semantics.size() && "no semantic expressions!");
3759
3760 QualType type;
3761 ExprValueKind VK;
3762 if (resultIndex == NoResult) {
3763 type = C.VoidTy;
3764 VK = VK_RValue;
3765 } else {
3766 assert(resultIndex < semantics.size());
3767 type = semantics[resultIndex]->getType();
3768 VK = semantics[resultIndex]->getValueKind();
3769 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3770 }
3771
James Y Knighte00a67e2015-12-31 04:18:25 +00003772 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
John McCallfe96e0b2011-11-06 09:01:30 +00003773 llvm::alignOf<PseudoObjectExpr>());
3774 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3775 resultIndex);
3776}
3777
3778PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3779 Expr *syntax, ArrayRef<Expr*> semantics,
3780 unsigned resultIndex)
3781 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3782 /*filled in at end of ctor*/ false, false, false, false) {
3783 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3784 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3785
3786 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3787 Expr *E = (i == 0 ? syntax : semantics[i-1]);
3788 getSubExprsBuffer()[i] = E;
3789
3790 if (E->isTypeDependent())
3791 ExprBits.TypeDependent = true;
3792 if (E->isValueDependent())
3793 ExprBits.ValueDependent = true;
3794 if (E->isInstantiationDependent())
3795 ExprBits.InstantiationDependent = true;
3796 if (E->containsUnexpandedParameterPack())
3797 ExprBits.ContainsUnexpandedParameterPack = true;
3798
3799 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00003800 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00003801 "opaque-value semantic expressions for pseudo-object "
3802 "operations must have sources");
3803 }
3804}
3805
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003806//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003807// Child Iterators for iterating over subexpressions/substatements
3808//===----------------------------------------------------------------------===//
3809
Peter Collingbournee190dee2011-03-11 19:24:49 +00003810// UnaryExprOrTypeTraitExpr
3811Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Sebastian Redl6f282892008-11-11 17:56:53 +00003812 // If this is of a type and the type is a VLA type (and not a typedef), the
3813 // size expression of the VLA needs to be treated as an executable expression.
3814 // Why isn't this weirdness documented better in StmtIterator?
3815 if (isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003816 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
Sebastian Redl6f282892008-11-11 17:56:53 +00003817 getArgumentType().getTypePtr()))
John McCallbd066782011-02-09 08:16:59 +00003818 return child_range(child_iterator(T), child_iterator());
Benjamin Kramer5733e352015-07-18 17:09:36 +00003819 return child_range(child_iterator(), child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00003820 }
John McCallbd066782011-02-09 08:16:59 +00003821 return child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00003822}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003823
Benjamin Kramerc215e762012-08-24 11:54:20 +00003824AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003825 QualType t, AtomicOp op, SourceLocation RP)
3826 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3827 false, false, false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003828 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003829{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003830 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
3831 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003832 if (args[i]->isTypeDependent())
3833 ExprBits.TypeDependent = true;
3834 if (args[i]->isValueDependent())
3835 ExprBits.ValueDependent = true;
3836 if (args[i]->isInstantiationDependent())
3837 ExprBits.InstantiationDependent = true;
3838 if (args[i]->containsUnexpandedParameterPack())
3839 ExprBits.ContainsUnexpandedParameterPack = true;
3840
3841 SubExprs[i] = args[i];
3842 }
3843}
Richard Smithaa22a8c2012-04-10 22:49:28 +00003844
3845unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
3846 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00003847 case AO__c11_atomic_init:
3848 case AO__c11_atomic_load:
3849 case AO__atomic_load_n:
Richard Smithaa22a8c2012-04-10 22:49:28 +00003850 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00003851
3852 case AO__c11_atomic_store:
3853 case AO__c11_atomic_exchange:
3854 case AO__atomic_load:
3855 case AO__atomic_store:
3856 case AO__atomic_store_n:
3857 case AO__atomic_exchange_n:
3858 case AO__c11_atomic_fetch_add:
3859 case AO__c11_atomic_fetch_sub:
3860 case AO__c11_atomic_fetch_and:
3861 case AO__c11_atomic_fetch_or:
3862 case AO__c11_atomic_fetch_xor:
3863 case AO__atomic_fetch_add:
3864 case AO__atomic_fetch_sub:
3865 case AO__atomic_fetch_and:
3866 case AO__atomic_fetch_or:
3867 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003868 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003869 case AO__atomic_add_fetch:
3870 case AO__atomic_sub_fetch:
3871 case AO__atomic_and_fetch:
3872 case AO__atomic_or_fetch:
3873 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003874 case AO__atomic_nand_fetch:
Richard Smithaa22a8c2012-04-10 22:49:28 +00003875 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00003876
3877 case AO__atomic_exchange:
3878 return 4;
3879
3880 case AO__c11_atomic_compare_exchange_strong:
3881 case AO__c11_atomic_compare_exchange_weak:
Richard Smithaa22a8c2012-04-10 22:49:28 +00003882 return 5;
Richard Smithfeea8832012-04-12 05:08:17 +00003883
3884 case AO__atomic_compare_exchange:
3885 case AO__atomic_compare_exchange_n:
3886 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00003887 }
3888 llvm_unreachable("unknown atomic op");
3889}
Alexey Bataeva1764212015-09-30 09:22:36 +00003890
Alexey Bataev31300ed2016-02-04 11:27:03 +00003891QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00003892 unsigned ArraySectionCount = 0;
3893 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
3894 Base = OASE->getBase();
3895 ++ArraySectionCount;
3896 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00003897 while (auto *ASE =
3898 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003899 Base = ASE->getBase();
3900 ++ArraySectionCount;
3901 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00003902 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00003903 auto OriginalTy = Base->getType();
3904 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
3905 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3906 OriginalTy = PVD->getOriginalType().getNonReferenceType();
3907
3908 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
3909 if (OriginalTy->isAnyPointerType())
3910 OriginalTy = OriginalTy->getPointeeType();
3911 else {
3912 assert (OriginalTy->isArrayType());
3913 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
3914 }
3915 }
3916 return OriginalTy;
3917}