blob: 5590527819e9b1db487744b357469e22f68b909e [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 Lattner86ee2862008-10-06 06:40:35 +000014#include "clang/AST/APValue.h"
Chris Lattner5c4664e2007-07-15 23:32:58 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Douglas Gregor9a657932008-10-21 23:43:52 +000017#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor1be329d2012-02-23 07:33:15 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
David Majnemerbed356a2013-11-06 23:31:56 +000023#include "clang/AST/Mangle.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Chris Lattner5e9a8782006-11-04 06:21:51 +000025#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Chris Lattnere925d612010-11-17 07:37:15 +000028#include "clang/Basic/SourceManager.h"
Chris Lattnera7944d82007-11-27 18:22:04 +000029#include "clang/Basic/TargetInfo.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "clang/Lex/Lexer.h"
31#include "clang/Lex/LiteralSupport.h"
32#include "clang/Sema/SemaDiagnostic.h"
Douglas Gregor0840cc02009-11-01 20:32:48 +000033#include "llvm/Support/ErrorHandling.h"
Anders Carlsson2fb08242009-09-08 18:24:21 +000034#include "llvm/Support/raw_ostream.h"
Douglas Gregord5846a12009-04-15 06:41:24 +000035#include <algorithm>
Eli Friedmanfcec6302011-11-01 02:23:42 +000036#include <cstring>
Chris Lattner1b926492006-08-23 06:42:10 +000037using namespace clang;
38
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000039const CXXRecordDecl *Expr::getBestDynamicClassType() const {
Rafael Espindolaecbe2e92012-06-28 01:56:38 +000040 const Expr *E = ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000041
42 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000043 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
44 DerivedType = PTy->getPointeeType();
45
Rafael Espindola60a2bba2012-07-17 20:24:05 +000046 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000047 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000048
Rafael Espindola49e860b2012-06-26 17:45:31 +000049 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000050 Decl *D = Ty->getDecl();
51 return cast<CXXRecordDecl>(D);
52}
53
Richard Smithf3fabd22013-06-03 00:17:11 +000054const Expr *Expr::skipRValueSubobjectAdjustments(
55 SmallVectorImpl<const Expr *> &CommaLHSs,
56 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000057 const Expr *E = this;
58 while (true) {
59 E = E->IgnoreParens();
60
61 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
62 if ((CE->getCastKind() == CK_DerivedToBase ||
63 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
64 E->getType()->isRecordType()) {
65 E = CE->getSubExpr();
66 CXXRecordDecl *Derived
67 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
68 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
69 continue;
70 }
71
72 if (CE->getCastKind() == CK_NoOp) {
73 E = CE->getSubExpr();
74 continue;
75 }
76 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +000077 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +000078 assert(ME->getBase()->getType()->isRecordType());
79 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +000080 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +000081 E = ME->getBase();
82 Adjustments.push_back(SubobjectAdjustment(Field));
83 continue;
84 }
Rafael Espindola9c006de2012-10-27 01:03:43 +000085 }
86 }
87 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
88 if (BO->isPtrMemOp()) {
Rafael Espindola973aa202012-11-01 14:32:20 +000089 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +000090 E = BO->getLHS();
91 const MemberPointerType *MPT =
92 BO->getRHS()->getType()->getAs<MemberPointerType>();
93 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +000094 continue;
95 } else if (BO->getOpcode() == BO_Comma) {
96 CommaLHSs.push_back(BO->getLHS());
97 E = BO->getRHS();
98 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +000099 }
100 }
101
102 // Nothing changed.
103 break;
104 }
105 return E;
106}
107
Chris Lattner4ebae652010-04-16 23:34:13 +0000108/// isKnownToHaveBooleanValue - Return true if this is an integer expression
109/// that is known to return 0 or 1. This happens for _Bool/bool expressions
110/// but also int expressions which are produced by things like comparisons in
111/// C.
112bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000113 const Expr *E = IgnoreParens();
114
Chris Lattner4ebae652010-04-16 23:34:13 +0000115 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000116 if (E->getType()->isBooleanType()) return true;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000117 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000118 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000119
Peter Collingbourne91147592011-04-15 00:35:48 +0000120 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000121 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000122 case UO_Plus:
Chris Lattner4ebae652010-04-16 23:34:13 +0000123 return UO->getSubExpr()->isKnownToHaveBooleanValue();
Richard Trieu0f097742014-04-04 04:13:47 +0000124 case UO_LNot:
125 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000126 default:
127 return false;
128 }
129 }
Alexis Hunta8136cc2010-05-05 15:23:54 +0000130
John McCall45d30c32010-06-12 01:56:02 +0000131 // Only look through implicit casts. If the user writes
132 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbourne91147592011-04-15 00:35:48 +0000133 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000134 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000135
Peter Collingbourne91147592011-04-15 00:35:48 +0000136 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000137 switch (BO->getOpcode()) {
138 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000139 case BO_LT: // Relational operators.
140 case BO_GT:
141 case BO_LE:
142 case BO_GE:
143 case BO_EQ: // Equality operators.
144 case BO_NE:
145 case BO_LAnd: // AND operator.
146 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000147 return true;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000148
John McCalle3027922010-08-25 11:45:40 +0000149 case BO_And: // Bitwise AND operator.
150 case BO_Xor: // Bitwise XOR operator.
151 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000152 // Handle things like (x==2)|(y==12).
153 return BO->getLHS()->isKnownToHaveBooleanValue() &&
154 BO->getRHS()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000155
John McCalle3027922010-08-25 11:45:40 +0000156 case BO_Comma:
157 case BO_Assign:
Chris Lattner4ebae652010-04-16 23:34:13 +0000158 return BO->getRHS()->isKnownToHaveBooleanValue();
159 }
160 }
Alexis Hunta8136cc2010-05-05 15:23:54 +0000161
Peter Collingbourne91147592011-04-15 00:35:48 +0000162 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000163 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
164 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000165
Chris Lattner4ebae652010-04-16 23:34:13 +0000166 return false;
167}
168
John McCallbd066782011-02-09 08:16:59 +0000169// Amusing macro metaprogramming hack: check whether a class provides
170// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000171//
172// See also Stmt.cpp:{getLocStart(),getLocEnd()}.
John McCallbd066782011-02-09 08:16:59 +0000173namespace {
174 /// This implementation is used when a class provides a custom
175 /// implementation of getExprLoc.
176 template <class E, class T>
177 SourceLocation getExprLocImpl(const Expr *expr,
178 SourceLocation (T::*v)() const) {
179 return static_cast<const E*>(expr)->getExprLoc();
180 }
181
182 /// This implementation is used when a class doesn't provide
183 /// a custom implementation of getExprLoc. Overload resolution
184 /// should pick it over the implementation above because it's
185 /// more specialized according to function template partial ordering.
186 template <class E>
187 SourceLocation getExprLocImpl(const Expr *expr,
188 SourceLocation (Expr::*v)() const) {
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000189 return static_cast<const E*>(expr)->getLocStart();
John McCallbd066782011-02-09 08:16:59 +0000190 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000191}
John McCallbd066782011-02-09 08:16:59 +0000192
193SourceLocation Expr::getExprLoc() const {
194 switch (getStmtClass()) {
195 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
196#define ABSTRACT_STMT(type)
197#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000198 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000199#define EXPR(type, base) \
200 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
201#include "clang/AST/StmtNodes.inc"
202 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000203 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000204}
205
Chris Lattner0eedafe2006-08-24 04:56:27 +0000206//===----------------------------------------------------------------------===//
207// Primary Expressions.
208//===----------------------------------------------------------------------===//
209
Douglas Gregor678d76c2011-07-01 01:22:09 +0000210/// \brief Compute the type-, value-, and instantiation-dependence of a
211/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000212/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000213static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
214 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000215 bool &ValueDependent,
216 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000217 TypeDependent = false;
218 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000219 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000220
221 // (TD) C++ [temp.dep.expr]p3:
222 // An id-expression is type-dependent if it contains:
223 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000224 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000225 //
226 // (VD) C++ [temp.dep.constexpr]p2:
227 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000228
Douglas Gregored6c7442009-11-23 11:41:28 +0000229 // (TD) - an identifier that was declared with dependent type
230 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000231 if (T->isDependentType()) {
232 TypeDependent = true;
233 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000234 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000235 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000236 } else if (T->isInstantiationDependentType()) {
237 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000238 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000239
Douglas Gregored6c7442009-11-23 11:41:28 +0000240 // (TD) - a conversion-function-id that specifies a dependent type
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000241 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000242 == DeclarationName::CXXConversionFunctionName) {
243 QualType T = D->getDeclName().getCXXNameType();
244 if (T->isDependentType()) {
245 TypeDependent = true;
246 ValueDependent = true;
247 InstantiationDependent = true;
248 return;
249 }
250
251 if (T->isInstantiationDependentType())
252 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000253 }
Douglas Gregor678d76c2011-07-01 01:22:09 +0000254
Douglas Gregored6c7442009-11-23 11:41:28 +0000255 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000256 if (isa<NonTypeTemplateParmDecl>(D)) {
257 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000258 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000259 return;
260 }
261
Douglas Gregored6c7442009-11-23 11:41:28 +0000262 // (VD) - a constant with integral or enumeration type and is
263 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000264 // (VD) - a constant with literal type and is initialized with an
265 // expression that is value-dependent [C++11].
266 // (VD) - FIXME: Missing from the standard:
267 // - an entity with reference type and is initialized with an
268 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000269 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000270 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000271 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000272 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000273 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000274 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000275 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000276 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000277 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000278 InstantiationDependent = true;
279 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000280 }
281
Douglas Gregor0e4de762010-05-11 08:41:30 +0000282 // (VD) - FIXME: Missing from the standard:
283 // - a member function or a static data member of the current
284 // instantiation
Richard Smithec8dcd22011-11-08 01:31:09 +0000285 if (Var->isStaticDataMember() &&
286 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000287 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000288 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000289 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
290 if (TInfo->getType()->isIncompleteArrayType())
291 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000292 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000293
294 return;
295 }
296
Douglas Gregor0e4de762010-05-11 08:41:30 +0000297 // (VD) - FIXME: Missing from the standard:
298 // - a member function or a static data member of the current
299 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000300 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
301 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000302 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000303 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000304}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000305
Craig Topperce7167c2013-08-22 04:58:56 +0000306void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000307 bool TypeDependent = false;
308 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000309 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000310 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
311 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000312
313 ExprBits.TypeDependent |= TypeDependent;
314 ExprBits.ValueDependent |= ValueDependent;
315 ExprBits.InstantiationDependent |= InstantiationDependent;
316
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000317 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000318 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000319 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000320}
321
Craig Topperce7167c2013-08-22 04:58:56 +0000322DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000323 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000324 SourceLocation TemplateKWLoc,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000325 ValueDecl *D, bool RefersToEnclosingVariableOrCapture,
John McCall113bee02012-03-10 09:33:50 +0000326 const DeclarationNameInfo &NameInfo,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000327 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000328 const TemplateArgumentListInfo *TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +0000329 QualType T, ExprValueKind VK)
Douglas Gregor678d76c2011-07-01 01:22:09 +0000330 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
Chandler Carruth0e439962011-05-01 21:29:53 +0000331 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
332 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000333 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000334 new (getTrailingObjects<NestedNameSpecifierLoc>())
335 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000336 auto *NNS = QualifierLoc.getNestedNameSpecifier();
337 if (NNS->isInstantiationDependent())
338 ExprBits.InstantiationDependent = true;
339 if (NNS->containsUnexpandedParameterPack())
340 ExprBits.ContainsUnexpandedParameterPack = true;
341 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000342 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
343 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000344 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000345 DeclRefExprBits.HasTemplateKWAndArgsInfo
346 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000347 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
348 RefersToEnclosingVariableOrCapture;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000349 if (TemplateArgs) {
350 bool Dependent = false;
351 bool InstantiationDependent = false;
352 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000353 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
354 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
355 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000356 assert(!Dependent && "built a DeclRefExpr with dependent template args");
357 ExprBits.InstantiationDependent |= InstantiationDependent;
358 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000359 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000360 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
361 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000362 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000363 DeclRefExprBits.HadMultipleCandidates = 0;
364
Daniel Dunbar9d355812012-03-09 01:51:51 +0000365 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000366}
367
Craig Topperce7167c2013-08-22 04:58:56 +0000368DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000369 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000370 SourceLocation TemplateKWLoc,
John McCallce546572009-12-08 09:08:17 +0000371 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000372 bool RefersToEnclosingVariableOrCapture,
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000373 SourceLocation NameLoc,
Douglas Gregored6c7442009-11-23 11:41:28 +0000374 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000375 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000376 NamedDecl *FoundD,
Douglas Gregored6c7442009-11-23 11:41:28 +0000377 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000378 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000379 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000380 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000381 T, VK, FoundD, TemplateArgs);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000382}
383
Craig Topperce7167c2013-08-22 04:58:56 +0000384DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000385 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000386 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000387 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000388 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000389 const DeclarationNameInfo &NameInfo,
390 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000391 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000392 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000393 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000394 // Filter out cases where the found Decl is the same as the value refenenced.
395 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000396 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000397
James Y Knighte7d82282015-12-29 18:15:14 +0000398 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
399 std::size_t Size =
400 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
401 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
402 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
403 HasTemplateKWAndArgsInfo ? 1 : 0,
404 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000405
Chris Lattner5c0b4052010-10-30 05:14:06 +0000406 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Daniel Dunbar9d355812012-03-09 01:51:51 +0000407 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000408 RefersToEnclosingVariableOrCapture,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000409 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000410}
411
Craig Topperce7167c2013-08-22 04:58:56 +0000412DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000413 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000414 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000415 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000416 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000417 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
418 std::size_t Size =
419 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
420 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
421 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
422 NumTemplateArgs);
Chris Lattner5c0b4052010-10-30 05:14:06 +0000423 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000424 return new (Mem) DeclRefExpr(EmptyShell());
425}
426
Daniel Dunbarb507f272012-03-09 15:39:15 +0000427SourceLocation DeclRefExpr::getLocStart() const {
428 if (hasQualifier())
429 return getQualifierLoc().getBeginLoc();
430 return getNameInfo().getLocStart();
431}
432SourceLocation DeclRefExpr::getLocEnd() const {
433 if (hasExplicitTemplateArgs())
434 return getRAngleLoc();
435 return getNameInfo().getLocEnd();
436}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000437
Alexey Bataevec474782014-10-09 08:45:04 +0000438PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
439 StringLiteral *SL)
440 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
441 FNTy->isDependentType(), FNTy->isDependentType(),
442 FNTy->isInstantiationDependentType(),
443 /*ContainsUnexpandedParameterPack=*/false),
444 Loc(L), Type(IT), FnName(SL) {}
445
446StringLiteral *PredefinedExpr::getFunctionName() {
Alexey Bataev769562a2014-10-10 18:58:13 +0000447 return cast_or_null<StringLiteral>(FnName);
Alexey Bataevec474782014-10-09 08:45:04 +0000448}
449
450StringRef PredefinedExpr::getIdentTypeName(PredefinedExpr::IdentType IT) {
451 switch (IT) {
452 case Func:
453 return "__func__";
454 case Function:
455 return "__FUNCTION__";
456 case FuncDName:
457 return "__FUNCDNAME__";
458 case LFunction:
459 return "L__FUNCTION__";
460 case PrettyFunction:
461 return "__PRETTY_FUNCTION__";
462 case FuncSig:
463 return "__FUNCSIG__";
464 case PrettyFunctionNoVirtual:
465 break;
466 }
467 llvm_unreachable("Unknown ident type for PredefinedExpr");
468}
469
Anders Carlsson2fb08242009-09-08 18:24:21 +0000470// FIXME: Maybe this should use DeclPrinter with a special "print predefined
471// expr" policy instead.
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000472std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
473 ASTContext &Context = CurrentDecl->getASTContext();
474
David Majnemerbed356a2013-11-06 23:31:56 +0000475 if (IT == PredefinedExpr::FuncDName) {
476 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000477 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000478 MC.reset(Context.createMangleContext());
479
480 if (MC->shouldMangleDeclName(ND)) {
481 SmallString<256> Buffer;
482 llvm::raw_svector_ostream Out(Buffer);
483 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
484 MC->mangleCXXCtor(CD, Ctor_Base, Out);
485 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
486 MC->mangleCXXDtor(DD, Dtor_Base, Out);
487 else
488 MC->mangleName(ND, Out);
489
David Majnemerbed356a2013-11-06 23:31:56 +0000490 if (!Buffer.empty() && Buffer.front() == '\01')
491 return Buffer.substr(1);
492 return Buffer.str();
493 } else
494 return ND->getIdentifier()->getName();
495 }
496 return "";
497 }
Alexey Bataevec474782014-10-09 08:45:04 +0000498 if (auto *BD = dyn_cast<BlockDecl>(CurrentDecl)) {
499 std::unique_ptr<MangleContext> MC;
500 MC.reset(Context.createMangleContext());
501 SmallString<256> Buffer;
502 llvm::raw_svector_ostream Out(Buffer);
503 auto DC = CurrentDecl->getDeclContext();
504 if (DC->isFileContext())
505 MC->mangleGlobalBlock(BD, /*ID*/ nullptr, Out);
506 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
507 MC->mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, Out);
508 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
509 MC->mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, Out);
510 else
511 MC->mangleBlock(DC, BD, Out);
512 return Out.str();
513 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000514 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000515 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual && IT != FuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000516 return FD->getNameAsString();
517
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000518 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000519 llvm::raw_svector_ostream Out(Name);
520
521 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000522 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000523 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000524 if (MD->isStatic())
525 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000526 }
527
David Blaikiebbafb8a2012-03-11 07:00:24 +0000528 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000529 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000530 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000531
Douglas Gregor11a434a2012-04-10 20:14:15 +0000532 const FunctionDecl *Decl = FD;
533 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
534 Decl = Pattern;
535 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000536 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000537 if (FD->hasWrittenPrototype())
538 FT = dyn_cast<FunctionProtoType>(AFT);
539
Reid Kleckner52eddda2014-04-08 18:13:24 +0000540 if (IT == FuncSig) {
541 switch (FT->getCallConv()) {
542 case CC_C: POut << "__cdecl "; break;
543 case CC_X86StdCall: POut << "__stdcall "; break;
544 case CC_X86FastCall: POut << "__fastcall "; break;
545 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000546 case CC_X86VectorCall: POut << "__vectorcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000547 // Only bother printing the conventions that MSVC knows about.
548 default: break;
549 }
550 }
551
552 FD->printQualifiedName(POut, Policy);
553
Douglas Gregor11a434a2012-04-10 20:14:15 +0000554 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000555 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000556 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000557 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000558 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000559 }
560
561 if (FT->isVariadic()) {
562 if (FD->getNumParams()) POut << ", ";
563 POut << "...";
564 }
565 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000566 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000567
Sam Weinig4e83bd22009-12-27 01:38:20 +0000568 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Argyrios Kyrtzidis53e3d6d2012-12-14 19:44:11 +0000569 const FunctionType *FT = MD->getType()->castAs<FunctionType>();
David Blaikief5697e52012-08-10 00:55:35 +0000570 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000571 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000572 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000573 POut << " volatile";
574 RefQualifierKind Ref = MD->getRefQualifier();
575 if (Ref == RQ_LValue)
576 POut << " &";
577 else if (Ref == RQ_RValue)
578 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000579 }
580
Douglas Gregor11a434a2012-04-10 20:14:15 +0000581 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
582 SpecsTy Specs;
583 const DeclContext *Ctx = FD->getDeclContext();
584 while (Ctx && isa<NamedDecl>(Ctx)) {
585 const ClassTemplateSpecializationDecl *Spec
586 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
587 if (Spec && !Spec->isExplicitSpecialization())
588 Specs.push_back(Spec);
589 Ctx = Ctx->getParent();
590 }
591
592 std::string TemplateParams;
593 llvm::raw_string_ostream TOut(TemplateParams);
594 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
595 I != E; ++I) {
596 const TemplateParameterList *Params
597 = (*I)->getSpecializedTemplate()->getTemplateParameters();
598 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
599 assert(Params->size() == Args.size());
600 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
601 StringRef Param = Params->getParam(i)->getName();
602 if (Param.empty()) continue;
603 TOut << Param << " = ";
604 Args.get(i).print(Policy, TOut);
605 TOut << ", ";
606 }
607 }
608
609 FunctionTemplateSpecializationInfo *FSI
610 = FD->getTemplateSpecializationInfo();
611 if (FSI && !FSI->isExplicitSpecialization()) {
612 const TemplateParameterList* Params
613 = FSI->getTemplate()->getTemplateParameters();
614 const TemplateArgumentList* Args = FSI->TemplateArguments;
615 assert(Params->size() == Args->size());
616 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
617 StringRef Param = Params->getParam(i)->getName();
618 if (Param.empty()) continue;
619 TOut << Param << " = ";
620 Args->get(i).print(Policy, TOut);
621 TOut << ", ";
622 }
623 }
624
625 TOut.flush();
626 if (!TemplateParams.empty()) {
627 // remove the trailing comma and space
628 TemplateParams.resize(TemplateParams.size() - 2);
629 POut << " [" << TemplateParams << "]";
630 }
631
632 POut.flush();
633
Benjamin Kramer90f54222013-08-21 11:45:27 +0000634 // Print "auto" for all deduced return types. This includes C++1y return
635 // type deduction and lambdas. For trailing return types resolve the
636 // decltype expression. Otherwise print the real type when this is
637 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000638 if (isa<CXXMethodDecl>(FD) &&
639 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000640 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000641 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
642 FT->getReturnType()
643 ->getAs<DecltypeType>()
644 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000645 .getAsStringInternal(Proto, Policy);
646 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000647 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000648
649 Out << Proto;
650
Anders Carlsson2fb08242009-09-08 18:24:21 +0000651 return Name.str().str();
652 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000653 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
654 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
655 // Skip to its enclosing function or method, but not its enclosing
656 // CapturedDecl.
657 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
658 const Decl *D = Decl::castFromDeclContext(DC);
659 return ComputeName(IT, D);
660 }
661 llvm_unreachable("CapturedDecl not inside a function or method");
662 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000663 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000664 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000665 llvm::raw_svector_ostream Out(Name);
666 Out << (MD->isInstanceMethod() ? '-' : '+');
667 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000668
669 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
670 // a null check to avoid a crash.
671 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000672 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000673
Anders Carlsson2fb08242009-09-08 18:24:21 +0000674 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000675 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000676 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000677
Anders Carlsson2fb08242009-09-08 18:24:21 +0000678 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000679 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000680 Out << ']';
681
Anders Carlsson2fb08242009-09-08 18:24:21 +0000682 return Name.str().str();
683 }
684 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
685 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
686 return "top level";
687 }
688 return "";
689}
690
Craig Topper37932912013-08-18 10:09:15 +0000691void APNumericStorage::setIntValue(const ASTContext &C,
692 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000693 if (hasAllocation())
694 C.Deallocate(pVal);
695
696 BitWidth = Val.getBitWidth();
697 unsigned NumWords = Val.getNumWords();
698 const uint64_t* Words = Val.getRawData();
699 if (NumWords > 1) {
700 pVal = new (C) uint64_t[NumWords];
701 std::copy(Words, Words + NumWords, pVal);
702 } else if (NumWords == 1)
703 VAL = Words[0];
704 else
705 VAL = 0;
706}
707
Craig Topper37932912013-08-18 10:09:15 +0000708IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000709 QualType type, SourceLocation l)
710 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
711 false, false),
712 Loc(l) {
713 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
714 assert(V.getBitWidth() == C.getIntWidth(type) &&
715 "Integer type is not the correct size for constant.");
716 setValue(C, V);
717}
718
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000719IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000720IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000721 QualType type, SourceLocation l) {
722 return new (C) IntegerLiteral(C, V, type, l);
723}
724
725IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000726IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000727 return new (C) IntegerLiteral(Empty);
728}
729
Craig Topper37932912013-08-18 10:09:15 +0000730FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000731 bool isexact, QualType Type, SourceLocation L)
732 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
733 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000734 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000735 FloatingLiteralBits.IsExact = isexact;
736 setValue(C, V);
737}
738
Craig Topper37932912013-08-18 10:09:15 +0000739FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000740 : Expr(FloatingLiteralClass, Empty) {
Tim Northover178723a2013-01-22 09:46:51 +0000741 setRawSemantics(IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000742 FloatingLiteralBits.IsExact = false;
743}
744
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000745FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000746FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000747 bool isexact, QualType Type, SourceLocation L) {
748 return new (C) FloatingLiteral(C, V, isexact, Type, L);
749}
750
751FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000752FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000753 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000754}
755
Tim Northover178723a2013-01-22 09:46:51 +0000756const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
757 switch(FloatingLiteralBits.Semantics) {
758 case IEEEhalf:
759 return llvm::APFloat::IEEEhalf;
760 case IEEEsingle:
761 return llvm::APFloat::IEEEsingle;
762 case IEEEdouble:
763 return llvm::APFloat::IEEEdouble;
764 case x87DoubleExtended:
765 return llvm::APFloat::x87DoubleExtended;
766 case IEEEquad:
767 return llvm::APFloat::IEEEquad;
768 case PPCDoubleDouble:
769 return llvm::APFloat::PPCDoubleDouble;
770 }
771 llvm_unreachable("Unrecognised floating semantics");
772}
773
774void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
775 if (&Sem == &llvm::APFloat::IEEEhalf)
776 FloatingLiteralBits.Semantics = IEEEhalf;
777 else if (&Sem == &llvm::APFloat::IEEEsingle)
778 FloatingLiteralBits.Semantics = IEEEsingle;
779 else if (&Sem == &llvm::APFloat::IEEEdouble)
780 FloatingLiteralBits.Semantics = IEEEdouble;
781 else if (&Sem == &llvm::APFloat::x87DoubleExtended)
782 FloatingLiteralBits.Semantics = x87DoubleExtended;
783 else if (&Sem == &llvm::APFloat::IEEEquad)
784 FloatingLiteralBits.Semantics = IEEEquad;
785 else if (&Sem == &llvm::APFloat::PPCDoubleDouble)
786 FloatingLiteralBits.Semantics = PPCDoubleDouble;
787 else
788 llvm_unreachable("Unknown floating semantics");
789}
790
Chris Lattnera0173132008-06-07 22:13:43 +0000791/// getValueAsApproximateDouble - This returns the value as an inaccurate
792/// double. Note that this may cause loss of precision, but is useful for
793/// debugging dumps, etc.
794double FloatingLiteral::getValueAsApproximateDouble() const {
795 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000796 bool ignored;
797 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
798 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000799 return V.convertToDouble();
800}
801
Nick Lewycky4ed84042012-02-24 09:07:53 +0000802int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
Eli Friedman381f4312012-02-29 20:59:56 +0000803 int CharByteWidth = 0;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000804 switch(k) {
Eli Friedmanfcec6302011-11-01 02:23:42 +0000805 case Ascii:
806 case UTF8:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000807 CharByteWidth = target.getCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000808 break;
809 case Wide:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000810 CharByteWidth = target.getWCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000811 break;
812 case UTF16:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000813 CharByteWidth = target.getChar16Width();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000814 break;
815 case UTF32:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000816 CharByteWidth = target.getChar32Width();
Eli Friedman381f4312012-02-29 20:59:56 +0000817 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000818 }
819 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
820 CharByteWidth /= 8;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000821 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
Eli Friedmanfcec6302011-11-01 02:23:42 +0000822 && "character byte widths supported are 1, 2, and 4 only");
823 return CharByteWidth;
824}
825
Craig Topper37932912013-08-18 10:09:15 +0000826StringLiteral *StringLiteral::Create(const ASTContext &C, StringRef Str,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000827 StringKind Kind, bool Pascal, QualType Ty,
Mike Stump11289f42009-09-09 15:08:12 +0000828 const SourceLocation *Loc,
Anders Carlssona3905812009-03-15 18:34:13 +0000829 unsigned NumStrs) {
Benjamin Kramercdac7612014-02-25 12:26:20 +0000830 assert(C.getAsConstantArrayType(Ty) &&
831 "StringLiteral must be of constant array type!");
832
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000833 // Allocate enough space for the StringLiteral plus an array of locations for
834 // any concatenated string tokens.
835 void *Mem = C.Allocate(sizeof(StringLiteral)+
836 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner5c0b4052010-10-30 05:14:06 +0000837 llvm::alignOf<StringLiteral>());
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000838 StringLiteral *SL = new (Mem) StringLiteral(Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000839
Steve Naroffdf7855b2007-02-21 23:46:25 +0000840 // OPTIMIZE: could allocate this appended to the StringLiteral.
Eli Friedmanfcec6302011-11-01 02:23:42 +0000841 SL->setString(C,Str,Kind,Pascal);
842
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000843 SL->TokLocs[0] = Loc[0];
844 SL->NumConcatenated = NumStrs;
Chris Lattnerd3e98952006-10-06 05:22:26 +0000845
Chris Lattner630970d2009-02-18 05:49:11 +0000846 if (NumStrs != 1)
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000847 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
848 return SL;
Chris Lattner630970d2009-02-18 05:49:11 +0000849}
850
Craig Topper37932912013-08-18 10:09:15 +0000851StringLiteral *StringLiteral::CreateEmpty(const ASTContext &C,
852 unsigned NumStrs) {
Douglas Gregor958dfc92009-04-15 16:35:07 +0000853 void *Mem = C.Allocate(sizeof(StringLiteral)+
854 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner5c0b4052010-10-30 05:14:06 +0000855 llvm::alignOf<StringLiteral>());
Douglas Gregor958dfc92009-04-15 16:35:07 +0000856 StringLiteral *SL = new (Mem) StringLiteral(QualType());
Eli Friedmanfcec6302011-11-01 02:23:42 +0000857 SL->CharByteWidth = 0;
858 SL->Length = 0;
Douglas Gregor958dfc92009-04-15 16:35:07 +0000859 SL->NumConcatenated = NumStrs;
860 return SL;
861}
862
Alexander Kornienko540bacb2013-02-01 12:35:51 +0000863void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +0000864 switch (getKind()) {
865 case Ascii: break; // no prefix.
866 case Wide: OS << 'L'; break;
867 case UTF8: OS << "u8"; break;
868 case UTF16: OS << 'u'; break;
869 case UTF32: OS << 'U'; break;
870 }
871 OS << '"';
872 static const char Hex[] = "0123456789ABCDEF";
873
874 unsigned LastSlashX = getLength();
875 for (unsigned I = 0, N = getLength(); I != N; ++I) {
876 switch (uint32_t Char = getCodeUnit(I)) {
877 default:
878 // FIXME: Convert UTF-8 back to codepoints before rendering.
879
880 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
881 // Leave invalid surrogates alone; we'll use \x for those.
882 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
883 Char <= 0xdbff) {
884 uint32_t Trail = getCodeUnit(I + 1);
885 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
886 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
887 ++I;
888 }
889 }
890
891 if (Char > 0xff) {
892 // If this is a wide string, output characters over 0xff using \x
893 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
894 // codepoint: use \x escapes for invalid codepoints.
895 if (getKind() == Wide ||
896 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
897 // FIXME: Is this the best way to print wchar_t?
898 OS << "\\x";
899 int Shift = 28;
900 while ((Char >> Shift) == 0)
901 Shift -= 4;
902 for (/**/; Shift >= 0; Shift -= 4)
903 OS << Hex[(Char >> Shift) & 15];
904 LastSlashX = I;
905 break;
906 }
907
908 if (Char > 0xffff)
909 OS << "\\U00"
910 << Hex[(Char >> 20) & 15]
911 << Hex[(Char >> 16) & 15];
912 else
913 OS << "\\u";
914 OS << Hex[(Char >> 12) & 15]
915 << Hex[(Char >> 8) & 15]
916 << Hex[(Char >> 4) & 15]
917 << Hex[(Char >> 0) & 15];
918 break;
919 }
920
921 // If we used \x... for the previous character, and this character is a
922 // hexadecimal digit, prevent it being slurped as part of the \x.
923 if (LastSlashX + 1 == I) {
924 switch (Char) {
925 case '0': case '1': case '2': case '3': case '4':
926 case '5': case '6': case '7': case '8': case '9':
927 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
928 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
929 OS << "\"\"";
930 }
931 }
932
933 assert(Char <= 0xff &&
934 "Characters above 0xff should already have been handled.");
935
Jordan Rosea7d03842013-02-08 22:30:41 +0000936 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +0000937 OS << (char)Char;
938 else // Output anything hard as an octal escape.
939 OS << '\\'
940 << (char)('0' + ((Char >> 6) & 7))
941 << (char)('0' + ((Char >> 3) & 7))
942 << (char)('0' + ((Char >> 0) & 7));
943 break;
944 // Handle some common non-printable cases to make dumps prettier.
945 case '\\': OS << "\\\\"; break;
946 case '"': OS << "\\\""; break;
947 case '\n': OS << "\\n"; break;
948 case '\t': OS << "\\t"; break;
949 case '\a': OS << "\\a"; break;
950 case '\b': OS << "\\b"; break;
951 }
952 }
953 OS << '"';
954}
955
Craig Topper37932912013-08-18 10:09:15 +0000956void StringLiteral::setString(const ASTContext &C, StringRef Str,
Eli Friedmanfcec6302011-11-01 02:23:42 +0000957 StringKind Kind, bool IsPascal) {
958 //FIXME: we assume that the string data comes from a target that uses the same
959 // code unit size and endianess for the type of string.
960 this->Kind = Kind;
961 this->IsPascal = IsPascal;
962
Nick Lewycky4ed84042012-02-24 09:07:53 +0000963 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
Eli Friedmanfcec6302011-11-01 02:23:42 +0000964 assert((Str.size()%CharByteWidth == 0)
965 && "size of data must be multiple of CharByteWidth");
966 Length = Str.size()/CharByteWidth;
967
968 switch(CharByteWidth) {
969 case 1: {
970 char *AStrData = new (C) char[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +0000971 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000972 StrData.asChar = AStrData;
973 break;
974 }
975 case 2: {
976 uint16_t *AStrData = new (C) uint16_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +0000977 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000978 StrData.asUInt16 = AStrData;
979 break;
980 }
981 case 4: {
982 uint32_t *AStrData = new (C) uint32_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +0000983 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000984 StrData.asUInt32 = AStrData;
985 break;
986 }
987 default:
Davide Italiano04839a52016-01-30 08:03:54 +0000988 llvm_unreachable("unsupported CharByteWidth");
Eli Friedmanfcec6302011-11-01 02:23:42 +0000989 }
Douglas Gregor958dfc92009-04-15 16:35:07 +0000990}
991
Chris Lattnere925d612010-11-17 07:37:15 +0000992/// getLocationOfByte - Return a source location that points to the specified
993/// byte of this string literal.
994///
995/// Strings are amazingly complex. They can be formed from multiple tokens and
996/// can have escape sequences in them in addition to the usual trigraph and
997/// escaped newline business. This routine handles this complexity.
998///
Richard Smithefb116f2015-12-10 01:11:47 +0000999/// The *StartToken sets the first token to be searched in this function and
1000/// the *StartTokenByteOffset is the byte offset of the first token. Before
1001/// returning, it updates the *StartToken to the TokNo of the token being found
1002/// and sets *StartTokenByteOffset to the byte offset of the token in the
1003/// string.
1004/// Using these two parameters can reduce the time complexity from O(n^2) to
1005/// O(n) if one wants to get the location of byte for all the tokens in a
1006/// string.
1007///
1008SourceLocation
1009StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1010 const LangOptions &Features,
1011 const TargetInfo &Target, unsigned *StartToken,
1012 unsigned *StartTokenByteOffset) const {
Richard Smith4060f772012-06-13 05:37:23 +00001013 assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
1014 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001015
Chris Lattnere925d612010-11-17 07:37:15 +00001016 // Loop over all of the tokens in this string until we find the one that
1017 // contains the byte we're looking for.
1018 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001019 unsigned StringOffset = 0;
1020 if (StartToken)
1021 TokNo = *StartToken;
1022 if (StartTokenByteOffset) {
1023 StringOffset = *StartTokenByteOffset;
1024 ByteNo -= StringOffset;
1025 }
Chris Lattnere925d612010-11-17 07:37:15 +00001026 while (1) {
1027 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1028 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1029
1030 // Get the spelling of the string so that we can get the data that makes up
1031 // the string literal, not the identifier for the macro it is potentially
1032 // expanded through.
1033 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001034
Chris Lattnere925d612010-11-17 07:37:15 +00001035 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001036 std::pair<FileID, unsigned> LocInfo =
1037 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001038 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001039 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001040 if (Invalid) {
1041 if (StartTokenByteOffset != nullptr)
1042 *StartTokenByteOffset = StringOffset;
1043 if (StartToken != nullptr)
1044 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001045 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001046 }
1047
Chris Lattnere925d612010-11-17 07:37:15 +00001048 const char *StrData = Buffer.data()+LocInfo.second;
1049
Chris Lattnere925d612010-11-17 07:37:15 +00001050 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001051 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1052 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001053 Token TheTok;
1054 TheLexer.LexFromRawLexer(TheTok);
1055
1056 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001057 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001058 unsigned TokNumBytes = SLP.GetStringLength();
1059
1060 // If the byte is in this token, return the location of the byte.
1061 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001062 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001063 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1064
Chris Lattnere925d612010-11-17 07:37:15 +00001065 // Now that we know the offset of the token in the spelling, use the
1066 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001067 if (StartTokenByteOffset != nullptr)
1068 *StartTokenByteOffset = StringOffset;
1069 if (StartToken != nullptr)
1070 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001071 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1072 }
Richard Smithefb116f2015-12-10 01:11:47 +00001073
Chris Lattnere925d612010-11-17 07:37:15 +00001074 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001075 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001076 ++TokNo;
1077 ByteNo -= TokNumBytes;
1078 }
1079}
1080
1081
1082
Chris Lattner1b926492006-08-23 06:42:10 +00001083/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1084/// corresponds to, e.g. "sizeof" or "[pre]++".
David Blaikie1d202a62012-10-08 01:11:04 +00001085StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001086 switch (Op) {
John McCalle3027922010-08-25 11:45:40 +00001087 case UO_PostInc: return "++";
1088 case UO_PostDec: return "--";
1089 case UO_PreInc: return "++";
1090 case UO_PreDec: return "--";
1091 case UO_AddrOf: return "&";
1092 case UO_Deref: return "*";
1093 case UO_Plus: return "+";
1094 case UO_Minus: return "-";
1095 case UO_Not: return "~";
1096 case UO_LNot: return "!";
1097 case UO_Real: return "__real";
1098 case UO_Imag: return "__imag";
1099 case UO_Extension: return "__extension__";
Richard Smith9f690bd2015-10-27 06:02:45 +00001100 case UO_Coawait: return "co_await";
Chris Lattner1b926492006-08-23 06:42:10 +00001101 }
David Blaikief47fa302012-01-17 02:30:50 +00001102 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001103}
1104
John McCalle3027922010-08-25 11:45:40 +00001105UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001106UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1107 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001108 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001109 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1110 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1111 case OO_Amp: return UO_AddrOf;
1112 case OO_Star: return UO_Deref;
1113 case OO_Plus: return UO_Plus;
1114 case OO_Minus: return UO_Minus;
1115 case OO_Tilde: return UO_Not;
1116 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001117 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001118 }
1119}
1120
1121OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1122 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001123 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1124 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1125 case UO_AddrOf: return OO_Amp;
1126 case UO_Deref: return OO_Star;
1127 case UO_Plus: return OO_Plus;
1128 case UO_Minus: return OO_Minus;
1129 case UO_Not: return OO_Tilde;
1130 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001131 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001132 default: return OO_None;
1133 }
1134}
1135
1136
Chris Lattner0eedafe2006-08-24 04:56:27 +00001137//===----------------------------------------------------------------------===//
1138// Postfix Operators.
1139//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001140
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001141CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1142 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
Craig Topper37932912013-08-18 10:09:15 +00001143 ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001144 : Expr(SC, t, VK, OK_Ordinary, fn->isTypeDependent(),
1145 fn->isValueDependent(), fn->isInstantiationDependent(),
1146 fn->containsUnexpandedParameterPack()),
1147 NumArgs(args.size()) {
Mike Stump11289f42009-09-09 15:08:12 +00001148
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001149 unsigned NumPreArgs = preargs.size();
1150 SubExprs = new (C) Stmt *[args.size()+PREARGS_START+NumPreArgs];
Douglas Gregor993603d2008-11-14 16:09:21 +00001151 SubExprs[FN] = fn;
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001152 for (unsigned i = 0; i != NumPreArgs; ++i) {
1153 updateDependenciesFromArg(preargs[i]);
1154 SubExprs[i+PREARGS_START] = preargs[i];
1155 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00001156 for (unsigned i = 0; i != args.size(); ++i) {
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001157 updateDependenciesFromArg(args[i]);
Peter Collingbourne3a347252011-02-08 21:18:02 +00001158 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00001159 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001160
Peter Collingbourne3a347252011-02-08 21:18:02 +00001161 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor993603d2008-11-14 16:09:21 +00001162 RParenLoc = rparenloc;
1163}
Nate Begeman1e36a852008-01-17 17:46:27 +00001164
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001165CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1166 ArrayRef<Expr *> args, QualType t, ExprValueKind VK,
1167 SourceLocation rparenloc)
1168 : CallExpr(C, SC, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {}
1169
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001170CallExpr::CallExpr(const ASTContext &C, Expr *fn, ArrayRef<Expr *> args,
John McCall7decc9e2010-11-18 06:31:45 +00001171 QualType t, ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001172 : CallExpr(C, CallExprClass, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {
Chris Lattnere165d942006-08-24 04:40:38 +00001173}
1174
Craig Topper37932912013-08-18 10:09:15 +00001175CallExpr::CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001176 : CallExpr(C, SC, /*NumPreArgs=*/0, Empty) {}
Peter Collingbourne3a347252011-02-08 21:18:02 +00001177
Craig Topper37932912013-08-18 10:09:15 +00001178CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
Peter Collingbourne3a347252011-02-08 21:18:02 +00001179 EmptyShell Empty)
Craig Topper36250ad2014-05-12 05:36:57 +00001180 : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001181 // FIXME: Why do we allocate this?
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001182 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs]();
Peter Collingbourne3a347252011-02-08 21:18:02 +00001183 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregore20a2e52009-04-15 17:43:59 +00001184}
1185
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001186void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1187 if (Arg->isTypeDependent())
1188 ExprBits.TypeDependent = true;
1189 if (Arg->isValueDependent())
1190 ExprBits.ValueDependent = true;
1191 if (Arg->isInstantiationDependent())
1192 ExprBits.InstantiationDependent = true;
1193 if (Arg->containsUnexpandedParameterPack())
1194 ExprBits.ContainsUnexpandedParameterPack = true;
1195}
1196
Nuno Lopes518e3702009-12-20 23:11:08 +00001197Decl *CallExpr::getCalleeDecl() {
John McCalle3ca8eb2011-09-13 23:08:34 +00001198 Expr *CEE = getCallee()->IgnoreParenImpCasts();
Douglas Gregore0e96302011-09-06 21:41:04 +00001199
1200 while (SubstNonTypeTemplateParmExpr *NTTP
1201 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1202 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1203 }
1204
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001205 // If we're calling a dereference, look at the pointer instead.
1206 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1207 if (BO->isPtrMemOp())
1208 CEE = BO->getRHS()->IgnoreParenCasts();
1209 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1210 if (UO->getOpcode() == UO_Deref)
1211 CEE = UO->getSubExpr()->IgnoreParenCasts();
1212 }
Chris Lattner52301912009-07-17 15:46:27 +00001213 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001214 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001215 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1216 return ME->getMemberDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001217
Craig Topper36250ad2014-05-12 05:36:57 +00001218 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001219}
1220
Nuno Lopes518e3702009-12-20 23:11:08 +00001221FunctionDecl *CallExpr::getDirectCallee() {
Chris Lattner3a6af3d2009-12-21 01:10:56 +00001222 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
Nuno Lopes518e3702009-12-20 23:11:08 +00001223}
1224
Chris Lattnere4407ed2007-12-28 05:25:02 +00001225/// setNumArgs - This changes the number of arguments present in this call.
1226/// Any orphaned expressions are deleted by this, and any new operands are set
1227/// to null.
Craig Topper37932912013-08-18 10:09:15 +00001228void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001229 // No change, just return.
1230 if (NumArgs == getNumArgs()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001231
Chris Lattnere4407ed2007-12-28 05:25:02 +00001232 // If shrinking # arguments, just delete the extras and forgot them.
1233 if (NumArgs < getNumArgs()) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001234 this->NumArgs = NumArgs;
1235 return;
1236 }
1237
1238 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001239 unsigned NumPreArgs = getNumPreArgs();
1240 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnere4407ed2007-12-28 05:25:02 +00001241 // Copy over args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001242 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnere4407ed2007-12-28 05:25:02 +00001243 NewSubExprs[i] = SubExprs[i];
1244 // Null out new args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001245 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1246 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001247 NewSubExprs[i] = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001248
Douglas Gregorba6e5572009-04-17 21:46:47 +00001249 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnere4407ed2007-12-28 05:25:02 +00001250 SubExprs = NewSubExprs;
1251 this->NumArgs = NumArgs;
1252}
1253
Alp Tokera724cff2013-12-28 21:59:02 +00001254/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001255/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001256unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001257 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001258 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001259 // ImplicitCastExpr.
1260 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1261 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001262 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001263
Steve Narofff6e3b3292008-01-31 01:07:12 +00001264 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1265 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001266 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001267
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001268 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1269 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001270 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001271
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001272 if (!FDecl->getIdentifier())
1273 return 0;
1274
Douglas Gregor15fc9562009-09-12 00:22:50 +00001275 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001276}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001277
Scott Douglass503fc392015-06-10 13:53:15 +00001278bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001279 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001280 return Ctx.BuiltinInfo.isUnevaluated(BI);
1281 return false;
1282}
1283
David Majnemerced8bdf2015-02-25 17:36:15 +00001284QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1285 const Expr *Callee = getCallee();
1286 QualType CalleeType = Callee->getType();
1287 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001288 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001289 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001290 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001291 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1292 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1293 return Ctx.VoidTy;
1294
John McCall0009fcc2011-04-26 20:42:42 +00001295 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001296 CalleeType = Expr::findBoundMemberType(Callee);
1297 }
1298
John McCall0009fcc2011-04-26 20:42:42 +00001299 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001300 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001301}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001302
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001303SourceLocation CallExpr::getLocStart() const {
1304 if (isa<CXXOperatorCallExpr>(this))
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001305 return cast<CXXOperatorCallExpr>(this)->getLocStart();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001306
1307 SourceLocation begin = getCallee()->getLocStart();
Keno Fischer070db172014-08-15 01:39:12 +00001308 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001309 begin = getArg(0)->getLocStart();
1310 return begin;
1311}
1312SourceLocation CallExpr::getLocEnd() const {
1313 if (isa<CXXOperatorCallExpr>(this))
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001314 return cast<CXXOperatorCallExpr>(this)->getLocEnd();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001315
1316 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001317 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001318 end = getArg(getNumArgs() - 1)->getLocEnd();
1319 return end;
1320}
John McCall701417a2011-02-21 06:23:05 +00001321
Craig Topper37932912013-08-18 10:09:15 +00001322OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001323 SourceLocation OperatorLoc,
Alexis Hunta8136cc2010-05-05 15:23:54 +00001324 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001325 ArrayRef<OffsetOfNode> comps,
1326 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001327 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001328 void *Mem = C.Allocate(
1329 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001330
Benjamin Kramerc215e762012-08-24 11:54:20 +00001331 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1332 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001333}
1334
Craig Topper37932912013-08-18 10:09:15 +00001335OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001336 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001337 void *Mem =
1338 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001339 return new (Mem) OffsetOfExpr(numComps, numExprs);
1340}
1341
Craig Topper37932912013-08-18 10:09:15 +00001342OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001343 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001344 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001345 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001346 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1347 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001348 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001349 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001350 tsi->getType()->containsUnexpandedParameterPack()),
Alexis Hunta8136cc2010-05-05 15:23:54 +00001351 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001352 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001353{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001354 for (unsigned i = 0; i != comps.size(); ++i) {
1355 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001356 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001357
Benjamin Kramerc215e762012-08-24 11:54:20 +00001358 for (unsigned i = 0; i != exprs.size(); ++i) {
1359 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001360 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001361 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001362 ExprBits.ContainsUnexpandedParameterPack = true;
1363
Benjamin Kramerc215e762012-08-24 11:54:20 +00001364 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001365 }
1366}
1367
James Y Knight7281c352015-12-29 22:31:18 +00001368IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001369 assert(getKind() == Field || getKind() == Identifier);
1370 if (getKind() == Field)
1371 return getField()->getIdentifier();
Alexis Hunta8136cc2010-05-05 15:23:54 +00001372
Douglas Gregor882211c2010-04-28 22:16:22 +00001373 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1374}
1375
David Majnemer10fd83d2015-01-15 10:04:14 +00001376UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1377 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1378 SourceLocation op, SourceLocation rp)
1379 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1380 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1381 // Value-dependent if the argument is type-dependent.
1382 E->isTypeDependent(), E->isInstantiationDependent(),
1383 E->containsUnexpandedParameterPack()),
1384 OpLoc(op), RParenLoc(rp) {
1385 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1386 UnaryExprOrTypeTraitExprBits.IsType = false;
1387 Argument.Ex = E;
1388
1389 // Check to see if we are in the situation where alignof(decl) should be
1390 // dependent because decl's alignment is dependent.
1391 if (ExprKind == UETT_AlignOf) {
1392 if (!isValueDependent() || !isInstantiationDependent()) {
1393 E = E->IgnoreParens();
1394
1395 const ValueDecl *D = nullptr;
1396 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1397 D = DRE->getDecl();
1398 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1399 D = ME->getMemberDecl();
1400
1401 if (D) {
1402 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1403 if (I->isAlignmentDependent()) {
1404 setValueDependent(true);
1405 setInstantiationDependent(true);
1406 break;
1407 }
1408 }
1409 }
1410 }
1411 }
1412}
1413
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001414MemberExpr *MemberExpr::Create(
1415 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1416 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1417 ValueDecl *memberdecl, DeclAccessPair founddecl,
1418 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1419 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
John McCall16df1e52010-03-30 21:47:33 +00001420
Douglas Gregorea972d32011-02-28 21:54:11 +00001421 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001422 founddecl.getDecl() != memberdecl ||
1423 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001424
James Y Knighte7d82282015-12-29 18:15:14 +00001425 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1426 std::size_t Size =
1427 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1428 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1429 HasTemplateKWAndArgsInfo ? 1 : 0,
1430 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001431
Chris Lattner5c0b4052010-10-30 05:14:06 +00001432 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001433 MemberExpr *E = new (Mem)
1434 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001435
1436 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001437 // FIXME: Wrong. We should be looking at the member declaration we found.
1438 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001439 E->setValueDependent(true);
1440 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001441 E->setInstantiationDependent(true);
1442 }
1443 else if (QualifierLoc &&
1444 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1445 E->setInstantiationDependent(true);
1446
John McCall16df1e52010-03-30 21:47:33 +00001447 E->HasQualifierOrFoundDecl = true;
1448
James Y Knighte7d82282015-12-29 18:15:14 +00001449 MemberExprNameQualifier *NQ =
1450 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001451 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001452 NQ->FoundDecl = founddecl;
1453 }
1454
Abramo Bagnara7945c982012-01-27 09:46:47 +00001455 E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1456
John McCall16df1e52010-03-30 21:47:33 +00001457 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001458 bool Dependent = false;
1459 bool InstantiationDependent = false;
1460 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001461 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1462 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1463 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001464 if (InstantiationDependent)
1465 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001466 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001467 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1468 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001469 }
1470
1471 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001472}
1473
Daniel Dunbarb507f272012-03-09 15:39:15 +00001474SourceLocation MemberExpr::getLocStart() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001475 if (isImplicitAccess()) {
1476 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001477 return getQualifierLoc().getBeginLoc();
1478 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001479 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001480
Daniel Dunbarb507f272012-03-09 15:39:15 +00001481 // FIXME: We don't want this to happen. Rather, we should be able to
1482 // detect all kinds of implicit accesses more cleanly.
1483 SourceLocation BaseStartLoc = getBase()->getLocStart();
1484 if (BaseStartLoc.isValid())
1485 return BaseStartLoc;
1486 return MemberLoc;
1487}
1488SourceLocation MemberExpr::getLocEnd() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001489 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001490 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001491 EndLoc = getRAngleLoc();
1492 else if (EndLoc.isInvalid())
1493 EndLoc = getBase()->getLocEnd();
1494 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001495}
1496
Alp Tokerc1086762013-12-07 13:51:35 +00001497bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001498 switch (getCastKind()) {
1499 case CK_DerivedToBase:
1500 case CK_UncheckedDerivedToBase:
1501 case CK_DerivedToBaseMemberPointer:
1502 case CK_BaseToDerived:
1503 case CK_BaseToDerivedMemberPointer:
1504 assert(!path_empty() && "Cast kind should have a base path!");
1505 break;
1506
1507 case CK_CPointerToObjCPointerCast:
1508 assert(getType()->isObjCObjectPointerType());
1509 assert(getSubExpr()->getType()->isPointerType());
1510 goto CheckNoBasePath;
1511
1512 case CK_BlockPointerToObjCPointerCast:
1513 assert(getType()->isObjCObjectPointerType());
1514 assert(getSubExpr()->getType()->isBlockPointerType());
1515 goto CheckNoBasePath;
1516
John McCallc62bb392012-02-15 01:22:51 +00001517 case CK_ReinterpretMemberPointer:
1518 assert(getType()->isMemberPointerType());
1519 assert(getSubExpr()->getType()->isMemberPointerType());
1520 goto CheckNoBasePath;
1521
John McCall9320b872011-09-09 05:25:32 +00001522 case CK_BitCast:
1523 // Arbitrary casts to C pointer types count as bitcasts.
1524 // Otherwise, we should only have block and ObjC pointer casts
1525 // here if they stay within the type kind.
1526 if (!getType()->isPointerType()) {
1527 assert(getType()->isObjCObjectPointerType() ==
1528 getSubExpr()->getType()->isObjCObjectPointerType());
1529 assert(getType()->isBlockPointerType() ==
1530 getSubExpr()->getType()->isBlockPointerType());
1531 }
1532 goto CheckNoBasePath;
1533
1534 case CK_AnyPointerToBlockPointerCast:
1535 assert(getType()->isBlockPointerType());
1536 assert(getSubExpr()->getType()->isAnyPointerType() &&
1537 !getSubExpr()->getType()->isBlockPointerType());
1538 goto CheckNoBasePath;
1539
Douglas Gregored90df32012-02-22 05:02:47 +00001540 case CK_CopyAndAutoreleaseBlockObject:
1541 assert(getType()->isBlockPointerType());
1542 assert(getSubExpr()->getType()->isBlockPointerType());
1543 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001544
1545 case CK_FunctionToPointerDecay:
1546 assert(getType()->isPointerType());
1547 assert(getSubExpr()->getType()->isFunctionType());
1548 goto CheckNoBasePath;
1549
David Tweede1468322013-12-11 13:39:46 +00001550 case CK_AddressSpaceConversion:
1551 assert(getType()->isPointerType());
1552 assert(getSubExpr()->getType()->isPointerType());
1553 assert(getType()->getPointeeType().getAddressSpace() !=
1554 getSubExpr()->getType()->getPointeeType().getAddressSpace());
John McCall9320b872011-09-09 05:25:32 +00001555 // These should not have an inheritance path.
1556 case CK_Dynamic:
1557 case CK_ToUnion:
1558 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001559 case CK_NullToMemberPointer:
1560 case CK_NullToPointer:
1561 case CK_ConstructorConversion:
1562 case CK_IntegralToPointer:
1563 case CK_PointerToIntegral:
1564 case CK_ToVoid:
1565 case CK_VectorSplat:
1566 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001567 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001568 case CK_IntegralToFloating:
1569 case CK_FloatingToIntegral:
1570 case CK_FloatingCast:
1571 case CK_ObjCObjectLValueCast:
1572 case CK_FloatingRealToComplex:
1573 case CK_FloatingComplexToReal:
1574 case CK_FloatingComplexCast:
1575 case CK_FloatingComplexToIntegralComplex:
1576 case CK_IntegralRealToComplex:
1577 case CK_IntegralComplexToReal:
1578 case CK_IntegralComplexCast:
1579 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001580 case CK_ARCProduceObject:
1581 case CK_ARCConsumeObject:
1582 case CK_ARCReclaimReturnedObject:
1583 case CK_ARCExtendBlockObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001584 case CK_ZeroToOCLEvent:
John McCall9320b872011-09-09 05:25:32 +00001585 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1586 goto CheckNoBasePath;
1587
1588 case CK_Dependent:
1589 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001590 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001591 case CK_AtomicToNonAtomic:
1592 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001593 case CK_PointerToBoolean:
1594 case CK_IntegralToBoolean:
1595 case CK_FloatingToBoolean:
1596 case CK_MemberPointerToBoolean:
1597 case CK_FloatingComplexToBoolean:
1598 case CK_IntegralComplexToBoolean:
1599 case CK_LValueBitCast: // -> bool&
1600 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001601 case CK_BuiltinFnToFnPtr:
John McCall9320b872011-09-09 05:25:32 +00001602 CheckNoBasePath:
1603 assert(path_empty() && "Cast kind should not have a base path!");
1604 break;
1605 }
Alp Tokerc1086762013-12-07 13:51:35 +00001606 return true;
John McCall9320b872011-09-09 05:25:32 +00001607}
1608
Anders Carlsson496335e2009-09-03 00:59:21 +00001609const char *CastExpr::getCastKindName() const {
1610 switch (getCastKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00001611 case CK_Dependent:
1612 return "Dependent";
John McCalle3027922010-08-25 11:45:40 +00001613 case CK_BitCast:
Anders Carlsson496335e2009-09-03 00:59:21 +00001614 return "BitCast";
John McCalle3027922010-08-25 11:45:40 +00001615 case CK_LValueBitCast:
Douglas Gregor51954272010-07-13 23:17:26 +00001616 return "LValueBitCast";
John McCallf3735e02010-12-01 04:43:34 +00001617 case CK_LValueToRValue:
1618 return "LValueToRValue";
John McCalle3027922010-08-25 11:45:40 +00001619 case CK_NoOp:
Anders Carlsson496335e2009-09-03 00:59:21 +00001620 return "NoOp";
John McCalle3027922010-08-25 11:45:40 +00001621 case CK_BaseToDerived:
Anders Carlssona70ad932009-11-12 16:43:42 +00001622 return "BaseToDerived";
John McCalle3027922010-08-25 11:45:40 +00001623 case CK_DerivedToBase:
Anders Carlsson496335e2009-09-03 00:59:21 +00001624 return "DerivedToBase";
John McCalle3027922010-08-25 11:45:40 +00001625 case CK_UncheckedDerivedToBase:
John McCalld9c7c6562010-03-30 23:58:03 +00001626 return "UncheckedDerivedToBase";
John McCalle3027922010-08-25 11:45:40 +00001627 case CK_Dynamic:
Anders Carlsson496335e2009-09-03 00:59:21 +00001628 return "Dynamic";
John McCalle3027922010-08-25 11:45:40 +00001629 case CK_ToUnion:
Anders Carlsson496335e2009-09-03 00:59:21 +00001630 return "ToUnion";
John McCalle3027922010-08-25 11:45:40 +00001631 case CK_ArrayToPointerDecay:
Anders Carlsson496335e2009-09-03 00:59:21 +00001632 return "ArrayToPointerDecay";
John McCalle3027922010-08-25 11:45:40 +00001633 case CK_FunctionToPointerDecay:
Anders Carlsson496335e2009-09-03 00:59:21 +00001634 return "FunctionToPointerDecay";
John McCalle3027922010-08-25 11:45:40 +00001635 case CK_NullToMemberPointer:
Anders Carlsson496335e2009-09-03 00:59:21 +00001636 return "NullToMemberPointer";
John McCalle84af4e2010-11-13 01:35:44 +00001637 case CK_NullToPointer:
1638 return "NullToPointer";
John McCalle3027922010-08-25 11:45:40 +00001639 case CK_BaseToDerivedMemberPointer:
Anders Carlsson496335e2009-09-03 00:59:21 +00001640 return "BaseToDerivedMemberPointer";
John McCalle3027922010-08-25 11:45:40 +00001641 case CK_DerivedToBaseMemberPointer:
Anders Carlsson3f0db2b2009-10-30 00:46:35 +00001642 return "DerivedToBaseMemberPointer";
John McCallc62bb392012-02-15 01:22:51 +00001643 case CK_ReinterpretMemberPointer:
1644 return "ReinterpretMemberPointer";
John McCalle3027922010-08-25 11:45:40 +00001645 case CK_UserDefinedConversion:
Anders Carlsson496335e2009-09-03 00:59:21 +00001646 return "UserDefinedConversion";
John McCalle3027922010-08-25 11:45:40 +00001647 case CK_ConstructorConversion:
Anders Carlsson496335e2009-09-03 00:59:21 +00001648 return "ConstructorConversion";
John McCalle3027922010-08-25 11:45:40 +00001649 case CK_IntegralToPointer:
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001650 return "IntegralToPointer";
John McCalle3027922010-08-25 11:45:40 +00001651 case CK_PointerToIntegral:
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001652 return "PointerToIntegral";
John McCall8cb679e2010-11-15 09:13:47 +00001653 case CK_PointerToBoolean:
1654 return "PointerToBoolean";
John McCalle3027922010-08-25 11:45:40 +00001655 case CK_ToVoid:
Anders Carlssonef918ac2009-10-16 02:35:04 +00001656 return "ToVoid";
John McCalle3027922010-08-25 11:45:40 +00001657 case CK_VectorSplat:
Anders Carlsson43d70f82009-10-16 05:23:41 +00001658 return "VectorSplat";
John McCalle3027922010-08-25 11:45:40 +00001659 case CK_IntegralCast:
Anders Carlsson094c4592009-10-18 18:12:03 +00001660 return "IntegralCast";
George Burgess IVdf1ed002016-01-13 01:52:39 +00001661 case CK_BooleanToSignedIntegral:
1662 return "BooleanToSignedIntegral";
John McCall8cb679e2010-11-15 09:13:47 +00001663 case CK_IntegralToBoolean:
1664 return "IntegralToBoolean";
John McCalle3027922010-08-25 11:45:40 +00001665 case CK_IntegralToFloating:
Anders Carlsson094c4592009-10-18 18:12:03 +00001666 return "IntegralToFloating";
John McCalle3027922010-08-25 11:45:40 +00001667 case CK_FloatingToIntegral:
Anders Carlsson094c4592009-10-18 18:12:03 +00001668 return "FloatingToIntegral";
John McCalle3027922010-08-25 11:45:40 +00001669 case CK_FloatingCast:
Benjamin Kramerbeb873d2009-10-18 19:02:15 +00001670 return "FloatingCast";
John McCall8cb679e2010-11-15 09:13:47 +00001671 case CK_FloatingToBoolean:
1672 return "FloatingToBoolean";
John McCalle3027922010-08-25 11:45:40 +00001673 case CK_MemberPointerToBoolean:
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001674 return "MemberPointerToBoolean";
John McCall9320b872011-09-09 05:25:32 +00001675 case CK_CPointerToObjCPointerCast:
1676 return "CPointerToObjCPointerCast";
1677 case CK_BlockPointerToObjCPointerCast:
1678 return "BlockPointerToObjCPointerCast";
John McCalle3027922010-08-25 11:45:40 +00001679 case CK_AnyPointerToBlockPointerCast:
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001680 return "AnyPointerToBlockPointerCast";
John McCalle3027922010-08-25 11:45:40 +00001681 case CK_ObjCObjectLValueCast:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001682 return "ObjCObjectLValueCast";
John McCallc5e62b42010-11-13 09:02:35 +00001683 case CK_FloatingRealToComplex:
1684 return "FloatingRealToComplex";
John McCalld7646252010-11-14 08:17:51 +00001685 case CK_FloatingComplexToReal:
1686 return "FloatingComplexToReal";
1687 case CK_FloatingComplexToBoolean:
1688 return "FloatingComplexToBoolean";
John McCallc5e62b42010-11-13 09:02:35 +00001689 case CK_FloatingComplexCast:
1690 return "FloatingComplexCast";
John McCalld7646252010-11-14 08:17:51 +00001691 case CK_FloatingComplexToIntegralComplex:
1692 return "FloatingComplexToIntegralComplex";
John McCallc5e62b42010-11-13 09:02:35 +00001693 case CK_IntegralRealToComplex:
1694 return "IntegralRealToComplex";
John McCalld7646252010-11-14 08:17:51 +00001695 case CK_IntegralComplexToReal:
1696 return "IntegralComplexToReal";
1697 case CK_IntegralComplexToBoolean:
1698 return "IntegralComplexToBoolean";
John McCallc5e62b42010-11-13 09:02:35 +00001699 case CK_IntegralComplexCast:
1700 return "IntegralComplexCast";
John McCalld7646252010-11-14 08:17:51 +00001701 case CK_IntegralComplexToFloatingComplex:
1702 return "IntegralComplexToFloatingComplex";
John McCall2d637d22011-09-10 06:18:15 +00001703 case CK_ARCConsumeObject:
1704 return "ARCConsumeObject";
1705 case CK_ARCProduceObject:
1706 return "ARCProduceObject";
1707 case CK_ARCReclaimReturnedObject:
1708 return "ARCReclaimReturnedObject";
1709 case CK_ARCExtendBlockObject:
Jordan Rose749b5812014-02-05 03:49:45 +00001710 return "ARCExtendBlockObject";
David Chisnallfa35df62012-01-16 17:27:18 +00001711 case CK_AtomicToNonAtomic:
1712 return "AtomicToNonAtomic";
1713 case CK_NonAtomicToAtomic:
1714 return "NonAtomicToAtomic";
Douglas Gregored90df32012-02-22 05:02:47 +00001715 case CK_CopyAndAutoreleaseBlockObject:
1716 return "CopyAndAutoreleaseBlockObject";
Eli Friedman34866c72012-08-31 00:14:07 +00001717 case CK_BuiltinFnToFnPtr:
1718 return "BuiltinFnToFnPtr";
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001719 case CK_ZeroToOCLEvent:
1720 return "ZeroToOCLEvent";
David Tweede1468322013-12-11 13:39:46 +00001721 case CK_AddressSpaceConversion:
1722 return "AddressSpaceConversion";
Anders Carlsson496335e2009-09-03 00:59:21 +00001723 }
Mike Stump11289f42009-09-09 15:08:12 +00001724
John McCallc5e62b42010-11-13 09:02:35 +00001725 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001726}
1727
Douglas Gregord196a582009-12-14 19:27:10 +00001728Expr *CastExpr::getSubExprAsWritten() {
Craig Topper36250ad2014-05-12 05:36:57 +00001729 Expr *SubExpr = nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001730 CastExpr *E = this;
1731 do {
1732 SubExpr = E->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00001733
1734 // Skip through reference binding to temporary.
1735 if (MaterializeTemporaryExpr *Materialize
1736 = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1737 SubExpr = Materialize->GetTemporaryExpr();
1738
Douglas Gregord196a582009-12-14 19:27:10 +00001739 // Skip any temporary bindings; they're implicit.
1740 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1741 SubExpr = Binder->getSubExpr();
Alexis Hunta8136cc2010-05-05 15:23:54 +00001742
Douglas Gregord196a582009-12-14 19:27:10 +00001743 // Conversions by constructor and conversion functions have a
1744 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001745 if (E->getCastKind() == CK_ConstructorConversion)
Douglas Gregord196a582009-12-14 19:27:10 +00001746 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
Manman Ren8abc2e52016-02-02 22:23:03 +00001747 else if (E->getCastKind() == CK_UserDefinedConversion) {
1748 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1749 isa<BlockExpr>(SubExpr)) &&
1750 "Unexpected SubExpr for CK_UserDefinedConversion.");
1751 if (isa<CXXMemberCallExpr>(SubExpr))
1752 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1753 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001754
Douglas Gregord196a582009-12-14 19:27:10 +00001755 // If the subexpression we're left with is an implicit cast, look
1756 // through that, too.
Alexis Hunta8136cc2010-05-05 15:23:54 +00001757 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1758
Douglas Gregord196a582009-12-14 19:27:10 +00001759 return SubExpr;
1760}
1761
John McCallcf142162010-08-07 06:22:56 +00001762CXXBaseSpecifier **CastExpr::path_buffer() {
1763 switch (getStmtClass()) {
1764#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001765#define CASTEXPR(Type, Base) \
1766 case Stmt::Type##Class: \
1767 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001768#define STMT(Type, Base)
1769#include "clang/AST/StmtNodes.inc"
1770 default:
1771 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001772 }
1773}
1774
Craig Topper37932912013-08-18 10:09:15 +00001775ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001776 CastKind Kind, Expr *Operand,
1777 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001778 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001779 unsigned PathSize = (BasePath ? BasePath->size() : 0);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001780 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001781 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001782 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001783 if (PathSize)
1784 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1785 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001786 return E;
1787}
1788
Craig Topper37932912013-08-18 10:09:15 +00001789ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001790 unsigned PathSize) {
James Y Knight1d75c5e2015-12-30 02:27:28 +00001791 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001792 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1793}
1794
1795
Craig Topper37932912013-08-18 10:09:15 +00001796CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001797 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001798 const CXXCastPath *BasePath,
1799 TypeSourceInfo *WrittenTy,
1800 SourceLocation L, SourceLocation R) {
1801 unsigned PathSize = (BasePath ? BasePath->size() : 0);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001802 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001803 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001804 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001805 if (PathSize)
1806 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1807 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001808 return E;
1809}
1810
Craig Topper37932912013-08-18 10:09:15 +00001811CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1812 unsigned PathSize) {
James Y Knight1d75c5e2015-12-30 02:27:28 +00001813 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001814 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1815}
1816
Chris Lattner1b926492006-08-23 06:42:10 +00001817/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1818/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001819StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001820 switch (Op) {
John McCalle3027922010-08-25 11:45:40 +00001821 case BO_PtrMemD: return ".*";
1822 case BO_PtrMemI: return "->*";
1823 case BO_Mul: return "*";
1824 case BO_Div: return "/";
1825 case BO_Rem: return "%";
1826 case BO_Add: return "+";
1827 case BO_Sub: return "-";
1828 case BO_Shl: return "<<";
1829 case BO_Shr: return ">>";
1830 case BO_LT: return "<";
1831 case BO_GT: return ">";
1832 case BO_LE: return "<=";
1833 case BO_GE: return ">=";
1834 case BO_EQ: return "==";
1835 case BO_NE: return "!=";
1836 case BO_And: return "&";
1837 case BO_Xor: return "^";
1838 case BO_Or: return "|";
1839 case BO_LAnd: return "&&";
1840 case BO_LOr: return "||";
1841 case BO_Assign: return "=";
1842 case BO_MulAssign: return "*=";
1843 case BO_DivAssign: return "/=";
1844 case BO_RemAssign: return "%=";
1845 case BO_AddAssign: return "+=";
1846 case BO_SubAssign: return "-=";
1847 case BO_ShlAssign: return "<<=";
1848 case BO_ShrAssign: return ">>=";
1849 case BO_AndAssign: return "&=";
1850 case BO_XorAssign: return "^=";
1851 case BO_OrAssign: return "|=";
1852 case BO_Comma: return ",";
Chris Lattner1b926492006-08-23 06:42:10 +00001853 }
Douglas Gregor0f60e9a2009-03-12 22:51:37 +00001854
David Blaikiee4d798f2012-01-20 21:50:17 +00001855 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001856}
Steve Naroff47500512007-04-19 23:00:49 +00001857
John McCalle3027922010-08-25 11:45:40 +00001858BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001859BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1860 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001861 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001862 case OO_Plus: return BO_Add;
1863 case OO_Minus: return BO_Sub;
1864 case OO_Star: return BO_Mul;
1865 case OO_Slash: return BO_Div;
1866 case OO_Percent: return BO_Rem;
1867 case OO_Caret: return BO_Xor;
1868 case OO_Amp: return BO_And;
1869 case OO_Pipe: return BO_Or;
1870 case OO_Equal: return BO_Assign;
1871 case OO_Less: return BO_LT;
1872 case OO_Greater: return BO_GT;
1873 case OO_PlusEqual: return BO_AddAssign;
1874 case OO_MinusEqual: return BO_SubAssign;
1875 case OO_StarEqual: return BO_MulAssign;
1876 case OO_SlashEqual: return BO_DivAssign;
1877 case OO_PercentEqual: return BO_RemAssign;
1878 case OO_CaretEqual: return BO_XorAssign;
1879 case OO_AmpEqual: return BO_AndAssign;
1880 case OO_PipeEqual: return BO_OrAssign;
1881 case OO_LessLess: return BO_Shl;
1882 case OO_GreaterGreater: return BO_Shr;
1883 case OO_LessLessEqual: return BO_ShlAssign;
1884 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1885 case OO_EqualEqual: return BO_EQ;
1886 case OO_ExclaimEqual: return BO_NE;
1887 case OO_LessEqual: return BO_LE;
1888 case OO_GreaterEqual: return BO_GE;
1889 case OO_AmpAmp: return BO_LAnd;
1890 case OO_PipePipe: return BO_LOr;
1891 case OO_Comma: return BO_Comma;
1892 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001893 }
1894}
1895
1896OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1897 static const OverloadedOperatorKind OverOps[] = {
1898 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1899 OO_Star, OO_Slash, OO_Percent,
1900 OO_Plus, OO_Minus,
1901 OO_LessLess, OO_GreaterGreater,
1902 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1903 OO_EqualEqual, OO_ExclaimEqual,
1904 OO_Amp,
1905 OO_Caret,
1906 OO_Pipe,
1907 OO_AmpAmp,
1908 OO_PipePipe,
1909 OO_Equal, OO_StarEqual,
1910 OO_SlashEqual, OO_PercentEqual,
1911 OO_PlusEqual, OO_MinusEqual,
1912 OO_LessLessEqual, OO_GreaterGreaterEqual,
1913 OO_AmpEqual, OO_CaretEqual,
1914 OO_PipeEqual,
1915 OO_Comma
1916 };
1917 return OverOps[Opc];
1918}
1919
Craig Topper37932912013-08-18 10:09:15 +00001920InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001921 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Douglas Gregora6e053e2010-12-15 01:34:56 +00001922 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
Douglas Gregor678d76c2011-07-01 01:22:09 +00001923 false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001924 InitExprs(C, initExprs.size()),
Craig Topper36250ad2014-05-12 05:36:57 +00001925 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
Sebastian Redlc83ed822012-02-17 08:42:25 +00001926{
1927 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00001928 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001929 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00001930 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00001931 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00001932 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00001933 if (initExprs[I]->isInstantiationDependent())
1934 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00001935 if (initExprs[I]->containsUnexpandedParameterPack())
1936 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00001937 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001938
Benjamin Kramerc215e762012-08-24 11:54:20 +00001939 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00001940}
Chris Lattner1ec5f562007-06-27 05:38:08 +00001941
Craig Topper37932912013-08-18 10:09:15 +00001942void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001943 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00001944 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001945}
1946
Craig Topper37932912013-08-18 10:09:15 +00001947void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00001948 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001949}
1950
Craig Topper37932912013-08-18 10:09:15 +00001951Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001952 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001953 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00001954 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00001955 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001956 }
Mike Stump11289f42009-09-09 15:08:12 +00001957
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001958 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00001959 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001960 return Result;
1961}
1962
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001963void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00001964 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001965 ArrayFillerOrUnionFieldInit = filler;
1966 // Fill out any "holes" in the array due to designated initializers.
1967 Expr **inits = getInits();
1968 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001969 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001970 inits[i] = filler;
1971}
1972
Richard Smith9ec1e482012-04-15 02:50:59 +00001973bool InitListExpr::isStringLiteralInit() const {
1974 if (getNumInits() != 1)
1975 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00001976 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
1977 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00001978 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00001979 // It is possible for getInit() to return null.
1980 const Expr *Init = getInit(0);
1981 if (!Init)
1982 return false;
1983 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00001984 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
1985}
1986
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001987SourceLocation InitListExpr::getLocStart() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00001988 if (InitListExpr *SyntacticForm = getSyntacticForm())
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001989 return SyntacticForm->getLocStart();
1990 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001991 if (Beg.isInvalid()) {
1992 // Find the first non-null initializer.
1993 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1994 E = InitExprs.end();
1995 I != E; ++I) {
1996 if (Stmt *S = *I) {
1997 Beg = S->getLocStart();
1998 break;
1999 }
2000 }
2001 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002002 return Beg;
2003}
2004
2005SourceLocation InitListExpr::getLocEnd() const {
2006 if (InitListExpr *SyntacticForm = getSyntacticForm())
2007 return SyntacticForm->getLocEnd();
2008 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002009 if (End.isInvalid()) {
2010 // Find the first non-null initializer from the end.
2011 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002012 E = InitExprs.rend();
2013 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002014 if (Stmt *S = *I) {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002015 End = S->getLocEnd();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002016 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002017 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002018 }
2019 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002020 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002021}
2022
Steve Naroff991e99d2008-09-04 15:31:07 +00002023/// getFunctionType - Return the underlying function type for this block.
Steve Naroffc540d662008-09-03 18:15:37 +00002024///
John McCallc833dea2012-02-17 03:32:35 +00002025const FunctionProtoType *BlockExpr::getFunctionType() const {
2026 // The block pointer is never sugared, but the function type might be.
2027 return cast<BlockPointerType>(getType())
2028 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002029}
2030
Mike Stump11289f42009-09-09 15:08:12 +00002031SourceLocation BlockExpr::getCaretLocation() const {
2032 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002033}
Mike Stump11289f42009-09-09 15:08:12 +00002034const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002035 return TheBlock->getBody();
2036}
Mike Stump11289f42009-09-09 15:08:12 +00002037Stmt *BlockExpr::getBody() {
2038 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002039}
Steve Naroff415d3d52008-10-08 17:01:13 +00002040
2041
Chris Lattner1ec5f562007-06-27 05:38:08 +00002042//===----------------------------------------------------------------------===//
2043// Generic Expression Routines
2044//===----------------------------------------------------------------------===//
2045
Chris Lattner237f2752009-02-14 07:37:35 +00002046/// isUnusedResultAWarning - Return true if this immediate expression should
2047/// be warned about if the result is unused. If so, fill in Loc and Ranges
2048/// with location to warn on and the source range[s] to report with the
2049/// warning.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002050bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2051 SourceRange &R1, SourceRange &R2,
2052 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002053 // Don't warn if the expr is type dependent. The type could end up
2054 // instantiating to void.
2055 if (isTypeDependent())
2056 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002057
Chris Lattner1ec5f562007-06-27 05:38:08 +00002058 switch (getStmtClass()) {
2059 default:
John McCallc493a732010-03-12 07:11:26 +00002060 if (getType()->isVoidType())
2061 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002062 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002063 Loc = getExprLoc();
2064 R1 = getSourceRange();
2065 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002066 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002067 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002068 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002069 case GenericSelectionExprClass:
2070 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002071 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002072 case ChooseExprClass:
2073 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2074 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002075 case UnaryOperatorClass: {
2076 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002077
Chris Lattner1ec5f562007-06-27 05:38:08 +00002078 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002079 case UO_Plus:
2080 case UO_Minus:
2081 case UO_AddrOf:
2082 case UO_Not:
2083 case UO_LNot:
2084 case UO_Deref:
2085 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002086 case UO_Coawait:
2087 // This is just the 'operator co_await' call inside the guts of a
2088 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002089 case UO_PostInc:
2090 case UO_PostDec:
2091 case UO_PreInc:
2092 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002093 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002094 case UO_Real:
2095 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002096 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002097 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2098 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002099 return false;
2100 break;
John McCalle3027922010-08-25 11:45:40 +00002101 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002102 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002103 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002104 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002105 Loc = UO->getOperatorLoc();
2106 R1 = UO->getSubExpr()->getSourceRange();
2107 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002108 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002109 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002110 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002111 switch (BO->getOpcode()) {
2112 default:
2113 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002114 // Consider the RHS of comma for side effects. LHS was checked by
2115 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002116 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002117 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2118 // lvalue-ness) of an assignment written in a macro.
2119 if (IntegerLiteral *IE =
2120 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2121 if (IE->getValue() == 0)
2122 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002123 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002124 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002125 case BO_LAnd:
2126 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002127 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2128 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002129 return false;
2130 break;
John McCall1e3715a2010-02-16 04:10:53 +00002131 }
Chris Lattner237f2752009-02-14 07:37:35 +00002132 if (BO->isAssignmentOp())
2133 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002134 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002135 Loc = BO->getOperatorLoc();
2136 R1 = BO->getLHS()->getSourceRange();
2137 R2 = BO->getRHS()->getSourceRange();
2138 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002139 }
Chris Lattner86928112007-08-25 02:00:02 +00002140 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002141 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002142 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002143 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002144
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002145 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002146 // If only one of the LHS or RHS is a warning, the operator might
2147 // be being used for control flow. Only warn if both the LHS and
2148 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002149 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002150 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00002151 return false;
2152 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00002153 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002154 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002155 }
2156
Chris Lattnera44d1162007-06-27 05:58:59 +00002157 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002158 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002159 Loc = cast<MemberExpr>(this)->getMemberLoc();
2160 R1 = SourceRange(Loc, Loc);
2161 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2162 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002163
Chris Lattner1ec5f562007-06-27 05:38:08 +00002164 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002165 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002166 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2167 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2168 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2169 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002170
Chandler Carruth46339472011-08-17 09:49:44 +00002171 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002172 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002173 // overloads as there is no reasonable way to define these such that they
2174 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002175 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002176 // provides additional value as well. If this list is updated,
2177 // DiagnoseUnusedComparison should be as well.
2178 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002179 switch (Op->getOperator()) {
2180 default:
2181 break;
2182 case OO_EqualEqual:
2183 case OO_ExclaimEqual:
2184 case OO_Less:
2185 case OO_Greater:
2186 case OO_GreaterEqual:
2187 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002188 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2189 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002190 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002191 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002192 Loc = Op->getOperatorLoc();
2193 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002194 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002195 }
Chandler Carruth46339472011-08-17 09:49:44 +00002196
2197 // Fallthrough for generic call handling.
2198 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002199 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002200 case CXXMemberCallExprClass:
2201 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002202 // If this is a direct call, get the callee.
2203 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002204 if (const Decl *FD = CE->getCalleeDecl()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002205 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2206 bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2207 : FD->hasAttr<WarnUnusedResultAttr>();
2208
Chris Lattner237f2752009-02-14 07:37:35 +00002209 // If the callee has attribute pure, const, or warn_unused_result, warn
2210 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002211 //
2212 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2213 // updated to match for QoI.
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002214 if (HasWarnUnusedResultAttr ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002215 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002216 WarnE = this;
Chris Lattner1a6babf2009-10-13 04:53:48 +00002217 Loc = CE->getCallee()->getLocStart();
2218 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002219
Chris Lattner1a6babf2009-10-13 04:53:48 +00002220 if (unsigned NumArgs = CE->getNumArgs())
2221 R2 = SourceRange(CE->getArg(0)->getLocStart(),
2222 CE->getArg(NumArgs-1)->getLocEnd());
2223 return true;
2224 }
Chris Lattner237f2752009-02-14 07:37:35 +00002225 }
2226 return false;
2227 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002228
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002229 // If we don't know precisely what we're looking at, let's not warn.
2230 case UnresolvedLookupExprClass:
2231 case CXXUnresolvedConstructExprClass:
2232 return false;
2233
Anders Carlsson6aa50392009-11-17 17:11:23 +00002234 case CXXTemporaryObjectExprClass:
Lubos Lunak1f490f32013-07-21 13:15:58 +00002235 case CXXConstructExprClass: {
2236 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2237 if (Type->hasAttr<WarnUnusedAttr>()) {
2238 WarnE = this;
2239 Loc = getLocStart();
2240 R1 = getSourceRange();
2241 return true;
2242 }
2243 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002244 return false;
Lubos Lunak1f490f32013-07-21 13:15:58 +00002245 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002246
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002247 case ObjCMessageExprClass: {
2248 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002249 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002250 ME->isInstanceMessage() &&
2251 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002252 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002253 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002254 Loc = getExprLoc();
2255 R1 = ME->getSourceRange();
2256 return true;
2257 }
2258
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002259 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002260 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002261 WarnE = this;
2262 Loc = getExprLoc();
2263 return true;
2264 }
2265
Chris Lattner237f2752009-02-14 07:37:35 +00002266 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002267 }
Mike Stump11289f42009-09-09 15:08:12 +00002268
John McCallb7bd14f2010-12-02 01:19:52 +00002269 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002270 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002271 Loc = getExprLoc();
2272 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002273 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002274
John McCallfe96e0b2011-11-06 09:01:30 +00002275 case PseudoObjectExprClass: {
2276 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2277
2278 // Only complain about things that have the form of a getter.
2279 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2280 isa<BinaryOperator>(PO->getSyntacticForm()))
2281 return false;
2282
Eli Friedmanc11535c2012-05-24 00:47:05 +00002283 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002284 Loc = getExprLoc();
2285 R1 = getSourceRange();
2286 return true;
2287 }
2288
Chris Lattner944d3062008-07-26 19:51:01 +00002289 case StmtExprClass: {
2290 // Statement exprs don't logically have side effects themselves, but are
2291 // sometimes used in macros in ways that give them a type that is unused.
2292 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2293 // however, if the result of the stmt expr is dead, we don't want to emit a
2294 // warning.
2295 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002296 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002297 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002298 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002299 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2300 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002301 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002302 }
Mike Stump11289f42009-09-09 15:08:12 +00002303
John McCallc493a732010-03-12 07:11:26 +00002304 if (getType()->isVoidType())
2305 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002306 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002307 Loc = cast<StmtExpr>(this)->getLParenLoc();
2308 R1 = getSourceRange();
2309 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002310 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002311 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002312 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002313 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002314 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002315 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002316 if (CE->getCastKind() == CK_ToVoid) {
2317 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002318 CE->getSubExpr()->getType().isVolatileQualified()) {
2319 const DeclRefExpr *DRE =
2320 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2321 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2322 cast<VarDecl>(DRE->getDecl())->hasLocalStorage())) {
2323 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2324 R1, R2, Ctx);
2325 }
2326 }
Chris Lattner2706a552009-07-28 18:25:28 +00002327 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002328 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002329
Eli Friedmanc11535c2012-05-24 00:47:05 +00002330 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002331 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002332 if (CE->getCastKind() == CK_ConstructorConversion)
2333 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002334
Eli Friedmanc11535c2012-05-24 00:47:05 +00002335 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002336 if (const CXXFunctionalCastExpr *CXXCE =
2337 dyn_cast<CXXFunctionalCastExpr>(this)) {
Eli Friedman89fe0d52013-08-15 22:02:56 +00002338 Loc = CXXCE->getLocStart();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002339 R1 = CXXCE->getSubExpr()->getSourceRange();
2340 } else {
2341 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2342 Loc = CStyleCE->getLParenLoc();
2343 R1 = CStyleCE->getSubExpr()->getSourceRange();
2344 }
Chris Lattner237f2752009-02-14 07:37:35 +00002345 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002346 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002347 case ImplicitCastExprClass: {
2348 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002349
Eli Friedmanc11535c2012-05-24 00:47:05 +00002350 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2351 if (ICE->getCastKind() == CK_LValueToRValue &&
2352 ICE->getSubExpr()->getType().isVolatileQualified())
2353 return false;
2354
2355 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2356 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002357 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002358 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002359 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002360 case CXXDefaultInitExprClass:
2361 return (cast<CXXDefaultInitExpr>(this)
2362 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002363
2364 case CXXNewExprClass:
2365 // FIXME: In theory, there might be new expressions that don't have side
2366 // effects (e.g. a placement new with an uninitialized POD).
2367 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002368 return false;
Anders Carlssone80ccac2009-08-16 04:11:06 +00002369 case CXXBindTemporaryExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002370 return (cast<CXXBindTemporaryExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002371 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
John McCall5d413782010-12-06 08:20:24 +00002372 case ExprWithCleanupsClass:
2373 return (cast<ExprWithCleanups>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002374 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002375 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002376}
2377
Fariborz Jahanian07735332009-02-22 18:40:18 +00002378/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002379/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002380bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002381 const Expr *E = IgnoreParens();
2382 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002383 default:
2384 return false;
2385 case ObjCIvarRefExprClass:
2386 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002387 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002388 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002389 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002390 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002391 case MaterializeTemporaryExprClass:
2392 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2393 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002394 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002395 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002396 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002397 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fariborz Jahanianc367b8f2011-09-23 18:57:30 +00002398
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002399 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2400 if (VD->hasGlobalStorage())
2401 return true;
2402 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002403 // dereferencing to a pointer is always a gc'able candidate,
2404 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002405 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002406 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002407 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002408 return false;
2409 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002410 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002411 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002412 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002413 }
2414 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002415 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002416 }
2417}
Sebastian Redlce354af2010-09-10 20:55:33 +00002418
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002419bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2420 if (isTypeDependent())
2421 return false;
John McCall086a4642010-11-24 05:12:34 +00002422 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002423}
2424
John McCall0009fcc2011-04-26 20:42:42 +00002425QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002426 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002427
2428 // Bound member expressions are always one of these possibilities:
2429 // x->m x.m x->*y x.*y
2430 // (possibly parenthesized)
2431
2432 expr = expr->IgnoreParens();
2433 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2434 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2435 return mem->getMemberDecl()->getType();
2436 }
2437
2438 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2439 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2440 ->getPointeeType();
2441 assert(type->isFunctionType());
2442 return type;
2443 }
2444
David Majnemerced8bdf2015-02-25 17:36:15 +00002445 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002446 return QualType();
2447}
2448
Ted Kremenekfff70962008-01-17 16:57:34 +00002449Expr* Expr::IgnoreParens() {
2450 Expr* E = this;
Abramo Bagnara932e3932010-10-15 07:51:18 +00002451 while (true) {
2452 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2453 E = P->getSubExpr();
2454 continue;
2455 }
2456 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2457 if (P->getOpcode() == UO_Extension) {
2458 E = P->getSubExpr();
2459 continue;
2460 }
2461 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002462 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2463 if (!P->isResultDependent()) {
2464 E = P->getResultExpr();
2465 continue;
2466 }
2467 }
Eli Friedman75807f22013-07-20 00:40:58 +00002468 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2469 if (!P->isConditionDependent()) {
2470 E = P->getChosenSubExpr();
2471 continue;
2472 }
2473 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002474 return E;
2475 }
Ted Kremenekfff70962008-01-17 16:57:34 +00002476}
2477
Chris Lattnerf2660962008-02-13 01:02:39 +00002478/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2479/// or CastExprs or ImplicitCastExprs, returning their operand.
2480Expr *Expr::IgnoreParenCasts() {
2481 Expr *E = this;
2482 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002483 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002484 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002485 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002486 continue;
2487 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002488 if (MaterializeTemporaryExpr *Materialize
2489 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2490 E = Materialize->GetTemporaryExpr();
2491 continue;
2492 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002493 if (SubstNonTypeTemplateParmExpr *NTTP
2494 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2495 E = NTTP->getReplacement();
2496 continue;
2497 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002498 return E;
Chris Lattnerf2660962008-02-13 01:02:39 +00002499 }
2500}
2501
Ted Kremenek6f375e52014-04-16 07:26:09 +00002502Expr *Expr::IgnoreCasts() {
2503 Expr *E = this;
2504 while (true) {
2505 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2506 E = P->getSubExpr();
2507 continue;
2508 }
2509 if (MaterializeTemporaryExpr *Materialize
2510 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2511 E = Materialize->GetTemporaryExpr();
2512 continue;
2513 }
2514 if (SubstNonTypeTemplateParmExpr *NTTP
2515 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2516 E = NTTP->getReplacement();
2517 continue;
2518 }
2519 return E;
2520 }
2521}
2522
John McCall5a4ce8b2010-12-04 08:24:19 +00002523/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2524/// casts. This is intended purely as a temporary workaround for code
2525/// that hasn't yet been rewritten to do the right thing about those
2526/// casts, and may disappear along with the last internal use.
John McCall34376a62010-12-04 03:47:34 +00002527Expr *Expr::IgnoreParenLValueCasts() {
2528 Expr *E = this;
John McCall5a4ce8b2010-12-04 08:24:19 +00002529 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002530 E = E->IgnoreParens();
2531 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00002532 if (P->getCastKind() == CK_LValueToRValue) {
2533 E = P->getSubExpr();
2534 continue;
2535 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002536 } else if (MaterializeTemporaryExpr *Materialize
2537 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2538 E = Materialize->GetTemporaryExpr();
2539 continue;
Douglas Gregor6a40b082011-09-08 17:56:33 +00002540 } else if (SubstNonTypeTemplateParmExpr *NTTP
2541 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2542 E = NTTP->getReplacement();
2543 continue;
John McCall34376a62010-12-04 03:47:34 +00002544 }
2545 break;
2546 }
2547 return E;
2548}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002549
2550Expr *Expr::ignoreParenBaseCasts() {
2551 Expr *E = this;
2552 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002553 E = E->IgnoreParens();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002554 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2555 if (CE->getCastKind() == CK_DerivedToBase ||
2556 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2557 CE->getCastKind() == CK_NoOp) {
2558 E = CE->getSubExpr();
2559 continue;
2560 }
2561 }
2562
2563 return E;
2564 }
2565}
2566
John McCalleebc8322010-05-05 22:59:52 +00002567Expr *Expr::IgnoreParenImpCasts() {
2568 Expr *E = this;
2569 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002570 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002571 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCalleebc8322010-05-05 22:59:52 +00002572 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002573 continue;
2574 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002575 if (MaterializeTemporaryExpr *Materialize
2576 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2577 E = Materialize->GetTemporaryExpr();
2578 continue;
2579 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002580 if (SubstNonTypeTemplateParmExpr *NTTP
2581 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2582 E = NTTP->getReplacement();
2583 continue;
2584 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002585 return E;
John McCalleebc8322010-05-05 22:59:52 +00002586 }
2587}
2588
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002589Expr *Expr::IgnoreConversionOperator() {
2590 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002591 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002592 return MCE->getImplicitObjectArgument();
2593 }
2594 return this;
2595}
2596
Chris Lattneref26c772009-03-13 17:28:01 +00002597/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2598/// value (including ptr->int casts of the same size). Strip off any
2599/// ParenExpr or CastExprs, returning their operand.
2600Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2601 Expr *E = this;
2602 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002603 E = E->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00002604
Chris Lattneref26c772009-03-13 17:28:01 +00002605 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2606 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregorb90df602010-06-16 00:17:44 +00002607 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattneref26c772009-03-13 17:28:01 +00002608 Expr *SE = P->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002609
Chris Lattneref26c772009-03-13 17:28:01 +00002610 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2611 E = SE;
2612 continue;
2613 }
Mike Stump11289f42009-09-09 15:08:12 +00002614
Abramo Bagnara932e3932010-10-15 07:51:18 +00002615 if ((E->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002616 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnara932e3932010-10-15 07:51:18 +00002617 (SE->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002618 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattneref26c772009-03-13 17:28:01 +00002619 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2620 E = SE;
2621 continue;
2622 }
2623 }
Mike Stump11289f42009-09-09 15:08:12 +00002624
Douglas Gregor6a40b082011-09-08 17:56:33 +00002625 if (SubstNonTypeTemplateParmExpr *NTTP
2626 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2627 E = NTTP->getReplacement();
2628 continue;
2629 }
2630
Chris Lattneref26c772009-03-13 17:28:01 +00002631 return E;
2632 }
2633}
2634
Douglas Gregord196a582009-12-14 19:27:10 +00002635bool Expr::isDefaultArgument() const {
2636 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002637 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2638 E = M->GetTemporaryExpr();
2639
Douglas Gregord196a582009-12-14 19:27:10 +00002640 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2641 E = ICE->getSubExprAsWritten();
Alexis Hunta8136cc2010-05-05 15:23:54 +00002642
Douglas Gregord196a582009-12-14 19:27:10 +00002643 return isa<CXXDefaultArgExpr>(E);
2644}
Chris Lattneref26c772009-03-13 17:28:01 +00002645
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002646/// \brief Skip over any no-op casts and any temporary-binding
2647/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002648static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002649 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2650 E = M->GetTemporaryExpr();
2651
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002652 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002653 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002654 E = ICE->getSubExpr();
2655 else
2656 break;
2657 }
2658
2659 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2660 E = BE->getSubExpr();
2661
2662 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002663 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002664 E = ICE->getSubExpr();
2665 else
2666 break;
2667 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002668
2669 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002670}
2671
John McCall7a626f62010-09-15 10:14:12 +00002672/// isTemporaryObject - Determines if this expression produces a
2673/// temporary of the given class type.
2674bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2675 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2676 return false;
2677
Anders Carlsson66bbf502010-11-28 16:40:49 +00002678 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002679
John McCall02dc8c72010-09-15 20:59:13 +00002680 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002681 if (!E->Classify(C).isPRValue()) {
2682 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002683 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002684 return false;
2685 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002686
John McCallf4ee1dd2010-09-16 06:57:56 +00002687 // Black-list a few cases which yield pr-values of class type that don't
2688 // refer to temporaries of that type:
2689
2690 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002691 if (isa<ImplicitCastExpr>(E)) {
2692 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2693 case CK_DerivedToBase:
2694 case CK_UncheckedDerivedToBase:
2695 return false;
2696 default:
2697 break;
2698 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002699 }
2700
John McCallf4ee1dd2010-09-16 06:57:56 +00002701 // - member expressions (all)
2702 if (isa<MemberExpr>(E))
2703 return false;
2704
Eli Friedman13ffdd82012-06-15 23:51:06 +00002705 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2706 if (BO->isPtrMemOp())
2707 return false;
2708
John McCallc07a0c72011-02-17 10:25:35 +00002709 // - opaque values (all)
2710 if (isa<OpaqueValueExpr>(E))
2711 return false;
2712
John McCall7a626f62010-09-15 10:14:12 +00002713 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002714}
2715
Douglas Gregor25b7e052011-03-02 21:06:53 +00002716bool Expr::isImplicitCXXThis() const {
2717 const Expr *E = this;
2718
2719 // Strip away parentheses and casts we don't care about.
2720 while (true) {
2721 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2722 E = Paren->getSubExpr();
2723 continue;
2724 }
2725
2726 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2727 if (ICE->getCastKind() == CK_NoOp ||
2728 ICE->getCastKind() == CK_LValueToRValue ||
2729 ICE->getCastKind() == CK_DerivedToBase ||
2730 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2731 E = ICE->getSubExpr();
2732 continue;
2733 }
2734 }
2735
2736 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2737 if (UnOp->getOpcode() == UO_Extension) {
2738 E = UnOp->getSubExpr();
2739 continue;
2740 }
2741 }
2742
Douglas Gregorfe314812011-06-21 17:03:29 +00002743 if (const MaterializeTemporaryExpr *M
2744 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2745 E = M->GetTemporaryExpr();
2746 continue;
2747 }
2748
Douglas Gregor25b7e052011-03-02 21:06:53 +00002749 break;
2750 }
2751
2752 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2753 return This->isImplicit();
2754
2755 return false;
2756}
2757
Douglas Gregor4619e432008-12-05 23:32:09 +00002758/// hasAnyTypeDependentArguments - Determines if any of the expressions
2759/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002760bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002761 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002762 if (Exprs[I]->isTypeDependent())
2763 return true;
2764
2765 return false;
2766}
2767
Abramo Bagnara847c6602014-05-22 19:20:46 +00002768bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2769 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002770 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002771 // which can be evaluated at compile-time. It very closely parallels
2772 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2773 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2774 // to isEvaluatable most of the time.
2775 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002776 // If we ever capture reference-binding directly in the AST, we can
2777 // kill the second parameter.
2778
2779 if (IsForRef) {
2780 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002781 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2782 return true;
2783 if (Culprit)
2784 *Culprit = this;
2785 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002786 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002787
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002788 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002789 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002790 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002791 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002792 return true;
John McCall81c9cea2010-08-01 21:51:45 +00002793 case CXXTemporaryObjectExprClass:
2794 case CXXConstructExprClass: {
2795 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00002796
Eli Friedman4c27ac22013-07-16 22:40:53 +00002797 if (CE->getConstructor()->isTrivial() &&
2798 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2799 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00002800 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00002801
Eli Friedman4c27ac22013-07-16 22:40:53 +00002802 // Trivial copy constructor
2803 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00002804 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00002805 }
2806
Richard Smithd62306a2011-11-10 06:34:14 +00002807 break;
John McCall81c9cea2010-08-01 21:51:45 +00002808 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002809 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002810 // This handles gcc's extension that allows global initializers like
2811 // "struct x {int x;} x = (struct x) {};".
2812 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002813 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002814 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002815 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00002816 case DesignatedInitUpdateExprClass: {
2817 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2818 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2819 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2820 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002821 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002822 const InitListExpr *ILE = cast<InitListExpr>(this);
2823 if (ILE->getType()->isArrayType()) {
2824 unsigned numInits = ILE->getNumInits();
2825 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002826 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002827 return false;
2828 }
2829 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002830 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002831
2832 if (ILE->getType()->isRecordType()) {
2833 unsigned ElementNo = 0;
2834 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00002835 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002836 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00002837 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00002838 continue;
2839
2840 // Don't emit anonymous bitfields, they just affect layout.
2841 if (Field->isUnnamedBitfield())
2842 continue;
2843
2844 if (ElementNo < ILE->getNumInits()) {
2845 const Expr *Elt = ILE->getInit(ElementNo++);
2846 if (Field->isBitField()) {
2847 // Bitfields have to evaluate to an integer.
2848 llvm::APSInt ResultTmp;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002849 if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
2850 if (Culprit)
2851 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00002852 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002853 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002854 } else {
2855 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002856 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002857 return false;
2858 }
2859 }
2860 }
2861 return true;
2862 }
2863
2864 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002865 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00002866 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002867 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00002868 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00002869 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00002870 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002871 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00002872 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002873 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002874 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00002875 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00002876 if (cast<ChooseExpr>(this)->isConditionDependent()) {
2877 if (Culprit)
2878 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00002879 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002880 }
Eli Friedman75807f22013-07-20 00:40:58 +00002881 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002882 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002883 case UnaryOperatorClass: {
2884 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00002885 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002886 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002887 break;
2888 }
John McCall8b0f4ff2010-08-02 21:13:48 +00002889 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00002890 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00002891 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00002892 case CStyleCastExprClass:
2893 case ObjCBridgedCastExprClass:
2894 case CXXDynamicCastExprClass:
2895 case CXXReinterpretCastExprClass:
2896 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00002897 const CastExpr *CE = cast<CastExpr>(this);
2898
Eli Friedman13ec75b2011-12-21 00:43:02 +00002899 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00002900 if (CE->getCastKind() == CK_NoOp ||
2901 CE->getCastKind() == CK_LValueToRValue ||
2902 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00002903 CE->getCastKind() == CK_ConstructorConversion ||
2904 CE->getCastKind() == CK_NonAtomicToAtomic ||
2905 CE->getCastKind() == CK_AtomicToNonAtomic)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002906 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00002907
Eli Friedman384da272009-01-25 03:12:18 +00002908 break;
Richard Smith161f09a2011-12-06 22:44:34 +00002909 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002910 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002911 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002912 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002913
2914 case SubstNonTypeTemplateParmExprClass:
2915 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002916 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002917 case CXXDefaultArgExprClass:
2918 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002919 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002920 case CXXDefaultInitExprClass:
2921 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002922 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002923 }
Richard Smithce8eca52015-12-08 03:21:47 +00002924 // Allow certain forms of UB in constant initializers: signed integer
2925 // overflow and floating-point division by zero. We'll give a warning on
2926 // these, but they're common enough that we have to accept them.
2927 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00002928 return true;
2929 if (Culprit)
2930 *Culprit = this;
2931 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00002932}
2933
Scott Douglasscc013592015-06-10 15:18:23 +00002934namespace {
2935 /// \brief Look for any side effects within a Stmt.
2936 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
2937 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
2938 const bool IncludePossibleEffects;
2939 bool HasSideEffects;
2940
2941 public:
2942 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
2943 : Inherited(Context),
2944 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
2945
2946 bool hasSideEffects() const { return HasSideEffects; }
2947
2948 void VisitExpr(const Expr *E) {
2949 if (!HasSideEffects &&
2950 E->HasSideEffects(Context, IncludePossibleEffects))
2951 HasSideEffects = true;
2952 }
2953 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002954}
Scott Douglasscc013592015-06-10 15:18:23 +00002955
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002956bool Expr::HasSideEffects(const ASTContext &Ctx,
2957 bool IncludePossibleEffects) const {
2958 // In circumstances where we care about definite side effects instead of
2959 // potential side effects, we want to ignore expressions that are part of a
2960 // macro expansion as a potential side effect.
2961 if (!IncludePossibleEffects && getExprLoc().isMacroID())
2962 return false;
2963
Richard Smith0421ce72012-08-07 04:16:51 +00002964 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002965 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00002966
2967 switch (getStmtClass()) {
2968 case NoStmtClass:
2969 #define ABSTRACT_STMT(Type)
2970 #define STMT(Type, Base) case Type##Class:
2971 #define EXPR(Type, Base)
2972 #include "clang/AST/StmtNodes.inc"
2973 llvm_unreachable("unexpected Expr kind");
2974
2975 case DependentScopeDeclRefExprClass:
2976 case CXXUnresolvedConstructExprClass:
2977 case CXXDependentScopeMemberExprClass:
2978 case UnresolvedLookupExprClass:
2979 case UnresolvedMemberExprClass:
2980 case PackExpansionExprClass:
2981 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00002982 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002983 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00002984 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002985 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
2986
Richard Smitha33e4fe2012-08-07 05:18:29 +00002987 case DeclRefExprClass:
2988 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002989 case PredefinedExprClass:
2990 case IntegerLiteralClass:
2991 case FloatingLiteralClass:
2992 case ImaginaryLiteralClass:
2993 case StringLiteralClass:
2994 case CharacterLiteralClass:
2995 case OffsetOfExprClass:
2996 case ImplicitValueInitExprClass:
2997 case UnaryExprOrTypeTraitExprClass:
2998 case AddrLabelExprClass:
2999 case GNUNullExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003000 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003001 case CXXBoolLiteralExprClass:
3002 case CXXNullPtrLiteralExprClass:
3003 case CXXThisExprClass:
3004 case CXXScalarValueInitExprClass:
3005 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003006 case ArrayTypeTraitExprClass:
3007 case ExpressionTraitExprClass:
3008 case CXXNoexceptExprClass:
3009 case SizeOfPackExprClass:
3010 case ObjCStringLiteralClass:
3011 case ObjCEncodeExprClass:
3012 case ObjCBoolLiteralExprClass:
3013 case CXXUuidofExprClass:
3014 case OpaqueValueExprClass:
3015 // These never have a side-effect.
3016 return false;
3017
3018 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003019 case CXXOperatorCallExprClass:
3020 case CXXMemberCallExprClass:
3021 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003022 case UserDefinedLiteralClass: {
3023 // We don't know a call definitely has side effects, except for calls
3024 // to pure/const functions that definitely don't.
3025 // If the call itself is considered side-effect free, check the operands.
3026 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3027 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3028 if (IsPure || !IncludePossibleEffects)
3029 break;
3030 return true;
3031 }
3032
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003033 case BlockExprClass:
3034 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003035 if (!IncludePossibleEffects)
3036 break;
3037 return true;
3038
John McCall5e77d762013-04-16 07:28:30 +00003039 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003040 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003041 case CompoundAssignOperatorClass:
3042 case VAArgExprClass:
3043 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003044 case CXXThrowExprClass:
3045 case CXXNewExprClass:
3046 case CXXDeleteExprClass:
3047 case ExprWithCleanupsClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003048 case CoawaitExprClass:
3049 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003050 // These always have a side-effect.
3051 return true;
3052
Scott Douglasscc013592015-06-10 15:18:23 +00003053 case StmtExprClass: {
3054 // StmtExprs have a side-effect if any substatement does.
3055 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3056 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3057 return Finder.hasSideEffects();
3058 }
3059
Richard Smith0421ce72012-08-07 04:16:51 +00003060 case ParenExprClass:
3061 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003062 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003063 case MemberExprClass:
3064 case ConditionalOperatorClass:
3065 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003066 case CompoundLiteralExprClass:
3067 case ExtVectorElementExprClass:
3068 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003069 case DesignatedInitUpdateExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003070 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003071 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003072 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003073 case SubstNonTypeTemplateParmExprClass:
3074 case MaterializeTemporaryExprClass:
3075 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003076 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003077 case AsTypeExprClass:
3078 // These have a side-effect if any subexpression does.
3079 break;
3080
Richard Smitha33e4fe2012-08-07 05:18:29 +00003081 case UnaryOperatorClass:
3082 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003083 return true;
3084 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003085
3086 case BinaryOperatorClass:
3087 if (cast<BinaryOperator>(this)->isAssignmentOp())
3088 return true;
3089 break;
3090
Richard Smith0421ce72012-08-07 04:16:51 +00003091 case InitListExprClass:
3092 // FIXME: The children for an InitListExpr doesn't include the array filler.
3093 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003094 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003095 return true;
3096 break;
3097
3098 case GenericSelectionExprClass:
3099 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003100 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003101
3102 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003103 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3104 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003105
3106 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003107 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3108 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003109
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003110 case CXXDefaultInitExprClass: {
3111 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3112 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003113 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003114 // If we've not yet parsed the initializer, assume it has side-effects.
3115 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003116 }
Richard Smith852c9db2013-04-20 22:23:05 +00003117
Richard Smith0421ce72012-08-07 04:16:51 +00003118 case CXXDynamicCastExprClass: {
3119 // A dynamic_cast expression has side-effects if it can throw.
3120 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3121 if (DCE->getTypeAsWritten()->isReferenceType() &&
3122 DCE->getCastKind() == CK_Dynamic)
3123 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003124 } // Fall through.
3125 case ImplicitCastExprClass:
3126 case CStyleCastExprClass:
3127 case CXXStaticCastExprClass:
3128 case CXXReinterpretCastExprClass:
3129 case CXXConstCastExprClass:
3130 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003131 // While volatile reads are side-effecting in both C and C++, we treat them
3132 // as having possible (not definite) side-effects. This allows idiomatic
3133 // code to behave without warning, such as sizeof(*v) for a volatile-
3134 // qualified pointer.
3135 if (!IncludePossibleEffects)
3136 break;
3137
Richard Smitha33e4fe2012-08-07 05:18:29 +00003138 const CastExpr *CE = cast<CastExpr>(this);
3139 if (CE->getCastKind() == CK_LValueToRValue &&
3140 CE->getSubExpr()->getType().isVolatileQualified())
3141 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003142 break;
3143 }
3144
Richard Smithef8bf432012-08-13 20:08:14 +00003145 case CXXTypeidExprClass:
3146 // typeid might throw if its subexpression is potentially-evaluated, so has
3147 // side-effects in that case whether or not its subexpression does.
3148 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003149
3150 case CXXConstructExprClass:
3151 case CXXTemporaryObjectExprClass: {
3152 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003153 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003154 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003155 // A trivial constructor does not add any side-effects of its own. Just look
3156 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003157 break;
3158 }
3159
3160 case LambdaExprClass: {
3161 const LambdaExpr *LE = cast<LambdaExpr>(this);
3162 for (LambdaExpr::capture_iterator I = LE->capture_begin(),
3163 E = LE->capture_end(); I != E; ++I)
3164 if (I->getCaptureKind() == LCK_ByCopy)
3165 // FIXME: Only has a side-effect if the variable is volatile or if
3166 // the copy would invoke a non-trivial copy constructor.
3167 return true;
3168 return false;
3169 }
3170
3171 case PseudoObjectExprClass: {
3172 // Only look for side-effects in the semantic form, and look past
3173 // OpaqueValueExpr bindings in that form.
3174 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3175 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3176 E = PO->semantics_end();
3177 I != E; ++I) {
3178 const Expr *Subexpr = *I;
3179 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3180 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003181 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003182 return true;
3183 }
3184 return false;
3185 }
3186
3187 case ObjCBoxedExprClass:
3188 case ObjCArrayLiteralClass:
3189 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003190 case ObjCSelectorExprClass:
3191 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003192 case ObjCIsaExprClass:
3193 case ObjCIndirectCopyRestoreExprClass:
3194 case ObjCSubscriptRefExprClass:
3195 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003196 case ObjCMessageExprClass:
3197 case ObjCPropertyRefExprClass:
3198 // FIXME: Classify these cases better.
3199 if (IncludePossibleEffects)
3200 return true;
3201 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003202 }
3203
3204 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003205 for (const Stmt *SubStmt : children())
3206 if (SubStmt &&
3207 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3208 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003209
3210 return false;
3211}
3212
Douglas Gregor1be329d2012-02-23 07:33:15 +00003213namespace {
3214 /// \brief Look for a call to a non-trivial function within an expression.
Scott Douglass503fc392015-06-10 13:53:15 +00003215 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
Douglas Gregor1be329d2012-02-23 07:33:15 +00003216 {
Scott Douglass503fc392015-06-10 13:53:15 +00003217 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3218
Douglas Gregor1be329d2012-02-23 07:33:15 +00003219 bool NonTrivial;
3220
3221 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003222 explicit NonTrivialCallFinder(const ASTContext &Context)
Douglas Gregor6427a5e2012-02-23 07:44:18 +00003223 : Inherited(Context), NonTrivial(false) { }
Douglas Gregor1be329d2012-02-23 07:33:15 +00003224
3225 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003226
3227 void VisitCallExpr(const CallExpr *E) {
3228 if (const CXXMethodDecl *Method
3229 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003230 if (Method->isTrivial()) {
3231 // Recurse to children of the call.
3232 Inherited::VisitStmt(E);
3233 return;
3234 }
3235 }
3236
3237 NonTrivial = true;
3238 }
Scott Douglass503fc392015-06-10 13:53:15 +00003239
3240 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003241 if (E->getConstructor()->isTrivial()) {
3242 // Recurse to children of the call.
3243 Inherited::VisitStmt(E);
3244 return;
3245 }
3246
3247 NonTrivial = true;
3248 }
Scott Douglass503fc392015-06-10 13:53:15 +00003249
3250 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003251 if (E->getTemporary()->getDestructor()->isTrivial()) {
3252 Inherited::VisitStmt(E);
3253 return;
3254 }
3255
3256 NonTrivial = true;
3257 }
3258 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003259}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003260
Scott Douglass503fc392015-06-10 13:53:15 +00003261bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003262 NonTrivialCallFinder Finder(Ctx);
3263 Finder.Visit(this);
3264 return Finder.hasNonTrivialCall();
3265}
3266
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003267/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3268/// pointer constant or not, as well as the specific kind of constant detected.
3269/// Null pointer constants can be integer constant expressions with the
3270/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3271/// (a GNU extension).
3272Expr::NullPointerConstantKind
3273Expr::isNullPointerConstant(ASTContext &Ctx,
3274 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003275 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003276 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003277 switch (NPC) {
3278 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003279 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003280 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003281 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003282 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003283 else
3284 return NPCK_NotNull;
Alexis Hunta8136cc2010-05-05 15:23:54 +00003285
Douglas Gregor56751b52009-09-25 04:25:58 +00003286 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003287 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003288 }
3289 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003290
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003291 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003292 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003293 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003294 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003295 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003296 QualType Pointee = PT->getPointeeType();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003297 Qualifiers Q = Pointee.getQualifiers();
3298 // In OpenCL v2.0 generic address space acts as a placeholder
3299 // and should be ignored.
3300 bool IsASValid = true;
3301 if (Ctx.getLangOpts().OpenCLVersion >= 200) {
3302 if (Pointee.getAddressSpace() == LangAS::opencl_generic)
3303 Q.removeAddressSpace();
3304 else
3305 IsASValid = false;
3306 }
3307
3308 if (IsASValid && !Q.hasQualifiers() &&
3309 Pointee->isVoidType() && // to void*
3310 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Douglas Gregor56751b52009-09-25 04:25:58 +00003311 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003312 }
Steve Naroffada7d422007-05-20 17:54:12 +00003313 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003314 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3315 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003316 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003317 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3318 // Accept ((void*)0) as a null pointer constant, as many other
3319 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003320 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003321 } else if (const GenericSelectionExpr *GE =
3322 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003323 if (GE->isResultDependent())
3324 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003325 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003326 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3327 if (CE->isConditionDependent())
3328 return NPCK_NotNull;
3329 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003330 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003331 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003332 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003333 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003334 } else if (const CXXDefaultInitExpr *DefaultInit
3335 = dyn_cast<CXXDefaultInitExpr>(this)) {
3336 // See through default initializer expressions.
3337 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003338 } else if (isa<GNUNullExpr>(this)) {
3339 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003340 return NPCK_GNUNull;
Douglas Gregorfe314812011-06-21 17:03:29 +00003341 } else if (const MaterializeTemporaryExpr *M
3342 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3343 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003344 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3345 if (const Expr *Source = OVE->getSourceExpr())
3346 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003347 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003348
Richard Smith89645bc2013-01-02 12:01:23 +00003349 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003350 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003351 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003352
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003353 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003354 if (!Ctx.getLangOpts().CPlusPlus11 &&
3355 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003356 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3357 const Expr *InitExpr = CLE->getInitializer();
3358 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3359 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3360 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003361 // This expression must be an integer type.
Alexis Hunta8136cc2010-05-05 15:23:54 +00003362 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003363 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003364 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003365
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003366 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003367 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3368 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003369 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003370 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003371 if (Lit && !Lit->getValue())
3372 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003373 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003374 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003375 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003376 // If we have an integer constant expression, we need to *evaluate* it and
3377 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003378 if (!isIntegerConstantExpr(Ctx))
3379 return NPCK_NotNull;
3380 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003381
David Blaikie1c7c8f72012-08-08 17:33:31 +00003382 if (EvaluateKnownConstInt(Ctx) != 0)
3383 return NPCK_NotNull;
3384
3385 if (isa<IntegerLiteral>(this))
3386 return NPCK_ZeroLiteral;
3387 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003388}
Steve Narofff7a5da12007-07-28 23:10:27 +00003389
John McCall34376a62010-12-04 03:47:34 +00003390/// \brief If this expression is an l-value for an Objective C
3391/// property, find the underlying property reference expression.
3392const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3393 const Expr *E = this;
3394 while (true) {
3395 assert((E->getValueKind() == VK_LValue &&
3396 E->getObjectKind() == OK_ObjCProperty) &&
3397 "expression is not a property reference");
3398 E = E->IgnoreParenCasts();
3399 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3400 if (BO->getOpcode() == BO_Comma) {
3401 E = BO->getRHS();
3402 continue;
3403 }
3404 }
3405
3406 break;
3407 }
3408
3409 return cast<ObjCPropertyRefExpr>(E);
3410}
3411
Anna Zaks97c7ce32012-10-01 20:34:04 +00003412bool Expr::isObjCSelfExpr() const {
3413 const Expr *E = IgnoreParenImpCasts();
3414
3415 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3416 if (!DRE)
3417 return false;
3418
3419 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3420 if (!Param)
3421 return false;
3422
3423 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3424 if (!M)
3425 return false;
3426
3427 return M->getSelfDecl() == Param;
3428}
3429
John McCalld25db7e2013-05-06 21:39:12 +00003430FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003431 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003432
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003433 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003434 if (ICE->getCastKind() == CK_LValueToRValue ||
3435 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003436 E = ICE->getSubExpr()->IgnoreParens();
3437 else
3438 break;
3439 }
3440
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003441 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003442 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003443 if (Field->isBitField())
3444 return Field;
3445
John McCalld25db7e2013-05-06 21:39:12 +00003446 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E))
3447 if (FieldDecl *Ivar = dyn_cast<FieldDecl>(IvarRef->getDecl()))
3448 if (Ivar->isBitField())
3449 return Ivar;
3450
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003451 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
3452 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3453 if (Field->isBitField())
3454 return Field;
3455
Eli Friedman609ada22011-07-13 02:05:57 +00003456 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003457 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003458 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003459
Eli Friedman609ada22011-07-13 02:05:57 +00003460 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003461 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003462 }
3463
Richard Smith5b571672014-09-24 23:55:00 +00003464 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3465 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3466 return UnOp->getSubExpr()->getSourceBitField();
3467
Craig Topper36250ad2014-05-12 05:36:57 +00003468 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003469}
3470
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003471bool Expr::refersToVectorElement() const {
3472 const Expr *E = this->IgnoreParens();
Alexis Hunta8136cc2010-05-05 15:23:54 +00003473
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003474 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003475 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003476 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003477 E = ICE->getSubExpr()->IgnoreParens();
3478 else
3479 break;
3480 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00003481
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003482 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3483 return ASE->getBase()->getType()->isVectorType();
3484
3485 if (isa<ExtVectorElementExpr>(E))
3486 return true;
3487
3488 return false;
3489}
3490
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003491bool Expr::refersToGlobalRegisterVar() const {
3492 const Expr *E = this->IgnoreParenImpCasts();
3493
3494 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3495 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3496 if (VD->getStorageClass() == SC_Register &&
3497 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3498 return true;
3499
3500 return false;
3501}
3502
Chris Lattnerb8211f62009-02-16 22:14:05 +00003503/// isArrow - Return true if the base expression is a pointer to vector,
3504/// return false if the base expression is a vector.
3505bool ExtVectorElementExpr::isArrow() const {
3506 return getBase()->getType()->isPointerType();
3507}
3508
Nate Begemance4d7fc2008-04-18 23:10:10 +00003509unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003510 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003511 return VT->getNumElements();
3512 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003513}
3514
Nate Begemanf322eab2008-05-09 06:41:27 +00003515/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003516bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003517 // FIXME: Refactor this code to an accessor on the AST node which returns the
3518 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003519 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003520
3521 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003522 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003523 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003524
Nate Begeman7e5185b2009-01-18 02:01:21 +00003525 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003526 if (Comp[0] == 's' || Comp[0] == 'S')
3527 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003528
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003529 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003530 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003531 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003532
Steve Naroff0d595ca2007-07-30 03:29:09 +00003533 return false;
3534}
Chris Lattner885b4952007-08-02 23:36:59 +00003535
Nate Begemanf322eab2008-05-09 06:41:27 +00003536/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003537void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003538 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003539 StringRef Comp = Accessor->getName();
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003540 if (Comp[0] == 's' || Comp[0] == 'S')
3541 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003542
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003543 bool isHi = Comp == "hi";
3544 bool isLo = Comp == "lo";
3545 bool isEven = Comp == "even";
3546 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003547
Nate Begemanf322eab2008-05-09 06:41:27 +00003548 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3549 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003550
Nate Begemanf322eab2008-05-09 06:41:27 +00003551 if (isHi)
3552 Index = e + i;
3553 else if (isLo)
3554 Index = i;
3555 else if (isEven)
3556 Index = 2 * i;
3557 else if (isOdd)
3558 Index = 2 * i + 1;
3559 else
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003560 Index = ExtVectorType::getAccessorIdx(Comp[i]);
Chris Lattner885b4952007-08-02 23:36:59 +00003561
Nate Begemand3862152008-05-13 21:03:02 +00003562 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003563 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003564}
3565
Craig Topper37932912013-08-18 10:09:15 +00003566ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003567 QualType Type, SourceLocation BLoc,
3568 SourceLocation RP)
3569 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3570 Type->isDependentType(), Type->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003571 Type->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003572 Type->containsUnexpandedParameterPack()),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003573 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
Douglas Gregora6e053e2010-12-15 01:34:56 +00003574{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003575 SubExprs = new (C) Stmt*[args.size()];
3576 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003577 if (args[i]->isTypeDependent())
3578 ExprBits.TypeDependent = true;
3579 if (args[i]->isValueDependent())
3580 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003581 if (args[i]->isInstantiationDependent())
3582 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003583 if (args[i]->containsUnexpandedParameterPack())
3584 ExprBits.ContainsUnexpandedParameterPack = true;
3585
3586 SubExprs[i] = args[i];
3587 }
3588}
3589
Craig Topper37932912013-08-18 10:09:15 +00003590void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003591 if (SubExprs) C.Deallocate(SubExprs);
3592
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003593 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003594 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003595 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003596}
Nate Begeman48745922009-08-12 02:28:50 +00003597
Craig Topper37932912013-08-18 10:09:15 +00003598GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003599 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003600 ArrayRef<TypeSourceInfo*> AssocTypes,
3601 ArrayRef<Expr*> AssocExprs,
3602 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003603 SourceLocation RParenLoc,
3604 bool ContainsUnexpandedParameterPack,
3605 unsigned ResultIndex)
3606 : Expr(GenericSelectionExprClass,
3607 AssocExprs[ResultIndex]->getType(),
3608 AssocExprs[ResultIndex]->getValueKind(),
3609 AssocExprs[ResultIndex]->getObjectKind(),
3610 AssocExprs[ResultIndex]->isTypeDependent(),
3611 AssocExprs[ResultIndex]->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003612 AssocExprs[ResultIndex]->isInstantiationDependent(),
Peter Collingbourne91147592011-04-15 00:35:48 +00003613 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003614 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3615 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3616 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3617 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003618 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003619 assert(AssocTypes.size() == AssocExprs.size());
3620 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3621 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003622}
3623
Craig Topper37932912013-08-18 10:09:15 +00003624GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003625 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003626 ArrayRef<TypeSourceInfo*> AssocTypes,
3627 ArrayRef<Expr*> AssocExprs,
3628 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003629 SourceLocation RParenLoc,
3630 bool ContainsUnexpandedParameterPack)
3631 : Expr(GenericSelectionExprClass,
3632 Context.DependentTy,
3633 VK_RValue,
3634 OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003635 /*isTypeDependent=*/true,
3636 /*isValueDependent=*/true,
3637 /*isInstantiationDependent=*/true,
Peter Collingbourne91147592011-04-15 00:35:48 +00003638 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003639 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3640 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3641 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3642 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003643 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003644 assert(AssocTypes.size() == AssocExprs.size());
3645 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3646 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003647}
3648
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003649//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003650// DesignatedInitExpr
3651//===----------------------------------------------------------------------===//
3652
Chandler Carruth631abd92011-06-16 06:47:06 +00003653IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003654 assert(Kind == FieldDesignator && "Only valid on a field designator");
3655 if (Field.NameOrField & 0x01)
3656 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3657 else
3658 return getField()->getIdentifier();
3659}
3660
Craig Topper37932912013-08-18 10:09:15 +00003661DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003662 unsigned NumDesignators,
Douglas Gregord5846a12009-04-15 06:41:24 +00003663 const Designator *Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003664 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003665 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003666 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003667 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003668 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003669 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003670 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003671 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003672 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003673 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003674 NumDesignators(NumDesignators), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003675 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003676
3677 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003678 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003679 *Child++ = Init;
3680
3681 // Copy the designators and their subexpressions, computing
3682 // value-dependence along the way.
3683 unsigned IndexIdx = 0;
3684 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003685 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003686
3687 if (this->Designators[I].isArrayDesignator()) {
3688 // Compute type- and value-dependence.
3689 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003690 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003691 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003692 if (Index->isInstantiationDependent())
3693 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003694 // Propagate unexpanded parameter packs.
3695 if (Index->containsUnexpandedParameterPack())
3696 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003697
3698 // Copy the index expressions into permanent storage.
3699 *Child++ = IndexExprs[IndexIdx++];
3700 } else if (this->Designators[I].isArrayRangeDesignator()) {
3701 // Compute type- and value-dependence.
3702 Expr *Start = IndexExprs[IndexIdx];
3703 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003704 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003705 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00003706 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003707 ExprBits.InstantiationDependent = true;
3708 } else if (Start->isInstantiationDependent() ||
3709 End->isInstantiationDependent()) {
3710 ExprBits.InstantiationDependent = true;
3711 }
3712
Douglas Gregora6e053e2010-12-15 01:34:56 +00003713 // Propagate unexpanded parameter packs.
3714 if (Start->containsUnexpandedParameterPack() ||
3715 End->containsUnexpandedParameterPack())
3716 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003717
3718 // Copy the start/end expressions into permanent storage.
3719 *Child++ = IndexExprs[IndexIdx++];
3720 *Child++ = IndexExprs[IndexIdx++];
3721 }
3722 }
3723
Benjamin Kramerc215e762012-08-24 11:54:20 +00003724 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00003725}
3726
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003727DesignatedInitExpr *
Craig Topper37932912013-08-18 10:09:15 +00003728DesignatedInitExpr::Create(const ASTContext &C, Designator *Designators,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003729 unsigned NumDesignators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003730 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003731 SourceLocation ColonOrEqualLoc,
3732 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003733 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
James Y Knight53c76162015-07-17 18:21:37 +00003734 llvm::alignOf<DesignatedInitExpr>());
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003735 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003736 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003737 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003738}
3739
Craig Topper37932912013-08-18 10:09:15 +00003740DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00003741 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003742 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
3743 llvm::alignOf<DesignatedInitExpr>());
Douglas Gregor38676d52009-04-16 00:55:48 +00003744 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3745}
3746
Craig Topper37932912013-08-18 10:09:15 +00003747void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003748 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00003749 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003750 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00003751 NumDesignators = NumDesigs;
3752 for (unsigned I = 0; I != NumDesigs; ++I)
3753 Designators[I] = Desigs[I];
3754}
3755
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003756SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3757 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3758 if (size() == 1)
3759 return DIE->getDesignator(0)->getSourceRange();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003760 return SourceRange(DIE->getDesignator(0)->getLocStart(),
3761 DIE->getDesignator(size()-1)->getLocEnd());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003762}
3763
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003764SourceLocation DesignatedInitExpr::getLocStart() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003765 SourceLocation StartLoc;
Chris Lattner8ba22472009-02-16 22:33:34 +00003766 Designator &First =
3767 *const_cast<DesignatedInitExpr*>(this)->designators_begin();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003768 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00003769 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003770 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3771 else
3772 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3773 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00003774 StartLoc =
3775 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003776 return StartLoc;
3777}
3778
3779SourceLocation DesignatedInitExpr::getLocEnd() const {
3780 return getInit()->getLocEnd();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003781}
3782
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003783Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003784 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003785 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003786}
3787
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003788Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003789 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003790 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003791 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003792}
3793
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003794Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003795 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003796 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003797 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003798}
3799
Douglas Gregord5846a12009-04-15 06:41:24 +00003800/// \brief Replaces the designator at index @p Idx with the series
3801/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00003802void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00003803 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00003804 const Designator *Last) {
3805 unsigned NumNewDesignators = Last - First;
3806 if (NumNewDesignators == 0) {
3807 std::copy_backward(Designators + Idx + 1,
3808 Designators + NumDesignators,
3809 Designators + Idx);
3810 --NumNewDesignators;
3811 return;
3812 } else if (NumNewDesignators == 1) {
3813 Designators[Idx] = *First;
3814 return;
3815 }
3816
Mike Stump11289f42009-09-09 15:08:12 +00003817 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003818 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00003819 std::copy(Designators, Designators + Idx, NewDesignators);
3820 std::copy(First, Last, NewDesignators + Idx);
3821 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3822 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00003823 Designators = NewDesignators;
3824 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3825}
3826
Yunzhong Gaocb779302015-06-10 00:27:52 +00003827DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
3828 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3829 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3830 OK_Ordinary, false, false, false, false) {
3831 BaseAndUpdaterExprs[0] = baseExpr;
3832
3833 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3834 ILE->setType(baseExpr->getType());
3835 BaseAndUpdaterExprs[1] = ILE;
3836}
3837
3838SourceLocation DesignatedInitUpdateExpr::getLocStart() const {
3839 return getBase()->getLocStart();
3840}
3841
3842SourceLocation DesignatedInitUpdateExpr::getLocEnd() const {
3843 return getBase()->getLocEnd();
3844}
3845
Craig Topper37932912013-08-18 10:09:15 +00003846ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003847 ArrayRef<Expr*> exprs,
Sebastian Redla9351792012-02-11 23:51:47 +00003848 SourceLocation rparenloc)
3849 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003850 false, false, false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003851 NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3852 Exprs = new (C) Stmt*[exprs.size()];
3853 for (unsigned i = 0; i != exprs.size(); ++i) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003854 if (exprs[i]->isTypeDependent())
3855 ExprBits.TypeDependent = true;
3856 if (exprs[i]->isValueDependent())
3857 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003858 if (exprs[i]->isInstantiationDependent())
3859 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003860 if (exprs[i]->containsUnexpandedParameterPack())
3861 ExprBits.ContainsUnexpandedParameterPack = true;
3862
Nate Begeman5ec4b312009-08-10 23:49:36 +00003863 Exprs[i] = exprs[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003864 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00003865}
3866
John McCall1bf58462011-02-16 08:02:54 +00003867const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3868 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3869 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00003870 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3871 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00003872 e = cast<CXXConstructExpr>(e)->getArg(0);
3873 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3874 e = ice->getSubExpr();
3875 return cast<OpaqueValueExpr>(e);
3876}
3877
Craig Topper37932912013-08-18 10:09:15 +00003878PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
3879 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00003880 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003881 void *buffer =
3882 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
3883 llvm::alignOf<PseudoObjectExpr>());
John McCallfe96e0b2011-11-06 09:01:30 +00003884 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3885}
3886
3887PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3888 : Expr(PseudoObjectExprClass, shell) {
3889 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3890}
3891
Craig Topper37932912013-08-18 10:09:15 +00003892PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00003893 ArrayRef<Expr*> semantics,
3894 unsigned resultIndex) {
3895 assert(syntax && "no syntactic expression!");
3896 assert(semantics.size() && "no semantic expressions!");
3897
3898 QualType type;
3899 ExprValueKind VK;
3900 if (resultIndex == NoResult) {
3901 type = C.VoidTy;
3902 VK = VK_RValue;
3903 } else {
3904 assert(resultIndex < semantics.size());
3905 type = semantics[resultIndex]->getType();
3906 VK = semantics[resultIndex]->getValueKind();
3907 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3908 }
3909
James Y Knighte00a67e2015-12-31 04:18:25 +00003910 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
John McCallfe96e0b2011-11-06 09:01:30 +00003911 llvm::alignOf<PseudoObjectExpr>());
3912 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3913 resultIndex);
3914}
3915
3916PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3917 Expr *syntax, ArrayRef<Expr*> semantics,
3918 unsigned resultIndex)
3919 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3920 /*filled in at end of ctor*/ false, false, false, false) {
3921 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3922 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3923
3924 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3925 Expr *E = (i == 0 ? syntax : semantics[i-1]);
3926 getSubExprsBuffer()[i] = E;
3927
3928 if (E->isTypeDependent())
3929 ExprBits.TypeDependent = true;
3930 if (E->isValueDependent())
3931 ExprBits.ValueDependent = true;
3932 if (E->isInstantiationDependent())
3933 ExprBits.InstantiationDependent = true;
3934 if (E->containsUnexpandedParameterPack())
3935 ExprBits.ContainsUnexpandedParameterPack = true;
3936
3937 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00003938 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00003939 "opaque-value semantic expressions for pseudo-object "
3940 "operations must have sources");
3941 }
3942}
3943
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003944//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003945// Child Iterators for iterating over subexpressions/substatements
3946//===----------------------------------------------------------------------===//
3947
Peter Collingbournee190dee2011-03-11 19:24:49 +00003948// UnaryExprOrTypeTraitExpr
3949Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Sebastian Redl6f282892008-11-11 17:56:53 +00003950 // If this is of a type and the type is a VLA type (and not a typedef), the
3951 // size expression of the VLA needs to be treated as an executable expression.
3952 // Why isn't this weirdness documented better in StmtIterator?
3953 if (isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003954 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
Sebastian Redl6f282892008-11-11 17:56:53 +00003955 getArgumentType().getTypePtr()))
John McCallbd066782011-02-09 08:16:59 +00003956 return child_range(child_iterator(T), child_iterator());
Benjamin Kramer5733e352015-07-18 17:09:36 +00003957 return child_range(child_iterator(), child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00003958 }
John McCallbd066782011-02-09 08:16:59 +00003959 return child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00003960}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003961
Benjamin Kramerc215e762012-08-24 11:54:20 +00003962AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003963 QualType t, AtomicOp op, SourceLocation RP)
3964 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3965 false, false, false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003966 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003967{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003968 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
3969 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003970 if (args[i]->isTypeDependent())
3971 ExprBits.TypeDependent = true;
3972 if (args[i]->isValueDependent())
3973 ExprBits.ValueDependent = true;
3974 if (args[i]->isInstantiationDependent())
3975 ExprBits.InstantiationDependent = true;
3976 if (args[i]->containsUnexpandedParameterPack())
3977 ExprBits.ContainsUnexpandedParameterPack = true;
3978
3979 SubExprs[i] = args[i];
3980 }
3981}
Richard Smithaa22a8c2012-04-10 22:49:28 +00003982
3983unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
3984 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00003985 case AO__c11_atomic_init:
3986 case AO__c11_atomic_load:
3987 case AO__atomic_load_n:
Richard Smithaa22a8c2012-04-10 22:49:28 +00003988 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00003989
3990 case AO__c11_atomic_store:
3991 case AO__c11_atomic_exchange:
3992 case AO__atomic_load:
3993 case AO__atomic_store:
3994 case AO__atomic_store_n:
3995 case AO__atomic_exchange_n:
3996 case AO__c11_atomic_fetch_add:
3997 case AO__c11_atomic_fetch_sub:
3998 case AO__c11_atomic_fetch_and:
3999 case AO__c11_atomic_fetch_or:
4000 case AO__c11_atomic_fetch_xor:
4001 case AO__atomic_fetch_add:
4002 case AO__atomic_fetch_sub:
4003 case AO__atomic_fetch_and:
4004 case AO__atomic_fetch_or:
4005 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004006 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004007 case AO__atomic_add_fetch:
4008 case AO__atomic_sub_fetch:
4009 case AO__atomic_and_fetch:
4010 case AO__atomic_or_fetch:
4011 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004012 case AO__atomic_nand_fetch:
Richard Smithaa22a8c2012-04-10 22:49:28 +00004013 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004014
4015 case AO__atomic_exchange:
4016 return 4;
4017
4018 case AO__c11_atomic_compare_exchange_strong:
4019 case AO__c11_atomic_compare_exchange_weak:
Richard Smithaa22a8c2012-04-10 22:49:28 +00004020 return 5;
Richard Smithfeea8832012-04-12 05:08:17 +00004021
4022 case AO__atomic_compare_exchange:
4023 case AO__atomic_compare_exchange_n:
4024 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004025 }
4026 llvm_unreachable("unknown atomic op");
4027}
Alexey Bataeva1764212015-09-30 09:22:36 +00004028
4029QualType OMPArraySectionExpr::getBaseOriginalType(Expr *Base) {
4030 unsigned ArraySectionCount = 0;
4031 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4032 Base = OASE->getBase();
4033 ++ArraySectionCount;
4034 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004035 while (auto *ASE = dyn_cast<ArraySubscriptExpr>(Base->IgnoreParens())) {
4036 Base = ASE->getBase();
4037 ++ArraySectionCount;
4038 }
Alexey Bataeva1764212015-09-30 09:22:36 +00004039 auto OriginalTy = Base->getType();
4040 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4041 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4042 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4043
4044 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4045 if (OriginalTy->isAnyPointerType())
4046 OriginalTy = OriginalTy->getPointeeType();
4047 else {
4048 assert (OriginalTy->isArrayType());
4049 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4050 }
4051 }
4052 return OriginalTy;
4053}