blob: 2948acd3b5eef638eecc52d7280eca834dd67209 [file] [log] [blame]
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
Chris Lattner1b926492006-08-23 06:42:10 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner1b926492006-08-23 06:42:10 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr class and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
Chris Lattner5c4664e2007-07-15 23:32:58 +000013#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000014#include "clang/AST/Attr.h"
Douglas Gregor9a657932008-10-21 23:43:52 +000015#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor1be329d2012-02-23 07:33:15 +000018#include "clang/AST/EvaluatedExprVisitor.h"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000019#include "clang/AST/Expr.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/AST/ExprCXX.h"
David Majnemerbed356a2013-11-06 23:31:56 +000021#include "clang/AST/Mangle.h"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000022#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000025#include "clang/Basic/CharInfo.h"
Chris Lattnere925d612010-11-17 07:37:15 +000026#include "clang/Basic/SourceManager.h"
Chris Lattnera7944d82007-11-27 18:22:04 +000027#include "clang/Basic/TargetInfo.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "clang/Lex/Lexer.h"
29#include "clang/Lex/LiteralSupport.h"
Douglas Gregor0840cc02009-11-01 20:32:48 +000030#include "llvm/Support/ErrorHandling.h"
Anders Carlsson2fb08242009-09-08 18:24:21 +000031#include "llvm/Support/raw_ostream.h"
Douglas Gregord5846a12009-04-15 06:41:24 +000032#include <algorithm>
Eli Friedmanfcec6302011-11-01 02:23:42 +000033#include <cstring>
Chris Lattner1b926492006-08-23 06:42:10 +000034using namespace clang;
35
Richard Smith018ac392016-11-03 18:55:18 +000036const Expr *Expr::getBestDynamicClassTypeExpr() const {
37 const Expr *E = this;
38 while (true) {
39 E = E->ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000040
Richard Smith018ac392016-11-03 18:55:18 +000041 // Follow the RHS of a comma operator.
42 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
43 if (BO->getOpcode() == BO_Comma) {
44 E = BO->getRHS();
45 continue;
46 }
47 }
48
49 // Step into initializer for materialized temporaries.
50 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
51 E = MTE->GetTemporaryExpr();
52 continue;
53 }
54
55 break;
56 }
57
58 return E;
59}
60
61const CXXRecordDecl *Expr::getBestDynamicClassType() const {
62 const Expr *E = getBestDynamicClassTypeExpr();
Rafael Espindola49e860b2012-06-26 17:45:31 +000063 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000064 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
65 DerivedType = PTy->getPointeeType();
66
Rafael Espindola60a2bba2012-07-17 20:24:05 +000067 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000068 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000069
Rafael Espindola49e860b2012-06-26 17:45:31 +000070 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000071 Decl *D = Ty->getDecl();
72 return cast<CXXRecordDecl>(D);
73}
74
Richard Smithf3fabd22013-06-03 00:17:11 +000075const Expr *Expr::skipRValueSubobjectAdjustments(
76 SmallVectorImpl<const Expr *> &CommaLHSs,
77 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000078 const Expr *E = this;
79 while (true) {
80 E = E->IgnoreParens();
81
82 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
83 if ((CE->getCastKind() == CK_DerivedToBase ||
84 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
85 E->getType()->isRecordType()) {
86 E = CE->getSubExpr();
87 CXXRecordDecl *Derived
88 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
89 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
90 continue;
91 }
92
93 if (CE->getCastKind() == CK_NoOp) {
94 E = CE->getSubExpr();
95 continue;
96 }
97 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +000098 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +000099 assert(ME->getBase()->getType()->isRecordType());
100 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000101 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +0000102 E = ME->getBase();
103 Adjustments.push_back(SubobjectAdjustment(Field));
104 continue;
105 }
Rafael Espindola9c006de2012-10-27 01:03:43 +0000106 }
107 }
108 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Richard Smitha3fd1162018-07-24 21:18:30 +0000109 if (BO->getOpcode() == BO_PtrMemD) {
Rafael Espindola973aa202012-11-01 14:32:20 +0000110 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +0000111 E = BO->getLHS();
112 const MemberPointerType *MPT =
113 BO->getRHS()->getType()->getAs<MemberPointerType>();
114 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +0000115 continue;
116 } else if (BO->getOpcode() == BO_Comma) {
117 CommaLHSs.push_back(BO->getLHS());
118 E = BO->getRHS();
119 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000120 }
121 }
122
123 // Nothing changed.
124 break;
125 }
126 return E;
127}
128
Chris Lattner4ebae652010-04-16 23:34:13 +0000129/// isKnownToHaveBooleanValue - Return true if this is an integer expression
130/// that is known to return 0 or 1. This happens for _Bool/bool expressions
131/// but also int expressions which are produced by things like comparisons in
132/// C.
133bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000134 const Expr *E = IgnoreParens();
135
Chris Lattner4ebae652010-04-16 23:34:13 +0000136 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000137 if (E->getType()->isBooleanType()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000138 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000139 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000140
Peter Collingbourne91147592011-04-15 00:35:48 +0000141 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000142 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000143 case UO_Plus:
Chris Lattner4ebae652010-04-16 23:34:13 +0000144 return UO->getSubExpr()->isKnownToHaveBooleanValue();
Richard Trieu0f097742014-04-04 04:13:47 +0000145 case UO_LNot:
146 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000147 default:
148 return false;
149 }
150 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000151
John McCall45d30c32010-06-12 01:56:02 +0000152 // Only look through implicit casts. If the user writes
153 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbourne91147592011-04-15 00:35:48 +0000154 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000155 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000156
Peter Collingbourne91147592011-04-15 00:35:48 +0000157 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000158 switch (BO->getOpcode()) {
159 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000160 case BO_LT: // Relational operators.
161 case BO_GT:
162 case BO_LE:
163 case BO_GE:
164 case BO_EQ: // Equality operators.
165 case BO_NE:
166 case BO_LAnd: // AND operator.
167 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000168 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000169
John McCalle3027922010-08-25 11:45:40 +0000170 case BO_And: // Bitwise AND operator.
171 case BO_Xor: // Bitwise XOR operator.
172 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000173 // Handle things like (x==2)|(y==12).
174 return BO->getLHS()->isKnownToHaveBooleanValue() &&
175 BO->getRHS()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000176
John McCalle3027922010-08-25 11:45:40 +0000177 case BO_Comma:
178 case BO_Assign:
Chris Lattner4ebae652010-04-16 23:34:13 +0000179 return BO->getRHS()->isKnownToHaveBooleanValue();
180 }
181 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000182
Peter Collingbourne91147592011-04-15 00:35:48 +0000183 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000184 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
185 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000186
Chris Lattner4ebae652010-04-16 23:34:13 +0000187 return false;
188}
189
John McCallbd066782011-02-09 08:16:59 +0000190// Amusing macro metaprogramming hack: check whether a class provides
191// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000192//
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000193// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000194namespace {
195 /// This implementation is used when a class provides a custom
196 /// implementation of getExprLoc.
197 template <class E, class T>
198 SourceLocation getExprLocImpl(const Expr *expr,
199 SourceLocation (T::*v)() const) {
200 return static_cast<const E*>(expr)->getExprLoc();
201 }
John McCallbd066782011-02-09 08:16:59 +0000202
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000203 /// This implementation is used when a class doesn't provide
204 /// a custom implementation of getExprLoc. Overload resolution
205 /// should pick it over the implementation above because it's
206 /// more specialized according to function template partial ordering.
207 template <class E>
208 SourceLocation getExprLocImpl(const Expr *expr,
209 SourceLocation (Expr::*v)() const) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000210 return static_cast<const E *>(expr)->getBeginLoc();
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000211 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000212}
John McCallbd066782011-02-09 08:16:59 +0000213
214SourceLocation Expr::getExprLoc() const {
215 switch (getStmtClass()) {
216 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
217#define ABSTRACT_STMT(type)
218#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000219 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000220#define EXPR(type, base) \
221 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
222#include "clang/AST/StmtNodes.inc"
223 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000224 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000225}
226
Chris Lattner0eedafe2006-08-24 04:56:27 +0000227//===----------------------------------------------------------------------===//
228// Primary Expressions.
229//===----------------------------------------------------------------------===//
230
Fangrui Song6907ce22018-07-30 19:24:48 +0000231/// Compute the type-, value-, and instantiation-dependence of a
Douglas Gregor678d76c2011-07-01 01:22:09 +0000232/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000233/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000234static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
235 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000236 bool &ValueDependent,
237 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000238 TypeDependent = false;
239 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000240 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000241
242 // (TD) C++ [temp.dep.expr]p3:
243 // An id-expression is type-dependent if it contains:
244 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000245 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000246 //
247 // (VD) C++ [temp.dep.constexpr]p2:
248 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000249
Douglas Gregored6c7442009-11-23 11:41:28 +0000250 // (TD) - an identifier that was declared with dependent type
251 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000252 if (T->isDependentType()) {
253 TypeDependent = true;
254 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000255 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000256 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000257 } else if (T->isInstantiationDependentType()) {
258 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000259 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000260
Douglas Gregored6c7442009-11-23 11:41:28 +0000261 // (TD) - a conversion-function-id that specifies a dependent type
Fangrui Song6907ce22018-07-30 19:24:48 +0000262 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000263 == DeclarationName::CXXConversionFunctionName) {
264 QualType T = D->getDeclName().getCXXNameType();
265 if (T->isDependentType()) {
266 TypeDependent = true;
267 ValueDependent = true;
268 InstantiationDependent = true;
269 return;
270 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000271
Douglas Gregor678d76c2011-07-01 01:22:09 +0000272 if (T->isInstantiationDependentType())
273 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000274 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000275
Douglas Gregored6c7442009-11-23 11:41:28 +0000276 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000277 if (isa<NonTypeTemplateParmDecl>(D)) {
278 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000279 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000280 return;
281 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000282
Douglas Gregored6c7442009-11-23 11:41:28 +0000283 // (VD) - a constant with integral or enumeration type and is
284 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000285 // (VD) - a constant with literal type and is initialized with an
286 // expression that is value-dependent [C++11].
287 // (VD) - FIXME: Missing from the standard:
288 // - an entity with reference type and is initialized with an
289 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000290 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000291 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000292 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000293 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000294 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000295 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000296 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000297 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000298 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000299 InstantiationDependent = true;
300 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000301 }
302
Fangrui Song6907ce22018-07-30 19:24:48 +0000303 // (VD) - FIXME: Missing from the standard:
304 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000305 // instantiation
Fangrui Song6907ce22018-07-30 19:24:48 +0000306 if (Var->isStaticDataMember() &&
Richard Smithec8dcd22011-11-08 01:31:09 +0000307 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000308 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000309 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000310 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
311 if (TInfo->getType()->isIncompleteArrayType())
312 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000313 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000314
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000315 return;
316 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000317
318 // (VD) - FIXME: Missing from the standard:
319 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000320 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000321 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
322 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000323 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000324 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000325}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000326
Craig Topperce7167c2013-08-22 04:58:56 +0000327void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000328 bool TypeDependent = false;
329 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000330 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000331 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
332 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000333
334 ExprBits.TypeDependent |= TypeDependent;
335 ExprBits.ValueDependent |= ValueDependent;
336 ExprBits.InstantiationDependent |= InstantiationDependent;
337
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000338 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000339 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000340 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000341}
342
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000343DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
344 bool RefersToEnclosingVariableOrCapture, QualType T,
345 ExprValueKind VK, SourceLocation L,
346 const DeclarationNameLoc &LocInfo)
347 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
348 D(D), DNLoc(LocInfo) {
349 DeclRefExprBits.HasQualifier = false;
350 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
351 DeclRefExprBits.HasFoundDecl = false;
352 DeclRefExprBits.HadMultipleCandidates = false;
353 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
354 RefersToEnclosingVariableOrCapture;
355 DeclRefExprBits.Loc = L;
356 computeDependence(Ctx);
357}
358
Craig Topperce7167c2013-08-22 04:58:56 +0000359DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000360 NestedNameSpecifierLoc QualifierLoc,
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000361 SourceLocation TemplateKWLoc, ValueDecl *D,
362 bool RefersToEnclosingVariableOrCapture,
363 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000364 const TemplateArgumentListInfo *TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +0000365 QualType T, ExprValueKind VK)
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000366 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
367 D(D), DNLoc(NameInfo.getInfo()) {
Bruno Riccia795e802018-11-13 17:56:44 +0000368 DeclRefExprBits.Loc = NameInfo.getLoc();
Chandler Carruth0e439962011-05-01 21:29:53 +0000369 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000370 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000371 new (getTrailingObjects<NestedNameSpecifierLoc>())
372 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000373 auto *NNS = QualifierLoc.getNestedNameSpecifier();
374 if (NNS->isInstantiationDependent())
375 ExprBits.InstantiationDependent = true;
376 if (NNS->containsUnexpandedParameterPack())
377 ExprBits.ContainsUnexpandedParameterPack = true;
378 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000379 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
380 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000381 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000382 DeclRefExprBits.HasTemplateKWAndArgsInfo
383 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000384 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
385 RefersToEnclosingVariableOrCapture;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000386 if (TemplateArgs) {
387 bool Dependent = false;
388 bool InstantiationDependent = false;
389 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000390 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
391 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
392 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000393 assert(!Dependent && "built a DeclRefExpr with dependent template args");
394 ExprBits.InstantiationDependent |= InstantiationDependent;
395 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000396 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000397 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
398 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000399 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000400 DeclRefExprBits.HadMultipleCandidates = 0;
401
Daniel Dunbar9d355812012-03-09 01:51:51 +0000402 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000403}
404
Craig Topperce7167c2013-08-22 04:58:56 +0000405DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000406 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000407 SourceLocation TemplateKWLoc,
John McCallce546572009-12-08 09:08:17 +0000408 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000409 bool RefersToEnclosingVariableOrCapture,
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000410 SourceLocation NameLoc,
Douglas Gregored6c7442009-11-23 11:41:28 +0000411 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000412 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000413 NamedDecl *FoundD,
Douglas Gregored6c7442009-11-23 11:41:28 +0000414 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000415 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000416 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000417 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000418 T, VK, FoundD, TemplateArgs);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000419}
420
Craig Topperce7167c2013-08-22 04:58:56 +0000421DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000422 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000423 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000424 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000425 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000426 const DeclarationNameInfo &NameInfo,
427 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000428 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000429 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000430 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000431 // Filter out cases where the found Decl is the same as the value refenenced.
432 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000433 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000434
James Y Knighte7d82282015-12-29 18:15:14 +0000435 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
436 std::size_t Size =
437 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
438 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
439 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
440 HasTemplateKWAndArgsInfo ? 1 : 0,
441 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000442
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000443 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000444 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000445 RefersToEnclosingVariableOrCapture,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000446 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000447}
448
Craig Topperce7167c2013-08-22 04:58:56 +0000449DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000450 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000451 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000452 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000453 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000454 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
455 std::size_t Size =
456 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
457 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
458 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
459 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000460 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000461 return new (Mem) DeclRefExpr(EmptyShell());
462}
463
Stephen Kelly724e9e52018-08-09 20:05:03 +0000464SourceLocation DeclRefExpr::getBeginLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000465 if (hasQualifier())
466 return getQualifierLoc().getBeginLoc();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000467 return getNameInfo().getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000468}
Stephen Kelly02a67ba2018-08-09 20:05:47 +0000469SourceLocation DeclRefExpr::getEndLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000470 if (hasExplicitTemplateArgs())
471 return getRAngleLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000472 return getNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000473}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000474
Bruno Ricci17ff0262018-10-27 19:21:19 +0000475PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
Alexey Bataevec474782014-10-09 08:45:04 +0000476 StringLiteral *SL)
477 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
478 FNTy->isDependentType(), FNTy->isDependentType(),
479 FNTy->isInstantiationDependentType(),
Bruno Ricci17ff0262018-10-27 19:21:19 +0000480 /*ContainsUnexpandedParameterPack=*/false) {
481 PredefinedExprBits.Kind = IK;
482 assert((getIdentKind() == IK) &&
483 "IdentKind do not fit in PredefinedExprBitfields!");
484 bool HasFunctionName = SL != nullptr;
485 PredefinedExprBits.HasFunctionName = HasFunctionName;
486 PredefinedExprBits.Loc = L;
487 if (HasFunctionName)
488 setFunctionName(SL);
Alexey Bataevec474782014-10-09 08:45:04 +0000489}
490
Bruno Ricci17ff0262018-10-27 19:21:19 +0000491PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
492 : Expr(PredefinedExprClass, Empty) {
493 PredefinedExprBits.HasFunctionName = HasFunctionName;
494}
495
496PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
497 QualType FNTy, IdentKind IK,
498 StringLiteral *SL) {
499 bool HasFunctionName = SL != nullptr;
500 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
501 alignof(PredefinedExpr));
502 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
503}
504
505PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
506 bool HasFunctionName) {
507 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
508 alignof(PredefinedExpr));
509 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
510}
511
512StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
513 switch (IK) {
Alexey Bataevec474782014-10-09 08:45:04 +0000514 case Func:
515 return "__func__";
516 case Function:
517 return "__FUNCTION__";
518 case FuncDName:
519 return "__FUNCDNAME__";
520 case LFunction:
521 return "L__FUNCTION__";
522 case PrettyFunction:
523 return "__PRETTY_FUNCTION__";
524 case FuncSig:
525 return "__FUNCSIG__";
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000526 case LFuncSig:
527 return "L__FUNCSIG__";
Alexey Bataevec474782014-10-09 08:45:04 +0000528 case PrettyFunctionNoVirtual:
529 break;
530 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000531 llvm_unreachable("Unknown ident kind for PredefinedExpr");
Alexey Bataevec474782014-10-09 08:45:04 +0000532}
533
Anders Carlsson2fb08242009-09-08 18:24:21 +0000534// FIXME: Maybe this should use DeclPrinter with a special "print predefined
535// expr" policy instead.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000536std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000537 ASTContext &Context = CurrentDecl->getASTContext();
538
Bruno Ricci17ff0262018-10-27 19:21:19 +0000539 if (IK == PredefinedExpr::FuncDName) {
David Majnemerbed356a2013-11-06 23:31:56 +0000540 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000541 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000542 MC.reset(Context.createMangleContext());
543
544 if (MC->shouldMangleDeclName(ND)) {
545 SmallString<256> Buffer;
546 llvm::raw_svector_ostream Out(Buffer);
547 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
548 MC->mangleCXXCtor(CD, Ctor_Base, Out);
549 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
550 MC->mangleCXXDtor(DD, Dtor_Base, Out);
551 else
552 MC->mangleName(ND, Out);
553
David Majnemerbed356a2013-11-06 23:31:56 +0000554 if (!Buffer.empty() && Buffer.front() == '\01')
555 return Buffer.substr(1);
556 return Buffer.str();
557 } else
558 return ND->getIdentifier()->getName();
559 }
560 return "";
561 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000562 if (isa<BlockDecl>(CurrentDecl)) {
563 // For blocks we only emit something if it is enclosed in a function
564 // For top-level block we'd like to include the name of variable, but we
565 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000566 auto DC = CurrentDecl->getDeclContext();
567 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000568 return "";
569
570 SmallString<256> Buffer;
571 llvm::raw_svector_ostream Out(Buffer);
572 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
573 // For nested blocks, propagate up to the parent.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000574 Out << ComputeName(IK, DCBlock);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000575 else if (auto *DCDecl = dyn_cast<Decl>(DC))
Bruno Ricci17ff0262018-10-27 19:21:19 +0000576 Out << ComputeName(IK, DCDecl) << "_block_invoke";
Alexey Bataevec474782014-10-09 08:45:04 +0000577 return Out.str();
578 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000579 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000580 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
581 IK != FuncSig && IK != LFuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000582 return FD->getNameAsString();
583
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000584 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000585 llvm::raw_svector_ostream Out(Name);
586
587 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000588 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000589 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000590 if (MD->isStatic())
591 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000592 }
593
David Blaikiebbafb8a2012-03-11 07:00:24 +0000594 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000595 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000596 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000597
Douglas Gregor11a434a2012-04-10 20:14:15 +0000598 const FunctionDecl *Decl = FD;
599 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
600 Decl = Pattern;
601 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000602 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000603 if (FD->hasWrittenPrototype())
604 FT = dyn_cast<FunctionProtoType>(AFT);
605
Bruno Ricci17ff0262018-10-27 19:21:19 +0000606 if (IK == FuncSig || IK == LFuncSig) {
Richard Smith2f63d462017-01-09 21:40:40 +0000607 switch (AFT->getCallConv()) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000608 case CC_C: POut << "__cdecl "; break;
609 case CC_X86StdCall: POut << "__stdcall "; break;
610 case CC_X86FastCall: POut << "__fastcall "; break;
611 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000612 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000613 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000614 // Only bother printing the conventions that MSVC knows about.
615 default: break;
616 }
617 }
618
619 FD->printQualifiedName(POut, Policy);
620
Douglas Gregor11a434a2012-04-10 20:14:15 +0000621 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000622 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000623 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000624 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000625 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000626 }
627
628 if (FT->isVariadic()) {
629 if (FD->getNumParams()) POut << ", ";
630 POut << "...";
Bruno Ricci17ff0262018-10-27 19:21:19 +0000631 } else if ((IK == FuncSig || IK == LFuncSig ||
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000632 !Context.getLangOpts().CPlusPlus) &&
Richard Smithcf63b842017-01-09 22:16:16 +0000633 !Decl->getNumParams()) {
634 POut << "void";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000635 }
636 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000637 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000638
Sam Weinig4e83bd22009-12-27 01:38:20 +0000639 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Richard Smith2f63d462017-01-09 21:40:40 +0000640 assert(FT && "We must have a written prototype in this case.");
David Blaikief5697e52012-08-10 00:55:35 +0000641 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000642 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000643 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000644 POut << " volatile";
645 RefQualifierKind Ref = MD->getRefQualifier();
646 if (Ref == RQ_LValue)
647 POut << " &";
648 else if (Ref == RQ_RValue)
649 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000650 }
651
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000652 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000653 SpecsTy Specs;
654 const DeclContext *Ctx = FD->getDeclContext();
655 while (Ctx && isa<NamedDecl>(Ctx)) {
656 const ClassTemplateSpecializationDecl *Spec
657 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
658 if (Spec && !Spec->isExplicitSpecialization())
659 Specs.push_back(Spec);
660 Ctx = Ctx->getParent();
661 }
662
663 std::string TemplateParams;
664 llvm::raw_string_ostream TOut(TemplateParams);
665 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
666 I != E; ++I) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000667 const TemplateParameterList *Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000668 = (*I)->getSpecializedTemplate()->getTemplateParameters();
669 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
670 assert(Params->size() == Args.size());
671 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
672 StringRef Param = Params->getParam(i)->getName();
673 if (Param.empty()) continue;
674 TOut << Param << " = ";
675 Args.get(i).print(Policy, TOut);
676 TOut << ", ";
677 }
678 }
679
Fangrui Song6907ce22018-07-30 19:24:48 +0000680 FunctionTemplateSpecializationInfo *FSI
Douglas Gregor11a434a2012-04-10 20:14:15 +0000681 = FD->getTemplateSpecializationInfo();
682 if (FSI && !FSI->isExplicitSpecialization()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000683 const TemplateParameterList* Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000684 = FSI->getTemplate()->getTemplateParameters();
685 const TemplateArgumentList* Args = FSI->TemplateArguments;
686 assert(Params->size() == Args->size());
687 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
688 StringRef Param = Params->getParam(i)->getName();
689 if (Param.empty()) continue;
690 TOut << Param << " = ";
691 Args->get(i).print(Policy, TOut);
692 TOut << ", ";
693 }
694 }
695
696 TOut.flush();
697 if (!TemplateParams.empty()) {
698 // remove the trailing comma and space
699 TemplateParams.resize(TemplateParams.size() - 2);
700 POut << " [" << TemplateParams << "]";
701 }
702
703 POut.flush();
704
Benjamin Kramer90f54222013-08-21 11:45:27 +0000705 // Print "auto" for all deduced return types. This includes C++1y return
706 // type deduction and lambdas. For trailing return types resolve the
707 // decltype expression. Otherwise print the real type when this is
708 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000709 if (isa<CXXMethodDecl>(FD) &&
710 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000711 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000712 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
713 FT->getReturnType()
714 ->getAs<DecltypeType>()
715 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000716 .getAsStringInternal(Proto, Policy);
717 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000718 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000719
720 Out << Proto;
721
Anders Carlsson2fb08242009-09-08 18:24:21 +0000722 return Name.str().str();
723 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000724 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
725 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
726 // Skip to its enclosing function or method, but not its enclosing
727 // CapturedDecl.
728 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
729 const Decl *D = Decl::castFromDeclContext(DC);
Bruno Ricci17ff0262018-10-27 19:21:19 +0000730 return ComputeName(IK, D);
Wei Pan8d6b19a2013-08-26 14:27:34 +0000731 }
732 llvm_unreachable("CapturedDecl not inside a function or method");
733 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000734 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000735 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000736 llvm::raw_svector_ostream Out(Name);
737 Out << (MD->isInstanceMethod() ? '-' : '+');
738 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000739
740 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
741 // a null check to avoid a crash.
742 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000743 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000744
Anders Carlsson2fb08242009-09-08 18:24:21 +0000745 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000746 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000747 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000748
Anders Carlsson2fb08242009-09-08 18:24:21 +0000749 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000750 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000751 Out << ']';
752
Anders Carlsson2fb08242009-09-08 18:24:21 +0000753 return Name.str().str();
754 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000755 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000756 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
757 return "top level";
758 }
759 return "";
760}
761
Craig Topper37932912013-08-18 10:09:15 +0000762void APNumericStorage::setIntValue(const ASTContext &C,
763 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000764 if (hasAllocation())
765 C.Deallocate(pVal);
766
767 BitWidth = Val.getBitWidth();
768 unsigned NumWords = Val.getNumWords();
769 const uint64_t* Words = Val.getRawData();
770 if (NumWords > 1) {
771 pVal = new (C) uint64_t[NumWords];
772 std::copy(Words, Words + NumWords, pVal);
773 } else if (NumWords == 1)
774 VAL = Words[0];
775 else
776 VAL = 0;
777}
778
Craig Topper37932912013-08-18 10:09:15 +0000779IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000780 QualType type, SourceLocation l)
781 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
782 false, false),
783 Loc(l) {
784 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
785 assert(V.getBitWidth() == C.getIntWidth(type) &&
786 "Integer type is not the correct size for constant.");
787 setValue(C, V);
788}
789
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000790IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000791IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000792 QualType type, SourceLocation l) {
793 return new (C) IntegerLiteral(C, V, type, l);
794}
795
796IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000797IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000798 return new (C) IntegerLiteral(Empty);
799}
800
Leonard Chandb01c3a2018-06-20 17:19:40 +0000801FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
802 QualType type, SourceLocation l,
803 unsigned Scale)
804 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
805 false, false),
806 Loc(l), Scale(Scale) {
807 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
808 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
809 "Fixed point type is not the correct size for constant.");
810 setValue(C, V);
811}
812
813FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
814 const llvm::APInt &V,
815 QualType type,
816 SourceLocation l,
817 unsigned Scale) {
818 return new (C) FixedPointLiteral(C, V, type, l, Scale);
819}
820
821std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
822 // Currently the longest decimal number that can be printed is the max for an
823 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
824 // which is 43 characters.
825 SmallString<64> S;
826 FixedPointValueToString(
Leonard Chanc03642e2018-08-06 16:05:08 +0000827 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
Leonard Chandb01c3a2018-06-20 17:19:40 +0000828 return S.str();
829}
830
Craig Topper37932912013-08-18 10:09:15 +0000831FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000832 bool isexact, QualType Type, SourceLocation L)
833 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
834 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000835 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000836 FloatingLiteralBits.IsExact = isexact;
837 setValue(C, V);
838}
839
Craig Topper37932912013-08-18 10:09:15 +0000840FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000841 : Expr(FloatingLiteralClass, Empty) {
Tim Northover178723a2013-01-22 09:46:51 +0000842 setRawSemantics(IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000843 FloatingLiteralBits.IsExact = false;
844}
845
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000846FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000847FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000848 bool isexact, QualType Type, SourceLocation L) {
849 return new (C) FloatingLiteral(C, V, isexact, Type, L);
850}
851
852FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000853FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000854 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000855}
856
Tim Northover178723a2013-01-22 09:46:51 +0000857const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
858 switch(FloatingLiteralBits.Semantics) {
859 case IEEEhalf:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000860 return llvm::APFloat::IEEEhalf();
Tim Northover178723a2013-01-22 09:46:51 +0000861 case IEEEsingle:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000862 return llvm::APFloat::IEEEsingle();
Tim Northover178723a2013-01-22 09:46:51 +0000863 case IEEEdouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000864 return llvm::APFloat::IEEEdouble();
Tim Northover178723a2013-01-22 09:46:51 +0000865 case x87DoubleExtended:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000866 return llvm::APFloat::x87DoubleExtended();
Tim Northover178723a2013-01-22 09:46:51 +0000867 case IEEEquad:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000868 return llvm::APFloat::IEEEquad();
Tim Northover178723a2013-01-22 09:46:51 +0000869 case PPCDoubleDouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000870 return llvm::APFloat::PPCDoubleDouble();
Tim Northover178723a2013-01-22 09:46:51 +0000871 }
872 llvm_unreachable("Unrecognised floating semantics");
873}
874
875void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000876 if (&Sem == &llvm::APFloat::IEEEhalf())
Tim Northover178723a2013-01-22 09:46:51 +0000877 FloatingLiteralBits.Semantics = IEEEhalf;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000878 else if (&Sem == &llvm::APFloat::IEEEsingle())
Tim Northover178723a2013-01-22 09:46:51 +0000879 FloatingLiteralBits.Semantics = IEEEsingle;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000880 else if (&Sem == &llvm::APFloat::IEEEdouble())
Tim Northover178723a2013-01-22 09:46:51 +0000881 FloatingLiteralBits.Semantics = IEEEdouble;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000882 else if (&Sem == &llvm::APFloat::x87DoubleExtended())
Tim Northover178723a2013-01-22 09:46:51 +0000883 FloatingLiteralBits.Semantics = x87DoubleExtended;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000884 else if (&Sem == &llvm::APFloat::IEEEquad())
Tim Northover178723a2013-01-22 09:46:51 +0000885 FloatingLiteralBits.Semantics = IEEEquad;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000886 else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
Tim Northover178723a2013-01-22 09:46:51 +0000887 FloatingLiteralBits.Semantics = PPCDoubleDouble;
888 else
889 llvm_unreachable("Unknown floating semantics");
890}
891
Chris Lattnera0173132008-06-07 22:13:43 +0000892/// getValueAsApproximateDouble - This returns the value as an inaccurate
893/// double. Note that this may cause loss of precision, but is useful for
894/// debugging dumps, etc.
895double FloatingLiteral::getValueAsApproximateDouble() const {
896 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000897 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000898 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
Dale Johannesenc48814b2008-10-09 23:02:32 +0000899 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000900 return V.convertToDouble();
901}
902
Bruno Ricciaf214882018-11-15 16:42:14 +0000903unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
904 StringKind SK) {
905 unsigned CharByteWidth = 0;
906 switch (SK) {
907 case Ascii:
908 case UTF8:
909 CharByteWidth = Target.getCharWidth();
910 break;
911 case Wide:
912 CharByteWidth = Target.getWCharWidth();
913 break;
914 case UTF16:
915 CharByteWidth = Target.getChar16Width();
916 break;
917 case UTF32:
918 CharByteWidth = Target.getChar32Width();
919 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000920 }
921 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
922 CharByteWidth /= 8;
Bruno Ricciaf214882018-11-15 16:42:14 +0000923 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
924 "The only supported character byte widths are 1,2 and 4!");
Eli Friedmanfcec6302011-11-01 02:23:42 +0000925 return CharByteWidth;
926}
927
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000928StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
929 StringKind Kind, bool Pascal, QualType Ty,
930 const SourceLocation *Loc,
931 unsigned NumConcatenated)
932 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
933 false) {
934 assert(Ctx.getAsConstantArrayType(Ty) &&
Benjamin Kramercdac7612014-02-25 12:26:20 +0000935 "StringLiteral must be of constant array type!");
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000936 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
937 unsigned ByteLength = Str.size();
938 assert((ByteLength % CharByteWidth == 0) &&
939 "The size of the data must be a multiple of CharByteWidth!");
Benjamin Kramercdac7612014-02-25 12:26:20 +0000940
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000941 // Avoid the expensive division. The compiler should be able to figure it
942 // out by itself. However as of clang 7, even with the appropriate
943 // llvm_unreachable added just here, it is not able to do so.
944 unsigned Length;
945 switch (CharByteWidth) {
946 case 1:
947 Length = ByteLength;
948 break;
949 case 2:
950 Length = ByteLength / 2;
951 break;
952 case 4:
953 Length = ByteLength / 4;
954 break;
955 default:
956 llvm_unreachable("Unsupported character width!");
957 }
Mike Stump11289f42009-09-09 15:08:12 +0000958
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000959 StringLiteralBits.Kind = Kind;
960 StringLiteralBits.CharByteWidth = CharByteWidth;
961 StringLiteralBits.IsPascal = Pascal;
962 StringLiteralBits.NumConcatenated = NumConcatenated;
963 *getTrailingObjects<unsigned>() = Length;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000964
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000965 // Initialize the trailing array of SourceLocation.
966 // This is safe since SourceLocation is POD-like.
967 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
968 NumConcatenated * sizeof(SourceLocation));
Chris Lattnerd3e98952006-10-06 05:22:26 +0000969
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000970 // Initialize the trailing array of char holding the string data.
971 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
Chris Lattner630970d2009-02-18 05:49:11 +0000972}
973
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000974StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
975 unsigned Length, unsigned CharByteWidth)
976 : Expr(StringLiteralClass, Empty) {
977 StringLiteralBits.CharByteWidth = CharByteWidth;
978 StringLiteralBits.NumConcatenated = NumConcatenated;
979 *getTrailingObjects<unsigned>() = Length;
980}
981
982StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
983 StringKind Kind, bool Pascal, QualType Ty,
984 const SourceLocation *Loc,
985 unsigned NumConcatenated) {
986 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
987 1, NumConcatenated, Str.size()),
988 alignof(StringLiteral));
989 return new (Mem)
990 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
991}
992
993StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
994 unsigned NumConcatenated,
995 unsigned Length,
996 unsigned CharByteWidth) {
997 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
998 1, NumConcatenated, Length * CharByteWidth),
999 alignof(StringLiteral));
1000 return new (Mem)
1001 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
Douglas Gregor958dfc92009-04-15 16:35:07 +00001002}
1003
Alexander Kornienko540bacb2013-02-01 12:35:51 +00001004void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +00001005 switch (getKind()) {
1006 case Ascii: break; // no prefix.
1007 case Wide: OS << 'L'; break;
1008 case UTF8: OS << "u8"; break;
1009 case UTF16: OS << 'u'; break;
1010 case UTF32: OS << 'U'; break;
1011 }
1012 OS << '"';
1013 static const char Hex[] = "0123456789ABCDEF";
1014
1015 unsigned LastSlashX = getLength();
1016 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1017 switch (uint32_t Char = getCodeUnit(I)) {
1018 default:
1019 // FIXME: Convert UTF-8 back to codepoints before rendering.
1020
1021 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1022 // Leave invalid surrogates alone; we'll use \x for those.
Fangrui Song6907ce22018-07-30 19:24:48 +00001023 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
Richard Trieudc355912012-06-13 20:25:24 +00001024 Char <= 0xdbff) {
1025 uint32_t Trail = getCodeUnit(I + 1);
1026 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1027 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1028 ++I;
1029 }
1030 }
1031
1032 if (Char > 0xff) {
1033 // If this is a wide string, output characters over 0xff using \x
1034 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1035 // codepoint: use \x escapes for invalid codepoints.
1036 if (getKind() == Wide ||
1037 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1038 // FIXME: Is this the best way to print wchar_t?
1039 OS << "\\x";
1040 int Shift = 28;
1041 while ((Char >> Shift) == 0)
1042 Shift -= 4;
1043 for (/**/; Shift >= 0; Shift -= 4)
1044 OS << Hex[(Char >> Shift) & 15];
1045 LastSlashX = I;
1046 break;
1047 }
1048
1049 if (Char > 0xffff)
1050 OS << "\\U00"
1051 << Hex[(Char >> 20) & 15]
1052 << Hex[(Char >> 16) & 15];
1053 else
1054 OS << "\\u";
1055 OS << Hex[(Char >> 12) & 15]
1056 << Hex[(Char >> 8) & 15]
1057 << Hex[(Char >> 4) & 15]
1058 << Hex[(Char >> 0) & 15];
1059 break;
1060 }
1061
1062 // If we used \x... for the previous character, and this character is a
1063 // hexadecimal digit, prevent it being slurped as part of the \x.
1064 if (LastSlashX + 1 == I) {
1065 switch (Char) {
1066 case '0': case '1': case '2': case '3': case '4':
1067 case '5': case '6': case '7': case '8': case '9':
1068 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1069 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1070 OS << "\"\"";
1071 }
1072 }
1073
1074 assert(Char <= 0xff &&
1075 "Characters above 0xff should already have been handled.");
1076
Jordan Rosea7d03842013-02-08 22:30:41 +00001077 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +00001078 OS << (char)Char;
1079 else // Output anything hard as an octal escape.
1080 OS << '\\'
1081 << (char)('0' + ((Char >> 6) & 7))
1082 << (char)('0' + ((Char >> 3) & 7))
1083 << (char)('0' + ((Char >> 0) & 7));
1084 break;
1085 // Handle some common non-printable cases to make dumps prettier.
1086 case '\\': OS << "\\\\"; break;
1087 case '"': OS << "\\\""; break;
Richard Trieudc355912012-06-13 20:25:24 +00001088 case '\a': OS << "\\a"; break;
1089 case '\b': OS << "\\b"; break;
Benjamin Kramer60a53d52016-11-24 09:41:33 +00001090 case '\f': OS << "\\f"; break;
1091 case '\n': OS << "\\n"; break;
1092 case '\r': OS << "\\r"; break;
1093 case '\t': OS << "\\t"; break;
1094 case '\v': OS << "\\v"; break;
Richard Trieudc355912012-06-13 20:25:24 +00001095 }
1096 }
1097 OS << '"';
1098}
1099
Chris Lattnere925d612010-11-17 07:37:15 +00001100/// getLocationOfByte - Return a source location that points to the specified
1101/// byte of this string literal.
1102///
1103/// Strings are amazingly complex. They can be formed from multiple tokens and
1104/// can have escape sequences in them in addition to the usual trigraph and
1105/// escaped newline business. This routine handles this complexity.
1106///
Richard Smithefb116f2015-12-10 01:11:47 +00001107/// The *StartToken sets the first token to be searched in this function and
1108/// the *StartTokenByteOffset is the byte offset of the first token. Before
1109/// returning, it updates the *StartToken to the TokNo of the token being found
1110/// and sets *StartTokenByteOffset to the byte offset of the token in the
1111/// string.
1112/// Using these two parameters can reduce the time complexity from O(n^2) to
1113/// O(n) if one wants to get the location of byte for all the tokens in a
1114/// string.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001115///
Richard Smithefb116f2015-12-10 01:11:47 +00001116SourceLocation
1117StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1118 const LangOptions &Features,
1119 const TargetInfo &Target, unsigned *StartToken,
1120 unsigned *StartTokenByteOffset) const {
Bruno Ricciaf214882018-11-15 16:42:14 +00001121 assert((getKind() == StringLiteral::Ascii ||
1122 getKind() == StringLiteral::UTF8) &&
Richard Smith4060f772012-06-13 05:37:23 +00001123 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001124
Chris Lattnere925d612010-11-17 07:37:15 +00001125 // Loop over all of the tokens in this string until we find the one that
1126 // contains the byte we're looking for.
1127 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001128 unsigned StringOffset = 0;
1129 if (StartToken)
1130 TokNo = *StartToken;
1131 if (StartTokenByteOffset) {
1132 StringOffset = *StartTokenByteOffset;
1133 ByteNo -= StringOffset;
1134 }
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001135 while (1) {
Chris Lattnere925d612010-11-17 07:37:15 +00001136 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1137 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
Fangrui Song6907ce22018-07-30 19:24:48 +00001138
Chris Lattnere925d612010-11-17 07:37:15 +00001139 // Get the spelling of the string so that we can get the data that makes up
1140 // the string literal, not the identifier for the macro it is potentially
1141 // expanded through.
1142 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001143
Chris Lattnere925d612010-11-17 07:37:15 +00001144 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001145 std::pair<FileID, unsigned> LocInfo =
1146 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001147 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001148 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001149 if (Invalid) {
1150 if (StartTokenByteOffset != nullptr)
1151 *StartTokenByteOffset = StringOffset;
1152 if (StartToken != nullptr)
1153 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001154 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001155 }
1156
Chris Lattnere925d612010-11-17 07:37:15 +00001157 const char *StrData = Buffer.data()+LocInfo.second;
Fangrui Song6907ce22018-07-30 19:24:48 +00001158
Chris Lattnere925d612010-11-17 07:37:15 +00001159 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001160 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1161 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001162 Token TheTok;
1163 TheLexer.LexFromRawLexer(TheTok);
Fangrui Song6907ce22018-07-30 19:24:48 +00001164
Chris Lattnere925d612010-11-17 07:37:15 +00001165 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001166 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001167 unsigned TokNumBytes = SLP.GetStringLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00001168
Chris Lattnere925d612010-11-17 07:37:15 +00001169 // If the byte is in this token, return the location of the byte.
1170 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001171 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001172 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1173
Chris Lattnere925d612010-11-17 07:37:15 +00001174 // Now that we know the offset of the token in the spelling, use the
1175 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001176 if (StartTokenByteOffset != nullptr)
1177 *StartTokenByteOffset = StringOffset;
1178 if (StartToken != nullptr)
1179 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001180 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1181 }
Richard Smithefb116f2015-12-10 01:11:47 +00001182
Chris Lattnere925d612010-11-17 07:37:15 +00001183 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001184 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001185 ++TokNo;
1186 ByteNo -= TokNumBytes;
1187 }
1188}
1189
Chris Lattner1b926492006-08-23 06:42:10 +00001190/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1191/// corresponds to, e.g. "sizeof" or "[pre]++".
Bruno Ricci3dfcb842018-11-13 21:33:22 +00001192StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1193 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001194#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1195#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001196 }
David Blaikief47fa302012-01-17 02:30:50 +00001197 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001198}
1199
John McCalle3027922010-08-25 11:45:40 +00001200UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001201UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1202 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001203 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001204 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1205 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1206 case OO_Amp: return UO_AddrOf;
1207 case OO_Star: return UO_Deref;
1208 case OO_Plus: return UO_Plus;
1209 case OO_Minus: return UO_Minus;
1210 case OO_Tilde: return UO_Not;
1211 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001212 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001213 }
1214}
1215
1216OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1217 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001218 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1219 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1220 case UO_AddrOf: return OO_Amp;
1221 case UO_Deref: return OO_Star;
1222 case UO_Plus: return OO_Plus;
1223 case UO_Minus: return OO_Minus;
1224 case UO_Not: return OO_Tilde;
1225 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001226 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001227 default: return OO_None;
1228 }
1229}
1230
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001231
Chris Lattner0eedafe2006-08-24 04:56:27 +00001232//===----------------------------------------------------------------------===//
1233// Postfix Operators.
1234//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001235
Bruno Riccic5885cf2018-12-21 15:20:32 +00001236CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1237 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1238 SourceLocation RParenLoc, unsigned MinNumArgs,
1239 ADLCallKind UsesADL)
1240 : Expr(SC, Ty, VK, OK_Ordinary, Fn->isTypeDependent(),
1241 Fn->isValueDependent(), Fn->isInstantiationDependent(),
1242 Fn->containsUnexpandedParameterPack()),
1243 RParenLoc(RParenLoc) {
1244 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1245 unsigned NumPreArgs = PreArgs.size();
1246 CallExprBits.NumPreArgs = NumPreArgs;
1247 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1248
1249 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1250 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1251 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1252 "OffsetToTrailingObjects overflow!");
1253
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001254 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1255
Bruno Riccic5885cf2018-12-21 15:20:32 +00001256 setCallee(Fn);
1257 for (unsigned I = 0; I != NumPreArgs; ++I) {
1258 updateDependenciesFromArg(PreArgs[I]);
1259 setPreArg(I, PreArgs[I]);
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001260 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00001261 for (unsigned I = 0; I != Args.size(); ++I) {
1262 updateDependenciesFromArg(Args[I]);
1263 setArg(I, Args[I]);
Douglas Gregora6e053e2010-12-15 01:34:56 +00001264 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00001265 for (unsigned I = Args.size(); I != NumArgs; ++I) {
1266 setArg(I, nullptr);
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001267 }
Douglas Gregor993603d2008-11-14 16:09:21 +00001268}
Nate Begeman1e36a852008-01-17 17:46:27 +00001269
Bruno Riccic5885cf2018-12-21 15:20:32 +00001270CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1271 EmptyShell Empty)
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001272 : Expr(SC, Empty), NumArgs(NumArgs) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001273 CallExprBits.NumPreArgs = NumPreArgs;
Bruno Riccic5885cf2018-12-21 15:20:32 +00001274 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1275
1276 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1277 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1278 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1279 "OffsetToTrailingObjects overflow!");
Douglas Gregore20a2e52009-04-15 17:43:59 +00001280}
1281
Bruno Riccic5885cf2018-12-21 15:20:32 +00001282CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1283 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1284 SourceLocation RParenLoc, unsigned MinNumArgs,
1285 ADLCallKind UsesADL) {
1286 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1287 unsigned SizeOfTrailingObjects =
1288 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1289 void *Mem =
1290 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1291 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1292 RParenLoc, MinNumArgs, UsesADL);
1293}
1294
1295CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1296 ExprValueKind VK, SourceLocation RParenLoc,
1297 ADLCallKind UsesADL) {
1298 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1299 "Misaligned memory in CallExpr::CreateTemporary!");
1300 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1301 VK, RParenLoc, /*MinNumArgs=*/0, UsesADL);
1302}
1303
1304CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1305 EmptyShell Empty) {
1306 unsigned SizeOfTrailingObjects =
1307 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1308 void *Mem =
1309 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1310 return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1311}
1312
1313unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1314 switch (SC) {
1315 case CallExprClass:
1316 return sizeof(CallExpr);
1317 case CXXOperatorCallExprClass:
1318 return sizeof(CXXOperatorCallExpr);
1319 case CXXMemberCallExprClass:
1320 return sizeof(CXXMemberCallExpr);
1321 case UserDefinedLiteralClass:
1322 return sizeof(UserDefinedLiteral);
1323 case CUDAKernelCallExprClass:
1324 return sizeof(CUDAKernelCallExpr);
1325 default:
1326 llvm_unreachable("unexpected class deriving from CallExpr!");
1327 }
1328}
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001329
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001330void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1331 if (Arg->isTypeDependent())
1332 ExprBits.TypeDependent = true;
1333 if (Arg->isValueDependent())
1334 ExprBits.ValueDependent = true;
1335 if (Arg->isInstantiationDependent())
1336 ExprBits.InstantiationDependent = true;
1337 if (Arg->containsUnexpandedParameterPack())
1338 ExprBits.ContainsUnexpandedParameterPack = true;
1339}
1340
John McCallb92ab1a2016-10-26 23:46:34 +00001341Decl *Expr::getReferencedDeclOfCallee() {
1342 Expr *CEE = IgnoreParenImpCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00001343
Douglas Gregore0e96302011-09-06 21:41:04 +00001344 while (SubstNonTypeTemplateParmExpr *NTTP
1345 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1346 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1347 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001348
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001349 // If we're calling a dereference, look at the pointer instead.
1350 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1351 if (BO->isPtrMemOp())
1352 CEE = BO->getRHS()->IgnoreParenCasts();
1353 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1354 if (UO->getOpcode() == UO_Deref)
1355 CEE = UO->getSubExpr()->IgnoreParenCasts();
1356 }
Chris Lattner52301912009-07-17 15:46:27 +00001357 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001358 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001359 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1360 return ME->getMemberDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001361
Craig Topper36250ad2014-05-12 05:36:57 +00001362 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001363}
1364
Alp Tokera724cff2013-12-28 21:59:02 +00001365/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001366/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001367unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001368 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001369 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001370 // ImplicitCastExpr.
1371 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1372 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001373 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001374
Steve Narofff6e3b3292008-01-31 01:07:12 +00001375 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1376 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001377 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001378
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001379 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1380 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001381 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001382
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001383 if (!FDecl->getIdentifier())
1384 return 0;
1385
Douglas Gregor15fc9562009-09-12 00:22:50 +00001386 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001387}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001388
Scott Douglass503fc392015-06-10 13:53:15 +00001389bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001390 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001391 return Ctx.BuiltinInfo.isUnevaluated(BI);
1392 return false;
1393}
1394
David Majnemerced8bdf2015-02-25 17:36:15 +00001395QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1396 const Expr *Callee = getCallee();
1397 QualType CalleeType = Callee->getType();
1398 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001399 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001400 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001401 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001402 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1403 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1404 return Ctx.VoidTy;
1405
John McCall0009fcc2011-04-26 20:42:42 +00001406 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001407 CalleeType = Expr::findBoundMemberType(Callee);
1408 }
1409
John McCall0009fcc2011-04-26 20:42:42 +00001410 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001411 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001412}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001413
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00001414const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1415 // If the return type is a struct, union, or enum that is marked nodiscard,
1416 // then return the return type attribute.
1417 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1418 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1419 return A;
1420
1421 // Otherwise, see if the callee is marked nodiscard and return that attribute
1422 // instead.
1423 const Decl *D = getCalleeDecl();
1424 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1425}
1426
Stephen Kelly724e9e52018-08-09 20:05:03 +00001427SourceLocation CallExpr::getBeginLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001428 if (isa<CXXOperatorCallExpr>(this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001429 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001430
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001431 SourceLocation begin = getCallee()->getBeginLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001432 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001433 begin = getArg(0)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001434 return begin;
1435}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001436SourceLocation CallExpr::getEndLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001437 if (isa<CXXOperatorCallExpr>(this))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001438 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001439
1440 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001441 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001442 end = getArg(getNumArgs() - 1)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001443 return end;
1444}
John McCall701417a2011-02-21 06:23:05 +00001445
Craig Topper37932912013-08-18 10:09:15 +00001446OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001447 SourceLocation OperatorLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001448 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001449 ArrayRef<OffsetOfNode> comps,
1450 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001451 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001452 void *Mem = C.Allocate(
1453 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001454
Benjamin Kramerc215e762012-08-24 11:54:20 +00001455 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1456 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001457}
1458
Craig Topper37932912013-08-18 10:09:15 +00001459OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001460 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001461 void *Mem =
1462 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001463 return new (Mem) OffsetOfExpr(numComps, numExprs);
1464}
1465
Craig Topper37932912013-08-18 10:09:15 +00001466OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001467 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001468 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001469 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001470 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
Fangrui Song6907ce22018-07-30 19:24:48 +00001471 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001472 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001473 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001474 tsi->getType()->containsUnexpandedParameterPack()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001475 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001476 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001477{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001478 for (unsigned i = 0; i != comps.size(); ++i) {
1479 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001480 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001481
Benjamin Kramerc215e762012-08-24 11:54:20 +00001482 for (unsigned i = 0; i != exprs.size(); ++i) {
1483 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001484 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001485 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001486 ExprBits.ContainsUnexpandedParameterPack = true;
1487
Benjamin Kramerc215e762012-08-24 11:54:20 +00001488 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001489 }
1490}
1491
James Y Knight7281c352015-12-29 22:31:18 +00001492IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001493 assert(getKind() == Field || getKind() == Identifier);
1494 if (getKind() == Field)
1495 return getField()->getIdentifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00001496
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001497 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001498}
1499
David Majnemer10fd83d2015-01-15 10:04:14 +00001500UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1501 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1502 SourceLocation op, SourceLocation rp)
1503 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1504 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1505 // Value-dependent if the argument is type-dependent.
1506 E->isTypeDependent(), E->isInstantiationDependent(),
1507 E->containsUnexpandedParameterPack()),
1508 OpLoc(op), RParenLoc(rp) {
1509 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1510 UnaryExprOrTypeTraitExprBits.IsType = false;
1511 Argument.Ex = E;
1512
1513 // Check to see if we are in the situation where alignof(decl) should be
1514 // dependent because decl's alignment is dependent.
Richard Smith6822bd72018-10-26 19:26:45 +00001515 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
David Majnemer10fd83d2015-01-15 10:04:14 +00001516 if (!isValueDependent() || !isInstantiationDependent()) {
1517 E = E->IgnoreParens();
1518
1519 const ValueDecl *D = nullptr;
1520 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1521 D = DRE->getDecl();
1522 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1523 D = ME->getMemberDecl();
1524
1525 if (D) {
1526 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1527 if (I->isAlignmentDependent()) {
1528 setValueDependent(true);
1529 setInstantiationDependent(true);
1530 break;
1531 }
1532 }
1533 }
1534 }
1535 }
1536}
1537
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001538MemberExpr *MemberExpr::Create(
1539 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1540 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1541 ValueDecl *memberdecl, DeclAccessPair founddecl,
1542 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1543 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001544
Douglas Gregorea972d32011-02-28 21:54:11 +00001545 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001546 founddecl.getDecl() != memberdecl ||
1547 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001548
James Y Knighte7d82282015-12-29 18:15:14 +00001549 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1550 std::size_t Size =
1551 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1552 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1553 HasTemplateKWAndArgsInfo ? 1 : 0,
1554 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001555
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001556 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001557 MemberExpr *E = new (Mem)
1558 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001559
1560 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001561 // FIXME: Wrong. We should be looking at the member declaration we found.
1562 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001563 E->setValueDependent(true);
1564 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001565 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001566 }
1567 else if (QualifierLoc &&
1568 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001569 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001570
Bruno Ricci4c742532018-11-15 13:56:22 +00001571 E->MemberExprBits.HasQualifierOrFoundDecl = true;
John McCall16df1e52010-03-30 21:47:33 +00001572
James Y Knighte7d82282015-12-29 18:15:14 +00001573 MemberExprNameQualifier *NQ =
1574 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001575 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001576 NQ->FoundDecl = founddecl;
1577 }
1578
Bruno Ricci4c742532018-11-15 13:56:22 +00001579 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1580 (targs || TemplateKWLoc.isValid());
Abramo Bagnara7945c982012-01-27 09:46:47 +00001581
John McCall16df1e52010-03-30 21:47:33 +00001582 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001583 bool Dependent = false;
1584 bool InstantiationDependent = false;
1585 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001586 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1587 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1588 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001589 if (InstantiationDependent)
1590 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001591 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001592 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1593 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001594 }
1595
1596 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001597}
1598
Stephen Kelly724e9e52018-08-09 20:05:03 +00001599SourceLocation MemberExpr::getBeginLoc() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001600 if (isImplicitAccess()) {
1601 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001602 return getQualifierLoc().getBeginLoc();
1603 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001604 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001605
Daniel Dunbarb507f272012-03-09 15:39:15 +00001606 // FIXME: We don't want this to happen. Rather, we should be able to
1607 // detect all kinds of implicit accesses more cleanly.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001608 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001609 if (BaseStartLoc.isValid())
1610 return BaseStartLoc;
1611 return MemberLoc;
1612}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001613SourceLocation MemberExpr::getEndLoc() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001614 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001615 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001616 EndLoc = getRAngleLoc();
1617 else if (EndLoc.isInvalid())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001618 EndLoc = getBase()->getEndLoc();
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001619 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001620}
1621
Alp Tokerc1086762013-12-07 13:51:35 +00001622bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001623 switch (getCastKind()) {
1624 case CK_DerivedToBase:
1625 case CK_UncheckedDerivedToBase:
1626 case CK_DerivedToBaseMemberPointer:
1627 case CK_BaseToDerived:
1628 case CK_BaseToDerivedMemberPointer:
1629 assert(!path_empty() && "Cast kind should have a base path!");
1630 break;
1631
1632 case CK_CPointerToObjCPointerCast:
1633 assert(getType()->isObjCObjectPointerType());
1634 assert(getSubExpr()->getType()->isPointerType());
1635 goto CheckNoBasePath;
1636
1637 case CK_BlockPointerToObjCPointerCast:
1638 assert(getType()->isObjCObjectPointerType());
1639 assert(getSubExpr()->getType()->isBlockPointerType());
1640 goto CheckNoBasePath;
1641
John McCallc62bb392012-02-15 01:22:51 +00001642 case CK_ReinterpretMemberPointer:
1643 assert(getType()->isMemberPointerType());
1644 assert(getSubExpr()->getType()->isMemberPointerType());
1645 goto CheckNoBasePath;
1646
John McCall9320b872011-09-09 05:25:32 +00001647 case CK_BitCast:
1648 // Arbitrary casts to C pointer types count as bitcasts.
1649 // Otherwise, we should only have block and ObjC pointer casts
1650 // here if they stay within the type kind.
1651 if (!getType()->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001652 assert(getType()->isObjCObjectPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001653 getSubExpr()->getType()->isObjCObjectPointerType());
Fangrui Song6907ce22018-07-30 19:24:48 +00001654 assert(getType()->isBlockPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001655 getSubExpr()->getType()->isBlockPointerType());
1656 }
1657 goto CheckNoBasePath;
1658
1659 case CK_AnyPointerToBlockPointerCast:
1660 assert(getType()->isBlockPointerType());
1661 assert(getSubExpr()->getType()->isAnyPointerType() &&
1662 !getSubExpr()->getType()->isBlockPointerType());
1663 goto CheckNoBasePath;
1664
Douglas Gregored90df32012-02-22 05:02:47 +00001665 case CK_CopyAndAutoreleaseBlockObject:
1666 assert(getType()->isBlockPointerType());
1667 assert(getSubExpr()->getType()->isBlockPointerType());
1668 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001669
1670 case CK_FunctionToPointerDecay:
1671 assert(getType()->isPointerType());
1672 assert(getSubExpr()->getType()->isFunctionType());
1673 goto CheckNoBasePath;
1674
Anastasia Stulova04307942018-11-16 16:22:56 +00001675 case CK_AddressSpaceConversion: {
1676 auto Ty = getType();
1677 auto SETy = getSubExpr()->getType();
1678 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
Anastasia Stulovad1986d12019-01-14 11:44:22 +00001679 if (isRValue()) {
Anastasia Stulova04307942018-11-16 16:22:56 +00001680 Ty = Ty->getPointeeType();
Anastasia Stulova04307942018-11-16 16:22:56 +00001681 SETy = SETy->getPointeeType();
Anastasia Stulovad1986d12019-01-14 11:44:22 +00001682 }
Anastasia Stulova04307942018-11-16 16:22:56 +00001683 assert(!Ty.isNull() && !SETy.isNull() &&
1684 Ty.getAddressSpace() != SETy.getAddressSpace());
1685 goto CheckNoBasePath;
1686 }
John McCall9320b872011-09-09 05:25:32 +00001687 // These should not have an inheritance path.
1688 case CK_Dynamic:
1689 case CK_ToUnion:
1690 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001691 case CK_NullToMemberPointer:
1692 case CK_NullToPointer:
1693 case CK_ConstructorConversion:
1694 case CK_IntegralToPointer:
1695 case CK_PointerToIntegral:
1696 case CK_ToVoid:
1697 case CK_VectorSplat:
1698 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001699 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001700 case CK_IntegralToFloating:
1701 case CK_FloatingToIntegral:
1702 case CK_FloatingCast:
1703 case CK_ObjCObjectLValueCast:
1704 case CK_FloatingRealToComplex:
1705 case CK_FloatingComplexToReal:
1706 case CK_FloatingComplexCast:
1707 case CK_FloatingComplexToIntegralComplex:
1708 case CK_IntegralRealToComplex:
1709 case CK_IntegralComplexToReal:
1710 case CK_IntegralComplexCast:
1711 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001712 case CK_ARCProduceObject:
1713 case CK_ARCConsumeObject:
1714 case CK_ARCReclaimReturnedObject:
1715 case CK_ARCExtendBlockObject:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001716 case CK_ZeroToOCLOpaqueType:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001717 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00001718 case CK_FixedPointCast:
John McCall9320b872011-09-09 05:25:32 +00001719 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1720 goto CheckNoBasePath;
1721
1722 case CK_Dependent:
1723 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001724 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001725 case CK_AtomicToNonAtomic:
1726 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001727 case CK_PointerToBoolean:
1728 case CK_IntegralToBoolean:
1729 case CK_FloatingToBoolean:
1730 case CK_MemberPointerToBoolean:
1731 case CK_FloatingComplexToBoolean:
1732 case CK_IntegralComplexToBoolean:
1733 case CK_LValueBitCast: // -> bool&
1734 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001735 case CK_BuiltinFnToFnPtr:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001736 case CK_FixedPointToBoolean:
John McCall9320b872011-09-09 05:25:32 +00001737 CheckNoBasePath:
1738 assert(path_empty() && "Cast kind should not have a base path!");
1739 break;
1740 }
Alp Tokerc1086762013-12-07 13:51:35 +00001741 return true;
John McCall9320b872011-09-09 05:25:32 +00001742}
1743
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001744const char *CastExpr::getCastKindName(CastKind CK) {
1745 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001746#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1747#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001748 }
John McCallc5e62b42010-11-13 09:02:35 +00001749 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001750}
1751
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001752namespace {
Richard Smith1ef75542018-06-27 20:30:34 +00001753 const Expr *skipImplicitTemporary(const Expr *E) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001754 // Skip through reference binding to temporary.
Richard Smith1ef75542018-06-27 20:30:34 +00001755 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1756 E = Materialize->GetTemporaryExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001757
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001758 // Skip any temporary bindings; they're implicit.
Richard Smith1ef75542018-06-27 20:30:34 +00001759 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1760 E = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001761
Richard Smith1ef75542018-06-27 20:30:34 +00001762 return E;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001763 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001764}
1765
Douglas Gregord196a582009-12-14 19:27:10 +00001766Expr *CastExpr::getSubExprAsWritten() {
Richard Smith1ef75542018-06-27 20:30:34 +00001767 const Expr *SubExpr = nullptr;
1768 const CastExpr *E = this;
Douglas Gregord196a582009-12-14 19:27:10 +00001769 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001770 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001771
Douglas Gregord196a582009-12-14 19:27:10 +00001772 // Conversions by constructor and conversion functions have a
1773 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001774 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001775 SubExpr =
1776 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001777 else if (E->getCastKind() == CK_UserDefinedConversion) {
1778 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1779 isa<BlockExpr>(SubExpr)) &&
1780 "Unexpected SubExpr for CK_UserDefinedConversion.");
Richard Smith1ef75542018-06-27 20:30:34 +00001781 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1782 SubExpr = MCE->getImplicitObjectArgument();
Manman Ren8abc2e52016-02-02 22:23:03 +00001783 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001784
Douglas Gregord196a582009-12-14 19:27:10 +00001785 // If the subexpression we're left with is an implicit cast, look
1786 // through that, too.
Fangrui Song6907ce22018-07-30 19:24:48 +00001787 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1788
Richard Smith1ef75542018-06-27 20:30:34 +00001789 return const_cast<Expr*>(SubExpr);
1790}
1791
1792NamedDecl *CastExpr::getConversionFunction() const {
1793 const Expr *SubExpr = nullptr;
1794
1795 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1796 SubExpr = skipImplicitTemporary(E->getSubExpr());
1797
1798 if (E->getCastKind() == CK_ConstructorConversion)
1799 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1800
1801 if (E->getCastKind() == CK_UserDefinedConversion) {
1802 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1803 return MCE->getMethodDecl();
1804 }
1805 }
1806
1807 return nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001808}
1809
John McCallcf142162010-08-07 06:22:56 +00001810CXXBaseSpecifier **CastExpr::path_buffer() {
1811 switch (getStmtClass()) {
1812#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001813#define CASTEXPR(Type, Base) \
1814 case Stmt::Type##Class: \
1815 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001816#define STMT(Type, Base)
1817#include "clang/AST/StmtNodes.inc"
1818 default:
1819 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001820 }
1821}
1822
John McCallf1ef7962017-08-15 21:42:47 +00001823const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1824 QualType opType) {
1825 auto RD = unionType->castAs<RecordType>()->getDecl();
1826 return getTargetFieldForToUnionCast(RD, opType);
1827}
1828
1829const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1830 QualType OpType) {
1831 auto &Ctx = RD->getASTContext();
1832 RecordDecl::field_iterator Field, FieldEnd;
1833 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1834 Field != FieldEnd; ++Field) {
1835 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1836 !Field->isUnnamedBitfield()) {
1837 return *Field;
1838 }
1839 }
1840 return nullptr;
1841}
1842
Craig Topper37932912013-08-18 10:09:15 +00001843ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001844 CastKind Kind, Expr *Operand,
1845 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001846 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001847 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001848 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001849 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001850 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001851 if (PathSize)
1852 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1853 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001854 return E;
1855}
1856
Craig Topper37932912013-08-18 10:09:15 +00001857ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001858 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001859 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001860 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1861}
1862
1863
Craig Topper37932912013-08-18 10:09:15 +00001864CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001865 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001866 const CXXCastPath *BasePath,
1867 TypeSourceInfo *WrittenTy,
1868 SourceLocation L, SourceLocation R) {
1869 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001870 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001871 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001872 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001873 if (PathSize)
1874 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1875 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001876 return E;
1877}
1878
Craig Topper37932912013-08-18 10:09:15 +00001879CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1880 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001881 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001882 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1883}
1884
Chris Lattner1b926492006-08-23 06:42:10 +00001885/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1886/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001887StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001888 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001889#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1890#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001891 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001892 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001893}
Steve Naroff47500512007-04-19 23:00:49 +00001894
John McCalle3027922010-08-25 11:45:40 +00001895BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001896BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1897 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001898 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001899 case OO_Plus: return BO_Add;
1900 case OO_Minus: return BO_Sub;
1901 case OO_Star: return BO_Mul;
1902 case OO_Slash: return BO_Div;
1903 case OO_Percent: return BO_Rem;
1904 case OO_Caret: return BO_Xor;
1905 case OO_Amp: return BO_And;
1906 case OO_Pipe: return BO_Or;
1907 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00001908 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00001909 case OO_Less: return BO_LT;
1910 case OO_Greater: return BO_GT;
1911 case OO_PlusEqual: return BO_AddAssign;
1912 case OO_MinusEqual: return BO_SubAssign;
1913 case OO_StarEqual: return BO_MulAssign;
1914 case OO_SlashEqual: return BO_DivAssign;
1915 case OO_PercentEqual: return BO_RemAssign;
1916 case OO_CaretEqual: return BO_XorAssign;
1917 case OO_AmpEqual: return BO_AndAssign;
1918 case OO_PipeEqual: return BO_OrAssign;
1919 case OO_LessLess: return BO_Shl;
1920 case OO_GreaterGreater: return BO_Shr;
1921 case OO_LessLessEqual: return BO_ShlAssign;
1922 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1923 case OO_EqualEqual: return BO_EQ;
1924 case OO_ExclaimEqual: return BO_NE;
1925 case OO_LessEqual: return BO_LE;
1926 case OO_GreaterEqual: return BO_GE;
1927 case OO_AmpAmp: return BO_LAnd;
1928 case OO_PipePipe: return BO_LOr;
1929 case OO_Comma: return BO_Comma;
1930 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001931 }
1932}
1933
1934OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1935 static const OverloadedOperatorKind OverOps[] = {
1936 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1937 OO_Star, OO_Slash, OO_Percent,
1938 OO_Plus, OO_Minus,
1939 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00001940 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001941 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1942 OO_EqualEqual, OO_ExclaimEqual,
1943 OO_Amp,
1944 OO_Caret,
1945 OO_Pipe,
1946 OO_AmpAmp,
1947 OO_PipePipe,
1948 OO_Equal, OO_StarEqual,
1949 OO_SlashEqual, OO_PercentEqual,
1950 OO_PlusEqual, OO_MinusEqual,
1951 OO_LessLessEqual, OO_GreaterGreaterEqual,
1952 OO_AmpEqual, OO_CaretEqual,
1953 OO_PipeEqual,
1954 OO_Comma
1955 };
1956 return OverOps[Opc];
1957}
1958
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001959bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
1960 Opcode Opc,
1961 Expr *LHS, Expr *RHS) {
1962 if (Opc != BO_Add)
1963 return false;
1964
1965 // Check that we have one pointer and one integer operand.
1966 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001967 if (LHS->getType()->isPointerType()) {
1968 if (!RHS->getType()->isIntegerType())
1969 return false;
1970 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001971 } else if (RHS->getType()->isPointerType()) {
1972 if (!LHS->getType()->isIntegerType())
1973 return false;
1974 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001975 } else {
1976 return false;
1977 }
1978
1979 // Check that the pointer is a nullptr.
1980 if (!PExp->IgnoreParenCasts()
1981 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
1982 return false;
1983
1984 // Check that the pointee type is char-sized.
1985 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1986 if (!PTy || !PTy->getPointeeType()->isCharType())
1987 return false;
1988
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001989 return true;
1990}
Craig Topper37932912013-08-18 10:09:15 +00001991InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001992 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001993 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1994 false, false),
1995 InitExprs(C, initExprs.size()),
1996 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
1997{
Sebastian Redlc83ed822012-02-17 08:42:25 +00001998 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00001999 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002000 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00002001 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00002002 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00002003 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002004 if (initExprs[I]->isInstantiationDependent())
2005 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00002006 if (initExprs[I]->containsUnexpandedParameterPack())
2007 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00002008 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002009
Benjamin Kramerc215e762012-08-24 11:54:20 +00002010 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00002011}
Chris Lattner1ec5f562007-06-27 05:38:08 +00002012
Craig Topper37932912013-08-18 10:09:15 +00002013void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002014 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00002015 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002016}
2017
Craig Topper37932912013-08-18 10:09:15 +00002018void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00002019 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002020}
2021
Craig Topper37932912013-08-18 10:09:15 +00002022Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002023 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00002024 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00002025 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00002026 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002027 }
Mike Stump11289f42009-09-09 15:08:12 +00002028
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002029 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00002030 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002031 return Result;
2032}
2033
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002034void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00002035 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002036 ArrayFillerOrUnionFieldInit = filler;
2037 // Fill out any "holes" in the array due to designated initializers.
2038 Expr **inits = getInits();
2039 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00002040 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002041 inits[i] = filler;
2042}
2043
Richard Smith9ec1e482012-04-15 02:50:59 +00002044bool InitListExpr::isStringLiteralInit() const {
2045 if (getNumInits() != 1)
2046 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00002047 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2048 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00002049 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00002050 // It is possible for getInit() to return null.
2051 const Expr *Init = getInit(0);
2052 if (!Init)
2053 return false;
2054 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00002055 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2056}
2057
Richard Smith122f88d2016-12-06 23:52:28 +00002058bool InitListExpr::isTransparent() const {
2059 assert(isSemanticForm() && "syntactic form never semantically transparent");
2060
2061 // A glvalue InitListExpr is always just sugar.
2062 if (isGLValue()) {
2063 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2064 return true;
2065 }
2066
2067 // Otherwise, we're sugar if and only if we have exactly one initializer that
2068 // is of the same type.
2069 if (getNumInits() != 1 || !getInit(0))
2070 return false;
2071
Richard Smith382bc512017-02-23 22:41:47 +00002072 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2073 // transparent struct copy.
2074 if (!getInit(0)->isRValue() && getType()->isRecordType())
2075 return false;
2076
Richard Smith122f88d2016-12-06 23:52:28 +00002077 return getType().getCanonicalType() ==
2078 getInit(0)->getType().getCanonicalType();
2079}
2080
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002081bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2082 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2083
2084 if (LangOpts.CPlusPlus || getNumInits() != 1) {
2085 return false;
2086 }
2087
2088 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
2089 return Lit && Lit->getValue() == 0;
2090}
2091
Stephen Kelly724e9e52018-08-09 20:05:03 +00002092SourceLocation InitListExpr::getBeginLoc() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00002093 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002094 return SyntacticForm->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002095 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002096 if (Beg.isInvalid()) {
2097 // Find the first non-null initializer.
2098 for (InitExprsTy::const_iterator I = InitExprs.begin(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002099 E = InitExprs.end();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002100 I != E; ++I) {
2101 if (Stmt *S = *I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002102 Beg = S->getBeginLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002103 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002104 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002105 }
2106 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002107 return Beg;
2108}
2109
Stephen Kelly02a67ba2018-08-09 20:05:47 +00002110SourceLocation InitListExpr::getEndLoc() const {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002111 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002112 return SyntacticForm->getEndLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002113 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002114 if (End.isInvalid()) {
2115 // Find the first non-null initializer from the end.
2116 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002117 E = InitExprs.rend();
2118 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002119 if (Stmt *S = *I) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002120 End = S->getEndLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002121 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002122 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002123 }
2124 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002125 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002126}
2127
Steve Naroff991e99d2008-09-04 15:31:07 +00002128/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002129///
John McCallc833dea2012-02-17 03:32:35 +00002130const FunctionProtoType *BlockExpr::getFunctionType() const {
2131 // The block pointer is never sugared, but the function type might be.
2132 return cast<BlockPointerType>(getType())
2133 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002134}
2135
Mike Stump11289f42009-09-09 15:08:12 +00002136SourceLocation BlockExpr::getCaretLocation() const {
2137 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002138}
Mike Stump11289f42009-09-09 15:08:12 +00002139const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002140 return TheBlock->getBody();
2141}
Mike Stump11289f42009-09-09 15:08:12 +00002142Stmt *BlockExpr::getBody() {
2143 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002144}
Steve Naroff415d3d52008-10-08 17:01:13 +00002145
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002146
Chris Lattner1ec5f562007-06-27 05:38:08 +00002147//===----------------------------------------------------------------------===//
2148// Generic Expression Routines
2149//===----------------------------------------------------------------------===//
2150
Chris Lattner237f2752009-02-14 07:37:35 +00002151/// isUnusedResultAWarning - Return true if this immediate expression should
2152/// be warned about if the result is unused. If so, fill in Loc and Ranges
2153/// with location to warn on and the source range[s] to report with the
2154/// warning.
Fangrui Song6907ce22018-07-30 19:24:48 +00002155bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
Eli Friedmanc11535c2012-05-24 00:47:05 +00002156 SourceRange &R1, SourceRange &R2,
2157 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002158 // Don't warn if the expr is type dependent. The type could end up
2159 // instantiating to void.
2160 if (isTypeDependent())
2161 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002162
Chris Lattner1ec5f562007-06-27 05:38:08 +00002163 switch (getStmtClass()) {
2164 default:
John McCallc493a732010-03-12 07:11:26 +00002165 if (getType()->isVoidType())
2166 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002167 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002168 Loc = getExprLoc();
2169 R1 = getSourceRange();
2170 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002171 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002172 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002173 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002174 case GenericSelectionExprClass:
2175 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002176 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002177 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002178 case CoyieldExprClass:
2179 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002180 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002181 case ChooseExprClass:
2182 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2183 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002184 case UnaryOperatorClass: {
2185 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002186
Chris Lattner1ec5f562007-06-27 05:38:08 +00002187 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002188 case UO_Plus:
2189 case UO_Minus:
2190 case UO_AddrOf:
2191 case UO_Not:
2192 case UO_LNot:
2193 case UO_Deref:
2194 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002195 case UO_Coawait:
2196 // This is just the 'operator co_await' call inside the guts of a
2197 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002198 case UO_PostInc:
2199 case UO_PostDec:
2200 case UO_PreInc:
2201 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002202 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002203 case UO_Real:
2204 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002205 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002206 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2207 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002208 return false;
2209 break;
John McCalle3027922010-08-25 11:45:40 +00002210 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002211 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002212 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002213 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002214 Loc = UO->getOperatorLoc();
2215 R1 = UO->getSubExpr()->getSourceRange();
2216 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002217 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002218 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002219 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002220 switch (BO->getOpcode()) {
2221 default:
2222 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002223 // Consider the RHS of comma for side effects. LHS was checked by
2224 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002225 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002226 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2227 // lvalue-ness) of an assignment written in a macro.
2228 if (IntegerLiteral *IE =
2229 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2230 if (IE->getValue() == 0)
2231 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002232 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002233 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002234 case BO_LAnd:
2235 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002236 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2237 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002238 return false;
2239 break;
John McCall1e3715a2010-02-16 04:10:53 +00002240 }
Chris Lattner237f2752009-02-14 07:37:35 +00002241 if (BO->isAssignmentOp())
2242 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002243 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002244 Loc = BO->getOperatorLoc();
2245 R1 = BO->getLHS()->getSourceRange();
2246 R2 = BO->getRHS()->getSourceRange();
2247 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002248 }
Chris Lattner86928112007-08-25 02:00:02 +00002249 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002250 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002251 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002252 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002253
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002254 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002255 // If only one of the LHS or RHS is a warning, the operator might
2256 // be being used for control flow. Only warn if both the LHS and
2257 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002258 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002259 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00002260 return false;
2261 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00002262 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002263 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002264 }
2265
Chris Lattnera44d1162007-06-27 05:58:59 +00002266 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002267 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002268 Loc = cast<MemberExpr>(this)->getMemberLoc();
2269 R1 = SourceRange(Loc, Loc);
2270 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2271 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002272
Chris Lattner1ec5f562007-06-27 05:38:08 +00002273 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002274 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002275 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2276 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2277 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2278 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002279
Chandler Carruth46339472011-08-17 09:49:44 +00002280 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002281 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002282 // overloads as there is no reasonable way to define these such that they
2283 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002284 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002285 // provides additional value as well. If this list is updated,
2286 // DiagnoseUnusedComparison should be as well.
2287 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002288 switch (Op->getOperator()) {
2289 default:
2290 break;
2291 case OO_EqualEqual:
2292 case OO_ExclaimEqual:
2293 case OO_Less:
2294 case OO_Greater:
2295 case OO_GreaterEqual:
2296 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002297 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2298 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002299 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002300 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002301 Loc = Op->getOperatorLoc();
2302 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002303 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002304 }
Chandler Carruth46339472011-08-17 09:49:44 +00002305
2306 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002307 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002308 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002309 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002310 case CXXMemberCallExprClass:
2311 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002312 // If this is a direct call, get the callee.
2313 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002314 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner237f2752009-02-14 07:37:35 +00002315 // If the callee has attribute pure, const, or warn_unused_result, warn
2316 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002317 //
2318 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2319 // updated to match for QoI.
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00002320 if (CE->hasUnusedResultAttr(Ctx) ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002321 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002322 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002323 Loc = CE->getCallee()->getBeginLoc();
Chris Lattner1a6babf2009-10-13 04:53:48 +00002324 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002325
Chris Lattner1a6babf2009-10-13 04:53:48 +00002326 if (unsigned NumArgs = CE->getNumArgs())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002327 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002328 CE->getArg(NumArgs - 1)->getEndLoc());
Chris Lattner1a6babf2009-10-13 04:53:48 +00002329 return true;
2330 }
Chris Lattner237f2752009-02-14 07:37:35 +00002331 }
2332 return false;
2333 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002334
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002335 // If we don't know precisely what we're looking at, let's not warn.
2336 case UnresolvedLookupExprClass:
2337 case CXXUnresolvedConstructExprClass:
2338 return false;
2339
Anders Carlsson6aa50392009-11-17 17:11:23 +00002340 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002341 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002342 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2343 if (Type->hasAttr<WarnUnusedAttr>()) {
2344 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002345 Loc = getBeginLoc();
Lubos Lunak1f490f32013-07-21 13:15:58 +00002346 R1 = getSourceRange();
2347 return true;
2348 }
2349 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002350 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002351 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002352
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002353 case ObjCMessageExprClass: {
2354 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002355 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002356 ME->isInstanceMessage() &&
2357 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002358 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002359 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002360 Loc = getExprLoc();
2361 R1 = ME->getSourceRange();
2362 return true;
2363 }
2364
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002365 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002366 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002367 WarnE = this;
2368 Loc = getExprLoc();
2369 return true;
2370 }
2371
Chris Lattner237f2752009-02-14 07:37:35 +00002372 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002373 }
Mike Stump11289f42009-09-09 15:08:12 +00002374
John McCallb7bd14f2010-12-02 01:19:52 +00002375 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002376 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002377 Loc = getExprLoc();
2378 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002379 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002380
John McCallfe96e0b2011-11-06 09:01:30 +00002381 case PseudoObjectExprClass: {
2382 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2383
2384 // Only complain about things that have the form of a getter.
2385 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2386 isa<BinaryOperator>(PO->getSyntacticForm()))
2387 return false;
2388
Eli Friedmanc11535c2012-05-24 00:47:05 +00002389 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002390 Loc = getExprLoc();
2391 R1 = getSourceRange();
2392 return true;
2393 }
2394
Chris Lattner944d3062008-07-26 19:51:01 +00002395 case StmtExprClass: {
2396 // Statement exprs don't logically have side effects themselves, but are
2397 // sometimes used in macros in ways that give them a type that is unused.
2398 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2399 // however, if the result of the stmt expr is dead, we don't want to emit a
2400 // warning.
2401 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002402 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002403 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002404 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002405 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2406 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002407 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002408 }
Mike Stump11289f42009-09-09 15:08:12 +00002409
John McCallc493a732010-03-12 07:11:26 +00002410 if (getType()->isVoidType())
2411 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002412 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002413 Loc = cast<StmtExpr>(this)->getLParenLoc();
2414 R1 = getSourceRange();
2415 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002416 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002417 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002418 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002419 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002420 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002421 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002422 if (CE->getCastKind() == CK_ToVoid) {
2423 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002424 CE->getSubExpr()->getType().isVolatileQualified()) {
2425 const DeclRefExpr *DRE =
2426 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2427 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002428 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2429 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002430 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2431 R1, R2, Ctx);
2432 }
2433 }
Chris Lattner2706a552009-07-28 18:25:28 +00002434 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002435 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002436
Eli Friedmanc11535c2012-05-24 00:47:05 +00002437 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002438 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002439 if (CE->getCastKind() == CK_ConstructorConversion)
2440 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002441
Eli Friedmanc11535c2012-05-24 00:47:05 +00002442 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002443 if (const CXXFunctionalCastExpr *CXXCE =
2444 dyn_cast<CXXFunctionalCastExpr>(this)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002445 Loc = CXXCE->getBeginLoc();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002446 R1 = CXXCE->getSubExpr()->getSourceRange();
2447 } else {
2448 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2449 Loc = CStyleCE->getLParenLoc();
2450 R1 = CStyleCE->getSubExpr()->getSourceRange();
2451 }
Chris Lattner237f2752009-02-14 07:37:35 +00002452 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002453 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002454 case ImplicitCastExprClass: {
2455 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002456
Eli Friedmanc11535c2012-05-24 00:47:05 +00002457 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2458 if (ICE->getCastKind() == CK_LValueToRValue &&
2459 ICE->getSubExpr()->getType().isVolatileQualified())
2460 return false;
2461
2462 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2463 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002464 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002465 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002466 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002467 case CXXDefaultInitExprClass:
2468 return (cast<CXXDefaultInitExpr>(this)
2469 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002470
2471 case CXXNewExprClass:
2472 // FIXME: In theory, there might be new expressions that don't have side
2473 // effects (e.g. a placement new with an uninitialized POD).
2474 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002475 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002476 case MaterializeTemporaryExprClass:
2477 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2478 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002479 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002480 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2481 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002482 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002483 return cast<ExprWithCleanups>(this)->getSubExpr()
2484 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002485 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002486}
2487
Fariborz Jahanian07735332009-02-22 18:40:18 +00002488/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002489/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002490bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002491 const Expr *E = IgnoreParens();
2492 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002493 default:
2494 return false;
2495 case ObjCIvarRefExprClass:
2496 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002497 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002498 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002499 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002500 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002501 case MaterializeTemporaryExprClass:
2502 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2503 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002504 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002505 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002506 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002507 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002508
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002509 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2510 if (VD->hasGlobalStorage())
2511 return true;
2512 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002513 // dereferencing to a pointer is always a gc'able candidate,
2514 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002515 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002516 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002517 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002518 return false;
2519 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002520 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002521 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002522 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002523 }
2524 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002525 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002526 }
2527}
Sebastian Redlce354af2010-09-10 20:55:33 +00002528
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002529bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2530 if (isTypeDependent())
2531 return false;
John McCall086a4642010-11-24 05:12:34 +00002532 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002533}
2534
John McCall0009fcc2011-04-26 20:42:42 +00002535QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002536 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002537
2538 // Bound member expressions are always one of these possibilities:
2539 // x->m x.m x->*y x.*y
2540 // (possibly parenthesized)
2541
2542 expr = expr->IgnoreParens();
2543 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2544 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2545 return mem->getMemberDecl()->getType();
2546 }
2547
2548 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2549 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2550 ->getPointeeType();
2551 assert(type->isFunctionType());
2552 return type;
2553 }
2554
David Majnemerced8bdf2015-02-25 17:36:15 +00002555 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002556 return QualType();
2557}
2558
Ted Kremenekfff70962008-01-17 16:57:34 +00002559Expr* Expr::IgnoreParens() {
2560 Expr* E = this;
Abramo Bagnara932e3932010-10-15 07:51:18 +00002561 while (true) {
2562 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2563 E = P->getSubExpr();
2564 continue;
2565 }
2566 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2567 if (P->getOpcode() == UO_Extension) {
2568 E = P->getSubExpr();
2569 continue;
2570 }
2571 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002572 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2573 if (!P->isResultDependent()) {
2574 E = P->getResultExpr();
2575 continue;
2576 }
2577 }
Eli Friedman75807f22013-07-20 00:40:58 +00002578 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2579 if (!P->isConditionDependent()) {
2580 E = P->getChosenSubExpr();
2581 continue;
2582 }
2583 }
Reid Kleckner423b6532018-12-26 17:44:40 +00002584 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E)) {
2585 E = CE->getSubExpr();
2586 continue;
2587 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002588 return E;
2589 }
Ted Kremenekfff70962008-01-17 16:57:34 +00002590}
2591
Chris Lattnerf2660962008-02-13 01:02:39 +00002592/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2593/// or CastExprs or ImplicitCastExprs, returning their operand.
2594Expr *Expr::IgnoreParenCasts() {
2595 Expr *E = this;
2596 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002597 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002598 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002599 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002600 continue;
2601 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002602 if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002603 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2604 E = Materialize->GetTemporaryExpr();
2605 continue;
2606 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002607 if (SubstNonTypeTemplateParmExpr *NTTP
2608 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2609 E = NTTP->getReplacement();
2610 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002611 }
Fangrui Song407659a2018-11-30 23:41:18 +00002612 if (FullExpr *FE = dyn_cast<FullExpr>(E)) {
2613 E = FE->getSubExpr();
Bill Wendling8003edc2018-11-09 00:41:36 +00002614 continue;
2615 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002616 return E;
Chris Lattnerf2660962008-02-13 01:02:39 +00002617 }
2618}
2619
Ted Kremenek6f375e52014-04-16 07:26:09 +00002620Expr *Expr::IgnoreCasts() {
2621 Expr *E = this;
2622 while (true) {
2623 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2624 E = P->getSubExpr();
2625 continue;
2626 }
2627 if (MaterializeTemporaryExpr *Materialize
2628 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2629 E = Materialize->GetTemporaryExpr();
2630 continue;
2631 }
2632 if (SubstNonTypeTemplateParmExpr *NTTP
2633 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2634 E = NTTP->getReplacement();
2635 continue;
2636 }
Fangrui Song407659a2018-11-30 23:41:18 +00002637 if (FullExpr *FE = dyn_cast<FullExpr>(E)) {
2638 E = FE->getSubExpr();
Bill Wendling8003edc2018-11-09 00:41:36 +00002639 continue;
2640 }
Ted Kremenek6f375e52014-04-16 07:26:09 +00002641 return E;
2642 }
2643}
2644
John McCall5a4ce8b2010-12-04 08:24:19 +00002645/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2646/// casts. This is intended purely as a temporary workaround for code
2647/// that hasn't yet been rewritten to do the right thing about those
2648/// casts, and may disappear along with the last internal use.
John McCall34376a62010-12-04 03:47:34 +00002649Expr *Expr::IgnoreParenLValueCasts() {
2650 Expr *E = this;
John McCall5a4ce8b2010-12-04 08:24:19 +00002651 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002652 E = E->IgnoreParens();
2653 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00002654 if (P->getCastKind() == CK_LValueToRValue) {
2655 E = P->getSubExpr();
2656 continue;
2657 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002658 } else if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002659 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2660 E = Materialize->GetTemporaryExpr();
2661 continue;
Douglas Gregor6a40b082011-09-08 17:56:33 +00002662 } else if (SubstNonTypeTemplateParmExpr *NTTP
2663 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2664 E = NTTP->getReplacement();
2665 continue;
Fangrui Song407659a2018-11-30 23:41:18 +00002666 } else if (FullExpr *FE = dyn_cast<FullExpr>(E)) {
2667 E = FE->getSubExpr();
Bill Wendling8003edc2018-11-09 00:41:36 +00002668 continue;
John McCall34376a62010-12-04 03:47:34 +00002669 }
2670 break;
2671 }
2672 return E;
2673}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002674
2675Expr *Expr::ignoreParenBaseCasts() {
2676 Expr *E = this;
2677 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002678 E = E->IgnoreParens();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002679 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2680 if (CE->getCastKind() == CK_DerivedToBase ||
2681 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2682 CE->getCastKind() == CK_NoOp) {
2683 E = CE->getSubExpr();
2684 continue;
2685 }
2686 }
2687
2688 return E;
2689 }
2690}
2691
John McCalleebc8322010-05-05 22:59:52 +00002692Expr *Expr::IgnoreParenImpCasts() {
2693 Expr *E = this;
2694 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002695 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002696 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCalleebc8322010-05-05 22:59:52 +00002697 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002698 continue;
2699 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002700 if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002701 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2702 E = Materialize->GetTemporaryExpr();
2703 continue;
2704 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002705 if (SubstNonTypeTemplateParmExpr *NTTP
2706 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2707 E = NTTP->getReplacement();
2708 continue;
2709 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002710 return E;
John McCalleebc8322010-05-05 22:59:52 +00002711 }
2712}
2713
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002714Expr *Expr::IgnoreConversionOperator() {
2715 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002716 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002717 return MCE->getImplicitObjectArgument();
2718 }
2719 return this;
2720}
2721
Chris Lattneref26c772009-03-13 17:28:01 +00002722/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2723/// value (including ptr->int casts of the same size). Strip off any
2724/// ParenExpr or CastExprs, returning their operand.
2725Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2726 Expr *E = this;
2727 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002728 E = E->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00002729
Chris Lattneref26c772009-03-13 17:28:01 +00002730 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2731 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregorb90df602010-06-16 00:17:44 +00002732 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattneref26c772009-03-13 17:28:01 +00002733 Expr *SE = P->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002734
Chris Lattneref26c772009-03-13 17:28:01 +00002735 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2736 E = SE;
2737 continue;
2738 }
Mike Stump11289f42009-09-09 15:08:12 +00002739
Abramo Bagnara932e3932010-10-15 07:51:18 +00002740 if ((E->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002741 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnara932e3932010-10-15 07:51:18 +00002742 (SE->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002743 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattneref26c772009-03-13 17:28:01 +00002744 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2745 E = SE;
2746 continue;
2747 }
2748 }
Mike Stump11289f42009-09-09 15:08:12 +00002749
Douglas Gregor6a40b082011-09-08 17:56:33 +00002750 if (SubstNonTypeTemplateParmExpr *NTTP
2751 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2752 E = NTTP->getReplacement();
2753 continue;
2754 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002755
Chris Lattneref26c772009-03-13 17:28:01 +00002756 return E;
2757 }
2758}
2759
Douglas Gregord196a582009-12-14 19:27:10 +00002760bool Expr::isDefaultArgument() const {
2761 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002762 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2763 E = M->GetTemporaryExpr();
2764
Douglas Gregord196a582009-12-14 19:27:10 +00002765 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2766 E = ICE->getSubExprAsWritten();
Fangrui Song6907ce22018-07-30 19:24:48 +00002767
Douglas Gregord196a582009-12-14 19:27:10 +00002768 return isa<CXXDefaultArgExpr>(E);
2769}
Chris Lattneref26c772009-03-13 17:28:01 +00002770
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002771/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002772/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002773static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002774 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2775 E = M->GetTemporaryExpr();
2776
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002777 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002778 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002779 E = ICE->getSubExpr();
2780 else
2781 break;
2782 }
2783
2784 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2785 E = BE->getSubExpr();
2786
2787 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002788 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002789 E = ICE->getSubExpr();
2790 else
2791 break;
2792 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002793
2794 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002795}
2796
John McCall7a626f62010-09-15 10:14:12 +00002797/// isTemporaryObject - Determines if this expression produces a
2798/// temporary of the given class type.
2799bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2800 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2801 return false;
2802
Anders Carlsson66bbf502010-11-28 16:40:49 +00002803 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002804
John McCall02dc8c72010-09-15 20:59:13 +00002805 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002806 if (!E->Classify(C).isPRValue()) {
2807 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002808 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002809 return false;
2810 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002811
John McCallf4ee1dd2010-09-16 06:57:56 +00002812 // Black-list a few cases which yield pr-values of class type that don't
2813 // refer to temporaries of that type:
2814
2815 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002816 if (isa<ImplicitCastExpr>(E)) {
2817 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2818 case CK_DerivedToBase:
2819 case CK_UncheckedDerivedToBase:
2820 return false;
2821 default:
2822 break;
2823 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002824 }
2825
John McCallf4ee1dd2010-09-16 06:57:56 +00002826 // - member expressions (all)
2827 if (isa<MemberExpr>(E))
2828 return false;
2829
Eli Friedman13ffdd82012-06-15 23:51:06 +00002830 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2831 if (BO->isPtrMemOp())
2832 return false;
2833
John McCallc07a0c72011-02-17 10:25:35 +00002834 // - opaque values (all)
2835 if (isa<OpaqueValueExpr>(E))
2836 return false;
2837
John McCall7a626f62010-09-15 10:14:12 +00002838 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002839}
2840
Douglas Gregor25b7e052011-03-02 21:06:53 +00002841bool Expr::isImplicitCXXThis() const {
2842 const Expr *E = this;
Fangrui Song6907ce22018-07-30 19:24:48 +00002843
Douglas Gregor25b7e052011-03-02 21:06:53 +00002844 // Strip away parentheses and casts we don't care about.
2845 while (true) {
2846 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2847 E = Paren->getSubExpr();
2848 continue;
2849 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002850
Douglas Gregor25b7e052011-03-02 21:06:53 +00002851 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2852 if (ICE->getCastKind() == CK_NoOp ||
2853 ICE->getCastKind() == CK_LValueToRValue ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002854 ICE->getCastKind() == CK_DerivedToBase ||
Douglas Gregor25b7e052011-03-02 21:06:53 +00002855 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2856 E = ICE->getSubExpr();
2857 continue;
2858 }
2859 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002860
Douglas Gregor25b7e052011-03-02 21:06:53 +00002861 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2862 if (UnOp->getOpcode() == UO_Extension) {
2863 E = UnOp->getSubExpr();
2864 continue;
2865 }
2866 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002867
Douglas Gregorfe314812011-06-21 17:03:29 +00002868 if (const MaterializeTemporaryExpr *M
2869 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2870 E = M->GetTemporaryExpr();
2871 continue;
2872 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002873
Douglas Gregor25b7e052011-03-02 21:06:53 +00002874 break;
2875 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002876
Douglas Gregor25b7e052011-03-02 21:06:53 +00002877 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2878 return This->isImplicit();
Fangrui Song6907ce22018-07-30 19:24:48 +00002879
Douglas Gregor25b7e052011-03-02 21:06:53 +00002880 return false;
2881}
2882
Douglas Gregor4619e432008-12-05 23:32:09 +00002883/// hasAnyTypeDependentArguments - Determines if any of the expressions
2884/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002885bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002886 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002887 if (Exprs[I]->isTypeDependent())
2888 return true;
2889
2890 return false;
2891}
2892
Abramo Bagnara847c6602014-05-22 19:20:46 +00002893bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2894 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002895 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002896 // which can be evaluated at compile-time. It very closely parallels
2897 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2898 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2899 // to isEvaluatable most of the time.
2900 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002901 // If we ever capture reference-binding directly in the AST, we can
2902 // kill the second parameter.
2903
2904 if (IsForRef) {
2905 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002906 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2907 return true;
2908 if (Culprit)
2909 *Culprit = this;
2910 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002911 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002912
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002913 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002914 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002915 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002916 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002917 return true;
John McCall81c9cea2010-08-01 21:51:45 +00002918 case CXXTemporaryObjectExprClass:
2919 case CXXConstructExprClass: {
2920 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00002921
Eli Friedman4c27ac22013-07-16 22:40:53 +00002922 if (CE->getConstructor()->isTrivial() &&
2923 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2924 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00002925 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00002926
Eli Friedman4c27ac22013-07-16 22:40:53 +00002927 // Trivial copy constructor
2928 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00002929 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00002930 }
2931
Richard Smithd62306a2011-11-10 06:34:14 +00002932 break;
John McCall81c9cea2010-08-01 21:51:45 +00002933 }
Fangrui Song407659a2018-11-30 23:41:18 +00002934 case ConstantExprClass: {
2935 // FIXME: We should be able to return "true" here, but it can lead to extra
2936 // error messages. E.g. in Sema/array-init.c.
2937 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
2938 return Exp->isConstantInitializer(Ctx, false, Culprit);
2939 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002940 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002941 // This handles gcc's extension that allows global initializers like
2942 // "struct x {int x;} x = (struct x) {};".
2943 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002944 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002945 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002946 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00002947 case DesignatedInitUpdateExprClass: {
2948 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2949 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2950 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2951 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002952 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002953 const InitListExpr *ILE = cast<InitListExpr>(this);
2954 if (ILE->getType()->isArrayType()) {
2955 unsigned numInits = ILE->getNumInits();
2956 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002957 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002958 return false;
2959 }
2960 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002961 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002962
2963 if (ILE->getType()->isRecordType()) {
2964 unsigned ElementNo = 0;
2965 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00002966 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002967 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00002968 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00002969 continue;
2970
2971 // Don't emit anonymous bitfields, they just affect layout.
2972 if (Field->isUnnamedBitfield())
2973 continue;
2974
2975 if (ElementNo < ILE->getNumInits()) {
2976 const Expr *Elt = ILE->getInit(ElementNo++);
2977 if (Field->isBitField()) {
2978 // Bitfields have to evaluate to an integer.
Fangrui Song407659a2018-11-30 23:41:18 +00002979 EvalResult Result;
2980 if (!Elt->EvaluateAsInt(Result, Ctx)) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002981 if (Culprit)
2982 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00002983 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002984 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002985 } else {
2986 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002987 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002988 return false;
2989 }
2990 }
2991 }
2992 return true;
2993 }
2994
2995 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002996 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00002997 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002998 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00002999 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00003000 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00003001 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003002 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00003003 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00003004 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003005 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00003006 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00003007 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3008 if (Culprit)
3009 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00003010 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003011 }
Eli Friedman75807f22013-07-20 00:40:58 +00003012 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003013 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003014 case UnaryOperatorClass: {
3015 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00003016 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003017 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003018 break;
3019 }
John McCall8b0f4ff2010-08-02 21:13:48 +00003020 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00003021 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00003022 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00003023 case CStyleCastExprClass:
3024 case ObjCBridgedCastExprClass:
3025 case CXXDynamicCastExprClass:
3026 case CXXReinterpretCastExprClass:
3027 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00003028 const CastExpr *CE = cast<CastExpr>(this);
3029
Eli Friedman13ec75b2011-12-21 00:43:02 +00003030 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00003031 if (CE->getCastKind() == CK_NoOp ||
3032 CE->getCastKind() == CK_LValueToRValue ||
3033 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00003034 CE->getCastKind() == CK_ConstructorConversion ||
3035 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003036 CE->getCastKind() == CK_AtomicToNonAtomic ||
3037 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003038 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00003039
Eli Friedman384da272009-01-25 03:12:18 +00003040 break;
Richard Smith161f09a2011-12-06 22:44:34 +00003041 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003042 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003043 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003044 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003045
Eli Friedman4c27ac22013-07-16 22:40:53 +00003046 case SubstNonTypeTemplateParmExprClass:
3047 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003048 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003049 case CXXDefaultArgExprClass:
3050 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003051 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003052 case CXXDefaultInitExprClass:
3053 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003054 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003055 }
Richard Smithce8eca52015-12-08 03:21:47 +00003056 // Allow certain forms of UB in constant initializers: signed integer
3057 // overflow and floating-point division by zero. We'll give a warning on
3058 // these, but they're common enough that we have to accept them.
3059 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00003060 return true;
3061 if (Culprit)
3062 *Culprit = this;
3063 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00003064}
3065
Nico Weber758fbac2018-02-13 21:31:47 +00003066bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3067 const FunctionDecl* FD = getDirectCallee();
3068 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3069 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3070 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003071
Nico Weber758fbac2018-02-13 21:31:47 +00003072 const Expr* Arg = getArg(0);
3073 bool ArgVal;
3074 return !Arg->isValueDependent() &&
3075 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3076}
3077
Scott Douglasscc013592015-06-10 15:18:23 +00003078namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003079 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00003080 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003081 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00003082 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003083 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00003084
3085 public:
3086 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003087 : Inherited(Context),
3088 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00003089
3090 bool hasSideEffects() const { return HasSideEffects; }
3091
3092 void VisitExpr(const Expr *E) {
3093 if (!HasSideEffects &&
3094 E->HasSideEffects(Context, IncludePossibleEffects))
3095 HasSideEffects = true;
3096 }
3097 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003098}
Scott Douglasscc013592015-06-10 15:18:23 +00003099
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003100bool Expr::HasSideEffects(const ASTContext &Ctx,
3101 bool IncludePossibleEffects) const {
3102 // In circumstances where we care about definite side effects instead of
3103 // potential side effects, we want to ignore expressions that are part of a
3104 // macro expansion as a potential side effect.
3105 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3106 return false;
3107
Richard Smith0421ce72012-08-07 04:16:51 +00003108 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003109 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00003110
3111 switch (getStmtClass()) {
3112 case NoStmtClass:
3113 #define ABSTRACT_STMT(Type)
3114 #define STMT(Type, Base) case Type##Class:
3115 #define EXPR(Type, Base)
3116 #include "clang/AST/StmtNodes.inc"
3117 llvm_unreachable("unexpected Expr kind");
3118
3119 case DependentScopeDeclRefExprClass:
3120 case CXXUnresolvedConstructExprClass:
3121 case CXXDependentScopeMemberExprClass:
3122 case UnresolvedLookupExprClass:
3123 case UnresolvedMemberExprClass:
3124 case PackExpansionExprClass:
3125 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00003126 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003127 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00003128 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003129 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3130
Richard Smitha33e4fe2012-08-07 05:18:29 +00003131 case DeclRefExprClass:
3132 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003133 case PredefinedExprClass:
3134 case IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003135 case FixedPointLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003136 case FloatingLiteralClass:
3137 case ImaginaryLiteralClass:
3138 case StringLiteralClass:
3139 case CharacterLiteralClass:
3140 case OffsetOfExprClass:
3141 case ImplicitValueInitExprClass:
3142 case UnaryExprOrTypeTraitExprClass:
3143 case AddrLabelExprClass:
3144 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003145 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003146 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003147 case CXXBoolLiteralExprClass:
3148 case CXXNullPtrLiteralExprClass:
3149 case CXXThisExprClass:
3150 case CXXScalarValueInitExprClass:
3151 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003152 case ArrayTypeTraitExprClass:
3153 case ExpressionTraitExprClass:
3154 case CXXNoexceptExprClass:
3155 case SizeOfPackExprClass:
3156 case ObjCStringLiteralClass:
3157 case ObjCEncodeExprClass:
3158 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003159 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003160 case CXXUuidofExprClass:
3161 case OpaqueValueExprClass:
3162 // These never have a side-effect.
3163 return false;
3164
Bill Wendling7c44da22018-10-31 03:48:47 +00003165 case ConstantExprClass:
3166 // FIXME: Move this into the "return false;" block above.
3167 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3168 Ctx, IncludePossibleEffects);
3169
Richard Smith0421ce72012-08-07 04:16:51 +00003170 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003171 case CXXOperatorCallExprClass:
3172 case CXXMemberCallExprClass:
3173 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003174 case UserDefinedLiteralClass: {
3175 // We don't know a call definitely has side effects, except for calls
3176 // to pure/const functions that definitely don't.
3177 // If the call itself is considered side-effect free, check the operands.
3178 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3179 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3180 if (IsPure || !IncludePossibleEffects)
3181 break;
3182 return true;
3183 }
3184
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003185 case BlockExprClass:
3186 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003187 if (!IncludePossibleEffects)
3188 break;
3189 return true;
3190
John McCall5e77d762013-04-16 07:28:30 +00003191 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003192 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003193 case CompoundAssignOperatorClass:
3194 case VAArgExprClass:
3195 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003196 case CXXThrowExprClass:
3197 case CXXNewExprClass:
3198 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003199 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003200 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003201 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003202 // These always have a side-effect.
3203 return true;
3204
Scott Douglasscc013592015-06-10 15:18:23 +00003205 case StmtExprClass: {
3206 // StmtExprs have a side-effect if any substatement does.
3207 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3208 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3209 return Finder.hasSideEffects();
3210 }
3211
Tim Shen4a05bb82016-06-21 20:29:17 +00003212 case ExprWithCleanupsClass:
3213 if (IncludePossibleEffects)
3214 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3215 return true;
3216 break;
3217
Richard Smith0421ce72012-08-07 04:16:51 +00003218 case ParenExprClass:
3219 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003220 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003221 case MemberExprClass:
3222 case ConditionalOperatorClass:
3223 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003224 case CompoundLiteralExprClass:
3225 case ExtVectorElementExprClass:
3226 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003227 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003228 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003229 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003230 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003231 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003232 case SubstNonTypeTemplateParmExprClass:
3233 case MaterializeTemporaryExprClass:
3234 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003235 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003236 case AsTypeExprClass:
3237 // These have a side-effect if any subexpression does.
3238 break;
3239
Richard Smitha33e4fe2012-08-07 05:18:29 +00003240 case UnaryOperatorClass:
3241 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003242 return true;
3243 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003244
3245 case BinaryOperatorClass:
3246 if (cast<BinaryOperator>(this)->isAssignmentOp())
3247 return true;
3248 break;
3249
Richard Smith0421ce72012-08-07 04:16:51 +00003250 case InitListExprClass:
3251 // FIXME: The children for an InitListExpr doesn't include the array filler.
3252 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003253 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003254 return true;
3255 break;
3256
3257 case GenericSelectionExprClass:
3258 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003259 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003260
3261 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003262 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3263 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003264
3265 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003266 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3267 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003268
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003269 case CXXDefaultInitExprClass: {
3270 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3271 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003272 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003273 // If we've not yet parsed the initializer, assume it has side-effects.
3274 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003275 }
Richard Smith852c9db2013-04-20 22:23:05 +00003276
Richard Smith0421ce72012-08-07 04:16:51 +00003277 case CXXDynamicCastExprClass: {
3278 // A dynamic_cast expression has side-effects if it can throw.
3279 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3280 if (DCE->getTypeAsWritten()->isReferenceType() &&
3281 DCE->getCastKind() == CK_Dynamic)
3282 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003283 }
3284 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003285 case ImplicitCastExprClass:
3286 case CStyleCastExprClass:
3287 case CXXStaticCastExprClass:
3288 case CXXReinterpretCastExprClass:
3289 case CXXConstCastExprClass:
3290 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003291 // While volatile reads are side-effecting in both C and C++, we treat them
3292 // as having possible (not definite) side-effects. This allows idiomatic
3293 // code to behave without warning, such as sizeof(*v) for a volatile-
3294 // qualified pointer.
3295 if (!IncludePossibleEffects)
3296 break;
3297
Richard Smitha33e4fe2012-08-07 05:18:29 +00003298 const CastExpr *CE = cast<CastExpr>(this);
3299 if (CE->getCastKind() == CK_LValueToRValue &&
3300 CE->getSubExpr()->getType().isVolatileQualified())
3301 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003302 break;
3303 }
3304
Richard Smithef8bf432012-08-13 20:08:14 +00003305 case CXXTypeidExprClass:
3306 // typeid might throw if its subexpression is potentially-evaluated, so has
3307 // side-effects in that case whether or not its subexpression does.
3308 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003309
3310 case CXXConstructExprClass:
3311 case CXXTemporaryObjectExprClass: {
3312 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003313 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003314 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003315 // A trivial constructor does not add any side-effects of its own. Just look
3316 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003317 break;
3318 }
3319
Richard Smith5179eb72016-06-28 19:03:57 +00003320 case CXXInheritedCtorInitExprClass: {
3321 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3322 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3323 return true;
3324 break;
3325 }
3326
Richard Smith0421ce72012-08-07 04:16:51 +00003327 case LambdaExprClass: {
3328 const LambdaExpr *LE = cast<LambdaExpr>(this);
Richard Smithb3d203f2018-10-19 19:01:34 +00003329 for (Expr *E : LE->capture_inits())
3330 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003331 return true;
3332 return false;
3333 }
3334
3335 case PseudoObjectExprClass: {
3336 // Only look for side-effects in the semantic form, and look past
3337 // OpaqueValueExpr bindings in that form.
3338 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3339 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3340 E = PO->semantics_end();
3341 I != E; ++I) {
3342 const Expr *Subexpr = *I;
3343 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3344 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003345 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003346 return true;
3347 }
3348 return false;
3349 }
3350
3351 case ObjCBoxedExprClass:
3352 case ObjCArrayLiteralClass:
3353 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003354 case ObjCSelectorExprClass:
3355 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003356 case ObjCIsaExprClass:
3357 case ObjCIndirectCopyRestoreExprClass:
3358 case ObjCSubscriptRefExprClass:
3359 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003360 case ObjCMessageExprClass:
3361 case ObjCPropertyRefExprClass:
3362 // FIXME: Classify these cases better.
3363 if (IncludePossibleEffects)
3364 return true;
3365 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003366 }
3367
3368 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003369 for (const Stmt *SubStmt : children())
3370 if (SubStmt &&
3371 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3372 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003373
3374 return false;
3375}
3376
Douglas Gregor1be329d2012-02-23 07:33:15 +00003377namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003378 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003379 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3380 {
3381 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003382
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003383 bool NonTrivial;
Fangrui Song6907ce22018-07-30 19:24:48 +00003384
Douglas Gregor1be329d2012-02-23 07:33:15 +00003385 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003386 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003387 : Inherited(Context), NonTrivial(false) { }
Fangrui Song6907ce22018-07-30 19:24:48 +00003388
Douglas Gregor1be329d2012-02-23 07:33:15 +00003389 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003390
3391 void VisitCallExpr(const CallExpr *E) {
3392 if (const CXXMethodDecl *Method
3393 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003394 if (Method->isTrivial()) {
3395 // Recurse to children of the call.
3396 Inherited::VisitStmt(E);
3397 return;
3398 }
3399 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003400
Douglas Gregor1be329d2012-02-23 07:33:15 +00003401 NonTrivial = true;
3402 }
Scott Douglass503fc392015-06-10 13:53:15 +00003403
3404 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003405 if (E->getConstructor()->isTrivial()) {
3406 // Recurse to children of the call.
3407 Inherited::VisitStmt(E);
3408 return;
3409 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003410
Douglas Gregor1be329d2012-02-23 07:33:15 +00003411 NonTrivial = true;
3412 }
Scott Douglass503fc392015-06-10 13:53:15 +00003413
3414 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003415 if (E->getTemporary()->getDestructor()->isTrivial()) {
3416 Inherited::VisitStmt(E);
3417 return;
3418 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003419
Douglas Gregor1be329d2012-02-23 07:33:15 +00003420 NonTrivial = true;
3421 }
3422 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003423}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003424
Scott Douglass503fc392015-06-10 13:53:15 +00003425bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003426 NonTrivialCallFinder Finder(Ctx);
3427 Finder.Visit(this);
Fangrui Song6907ce22018-07-30 19:24:48 +00003428 return Finder.hasNonTrivialCall();
Douglas Gregor1be329d2012-02-23 07:33:15 +00003429}
3430
Fangrui Song6907ce22018-07-30 19:24:48 +00003431/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003432/// pointer constant or not, as well as the specific kind of constant detected.
3433/// Null pointer constants can be integer constant expressions with the
3434/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3435/// (a GNU extension).
3436Expr::NullPointerConstantKind
3437Expr::isNullPointerConstant(ASTContext &Ctx,
3438 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003439 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003440 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003441 switch (NPC) {
3442 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003443 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003444 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003445 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003446 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003447 else
3448 return NPCK_NotNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003449
Douglas Gregor56751b52009-09-25 04:25:58 +00003450 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003451 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003452 }
3453 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003454
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003455 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003456 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003457 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003458 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003459 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003460 QualType Pointee = PT->getPointeeType();
Richard Smithdab73ce2018-11-28 06:25:06 +00003461 Qualifiers Qs = Pointee.getQualifiers();
Yaxun Liub7318e02017-10-13 03:37:48 +00003462 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3463 // has non-default address space it is not treated as nullptr.
3464 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3465 // since it cannot be assigned to a pointer to constant address space.
Richard Smithdab73ce2018-11-28 06:25:06 +00003466 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
Yaxun Liub7318e02017-10-13 03:37:48 +00003467 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3468 (Ctx.getLangOpts().OpenCL &&
3469 Ctx.getLangOpts().OpenCLVersion < 200 &&
Richard Smithdab73ce2018-11-28 06:25:06 +00003470 Pointee.getAddressSpace() == LangAS::opencl_private))
3471 Qs.removeAddressSpace();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003472
Richard Smithdab73ce2018-11-28 06:25:06 +00003473 if (Pointee->isVoidType() && Qs.empty() && // to void*
3474 CE->getSubExpr()->getType()->isIntegerType()) // from int
Douglas Gregor56751b52009-09-25 04:25:58 +00003475 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003476 }
Steve Naroffada7d422007-05-20 17:54:12 +00003477 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003478 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3479 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003480 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003481 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3482 // Accept ((void*)0) as a null pointer constant, as many other
3483 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003484 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003485 } else if (const GenericSelectionExpr *GE =
3486 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003487 if (GE->isResultDependent())
3488 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003489 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003490 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3491 if (CE->isConditionDependent())
3492 return NPCK_NotNull;
3493 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003494 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003495 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003496 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003497 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003498 } else if (const CXXDefaultInitExpr *DefaultInit
3499 = dyn_cast<CXXDefaultInitExpr>(this)) {
3500 // See through default initializer expressions.
3501 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003502 } else if (isa<GNUNullExpr>(this)) {
3503 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003504 return NPCK_GNUNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003505 } else if (const MaterializeTemporaryExpr *M
Douglas Gregorfe314812011-06-21 17:03:29 +00003506 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3507 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003508 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3509 if (const Expr *Source = OVE->getSourceExpr())
3510 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003511 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003512
Richard Smith89645bc2013-01-02 12:01:23 +00003513 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003514 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003515 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003516
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003517 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003518 if (!Ctx.getLangOpts().CPlusPlus11 &&
3519 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003520 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3521 const Expr *InitExpr = CLE->getInitializer();
3522 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3523 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3524 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003525 // This expression must be an integer type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003526 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003527 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003528 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003529
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003530 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003531 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3532 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003533 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003534 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003535 if (Lit && !Lit->getValue())
3536 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003537 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003538 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003539 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003540 // If we have an integer constant expression, we need to *evaluate* it and
3541 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003542 if (!isIntegerConstantExpr(Ctx))
3543 return NPCK_NotNull;
3544 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003545
David Blaikie1c7c8f72012-08-08 17:33:31 +00003546 if (EvaluateKnownConstInt(Ctx) != 0)
3547 return NPCK_NotNull;
3548
3549 if (isa<IntegerLiteral>(this))
3550 return NPCK_ZeroLiteral;
3551 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003552}
Steve Narofff7a5da12007-07-28 23:10:27 +00003553
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003554/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003555/// property, find the underlying property reference expression.
3556const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3557 const Expr *E = this;
3558 while (true) {
3559 assert((E->getValueKind() == VK_LValue &&
3560 E->getObjectKind() == OK_ObjCProperty) &&
3561 "expression is not a property reference");
3562 E = E->IgnoreParenCasts();
3563 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3564 if (BO->getOpcode() == BO_Comma) {
3565 E = BO->getRHS();
3566 continue;
3567 }
3568 }
3569
3570 break;
3571 }
3572
3573 return cast<ObjCPropertyRefExpr>(E);
3574}
3575
Anna Zaks97c7ce32012-10-01 20:34:04 +00003576bool Expr::isObjCSelfExpr() const {
3577 const Expr *E = IgnoreParenImpCasts();
3578
3579 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3580 if (!DRE)
3581 return false;
3582
3583 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3584 if (!Param)
3585 return false;
3586
3587 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3588 if (!M)
3589 return false;
3590
3591 return M->getSelfDecl() == Param;
3592}
3593
John McCalld25db7e2013-05-06 21:39:12 +00003594FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003595 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003596
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003597 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003598 if (ICE->getCastKind() == CK_LValueToRValue ||
3599 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003600 E = ICE->getSubExpr()->IgnoreParens();
3601 else
3602 break;
3603 }
3604
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003605 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003606 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003607 if (Field->isBitField())
3608 return Field;
3609
George Burgess IV00f70bd2018-03-01 05:43:23 +00003610 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3611 FieldDecl *Ivar = IvarRef->getDecl();
3612 if (Ivar->isBitField())
3613 return Ivar;
3614 }
John McCalld25db7e2013-05-06 21:39:12 +00003615
Richard Smith7873de02016-08-11 22:25:46 +00003616 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003617 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3618 if (Field->isBitField())
3619 return Field;
3620
Richard Smith7873de02016-08-11 22:25:46 +00003621 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3622 if (Expr *E = BD->getBinding())
3623 return E->getSourceBitField();
3624 }
3625
Eli Friedman609ada22011-07-13 02:05:57 +00003626 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003627 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003628 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003629
Eli Friedman609ada22011-07-13 02:05:57 +00003630 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003631 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003632 }
3633
Richard Smith5b571672014-09-24 23:55:00 +00003634 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3635 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3636 return UnOp->getSubExpr()->getSourceBitField();
3637
Craig Topper36250ad2014-05-12 05:36:57 +00003638 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003639}
3640
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003641bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003642 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003643 const Expr *E = this->IgnoreParens();
Fangrui Song6907ce22018-07-30 19:24:48 +00003644
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003645 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003646 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003647 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003648 E = ICE->getSubExpr()->IgnoreParens();
3649 else
3650 break;
3651 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003652
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003653 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3654 return ASE->getBase()->getType()->isVectorType();
3655
3656 if (isa<ExtVectorElementExpr>(E))
3657 return true;
3658
Richard Smith7873de02016-08-11 22:25:46 +00003659 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3660 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3661 if (auto *E = BD->getBinding())
3662 return E->refersToVectorElement();
3663
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003664 return false;
3665}
3666
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003667bool Expr::refersToGlobalRegisterVar() const {
3668 const Expr *E = this->IgnoreParenImpCasts();
3669
3670 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3671 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3672 if (VD->getStorageClass() == SC_Register &&
3673 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3674 return true;
3675
3676 return false;
3677}
3678
Chris Lattnerb8211f62009-02-16 22:14:05 +00003679/// isArrow - Return true if the base expression is a pointer to vector,
3680/// return false if the base expression is a vector.
3681bool ExtVectorElementExpr::isArrow() const {
3682 return getBase()->getType()->isPointerType();
3683}
3684
Nate Begemance4d7fc2008-04-18 23:10:10 +00003685unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003686 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003687 return VT->getNumElements();
3688 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003689}
3690
Nate Begemanf322eab2008-05-09 06:41:27 +00003691/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003692bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003693 // FIXME: Refactor this code to an accessor on the AST node which returns the
3694 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003695 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003696
3697 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003698 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003699 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003700
Nate Begeman7e5185b2009-01-18 02:01:21 +00003701 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003702 if (Comp[0] == 's' || Comp[0] == 'S')
3703 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003704
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003705 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003706 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003707 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003708
Steve Naroff0d595ca2007-07-30 03:29:09 +00003709 return false;
3710}
Chris Lattner885b4952007-08-02 23:36:59 +00003711
Nate Begemanf322eab2008-05-09 06:41:27 +00003712/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003713void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003714 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003715 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003716 bool isNumericAccessor = false;
3717 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003718 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003719 isNumericAccessor = true;
3720 }
Mike Stump11289f42009-09-09 15:08:12 +00003721
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003722 bool isHi = Comp == "hi";
3723 bool isLo = Comp == "lo";
3724 bool isEven = Comp == "even";
3725 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003726
Nate Begemanf322eab2008-05-09 06:41:27 +00003727 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3728 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003729
Nate Begemanf322eab2008-05-09 06:41:27 +00003730 if (isHi)
3731 Index = e + i;
3732 else if (isLo)
3733 Index = i;
3734 else if (isEven)
3735 Index = 2 * i;
3736 else if (isOdd)
3737 Index = 2 * i + 1;
3738 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003739 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003740
Nate Begemand3862152008-05-13 21:03:02 +00003741 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003742 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003743}
3744
Craig Topper37932912013-08-18 10:09:15 +00003745ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003746 QualType Type, SourceLocation BLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00003747 SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003748 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3749 Type->isDependentType(), Type->isDependentType(),
3750 Type->isInstantiationDependentType(),
3751 Type->containsUnexpandedParameterPack()),
3752 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3753{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003754 SubExprs = new (C) Stmt*[args.size()];
3755 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003756 if (args[i]->isTypeDependent())
3757 ExprBits.TypeDependent = true;
3758 if (args[i]->isValueDependent())
3759 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003760 if (args[i]->isInstantiationDependent())
3761 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003762 if (args[i]->containsUnexpandedParameterPack())
3763 ExprBits.ContainsUnexpandedParameterPack = true;
3764
3765 SubExprs[i] = args[i];
3766 }
3767}
3768
Craig Topper37932912013-08-18 10:09:15 +00003769void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003770 if (SubExprs) C.Deallocate(SubExprs);
3771
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003772 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003773 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003774 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003775}
Nate Begeman48745922009-08-12 02:28:50 +00003776
Bruno Ricci94498c72019-01-26 13:58:15 +00003777GenericSelectionExpr::GenericSelectionExpr(
Bruno Riccidb076832019-01-26 14:15:10 +00003778 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
Bruno Ricci94498c72019-01-26 13:58:15 +00003779 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3780 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3781 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
3782 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
3783 AssocExprs[ResultIndex]->getValueKind(),
3784 AssocExprs[ResultIndex]->getObjectKind(),
3785 AssocExprs[ResultIndex]->isTypeDependent(),
3786 AssocExprs[ResultIndex]->isValueDependent(),
3787 AssocExprs[ResultIndex]->isInstantiationDependent(),
3788 ContainsUnexpandedParameterPack),
3789 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00003790 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00003791 assert(AssocTypes.size() == AssocExprs.size() &&
3792 "Must have the same number of association expressions"
3793 " and TypeSourceInfo!");
3794 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
3795
Bruno Riccidb076832019-01-26 14:15:10 +00003796 GenericSelectionExprBits.GenericLoc = GenericLoc;
3797 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00003798 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00003799 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
3800 std::copy(AssocTypes.begin(), AssocTypes.end(),
3801 getTrailingObjects<TypeSourceInfo *>());
Peter Collingbourne91147592011-04-15 00:35:48 +00003802}
3803
Bruno Ricci94498c72019-01-26 13:58:15 +00003804GenericSelectionExpr::GenericSelectionExpr(
3805 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3806 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3807 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3808 bool ContainsUnexpandedParameterPack)
3809 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
3810 OK_Ordinary,
3811 /*isTypeDependent=*/true,
3812 /*isValueDependent=*/true,
3813 /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
3814 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00003815 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00003816 assert(AssocTypes.size() == AssocExprs.size() &&
3817 "Must have the same number of association expressions"
3818 " and TypeSourceInfo!");
3819
Bruno Riccidb076832019-01-26 14:15:10 +00003820 GenericSelectionExprBits.GenericLoc = GenericLoc;
3821 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00003822 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00003823 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
3824 std::copy(AssocTypes.begin(), AssocTypes.end(),
3825 getTrailingObjects<TypeSourceInfo *>());
3826}
3827
3828GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
3829 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
3830
3831GenericSelectionExpr *GenericSelectionExpr::Create(
3832 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3833 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3834 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3835 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
3836 unsigned NumAssocs = AssocExprs.size();
3837 void *Mem = Context.Allocate(
3838 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3839 alignof(GenericSelectionExpr));
3840 return new (Mem) GenericSelectionExpr(
3841 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
3842 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
3843}
3844
3845GenericSelectionExpr *GenericSelectionExpr::Create(
3846 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3847 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3848 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3849 bool ContainsUnexpandedParameterPack) {
3850 unsigned NumAssocs = AssocExprs.size();
3851 void *Mem = Context.Allocate(
3852 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3853 alignof(GenericSelectionExpr));
3854 return new (Mem) GenericSelectionExpr(
3855 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
3856 RParenLoc, ContainsUnexpandedParameterPack);
3857}
3858
3859GenericSelectionExpr *
3860GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
3861 unsigned NumAssocs) {
3862 void *Mem = Context.Allocate(
3863 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3864 alignof(GenericSelectionExpr));
3865 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
Peter Collingbourne91147592011-04-15 00:35:48 +00003866}
3867
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003868//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003869// DesignatedInitExpr
3870//===----------------------------------------------------------------------===//
3871
Chandler Carruth631abd92011-06-16 06:47:06 +00003872IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003873 assert(Kind == FieldDesignator && "Only valid on a field designator");
3874 if (Field.NameOrField & 0x01)
3875 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3876 else
3877 return getField()->getIdentifier();
3878}
3879
Craig Topper37932912013-08-18 10:09:15 +00003880DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00003881 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003882 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003883 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003884 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003885 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003886 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003887 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003888 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003889 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003890 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003891 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00003892 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003893 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003894
3895 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003896 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003897 *Child++ = Init;
3898
3899 // Copy the designators and their subexpressions, computing
3900 // value-dependence along the way.
3901 unsigned IndexIdx = 0;
3902 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003903 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003904
3905 if (this->Designators[I].isArrayDesignator()) {
3906 // Compute type- and value-dependence.
3907 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003908 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003909 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003910 if (Index->isInstantiationDependent())
3911 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003912 // Propagate unexpanded parameter packs.
3913 if (Index->containsUnexpandedParameterPack())
3914 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003915
3916 // Copy the index expressions into permanent storage.
3917 *Child++ = IndexExprs[IndexIdx++];
3918 } else if (this->Designators[I].isArrayRangeDesignator()) {
3919 // Compute type- and value-dependence.
3920 Expr *Start = IndexExprs[IndexIdx];
3921 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003922 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003923 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00003924 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003925 ExprBits.InstantiationDependent = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003926 } else if (Start->isInstantiationDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003927 End->isInstantiationDependent()) {
3928 ExprBits.InstantiationDependent = true;
3929 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003930
Douglas Gregora6e053e2010-12-15 01:34:56 +00003931 // Propagate unexpanded parameter packs.
3932 if (Start->containsUnexpandedParameterPack() ||
3933 End->containsUnexpandedParameterPack())
3934 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003935
3936 // Copy the start/end expressions into permanent storage.
3937 *Child++ = IndexExprs[IndexIdx++];
3938 *Child++ = IndexExprs[IndexIdx++];
3939 }
3940 }
3941
Benjamin Kramerc215e762012-08-24 11:54:20 +00003942 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00003943}
3944
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003945DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00003946DesignatedInitExpr::Create(const ASTContext &C,
3947 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003948 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003949 SourceLocation ColonOrEqualLoc,
3950 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003951 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003952 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00003953 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003954 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003955 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003956}
3957
Craig Topper37932912013-08-18 10:09:15 +00003958DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00003959 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003960 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003961 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00003962 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3963}
3964
Craig Topper37932912013-08-18 10:09:15 +00003965void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003966 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00003967 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003968 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00003969 NumDesignators = NumDesigs;
3970 for (unsigned I = 0; I != NumDesigs; ++I)
3971 Designators[I] = Desigs[I];
3972}
3973
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003974SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3975 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3976 if (size() == 1)
3977 return DIE->getDesignator(0)->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003978 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003979 DIE->getDesignator(size() - 1)->getEndLoc());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003980}
3981
Stephen Kelly724e9e52018-08-09 20:05:03 +00003982SourceLocation DesignatedInitExpr::getBeginLoc() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003983 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00003984 auto *DIE = const_cast<DesignatedInitExpr *>(this);
3985 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003986 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00003987 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003988 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3989 else
3990 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3991 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00003992 StartLoc =
3993 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003994 return StartLoc;
3995}
3996
Stephen Kelly02a67ba2018-08-09 20:05:47 +00003997SourceLocation DesignatedInitExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003998 return getInit()->getEndLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003999}
4000
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004001Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004002 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004003 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004004}
4005
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004006Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004007 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004008 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004009 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004010}
4011
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004012Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004013 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004014 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004015 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004016}
4017
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004018/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00004019/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00004020void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00004021 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00004022 const Designator *Last) {
4023 unsigned NumNewDesignators = Last - First;
4024 if (NumNewDesignators == 0) {
4025 std::copy_backward(Designators + Idx + 1,
4026 Designators + NumDesignators,
4027 Designators + Idx);
4028 --NumNewDesignators;
4029 return;
4030 } else if (NumNewDesignators == 1) {
4031 Designators[Idx] = *First;
4032 return;
4033 }
4034
Mike Stump11289f42009-09-09 15:08:12 +00004035 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004036 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00004037 std::copy(Designators, Designators + Idx, NewDesignators);
4038 std::copy(First, Last, NewDesignators + Idx);
4039 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4040 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00004041 Designators = NewDesignators;
4042 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4043}
4044
Yunzhong Gaocb779302015-06-10 00:27:52 +00004045DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4046 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4047 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4048 OK_Ordinary, false, false, false, false) {
4049 BaseAndUpdaterExprs[0] = baseExpr;
4050
4051 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4052 ILE->setType(baseExpr->getType());
4053 BaseAndUpdaterExprs[1] = ILE;
4054}
4055
Stephen Kelly724e9e52018-08-09 20:05:03 +00004056SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004057 return getBase()->getBeginLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004058}
4059
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004060SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004061 return getBase()->getEndLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004062}
4063
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004064ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4065 SourceLocation RParenLoc)
4066 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4067 false, false),
4068 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4069 ParenListExprBits.NumExprs = Exprs.size();
4070
4071 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4072 if (Exprs[I]->isTypeDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004073 ExprBits.TypeDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004074 if (Exprs[I]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004075 ExprBits.ValueDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004076 if (Exprs[I]->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00004077 ExprBits.InstantiationDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004078 if (Exprs[I]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004079 ExprBits.ContainsUnexpandedParameterPack = true;
4080
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004081 getTrailingObjects<Stmt *>()[I] = Exprs[I];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004082 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004083}
4084
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004085ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4086 : Expr(ParenListExprClass, Empty) {
4087 ParenListExprBits.NumExprs = NumExprs;
4088}
4089
4090ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4091 SourceLocation LParenLoc,
4092 ArrayRef<Expr *> Exprs,
4093 SourceLocation RParenLoc) {
4094 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4095 alignof(ParenListExpr));
4096 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4097}
4098
4099ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4100 unsigned NumExprs) {
4101 void *Mem =
4102 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4103 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4104}
4105
John McCall1bf58462011-02-16 08:02:54 +00004106const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4107 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4108 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00004109 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4110 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00004111 e = cast<CXXConstructExpr>(e)->getArg(0);
4112 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4113 e = ice->getSubExpr();
4114 return cast<OpaqueValueExpr>(e);
4115}
4116
Craig Topper37932912013-08-18 10:09:15 +00004117PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4118 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00004119 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004120 void *buffer =
4121 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004122 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004123 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4124}
4125
4126PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4127 : Expr(PseudoObjectExprClass, shell) {
4128 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4129}
4130
Craig Topper37932912013-08-18 10:09:15 +00004131PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00004132 ArrayRef<Expr*> semantics,
4133 unsigned resultIndex) {
4134 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004135 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00004136
4137 QualType type;
4138 ExprValueKind VK;
4139 if (resultIndex == NoResult) {
4140 type = C.VoidTy;
4141 VK = VK_RValue;
4142 } else {
4143 assert(resultIndex < semantics.size());
4144 type = semantics[resultIndex]->getType();
4145 VK = semantics[resultIndex]->getValueKind();
4146 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4147 }
4148
James Y Knighte00a67e2015-12-31 04:18:25 +00004149 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004150 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004151 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4152 resultIndex);
4153}
4154
4155PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4156 Expr *syntax, ArrayRef<Expr*> semantics,
4157 unsigned resultIndex)
4158 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4159 /*filled in at end of ctor*/ false, false, false, false) {
4160 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4161 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4162
4163 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4164 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4165 getSubExprsBuffer()[i] = E;
4166
4167 if (E->isTypeDependent())
4168 ExprBits.TypeDependent = true;
4169 if (E->isValueDependent())
4170 ExprBits.ValueDependent = true;
4171 if (E->isInstantiationDependent())
4172 ExprBits.InstantiationDependent = true;
4173 if (E->containsUnexpandedParameterPack())
4174 ExprBits.ContainsUnexpandedParameterPack = true;
4175
4176 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00004177 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00004178 "opaque-value semantic expressions for pseudo-object "
4179 "operations must have sources");
4180 }
4181}
4182
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004183//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004184// Child Iterators for iterating over subexpressions/substatements
4185//===----------------------------------------------------------------------===//
4186
Peter Collingbournee190dee2011-03-11 19:24:49 +00004187// UnaryExprOrTypeTraitExpr
4188Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004189 const_child_range CCR =
4190 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4191 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4192}
4193
4194Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00004195 // If this is of a type and the type is a VLA type (and not a typedef), the
4196 // size expression of the VLA needs to be treated as an executable expression.
4197 // Why isn't this weirdness documented better in StmtIterator?
4198 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004199 if (const VariableArrayType *T =
4200 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4201 return const_child_range(const_child_iterator(T), const_child_iterator());
4202 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00004203 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004204 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004205}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004206
Benjamin Kramerc215e762012-08-24 11:54:20 +00004207AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004208 QualType t, AtomicOp op, SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004209 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4210 false, false, false, false),
4211 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4212{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004213 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4214 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004215 if (args[i]->isTypeDependent())
4216 ExprBits.TypeDependent = true;
4217 if (args[i]->isValueDependent())
4218 ExprBits.ValueDependent = true;
4219 if (args[i]->isInstantiationDependent())
4220 ExprBits.InstantiationDependent = true;
4221 if (args[i]->containsUnexpandedParameterPack())
4222 ExprBits.ContainsUnexpandedParameterPack = true;
4223
4224 SubExprs[i] = args[i];
4225 }
4226}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004227
4228unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4229 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004230 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004231 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004232 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004233 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004234 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004235
Yaxun Liu30d652a2017-08-15 16:02:49 +00004236 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004237 case AO__c11_atomic_store:
4238 case AO__c11_atomic_exchange:
4239 case AO__atomic_load:
4240 case AO__atomic_store:
4241 case AO__atomic_store_n:
4242 case AO__atomic_exchange_n:
4243 case AO__c11_atomic_fetch_add:
4244 case AO__c11_atomic_fetch_sub:
4245 case AO__c11_atomic_fetch_and:
4246 case AO__c11_atomic_fetch_or:
4247 case AO__c11_atomic_fetch_xor:
4248 case AO__atomic_fetch_add:
4249 case AO__atomic_fetch_sub:
4250 case AO__atomic_fetch_and:
4251 case AO__atomic_fetch_or:
4252 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004253 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004254 case AO__atomic_add_fetch:
4255 case AO__atomic_sub_fetch:
4256 case AO__atomic_and_fetch:
4257 case AO__atomic_or_fetch:
4258 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004259 case AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004260 case AO__atomic_fetch_min:
4261 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004262 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004263
Yaxun Liu30d652a2017-08-15 16:02:49 +00004264 case AO__opencl_atomic_store:
4265 case AO__opencl_atomic_exchange:
4266 case AO__opencl_atomic_fetch_add:
4267 case AO__opencl_atomic_fetch_sub:
4268 case AO__opencl_atomic_fetch_and:
4269 case AO__opencl_atomic_fetch_or:
4270 case AO__opencl_atomic_fetch_xor:
4271 case AO__opencl_atomic_fetch_min:
4272 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004273 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004274 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004275
4276 case AO__c11_atomic_compare_exchange_strong:
4277 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004278 return 5;
4279
Yaxun Liu39195062017-08-04 18:16:31 +00004280 case AO__opencl_atomic_compare_exchange_strong:
4281 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004282 case AO__atomic_compare_exchange:
4283 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004284 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004285 }
4286 llvm_unreachable("unknown atomic op");
4287}
Alexey Bataeva1764212015-09-30 09:22:36 +00004288
Yaxun Liu39195062017-08-04 18:16:31 +00004289QualType AtomicExpr::getValueType() const {
4290 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4291 if (auto AT = T->getAs<AtomicType>())
4292 return AT->getValueType();
4293 return T;
4294}
4295
Alexey Bataev31300ed2016-02-04 11:27:03 +00004296QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004297 unsigned ArraySectionCount = 0;
4298 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4299 Base = OASE->getBase();
4300 ++ArraySectionCount;
4301 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004302 while (auto *ASE =
4303 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004304 Base = ASE->getBase();
4305 ++ArraySectionCount;
4306 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004307 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004308 auto OriginalTy = Base->getType();
4309 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4310 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4311 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4312
4313 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4314 if (OriginalTy->isAnyPointerType())
4315 OriginalTy = OriginalTy->getPointeeType();
4316 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004317 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004318 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4319 }
4320 }
4321 return OriginalTy;
4322}