blob: cf488850d375271fe9133bb3654bdd68f7e044f8 [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();
Yaxun Liud83c7402019-02-26 16:20:41 +00001361 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1362 return BE->getBlockDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001363
Craig Topper36250ad2014-05-12 05:36:57 +00001364 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001365}
1366
Alp Tokera724cff2013-12-28 21:59:02 +00001367/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001368/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001369unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001370 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001371 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001372 // ImplicitCastExpr.
1373 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1374 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001375 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001376
Steve Narofff6e3b3292008-01-31 01:07:12 +00001377 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1378 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001379 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001380
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001381 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1382 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001383 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001384
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001385 if (!FDecl->getIdentifier())
1386 return 0;
1387
Douglas Gregor15fc9562009-09-12 00:22:50 +00001388 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001389}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001390
Scott Douglass503fc392015-06-10 13:53:15 +00001391bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001392 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001393 return Ctx.BuiltinInfo.isUnevaluated(BI);
1394 return false;
1395}
1396
David Majnemerced8bdf2015-02-25 17:36:15 +00001397QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1398 const Expr *Callee = getCallee();
1399 QualType CalleeType = Callee->getType();
1400 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001401 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001402 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001403 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001404 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1405 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1406 return Ctx.VoidTy;
1407
John McCall0009fcc2011-04-26 20:42:42 +00001408 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001409 CalleeType = Expr::findBoundMemberType(Callee);
1410 }
1411
John McCall0009fcc2011-04-26 20:42:42 +00001412 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001413 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001414}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001415
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00001416const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1417 // If the return type is a struct, union, or enum that is marked nodiscard,
1418 // then return the return type attribute.
1419 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1420 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1421 return A;
1422
1423 // Otherwise, see if the callee is marked nodiscard and return that attribute
1424 // instead.
1425 const Decl *D = getCalleeDecl();
1426 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1427}
1428
Stephen Kelly724e9e52018-08-09 20:05:03 +00001429SourceLocation CallExpr::getBeginLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001430 if (isa<CXXOperatorCallExpr>(this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001431 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001432
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001433 SourceLocation begin = getCallee()->getBeginLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001434 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001435 begin = getArg(0)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001436 return begin;
1437}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001438SourceLocation CallExpr::getEndLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001439 if (isa<CXXOperatorCallExpr>(this))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001440 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001441
1442 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001443 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001444 end = getArg(getNumArgs() - 1)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001445 return end;
1446}
John McCall701417a2011-02-21 06:23:05 +00001447
Craig Topper37932912013-08-18 10:09:15 +00001448OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001449 SourceLocation OperatorLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001450 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001451 ArrayRef<OffsetOfNode> comps,
1452 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001453 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001454 void *Mem = C.Allocate(
1455 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001456
Benjamin Kramerc215e762012-08-24 11:54:20 +00001457 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1458 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001459}
1460
Craig Topper37932912013-08-18 10:09:15 +00001461OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001462 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001463 void *Mem =
1464 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001465 return new (Mem) OffsetOfExpr(numComps, numExprs);
1466}
1467
Craig Topper37932912013-08-18 10:09:15 +00001468OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001469 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001470 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001471 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001472 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
Fangrui Song6907ce22018-07-30 19:24:48 +00001473 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001474 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001475 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001476 tsi->getType()->containsUnexpandedParameterPack()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001477 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001478 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001479{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001480 for (unsigned i = 0; i != comps.size(); ++i) {
1481 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001482 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001483
Benjamin Kramerc215e762012-08-24 11:54:20 +00001484 for (unsigned i = 0; i != exprs.size(); ++i) {
1485 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001486 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001487 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001488 ExprBits.ContainsUnexpandedParameterPack = true;
1489
Benjamin Kramerc215e762012-08-24 11:54:20 +00001490 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001491 }
1492}
1493
James Y Knight7281c352015-12-29 22:31:18 +00001494IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001495 assert(getKind() == Field || getKind() == Identifier);
1496 if (getKind() == Field)
1497 return getField()->getIdentifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00001498
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001499 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001500}
1501
David Majnemer10fd83d2015-01-15 10:04:14 +00001502UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1503 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1504 SourceLocation op, SourceLocation rp)
1505 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1506 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1507 // Value-dependent if the argument is type-dependent.
1508 E->isTypeDependent(), E->isInstantiationDependent(),
1509 E->containsUnexpandedParameterPack()),
1510 OpLoc(op), RParenLoc(rp) {
1511 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1512 UnaryExprOrTypeTraitExprBits.IsType = false;
1513 Argument.Ex = E;
1514
1515 // Check to see if we are in the situation where alignof(decl) should be
1516 // dependent because decl's alignment is dependent.
Richard Smith6822bd72018-10-26 19:26:45 +00001517 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
David Majnemer10fd83d2015-01-15 10:04:14 +00001518 if (!isValueDependent() || !isInstantiationDependent()) {
1519 E = E->IgnoreParens();
1520
1521 const ValueDecl *D = nullptr;
1522 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1523 D = DRE->getDecl();
1524 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1525 D = ME->getMemberDecl();
1526
1527 if (D) {
1528 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1529 if (I->isAlignmentDependent()) {
1530 setValueDependent(true);
1531 setInstantiationDependent(true);
1532 break;
1533 }
1534 }
1535 }
1536 }
1537 }
1538}
1539
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001540MemberExpr *MemberExpr::Create(
1541 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1542 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1543 ValueDecl *memberdecl, DeclAccessPair founddecl,
1544 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1545 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001546
Douglas Gregorea972d32011-02-28 21:54:11 +00001547 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001548 founddecl.getDecl() != memberdecl ||
1549 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001550
James Y Knighte7d82282015-12-29 18:15:14 +00001551 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1552 std::size_t Size =
1553 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1554 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1555 HasTemplateKWAndArgsInfo ? 1 : 0,
1556 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001557
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001558 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001559 MemberExpr *E = new (Mem)
1560 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001561
1562 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001563 // FIXME: Wrong. We should be looking at the member declaration we found.
1564 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001565 E->setValueDependent(true);
1566 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001567 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001568 }
1569 else if (QualifierLoc &&
1570 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001571 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001572
Bruno Ricci4c742532018-11-15 13:56:22 +00001573 E->MemberExprBits.HasQualifierOrFoundDecl = true;
John McCall16df1e52010-03-30 21:47:33 +00001574
James Y Knighte7d82282015-12-29 18:15:14 +00001575 MemberExprNameQualifier *NQ =
1576 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001577 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001578 NQ->FoundDecl = founddecl;
1579 }
1580
Bruno Ricci4c742532018-11-15 13:56:22 +00001581 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1582 (targs || TemplateKWLoc.isValid());
Abramo Bagnara7945c982012-01-27 09:46:47 +00001583
John McCall16df1e52010-03-30 21:47:33 +00001584 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001585 bool Dependent = false;
1586 bool InstantiationDependent = false;
1587 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001588 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1589 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1590 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001591 if (InstantiationDependent)
1592 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001593 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001594 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1595 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001596 }
1597
1598 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001599}
1600
Stephen Kelly724e9e52018-08-09 20:05:03 +00001601SourceLocation MemberExpr::getBeginLoc() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001602 if (isImplicitAccess()) {
1603 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001604 return getQualifierLoc().getBeginLoc();
1605 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001606 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001607
Daniel Dunbarb507f272012-03-09 15:39:15 +00001608 // FIXME: We don't want this to happen. Rather, we should be able to
1609 // detect all kinds of implicit accesses more cleanly.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001610 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001611 if (BaseStartLoc.isValid())
1612 return BaseStartLoc;
1613 return MemberLoc;
1614}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001615SourceLocation MemberExpr::getEndLoc() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001616 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001617 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001618 EndLoc = getRAngleLoc();
1619 else if (EndLoc.isInvalid())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001620 EndLoc = getBase()->getEndLoc();
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001621 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001622}
1623
Alp Tokerc1086762013-12-07 13:51:35 +00001624bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001625 switch (getCastKind()) {
1626 case CK_DerivedToBase:
1627 case CK_UncheckedDerivedToBase:
1628 case CK_DerivedToBaseMemberPointer:
1629 case CK_BaseToDerived:
1630 case CK_BaseToDerivedMemberPointer:
1631 assert(!path_empty() && "Cast kind should have a base path!");
1632 break;
1633
1634 case CK_CPointerToObjCPointerCast:
1635 assert(getType()->isObjCObjectPointerType());
1636 assert(getSubExpr()->getType()->isPointerType());
1637 goto CheckNoBasePath;
1638
1639 case CK_BlockPointerToObjCPointerCast:
1640 assert(getType()->isObjCObjectPointerType());
1641 assert(getSubExpr()->getType()->isBlockPointerType());
1642 goto CheckNoBasePath;
1643
John McCallc62bb392012-02-15 01:22:51 +00001644 case CK_ReinterpretMemberPointer:
1645 assert(getType()->isMemberPointerType());
1646 assert(getSubExpr()->getType()->isMemberPointerType());
1647 goto CheckNoBasePath;
1648
John McCall9320b872011-09-09 05:25:32 +00001649 case CK_BitCast:
1650 // Arbitrary casts to C pointer types count as bitcasts.
1651 // Otherwise, we should only have block and ObjC pointer casts
1652 // here if they stay within the type kind.
1653 if (!getType()->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001654 assert(getType()->isObjCObjectPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001655 getSubExpr()->getType()->isObjCObjectPointerType());
Fangrui Song6907ce22018-07-30 19:24:48 +00001656 assert(getType()->isBlockPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001657 getSubExpr()->getType()->isBlockPointerType());
1658 }
1659 goto CheckNoBasePath;
1660
1661 case CK_AnyPointerToBlockPointerCast:
1662 assert(getType()->isBlockPointerType());
1663 assert(getSubExpr()->getType()->isAnyPointerType() &&
1664 !getSubExpr()->getType()->isBlockPointerType());
1665 goto CheckNoBasePath;
1666
Douglas Gregored90df32012-02-22 05:02:47 +00001667 case CK_CopyAndAutoreleaseBlockObject:
1668 assert(getType()->isBlockPointerType());
1669 assert(getSubExpr()->getType()->isBlockPointerType());
1670 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001671
1672 case CK_FunctionToPointerDecay:
1673 assert(getType()->isPointerType());
1674 assert(getSubExpr()->getType()->isFunctionType());
1675 goto CheckNoBasePath;
1676
Anastasia Stulova04307942018-11-16 16:22:56 +00001677 case CK_AddressSpaceConversion: {
1678 auto Ty = getType();
1679 auto SETy = getSubExpr()->getType();
1680 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
Anastasia Stulova094c7262019-04-04 10:48:36 +00001681 if (/*isRValue()*/ !Ty->getPointeeType().isNull()) {
Anastasia Stulova04307942018-11-16 16:22:56 +00001682 Ty = Ty->getPointeeType();
Anastasia Stulova04307942018-11-16 16:22:56 +00001683 SETy = SETy->getPointeeType();
Anastasia Stulovad1986d12019-01-14 11:44:22 +00001684 }
Anastasia Stulova04307942018-11-16 16:22:56 +00001685 assert(!Ty.isNull() && !SETy.isNull() &&
1686 Ty.getAddressSpace() != SETy.getAddressSpace());
1687 goto CheckNoBasePath;
1688 }
John McCall9320b872011-09-09 05:25:32 +00001689 // These should not have an inheritance path.
1690 case CK_Dynamic:
1691 case CK_ToUnion:
1692 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001693 case CK_NullToMemberPointer:
1694 case CK_NullToPointer:
1695 case CK_ConstructorConversion:
1696 case CK_IntegralToPointer:
1697 case CK_PointerToIntegral:
1698 case CK_ToVoid:
1699 case CK_VectorSplat:
1700 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001701 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001702 case CK_IntegralToFloating:
1703 case CK_FloatingToIntegral:
1704 case CK_FloatingCast:
1705 case CK_ObjCObjectLValueCast:
1706 case CK_FloatingRealToComplex:
1707 case CK_FloatingComplexToReal:
1708 case CK_FloatingComplexCast:
1709 case CK_FloatingComplexToIntegralComplex:
1710 case CK_IntegralRealToComplex:
1711 case CK_IntegralComplexToReal:
1712 case CK_IntegralComplexCast:
1713 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001714 case CK_ARCProduceObject:
1715 case CK_ARCConsumeObject:
1716 case CK_ARCReclaimReturnedObject:
1717 case CK_ARCExtendBlockObject:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001718 case CK_ZeroToOCLOpaqueType:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001719 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00001720 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +00001721 case CK_FixedPointToIntegral:
1722 case CK_IntegralToFixedPoint:
John McCall9320b872011-09-09 05:25:32 +00001723 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1724 goto CheckNoBasePath;
1725
1726 case CK_Dependent:
1727 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001728 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001729 case CK_AtomicToNonAtomic:
1730 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001731 case CK_PointerToBoolean:
1732 case CK_IntegralToBoolean:
1733 case CK_FloatingToBoolean:
1734 case CK_MemberPointerToBoolean:
1735 case CK_FloatingComplexToBoolean:
1736 case CK_IntegralComplexToBoolean:
1737 case CK_LValueBitCast: // -> bool&
1738 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001739 case CK_BuiltinFnToFnPtr:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001740 case CK_FixedPointToBoolean:
John McCall9320b872011-09-09 05:25:32 +00001741 CheckNoBasePath:
1742 assert(path_empty() && "Cast kind should not have a base path!");
1743 break;
1744 }
Alp Tokerc1086762013-12-07 13:51:35 +00001745 return true;
John McCall9320b872011-09-09 05:25:32 +00001746}
1747
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001748const char *CastExpr::getCastKindName(CastKind CK) {
1749 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001750#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1751#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001752 }
John McCallc5e62b42010-11-13 09:02:35 +00001753 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001754}
1755
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001756namespace {
Richard Smith1ef75542018-06-27 20:30:34 +00001757 const Expr *skipImplicitTemporary(const Expr *E) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001758 // Skip through reference binding to temporary.
Richard Smith1ef75542018-06-27 20:30:34 +00001759 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1760 E = Materialize->GetTemporaryExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001761
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001762 // Skip any temporary bindings; they're implicit.
Richard Smith1ef75542018-06-27 20:30:34 +00001763 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1764 E = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001765
Richard Smith1ef75542018-06-27 20:30:34 +00001766 return E;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001767 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001768}
1769
Douglas Gregord196a582009-12-14 19:27:10 +00001770Expr *CastExpr::getSubExprAsWritten() {
Richard Smith1ef75542018-06-27 20:30:34 +00001771 const Expr *SubExpr = nullptr;
1772 const CastExpr *E = this;
Douglas Gregord196a582009-12-14 19:27:10 +00001773 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001774 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001775
Douglas Gregord196a582009-12-14 19:27:10 +00001776 // Conversions by constructor and conversion functions have a
1777 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001778 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001779 SubExpr =
1780 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001781 else if (E->getCastKind() == CK_UserDefinedConversion) {
1782 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1783 isa<BlockExpr>(SubExpr)) &&
1784 "Unexpected SubExpr for CK_UserDefinedConversion.");
Richard Smith1ef75542018-06-27 20:30:34 +00001785 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1786 SubExpr = MCE->getImplicitObjectArgument();
Manman Ren8abc2e52016-02-02 22:23:03 +00001787 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001788
Douglas Gregord196a582009-12-14 19:27:10 +00001789 // If the subexpression we're left with is an implicit cast, look
1790 // through that, too.
Fangrui Song6907ce22018-07-30 19:24:48 +00001791 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1792
Richard Smith1ef75542018-06-27 20:30:34 +00001793 return const_cast<Expr*>(SubExpr);
1794}
1795
1796NamedDecl *CastExpr::getConversionFunction() const {
1797 const Expr *SubExpr = nullptr;
1798
1799 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1800 SubExpr = skipImplicitTemporary(E->getSubExpr());
1801
1802 if (E->getCastKind() == CK_ConstructorConversion)
1803 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1804
1805 if (E->getCastKind() == CK_UserDefinedConversion) {
1806 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1807 return MCE->getMethodDecl();
1808 }
1809 }
1810
1811 return nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001812}
1813
John McCallcf142162010-08-07 06:22:56 +00001814CXXBaseSpecifier **CastExpr::path_buffer() {
1815 switch (getStmtClass()) {
1816#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001817#define CASTEXPR(Type, Base) \
1818 case Stmt::Type##Class: \
1819 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001820#define STMT(Type, Base)
1821#include "clang/AST/StmtNodes.inc"
1822 default:
1823 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001824 }
1825}
1826
John McCallf1ef7962017-08-15 21:42:47 +00001827const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1828 QualType opType) {
1829 auto RD = unionType->castAs<RecordType>()->getDecl();
1830 return getTargetFieldForToUnionCast(RD, opType);
1831}
1832
1833const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1834 QualType OpType) {
1835 auto &Ctx = RD->getASTContext();
1836 RecordDecl::field_iterator Field, FieldEnd;
1837 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1838 Field != FieldEnd; ++Field) {
1839 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1840 !Field->isUnnamedBitfield()) {
1841 return *Field;
1842 }
1843 }
1844 return nullptr;
1845}
1846
Craig Topper37932912013-08-18 10:09:15 +00001847ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001848 CastKind Kind, Expr *Operand,
1849 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001850 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001851 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001852 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001853 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001854 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001855 if (PathSize)
1856 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1857 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001858 return E;
1859}
1860
Craig Topper37932912013-08-18 10:09:15 +00001861ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001862 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001863 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001864 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1865}
1866
1867
Craig Topper37932912013-08-18 10:09:15 +00001868CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001869 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001870 const CXXCastPath *BasePath,
1871 TypeSourceInfo *WrittenTy,
1872 SourceLocation L, SourceLocation R) {
1873 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001874 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001875 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001876 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001877 if (PathSize)
1878 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1879 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001880 return E;
1881}
1882
Craig Topper37932912013-08-18 10:09:15 +00001883CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1884 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001885 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001886 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1887}
1888
Chris Lattner1b926492006-08-23 06:42:10 +00001889/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1890/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001891StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001892 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001893#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1894#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001895 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001896 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001897}
Steve Naroff47500512007-04-19 23:00:49 +00001898
John McCalle3027922010-08-25 11:45:40 +00001899BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001900BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1901 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001902 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001903 case OO_Plus: return BO_Add;
1904 case OO_Minus: return BO_Sub;
1905 case OO_Star: return BO_Mul;
1906 case OO_Slash: return BO_Div;
1907 case OO_Percent: return BO_Rem;
1908 case OO_Caret: return BO_Xor;
1909 case OO_Amp: return BO_And;
1910 case OO_Pipe: return BO_Or;
1911 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00001912 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00001913 case OO_Less: return BO_LT;
1914 case OO_Greater: return BO_GT;
1915 case OO_PlusEqual: return BO_AddAssign;
1916 case OO_MinusEqual: return BO_SubAssign;
1917 case OO_StarEqual: return BO_MulAssign;
1918 case OO_SlashEqual: return BO_DivAssign;
1919 case OO_PercentEqual: return BO_RemAssign;
1920 case OO_CaretEqual: return BO_XorAssign;
1921 case OO_AmpEqual: return BO_AndAssign;
1922 case OO_PipeEqual: return BO_OrAssign;
1923 case OO_LessLess: return BO_Shl;
1924 case OO_GreaterGreater: return BO_Shr;
1925 case OO_LessLessEqual: return BO_ShlAssign;
1926 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1927 case OO_EqualEqual: return BO_EQ;
1928 case OO_ExclaimEqual: return BO_NE;
1929 case OO_LessEqual: return BO_LE;
1930 case OO_GreaterEqual: return BO_GE;
1931 case OO_AmpAmp: return BO_LAnd;
1932 case OO_PipePipe: return BO_LOr;
1933 case OO_Comma: return BO_Comma;
1934 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001935 }
1936}
1937
1938OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1939 static const OverloadedOperatorKind OverOps[] = {
1940 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1941 OO_Star, OO_Slash, OO_Percent,
1942 OO_Plus, OO_Minus,
1943 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00001944 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001945 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1946 OO_EqualEqual, OO_ExclaimEqual,
1947 OO_Amp,
1948 OO_Caret,
1949 OO_Pipe,
1950 OO_AmpAmp,
1951 OO_PipePipe,
1952 OO_Equal, OO_StarEqual,
1953 OO_SlashEqual, OO_PercentEqual,
1954 OO_PlusEqual, OO_MinusEqual,
1955 OO_LessLessEqual, OO_GreaterGreaterEqual,
1956 OO_AmpEqual, OO_CaretEqual,
1957 OO_PipeEqual,
1958 OO_Comma
1959 };
1960 return OverOps[Opc];
1961}
1962
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001963bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
1964 Opcode Opc,
1965 Expr *LHS, Expr *RHS) {
1966 if (Opc != BO_Add)
1967 return false;
1968
1969 // Check that we have one pointer and one integer operand.
1970 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001971 if (LHS->getType()->isPointerType()) {
1972 if (!RHS->getType()->isIntegerType())
1973 return false;
1974 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001975 } else if (RHS->getType()->isPointerType()) {
1976 if (!LHS->getType()->isIntegerType())
1977 return false;
1978 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001979 } else {
1980 return false;
1981 }
1982
1983 // Check that the pointer is a nullptr.
1984 if (!PExp->IgnoreParenCasts()
1985 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
1986 return false;
1987
1988 // Check that the pointee type is char-sized.
1989 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1990 if (!PTy || !PTy->getPointeeType()->isCharType())
1991 return false;
1992
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001993 return true;
1994}
Craig Topper37932912013-08-18 10:09:15 +00001995InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001996 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001997 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1998 false, false),
1999 InitExprs(C, initExprs.size()),
2000 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
2001{
Sebastian Redlc83ed822012-02-17 08:42:25 +00002002 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00002003 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002004 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00002005 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00002006 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00002007 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002008 if (initExprs[I]->isInstantiationDependent())
2009 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00002010 if (initExprs[I]->containsUnexpandedParameterPack())
2011 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00002012 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002013
Benjamin Kramerc215e762012-08-24 11:54:20 +00002014 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00002015}
Chris Lattner1ec5f562007-06-27 05:38:08 +00002016
Craig Topper37932912013-08-18 10:09:15 +00002017void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002018 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00002019 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002020}
2021
Craig Topper37932912013-08-18 10:09:15 +00002022void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00002023 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002024}
2025
Craig Topper37932912013-08-18 10:09:15 +00002026Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002027 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00002028 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00002029 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00002030 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002031 }
Mike Stump11289f42009-09-09 15:08:12 +00002032
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002033 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00002034 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002035 return Result;
2036}
2037
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002038void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00002039 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002040 ArrayFillerOrUnionFieldInit = filler;
2041 // Fill out any "holes" in the array due to designated initializers.
2042 Expr **inits = getInits();
2043 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00002044 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002045 inits[i] = filler;
2046}
2047
Richard Smith9ec1e482012-04-15 02:50:59 +00002048bool InitListExpr::isStringLiteralInit() const {
2049 if (getNumInits() != 1)
2050 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00002051 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2052 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00002053 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00002054 // It is possible for getInit() to return null.
2055 const Expr *Init = getInit(0);
2056 if (!Init)
2057 return false;
2058 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00002059 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2060}
2061
Richard Smith122f88d2016-12-06 23:52:28 +00002062bool InitListExpr::isTransparent() const {
2063 assert(isSemanticForm() && "syntactic form never semantically transparent");
2064
2065 // A glvalue InitListExpr is always just sugar.
2066 if (isGLValue()) {
2067 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2068 return true;
2069 }
2070
2071 // Otherwise, we're sugar if and only if we have exactly one initializer that
2072 // is of the same type.
2073 if (getNumInits() != 1 || !getInit(0))
2074 return false;
2075
Richard Smith382bc512017-02-23 22:41:47 +00002076 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2077 // transparent struct copy.
2078 if (!getInit(0)->isRValue() && getType()->isRecordType())
2079 return false;
2080
Richard Smith122f88d2016-12-06 23:52:28 +00002081 return getType().getCanonicalType() ==
2082 getInit(0)->getType().getCanonicalType();
2083}
2084
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002085bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2086 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2087
2088 if (LangOpts.CPlusPlus || getNumInits() != 1) {
2089 return false;
2090 }
2091
2092 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
2093 return Lit && Lit->getValue() == 0;
2094}
2095
Stephen Kelly724e9e52018-08-09 20:05:03 +00002096SourceLocation InitListExpr::getBeginLoc() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00002097 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002098 return SyntacticForm->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002099 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002100 if (Beg.isInvalid()) {
2101 // Find the first non-null initializer.
2102 for (InitExprsTy::const_iterator I = InitExprs.begin(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002103 E = InitExprs.end();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002104 I != E; ++I) {
2105 if (Stmt *S = *I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002106 Beg = S->getBeginLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002107 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002108 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002109 }
2110 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002111 return Beg;
2112}
2113
Stephen Kelly02a67ba2018-08-09 20:05:47 +00002114SourceLocation InitListExpr::getEndLoc() const {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002115 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002116 return SyntacticForm->getEndLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002117 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002118 if (End.isInvalid()) {
2119 // Find the first non-null initializer from the end.
2120 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002121 E = InitExprs.rend();
2122 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002123 if (Stmt *S = *I) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002124 End = S->getEndLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002125 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002126 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002127 }
2128 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002129 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002130}
2131
Steve Naroff991e99d2008-09-04 15:31:07 +00002132/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002133///
John McCallc833dea2012-02-17 03:32:35 +00002134const FunctionProtoType *BlockExpr::getFunctionType() const {
2135 // The block pointer is never sugared, but the function type might be.
2136 return cast<BlockPointerType>(getType())
2137 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002138}
2139
Mike Stump11289f42009-09-09 15:08:12 +00002140SourceLocation BlockExpr::getCaretLocation() const {
2141 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002142}
Mike Stump11289f42009-09-09 15:08:12 +00002143const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002144 return TheBlock->getBody();
2145}
Mike Stump11289f42009-09-09 15:08:12 +00002146Stmt *BlockExpr::getBody() {
2147 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002148}
Steve Naroff415d3d52008-10-08 17:01:13 +00002149
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002150
Chris Lattner1ec5f562007-06-27 05:38:08 +00002151//===----------------------------------------------------------------------===//
2152// Generic Expression Routines
2153//===----------------------------------------------------------------------===//
2154
Chris Lattner237f2752009-02-14 07:37:35 +00002155/// isUnusedResultAWarning - Return true if this immediate expression should
2156/// be warned about if the result is unused. If so, fill in Loc and Ranges
2157/// with location to warn on and the source range[s] to report with the
2158/// warning.
Fangrui Song6907ce22018-07-30 19:24:48 +00002159bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
Eli Friedmanc11535c2012-05-24 00:47:05 +00002160 SourceRange &R1, SourceRange &R2,
2161 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002162 // Don't warn if the expr is type dependent. The type could end up
2163 // instantiating to void.
2164 if (isTypeDependent())
2165 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002166
Chris Lattner1ec5f562007-06-27 05:38:08 +00002167 switch (getStmtClass()) {
2168 default:
John McCallc493a732010-03-12 07:11:26 +00002169 if (getType()->isVoidType())
2170 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002171 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002172 Loc = getExprLoc();
2173 R1 = getSourceRange();
2174 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002175 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002176 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002177 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002178 case GenericSelectionExprClass:
2179 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002180 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002181 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002182 case CoyieldExprClass:
2183 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002184 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002185 case ChooseExprClass:
2186 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2187 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002188 case UnaryOperatorClass: {
2189 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002190
Chris Lattner1ec5f562007-06-27 05:38:08 +00002191 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002192 case UO_Plus:
2193 case UO_Minus:
2194 case UO_AddrOf:
2195 case UO_Not:
2196 case UO_LNot:
2197 case UO_Deref:
2198 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002199 case UO_Coawait:
2200 // This is just the 'operator co_await' call inside the guts of a
2201 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002202 case UO_PostInc:
2203 case UO_PostDec:
2204 case UO_PreInc:
2205 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002206 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002207 case UO_Real:
2208 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002209 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002210 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2211 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002212 return false;
2213 break;
John McCalle3027922010-08-25 11:45:40 +00002214 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002215 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002216 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002217 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002218 Loc = UO->getOperatorLoc();
2219 R1 = UO->getSubExpr()->getSourceRange();
2220 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002221 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002222 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002223 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002224 switch (BO->getOpcode()) {
2225 default:
2226 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002227 // Consider the RHS of comma for side effects. LHS was checked by
2228 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002229 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002230 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2231 // lvalue-ness) of an assignment written in a macro.
2232 if (IntegerLiteral *IE =
2233 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2234 if (IE->getValue() == 0)
2235 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002236 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002237 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002238 case BO_LAnd:
2239 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002240 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2241 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002242 return false;
2243 break;
John McCall1e3715a2010-02-16 04:10:53 +00002244 }
Chris Lattner237f2752009-02-14 07:37:35 +00002245 if (BO->isAssignmentOp())
2246 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002247 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002248 Loc = BO->getOperatorLoc();
2249 R1 = BO->getLHS()->getSourceRange();
2250 R2 = BO->getRHS()->getSourceRange();
2251 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002252 }
Chris Lattner86928112007-08-25 02:00:02 +00002253 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002254 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002255 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002256 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002257
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002258 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002259 // If only one of the LHS or RHS is a warning, the operator might
2260 // be being used for control flow. Only warn if both the LHS and
2261 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002262 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002263 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00002264 return false;
2265 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00002266 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002267 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002268 }
2269
Chris Lattnera44d1162007-06-27 05:58:59 +00002270 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002271 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002272 Loc = cast<MemberExpr>(this)->getMemberLoc();
2273 R1 = SourceRange(Loc, Loc);
2274 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2275 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002276
Chris Lattner1ec5f562007-06-27 05:38:08 +00002277 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002278 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002279 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2280 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2281 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2282 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002283
Chandler Carruth46339472011-08-17 09:49:44 +00002284 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002285 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002286 // overloads as there is no reasonable way to define these such that they
2287 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002288 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002289 // provides additional value as well. If this list is updated,
2290 // DiagnoseUnusedComparison should be as well.
2291 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002292 switch (Op->getOperator()) {
2293 default:
2294 break;
2295 case OO_EqualEqual:
2296 case OO_ExclaimEqual:
2297 case OO_Less:
2298 case OO_Greater:
2299 case OO_GreaterEqual:
2300 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002301 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2302 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002303 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002304 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002305 Loc = Op->getOperatorLoc();
2306 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002307 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002308 }
Chandler Carruth46339472011-08-17 09:49:44 +00002309
2310 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002311 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002312 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002313 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002314 case CXXMemberCallExprClass:
2315 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002316 // If this is a direct call, get the callee.
2317 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002318 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner237f2752009-02-14 07:37:35 +00002319 // If the callee has attribute pure, const, or warn_unused_result, warn
2320 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002321 //
2322 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2323 // updated to match for QoI.
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00002324 if (CE->hasUnusedResultAttr(Ctx) ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002325 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002326 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002327 Loc = CE->getCallee()->getBeginLoc();
Chris Lattner1a6babf2009-10-13 04:53:48 +00002328 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002329
Chris Lattner1a6babf2009-10-13 04:53:48 +00002330 if (unsigned NumArgs = CE->getNumArgs())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002331 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002332 CE->getArg(NumArgs - 1)->getEndLoc());
Chris Lattner1a6babf2009-10-13 04:53:48 +00002333 return true;
2334 }
Chris Lattner237f2752009-02-14 07:37:35 +00002335 }
2336 return false;
2337 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002338
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002339 // If we don't know precisely what we're looking at, let's not warn.
2340 case UnresolvedLookupExprClass:
2341 case CXXUnresolvedConstructExprClass:
2342 return false;
2343
Anders Carlsson6aa50392009-11-17 17:11:23 +00002344 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002345 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002346 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2347 if (Type->hasAttr<WarnUnusedAttr>()) {
2348 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002349 Loc = getBeginLoc();
Lubos Lunak1f490f32013-07-21 13:15:58 +00002350 R1 = getSourceRange();
2351 return true;
2352 }
2353 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002354 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002355 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002356
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002357 case ObjCMessageExprClass: {
2358 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002359 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002360 ME->isInstanceMessage() &&
2361 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002362 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002363 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002364 Loc = getExprLoc();
2365 R1 = ME->getSourceRange();
2366 return true;
2367 }
2368
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002369 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002370 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002371 WarnE = this;
2372 Loc = getExprLoc();
2373 return true;
2374 }
2375
Chris Lattner237f2752009-02-14 07:37:35 +00002376 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002377 }
Mike Stump11289f42009-09-09 15:08:12 +00002378
John McCallb7bd14f2010-12-02 01:19:52 +00002379 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002380 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002381 Loc = getExprLoc();
2382 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002383 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002384
John McCallfe96e0b2011-11-06 09:01:30 +00002385 case PseudoObjectExprClass: {
2386 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2387
2388 // Only complain about things that have the form of a getter.
2389 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2390 isa<BinaryOperator>(PO->getSyntacticForm()))
2391 return false;
2392
Eli Friedmanc11535c2012-05-24 00:47:05 +00002393 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002394 Loc = getExprLoc();
2395 R1 = getSourceRange();
2396 return true;
2397 }
2398
Chris Lattner944d3062008-07-26 19:51:01 +00002399 case StmtExprClass: {
2400 // Statement exprs don't logically have side effects themselves, but are
2401 // sometimes used in macros in ways that give them a type that is unused.
2402 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2403 // however, if the result of the stmt expr is dead, we don't want to emit a
2404 // warning.
2405 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002406 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002407 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002408 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002409 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2410 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002411 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002412 }
Mike Stump11289f42009-09-09 15:08:12 +00002413
John McCallc493a732010-03-12 07:11:26 +00002414 if (getType()->isVoidType())
2415 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002416 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002417 Loc = cast<StmtExpr>(this)->getLParenLoc();
2418 R1 = getSourceRange();
2419 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002420 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002421 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002422 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002423 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002424 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002425 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002426 if (CE->getCastKind() == CK_ToVoid) {
2427 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002428 CE->getSubExpr()->getType().isVolatileQualified()) {
2429 const DeclRefExpr *DRE =
2430 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2431 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002432 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2433 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002434 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2435 R1, R2, Ctx);
2436 }
2437 }
Chris Lattner2706a552009-07-28 18:25:28 +00002438 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002439 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002440
Eli Friedmanc11535c2012-05-24 00:47:05 +00002441 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002442 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002443 if (CE->getCastKind() == CK_ConstructorConversion)
2444 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002445
Eli Friedmanc11535c2012-05-24 00:47:05 +00002446 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002447 if (const CXXFunctionalCastExpr *CXXCE =
2448 dyn_cast<CXXFunctionalCastExpr>(this)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002449 Loc = CXXCE->getBeginLoc();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002450 R1 = CXXCE->getSubExpr()->getSourceRange();
2451 } else {
2452 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2453 Loc = CStyleCE->getLParenLoc();
2454 R1 = CStyleCE->getSubExpr()->getSourceRange();
2455 }
Chris Lattner237f2752009-02-14 07:37:35 +00002456 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002457 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002458 case ImplicitCastExprClass: {
2459 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002460
Eli Friedmanc11535c2012-05-24 00:47:05 +00002461 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2462 if (ICE->getCastKind() == CK_LValueToRValue &&
2463 ICE->getSubExpr()->getType().isVolatileQualified())
2464 return false;
2465
2466 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2467 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002468 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002469 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002470 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002471 case CXXDefaultInitExprClass:
2472 return (cast<CXXDefaultInitExpr>(this)
2473 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002474
2475 case CXXNewExprClass:
2476 // FIXME: In theory, there might be new expressions that don't have side
2477 // effects (e.g. a placement new with an uninitialized POD).
2478 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002479 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002480 case MaterializeTemporaryExprClass:
2481 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2482 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002483 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002484 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2485 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002486 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002487 return cast<ExprWithCleanups>(this)->getSubExpr()
2488 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002489 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002490}
2491
Fariborz Jahanian07735332009-02-22 18:40:18 +00002492/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002493/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002494bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002495 const Expr *E = IgnoreParens();
2496 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002497 default:
2498 return false;
2499 case ObjCIvarRefExprClass:
2500 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002501 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002502 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002503 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002504 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002505 case MaterializeTemporaryExprClass:
2506 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2507 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002508 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002509 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002510 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002511 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002512
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002513 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2514 if (VD->hasGlobalStorage())
2515 return true;
2516 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002517 // dereferencing to a pointer is always a gc'able candidate,
2518 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002519 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002520 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002521 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002522 return false;
2523 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002524 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002525 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002526 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002527 }
2528 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002529 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002530 }
2531}
Sebastian Redlce354af2010-09-10 20:55:33 +00002532
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002533bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2534 if (isTypeDependent())
2535 return false;
John McCall086a4642010-11-24 05:12:34 +00002536 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002537}
2538
John McCall0009fcc2011-04-26 20:42:42 +00002539QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002540 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002541
2542 // Bound member expressions are always one of these possibilities:
2543 // x->m x.m x->*y x.*y
2544 // (possibly parenthesized)
2545
2546 expr = expr->IgnoreParens();
2547 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2548 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2549 return mem->getMemberDecl()->getType();
2550 }
2551
2552 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2553 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2554 ->getPointeeType();
2555 assert(type->isFunctionType());
2556 return type;
2557 }
2558
David Majnemerced8bdf2015-02-25 17:36:15 +00002559 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002560 return QualType();
2561}
2562
Bruno Ricci46148f22019-02-17 18:50:51 +00002563static Expr *IgnoreImpCastsSingleStep(Expr *E) {
2564 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2565 return ICE->getSubExpr();
2566
2567 if (auto *FE = dyn_cast<FullExpr>(E))
2568 return FE->getSubExpr();
2569
Bruno Riccid4038002019-02-17 13:47:29 +00002570 return E;
Ted Kremenek6f375e52014-04-16 07:26:09 +00002571}
2572
Bruno Ricci46148f22019-02-17 18:50:51 +00002573static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
2574 // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2575 // addition to what IgnoreImpCasts() skips to account for the current
2576 // behaviour of IgnoreParenImpCasts().
2577 Expr *SubE = IgnoreImpCastsSingleStep(E);
2578 if (SubE != E)
2579 return SubE;
2580
2581 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2582 return MTE->GetTemporaryExpr();
2583
2584 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2585 return NTTP->getReplacement();
2586
2587 return E;
2588}
2589
2590static Expr *IgnoreCastsSingleStep(Expr *E) {
2591 if (auto *CE = dyn_cast<CastExpr>(E))
2592 return CE->getSubExpr();
2593
2594 if (auto *FE = dyn_cast<FullExpr>(E))
2595 return FE->getSubExpr();
2596
2597 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2598 return MTE->GetTemporaryExpr();
2599
2600 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2601 return NTTP->getReplacement();
2602
2603 return E;
2604}
2605
2606static Expr *IgnoreLValueCastsSingleStep(Expr *E) {
2607 // Skip what IgnoreCastsSingleStep skips, except that only
2608 // lvalue-to-rvalue casts are skipped.
2609 if (auto *CE = dyn_cast<CastExpr>(E))
2610 if (CE->getCastKind() != CK_LValueToRValue)
2611 return E;
2612
2613 return IgnoreCastsSingleStep(E);
2614}
2615
2616static Expr *IgnoreBaseCastsSingleStep(Expr *E) {
2617 if (auto *CE = dyn_cast<CastExpr>(E))
2618 if (CE->getCastKind() == CK_DerivedToBase ||
2619 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2620 CE->getCastKind() == CK_NoOp)
2621 return CE->getSubExpr();
2622
2623 return E;
2624}
2625
2626static Expr *IgnoreImplicitSingleStep(Expr *E) {
2627 Expr *SubE = IgnoreImpCastsSingleStep(E);
2628 if (SubE != E)
2629 return SubE;
2630
2631 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2632 return MTE->GetTemporaryExpr();
2633
2634 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2635 return BTE->getSubExpr();
2636
2637 return E;
2638}
2639
2640static Expr *IgnoreParensSingleStep(Expr *E) {
2641 if (auto *PE = dyn_cast<ParenExpr>(E))
2642 return PE->getSubExpr();
2643
2644 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2645 if (UO->getOpcode() == UO_Extension)
2646 return UO->getSubExpr();
2647 }
2648
2649 else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2650 if (!GSE->isResultDependent())
2651 return GSE->getResultExpr();
2652 }
2653
2654 else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2655 if (!CE->isConditionDependent())
2656 return CE->getChosenSubExpr();
2657 }
2658
2659 else if (auto *CE = dyn_cast<ConstantExpr>(E))
2660 return CE->getSubExpr();
2661
2662 return E;
2663}
2664
2665static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
2666 if (auto *CE = dyn_cast<CastExpr>(E)) {
2667 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2668 // ptr<->int casts of the same width. We also ignore all identity casts.
2669 Expr *SubExpr = CE->getSubExpr();
2670 bool IsIdentityCast =
2671 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2672 bool IsSameWidthCast =
2673 (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2674 (SubExpr->getType()->isPointerType() ||
2675 SubExpr->getType()->isIntegralType(Ctx)) &&
2676 (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2677
2678 if (IsIdentityCast || IsSameWidthCast)
2679 return SubExpr;
2680 }
2681
2682 else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2683 return NTTP->getReplacement();
2684
2685 return E;
2686}
2687
2688static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2689template <typename FnTy, typename... FnTys>
2690static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2691 return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2692}
2693
2694/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2695/// Recursively apply each of the functions to E until reaching a fixed point.
2696/// Note that a null E is valid; in this case nothing is done.
2697template <typename... FnTys>
2698static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
Bruno Riccid4038002019-02-17 13:47:29 +00002699 Expr *LastE = nullptr;
2700 while (E != LastE) {
2701 LastE = E;
Bruno Ricci46148f22019-02-17 18:50:51 +00002702 E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
Bruno Riccid4038002019-02-17 13:47:29 +00002703 }
2704 return E;
John McCall34376a62010-12-04 03:47:34 +00002705}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002706
Bruno Ricci46148f22019-02-17 18:50:51 +00002707Expr *Expr::IgnoreImpCasts() {
2708 return IgnoreExprNodes(this, IgnoreImpCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002709}
2710
2711Expr *Expr::IgnoreCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002712 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002713}
2714
Bruno Ricci46148f22019-02-17 18:50:51 +00002715Expr *Expr::IgnoreImplicit() {
2716 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002717}
2718
Bruno Ricci46148f22019-02-17 18:50:51 +00002719Expr *Expr::IgnoreParens() {
2720 return IgnoreExprNodes(this, IgnoreParensSingleStep);
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002721}
2722
John McCalleebc8322010-05-05 22:59:52 +00002723Expr *Expr::IgnoreParenImpCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002724 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2725 IgnoreImpCastsExtraSingleStep);
2726}
2727
2728Expr *Expr::IgnoreParenCasts() {
2729 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
John McCalleebc8322010-05-05 22:59:52 +00002730}
2731
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002732Expr *Expr::IgnoreConversionOperator() {
Bruno Riccie64aee82019-02-03 19:50:56 +00002733 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002734 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002735 return MCE->getImplicitObjectArgument();
2736 }
2737 return this;
2738}
2739
Bruno Ricci46148f22019-02-17 18:50:51 +00002740Expr *Expr::IgnoreParenLValueCasts() {
2741 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2742 IgnoreLValueCastsSingleStep);
2743}
2744
2745Expr *Expr::ignoreParenBaseCasts() {
2746 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2747 IgnoreBaseCastsSingleStep);
2748}
2749
Bruno Riccie64aee82019-02-03 19:50:56 +00002750Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
Bruno Ricci46148f22019-02-17 18:50:51 +00002751 return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2752 return IgnoreNoopCastsSingleStep(Ctx, E);
2753 });
Chris Lattneref26c772009-03-13 17:28:01 +00002754}
2755
Douglas Gregord196a582009-12-14 19:27:10 +00002756bool Expr::isDefaultArgument() const {
2757 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002758 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2759 E = M->GetTemporaryExpr();
2760
Douglas Gregord196a582009-12-14 19:27:10 +00002761 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2762 E = ICE->getSubExprAsWritten();
Fangrui Song6907ce22018-07-30 19:24:48 +00002763
Douglas Gregord196a582009-12-14 19:27:10 +00002764 return isa<CXXDefaultArgExpr>(E);
2765}
Chris Lattneref26c772009-03-13 17:28:01 +00002766
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002767/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002768/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002769static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002770 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2771 E = M->GetTemporaryExpr();
2772
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002773 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002774 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002775 E = ICE->getSubExpr();
2776 else
2777 break;
2778 }
2779
2780 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2781 E = BE->getSubExpr();
2782
2783 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002784 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002785 E = ICE->getSubExpr();
2786 else
2787 break;
2788 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002789
2790 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002791}
2792
John McCall7a626f62010-09-15 10:14:12 +00002793/// isTemporaryObject - Determines if this expression produces a
2794/// temporary of the given class type.
2795bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2796 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2797 return false;
2798
Anders Carlsson66bbf502010-11-28 16:40:49 +00002799 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002800
John McCall02dc8c72010-09-15 20:59:13 +00002801 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002802 if (!E->Classify(C).isPRValue()) {
2803 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002804 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002805 return false;
2806 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002807
John McCallf4ee1dd2010-09-16 06:57:56 +00002808 // Black-list a few cases which yield pr-values of class type that don't
2809 // refer to temporaries of that type:
2810
2811 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002812 if (isa<ImplicitCastExpr>(E)) {
2813 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2814 case CK_DerivedToBase:
2815 case CK_UncheckedDerivedToBase:
2816 return false;
2817 default:
2818 break;
2819 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002820 }
2821
John McCallf4ee1dd2010-09-16 06:57:56 +00002822 // - member expressions (all)
2823 if (isa<MemberExpr>(E))
2824 return false;
2825
Eli Friedman13ffdd82012-06-15 23:51:06 +00002826 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2827 if (BO->isPtrMemOp())
2828 return false;
2829
John McCallc07a0c72011-02-17 10:25:35 +00002830 // - opaque values (all)
2831 if (isa<OpaqueValueExpr>(E))
2832 return false;
2833
John McCall7a626f62010-09-15 10:14:12 +00002834 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002835}
2836
Douglas Gregor25b7e052011-03-02 21:06:53 +00002837bool Expr::isImplicitCXXThis() const {
2838 const Expr *E = this;
Fangrui Song6907ce22018-07-30 19:24:48 +00002839
Douglas Gregor25b7e052011-03-02 21:06:53 +00002840 // Strip away parentheses and casts we don't care about.
2841 while (true) {
2842 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2843 E = Paren->getSubExpr();
2844 continue;
2845 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002846
Douglas Gregor25b7e052011-03-02 21:06:53 +00002847 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2848 if (ICE->getCastKind() == CK_NoOp ||
2849 ICE->getCastKind() == CK_LValueToRValue ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002850 ICE->getCastKind() == CK_DerivedToBase ||
Douglas Gregor25b7e052011-03-02 21:06:53 +00002851 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2852 E = ICE->getSubExpr();
2853 continue;
2854 }
2855 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002856
Douglas Gregor25b7e052011-03-02 21:06:53 +00002857 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2858 if (UnOp->getOpcode() == UO_Extension) {
2859 E = UnOp->getSubExpr();
2860 continue;
2861 }
2862 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002863
Douglas Gregorfe314812011-06-21 17:03:29 +00002864 if (const MaterializeTemporaryExpr *M
2865 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2866 E = M->GetTemporaryExpr();
2867 continue;
2868 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002869
Douglas Gregor25b7e052011-03-02 21:06:53 +00002870 break;
2871 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002872
Douglas Gregor25b7e052011-03-02 21:06:53 +00002873 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2874 return This->isImplicit();
Fangrui Song6907ce22018-07-30 19:24:48 +00002875
Douglas Gregor25b7e052011-03-02 21:06:53 +00002876 return false;
2877}
2878
Douglas Gregor4619e432008-12-05 23:32:09 +00002879/// hasAnyTypeDependentArguments - Determines if any of the expressions
2880/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002881bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002882 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002883 if (Exprs[I]->isTypeDependent())
2884 return true;
2885
2886 return false;
2887}
2888
Abramo Bagnara847c6602014-05-22 19:20:46 +00002889bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2890 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002891 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002892 // which can be evaluated at compile-time. It very closely parallels
2893 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2894 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2895 // to isEvaluatable most of the time.
2896 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002897 // If we ever capture reference-binding directly in the AST, we can
2898 // kill the second parameter.
2899
2900 if (IsForRef) {
2901 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002902 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2903 return true;
2904 if (Culprit)
2905 *Culprit = this;
2906 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002907 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002908
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002909 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002910 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002911 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002912 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002913 return true;
John McCall81c9cea2010-08-01 21:51:45 +00002914 case CXXTemporaryObjectExprClass:
2915 case CXXConstructExprClass: {
2916 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00002917
Eli Friedman4c27ac22013-07-16 22:40:53 +00002918 if (CE->getConstructor()->isTrivial() &&
2919 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2920 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00002921 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00002922
Eli Friedman4c27ac22013-07-16 22:40:53 +00002923 // Trivial copy constructor
2924 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00002925 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00002926 }
2927
Richard Smithd62306a2011-11-10 06:34:14 +00002928 break;
John McCall81c9cea2010-08-01 21:51:45 +00002929 }
Fangrui Song407659a2018-11-30 23:41:18 +00002930 case ConstantExprClass: {
2931 // FIXME: We should be able to return "true" here, but it can lead to extra
2932 // error messages. E.g. in Sema/array-init.c.
2933 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
2934 return Exp->isConstantInitializer(Ctx, false, Culprit);
2935 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002936 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002937 // This handles gcc's extension that allows global initializers like
2938 // "struct x {int x;} x = (struct x) {};".
2939 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002940 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002941 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002942 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00002943 case DesignatedInitUpdateExprClass: {
2944 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2945 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2946 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2947 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002948 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002949 const InitListExpr *ILE = cast<InitListExpr>(this);
2950 if (ILE->getType()->isArrayType()) {
2951 unsigned numInits = ILE->getNumInits();
2952 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002953 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002954 return false;
2955 }
2956 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002957 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002958
2959 if (ILE->getType()->isRecordType()) {
2960 unsigned ElementNo = 0;
2961 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00002962 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002963 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00002964 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00002965 continue;
2966
2967 // Don't emit anonymous bitfields, they just affect layout.
2968 if (Field->isUnnamedBitfield())
2969 continue;
2970
2971 if (ElementNo < ILE->getNumInits()) {
2972 const Expr *Elt = ILE->getInit(ElementNo++);
2973 if (Field->isBitField()) {
2974 // Bitfields have to evaluate to an integer.
Fangrui Song407659a2018-11-30 23:41:18 +00002975 EvalResult Result;
2976 if (!Elt->EvaluateAsInt(Result, Ctx)) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002977 if (Culprit)
2978 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00002979 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002980 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002981 } else {
2982 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002983 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002984 return false;
2985 }
2986 }
2987 }
2988 return true;
2989 }
2990
2991 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002992 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00002993 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002994 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00002995 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00002996 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00002997 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002998 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00002999 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00003000 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003001 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00003002 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00003003 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3004 if (Culprit)
3005 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00003006 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003007 }
Eli Friedman75807f22013-07-20 00:40:58 +00003008 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003009 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003010 case UnaryOperatorClass: {
3011 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00003012 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003013 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003014 break;
3015 }
John McCall8b0f4ff2010-08-02 21:13:48 +00003016 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00003017 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00003018 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00003019 case CStyleCastExprClass:
3020 case ObjCBridgedCastExprClass:
3021 case CXXDynamicCastExprClass:
3022 case CXXReinterpretCastExprClass:
3023 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00003024 const CastExpr *CE = cast<CastExpr>(this);
3025
Eli Friedman13ec75b2011-12-21 00:43:02 +00003026 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00003027 if (CE->getCastKind() == CK_NoOp ||
3028 CE->getCastKind() == CK_LValueToRValue ||
3029 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00003030 CE->getCastKind() == CK_ConstructorConversion ||
3031 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003032 CE->getCastKind() == CK_AtomicToNonAtomic ||
3033 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003034 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00003035
Eli Friedman384da272009-01-25 03:12:18 +00003036 break;
Richard Smith161f09a2011-12-06 22:44:34 +00003037 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003038 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003039 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003040 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003041
Eli Friedman4c27ac22013-07-16 22:40:53 +00003042 case SubstNonTypeTemplateParmExprClass:
3043 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003044 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003045 case CXXDefaultArgExprClass:
3046 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003047 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003048 case CXXDefaultInitExprClass:
3049 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003050 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003051 }
Richard Smithce8eca52015-12-08 03:21:47 +00003052 // Allow certain forms of UB in constant initializers: signed integer
3053 // overflow and floating-point division by zero. We'll give a warning on
3054 // these, but they're common enough that we have to accept them.
3055 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00003056 return true;
3057 if (Culprit)
3058 *Culprit = this;
3059 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00003060}
3061
Nico Weber758fbac2018-02-13 21:31:47 +00003062bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3063 const FunctionDecl* FD = getDirectCallee();
3064 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3065 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3066 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003067
Nico Weber758fbac2018-02-13 21:31:47 +00003068 const Expr* Arg = getArg(0);
3069 bool ArgVal;
3070 return !Arg->isValueDependent() &&
3071 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3072}
3073
Scott Douglasscc013592015-06-10 15:18:23 +00003074namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003075 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00003076 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003077 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00003078 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003079 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00003080
3081 public:
3082 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003083 : Inherited(Context),
3084 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00003085
3086 bool hasSideEffects() const { return HasSideEffects; }
3087
3088 void VisitExpr(const Expr *E) {
3089 if (!HasSideEffects &&
3090 E->HasSideEffects(Context, IncludePossibleEffects))
3091 HasSideEffects = true;
3092 }
3093 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003094}
Scott Douglasscc013592015-06-10 15:18:23 +00003095
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003096bool Expr::HasSideEffects(const ASTContext &Ctx,
3097 bool IncludePossibleEffects) const {
3098 // In circumstances where we care about definite side effects instead of
3099 // potential side effects, we want to ignore expressions that are part of a
3100 // macro expansion as a potential side effect.
3101 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3102 return false;
3103
Richard Smith0421ce72012-08-07 04:16:51 +00003104 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003105 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00003106
3107 switch (getStmtClass()) {
3108 case NoStmtClass:
3109 #define ABSTRACT_STMT(Type)
3110 #define STMT(Type, Base) case Type##Class:
3111 #define EXPR(Type, Base)
3112 #include "clang/AST/StmtNodes.inc"
3113 llvm_unreachable("unexpected Expr kind");
3114
3115 case DependentScopeDeclRefExprClass:
3116 case CXXUnresolvedConstructExprClass:
3117 case CXXDependentScopeMemberExprClass:
3118 case UnresolvedLookupExprClass:
3119 case UnresolvedMemberExprClass:
3120 case PackExpansionExprClass:
3121 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00003122 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003123 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00003124 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003125 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3126
Richard Smitha33e4fe2012-08-07 05:18:29 +00003127 case DeclRefExprClass:
3128 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003129 case PredefinedExprClass:
3130 case IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003131 case FixedPointLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003132 case FloatingLiteralClass:
3133 case ImaginaryLiteralClass:
3134 case StringLiteralClass:
3135 case CharacterLiteralClass:
3136 case OffsetOfExprClass:
3137 case ImplicitValueInitExprClass:
3138 case UnaryExprOrTypeTraitExprClass:
3139 case AddrLabelExprClass:
3140 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003141 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003142 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003143 case CXXBoolLiteralExprClass:
3144 case CXXNullPtrLiteralExprClass:
3145 case CXXThisExprClass:
3146 case CXXScalarValueInitExprClass:
3147 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003148 case ArrayTypeTraitExprClass:
3149 case ExpressionTraitExprClass:
3150 case CXXNoexceptExprClass:
3151 case SizeOfPackExprClass:
3152 case ObjCStringLiteralClass:
3153 case ObjCEncodeExprClass:
3154 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003155 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003156 case CXXUuidofExprClass:
3157 case OpaqueValueExprClass:
3158 // These never have a side-effect.
3159 return false;
3160
Bill Wendling7c44da22018-10-31 03:48:47 +00003161 case ConstantExprClass:
3162 // FIXME: Move this into the "return false;" block above.
3163 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3164 Ctx, IncludePossibleEffects);
3165
Richard Smith0421ce72012-08-07 04:16:51 +00003166 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003167 case CXXOperatorCallExprClass:
3168 case CXXMemberCallExprClass:
3169 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003170 case UserDefinedLiteralClass: {
3171 // We don't know a call definitely has side effects, except for calls
3172 // to pure/const functions that definitely don't.
3173 // If the call itself is considered side-effect free, check the operands.
3174 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3175 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3176 if (IsPure || !IncludePossibleEffects)
3177 break;
3178 return true;
3179 }
3180
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003181 case BlockExprClass:
3182 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003183 if (!IncludePossibleEffects)
3184 break;
3185 return true;
3186
John McCall5e77d762013-04-16 07:28:30 +00003187 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003188 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003189 case CompoundAssignOperatorClass:
3190 case VAArgExprClass:
3191 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003192 case CXXThrowExprClass:
3193 case CXXNewExprClass:
3194 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003195 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003196 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003197 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003198 // These always have a side-effect.
3199 return true;
3200
Scott Douglasscc013592015-06-10 15:18:23 +00003201 case StmtExprClass: {
3202 // StmtExprs have a side-effect if any substatement does.
3203 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3204 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3205 return Finder.hasSideEffects();
3206 }
3207
Tim Shen4a05bb82016-06-21 20:29:17 +00003208 case ExprWithCleanupsClass:
3209 if (IncludePossibleEffects)
3210 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3211 return true;
3212 break;
3213
Richard Smith0421ce72012-08-07 04:16:51 +00003214 case ParenExprClass:
3215 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003216 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003217 case MemberExprClass:
3218 case ConditionalOperatorClass:
3219 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003220 case CompoundLiteralExprClass:
3221 case ExtVectorElementExprClass:
3222 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003223 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003224 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003225 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003226 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003227 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003228 case SubstNonTypeTemplateParmExprClass:
3229 case MaterializeTemporaryExprClass:
3230 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003231 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003232 case AsTypeExprClass:
3233 // These have a side-effect if any subexpression does.
3234 break;
3235
Richard Smitha33e4fe2012-08-07 05:18:29 +00003236 case UnaryOperatorClass:
3237 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003238 return true;
3239 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003240
3241 case BinaryOperatorClass:
3242 if (cast<BinaryOperator>(this)->isAssignmentOp())
3243 return true;
3244 break;
3245
Richard Smith0421ce72012-08-07 04:16:51 +00003246 case InitListExprClass:
3247 // FIXME: The children for an InitListExpr doesn't include the array filler.
3248 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003249 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003250 return true;
3251 break;
3252
3253 case GenericSelectionExprClass:
3254 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003255 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003256
3257 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003258 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3259 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003260
3261 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003262 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3263 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003264
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003265 case CXXDefaultInitExprClass: {
3266 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3267 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003268 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003269 // If we've not yet parsed the initializer, assume it has side-effects.
3270 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003271 }
Richard Smith852c9db2013-04-20 22:23:05 +00003272
Richard Smith0421ce72012-08-07 04:16:51 +00003273 case CXXDynamicCastExprClass: {
3274 // A dynamic_cast expression has side-effects if it can throw.
3275 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3276 if (DCE->getTypeAsWritten()->isReferenceType() &&
3277 DCE->getCastKind() == CK_Dynamic)
3278 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003279 }
3280 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003281 case ImplicitCastExprClass:
3282 case CStyleCastExprClass:
3283 case CXXStaticCastExprClass:
3284 case CXXReinterpretCastExprClass:
3285 case CXXConstCastExprClass:
3286 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003287 // While volatile reads are side-effecting in both C and C++, we treat them
3288 // as having possible (not definite) side-effects. This allows idiomatic
3289 // code to behave without warning, such as sizeof(*v) for a volatile-
3290 // qualified pointer.
3291 if (!IncludePossibleEffects)
3292 break;
3293
Richard Smitha33e4fe2012-08-07 05:18:29 +00003294 const CastExpr *CE = cast<CastExpr>(this);
3295 if (CE->getCastKind() == CK_LValueToRValue &&
3296 CE->getSubExpr()->getType().isVolatileQualified())
3297 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003298 break;
3299 }
3300
Richard Smithef8bf432012-08-13 20:08:14 +00003301 case CXXTypeidExprClass:
3302 // typeid might throw if its subexpression is potentially-evaluated, so has
3303 // side-effects in that case whether or not its subexpression does.
3304 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003305
3306 case CXXConstructExprClass:
3307 case CXXTemporaryObjectExprClass: {
3308 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003309 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003310 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003311 // A trivial constructor does not add any side-effects of its own. Just look
3312 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003313 break;
3314 }
3315
Richard Smith5179eb72016-06-28 19:03:57 +00003316 case CXXInheritedCtorInitExprClass: {
3317 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3318 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3319 return true;
3320 break;
3321 }
3322
Richard Smith0421ce72012-08-07 04:16:51 +00003323 case LambdaExprClass: {
3324 const LambdaExpr *LE = cast<LambdaExpr>(this);
Richard Smithb3d203f2018-10-19 19:01:34 +00003325 for (Expr *E : LE->capture_inits())
3326 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003327 return true;
3328 return false;
3329 }
3330
3331 case PseudoObjectExprClass: {
3332 // Only look for side-effects in the semantic form, and look past
3333 // OpaqueValueExpr bindings in that form.
3334 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3335 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3336 E = PO->semantics_end();
3337 I != E; ++I) {
3338 const Expr *Subexpr = *I;
3339 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3340 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003341 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003342 return true;
3343 }
3344 return false;
3345 }
3346
3347 case ObjCBoxedExprClass:
3348 case ObjCArrayLiteralClass:
3349 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003350 case ObjCSelectorExprClass:
3351 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003352 case ObjCIsaExprClass:
3353 case ObjCIndirectCopyRestoreExprClass:
3354 case ObjCSubscriptRefExprClass:
3355 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003356 case ObjCMessageExprClass:
3357 case ObjCPropertyRefExprClass:
3358 // FIXME: Classify these cases better.
3359 if (IncludePossibleEffects)
3360 return true;
3361 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003362 }
3363
3364 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003365 for (const Stmt *SubStmt : children())
3366 if (SubStmt &&
3367 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3368 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003369
3370 return false;
3371}
3372
Douglas Gregor1be329d2012-02-23 07:33:15 +00003373namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003374 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003375 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3376 {
3377 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003378
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003379 bool NonTrivial;
Fangrui Song6907ce22018-07-30 19:24:48 +00003380
Douglas Gregor1be329d2012-02-23 07:33:15 +00003381 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003382 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003383 : Inherited(Context), NonTrivial(false) { }
Fangrui Song6907ce22018-07-30 19:24:48 +00003384
Douglas Gregor1be329d2012-02-23 07:33:15 +00003385 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003386
3387 void VisitCallExpr(const CallExpr *E) {
3388 if (const CXXMethodDecl *Method
3389 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003390 if (Method->isTrivial()) {
3391 // Recurse to children of the call.
3392 Inherited::VisitStmt(E);
3393 return;
3394 }
3395 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003396
Douglas Gregor1be329d2012-02-23 07:33:15 +00003397 NonTrivial = true;
3398 }
Scott Douglass503fc392015-06-10 13:53:15 +00003399
3400 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003401 if (E->getConstructor()->isTrivial()) {
3402 // Recurse to children of the call.
3403 Inherited::VisitStmt(E);
3404 return;
3405 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003406
Douglas Gregor1be329d2012-02-23 07:33:15 +00003407 NonTrivial = true;
3408 }
Scott Douglass503fc392015-06-10 13:53:15 +00003409
3410 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003411 if (E->getTemporary()->getDestructor()->isTrivial()) {
3412 Inherited::VisitStmt(E);
3413 return;
3414 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003415
Douglas Gregor1be329d2012-02-23 07:33:15 +00003416 NonTrivial = true;
3417 }
3418 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003419}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003420
Scott Douglass503fc392015-06-10 13:53:15 +00003421bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003422 NonTrivialCallFinder Finder(Ctx);
3423 Finder.Visit(this);
Fangrui Song6907ce22018-07-30 19:24:48 +00003424 return Finder.hasNonTrivialCall();
Douglas Gregor1be329d2012-02-23 07:33:15 +00003425}
3426
Fangrui Song6907ce22018-07-30 19:24:48 +00003427/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003428/// pointer constant or not, as well as the specific kind of constant detected.
3429/// Null pointer constants can be integer constant expressions with the
3430/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3431/// (a GNU extension).
3432Expr::NullPointerConstantKind
3433Expr::isNullPointerConstant(ASTContext &Ctx,
3434 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003435 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003436 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003437 switch (NPC) {
3438 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003439 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003440 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003441 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003442 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003443 else
3444 return NPCK_NotNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003445
Douglas Gregor56751b52009-09-25 04:25:58 +00003446 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003447 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003448 }
3449 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003450
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003451 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003452 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003453 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003454 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003455 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003456 QualType Pointee = PT->getPointeeType();
Richard Smithdab73ce2018-11-28 06:25:06 +00003457 Qualifiers Qs = Pointee.getQualifiers();
Yaxun Liub7318e02017-10-13 03:37:48 +00003458 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3459 // has non-default address space it is not treated as nullptr.
3460 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3461 // since it cannot be assigned to a pointer to constant address space.
Richard Smithdab73ce2018-11-28 06:25:06 +00003462 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
Yaxun Liub7318e02017-10-13 03:37:48 +00003463 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3464 (Ctx.getLangOpts().OpenCL &&
3465 Ctx.getLangOpts().OpenCLVersion < 200 &&
Richard Smithdab73ce2018-11-28 06:25:06 +00003466 Pointee.getAddressSpace() == LangAS::opencl_private))
3467 Qs.removeAddressSpace();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003468
Richard Smithdab73ce2018-11-28 06:25:06 +00003469 if (Pointee->isVoidType() && Qs.empty() && // to void*
3470 CE->getSubExpr()->getType()->isIntegerType()) // from int
Douglas Gregor56751b52009-09-25 04:25:58 +00003471 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003472 }
Steve Naroffada7d422007-05-20 17:54:12 +00003473 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003474 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3475 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003476 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003477 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3478 // Accept ((void*)0) as a null pointer constant, as many other
3479 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003480 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003481 } else if (const GenericSelectionExpr *GE =
3482 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003483 if (GE->isResultDependent())
3484 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003485 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003486 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3487 if (CE->isConditionDependent())
3488 return NPCK_NotNull;
3489 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003490 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003491 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003492 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003493 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003494 } else if (const CXXDefaultInitExpr *DefaultInit
3495 = dyn_cast<CXXDefaultInitExpr>(this)) {
3496 // See through default initializer expressions.
3497 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003498 } else if (isa<GNUNullExpr>(this)) {
3499 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003500 return NPCK_GNUNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003501 } else if (const MaterializeTemporaryExpr *M
Douglas Gregorfe314812011-06-21 17:03:29 +00003502 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3503 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003504 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3505 if (const Expr *Source = OVE->getSourceExpr())
3506 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003507 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003508
Richard Smith89645bc2013-01-02 12:01:23 +00003509 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003510 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003511 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003512
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003513 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003514 if (!Ctx.getLangOpts().CPlusPlus11 &&
3515 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003516 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3517 const Expr *InitExpr = CLE->getInitializer();
3518 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3519 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3520 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003521 // This expression must be an integer type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003522 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003523 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003524 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003525
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003526 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003527 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3528 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003529 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003530 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003531 if (Lit && !Lit->getValue())
3532 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003533 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003534 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003535 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003536 // If we have an integer constant expression, we need to *evaluate* it and
3537 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003538 if (!isIntegerConstantExpr(Ctx))
3539 return NPCK_NotNull;
3540 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003541
David Blaikie1c7c8f72012-08-08 17:33:31 +00003542 if (EvaluateKnownConstInt(Ctx) != 0)
3543 return NPCK_NotNull;
3544
3545 if (isa<IntegerLiteral>(this))
3546 return NPCK_ZeroLiteral;
3547 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003548}
Steve Narofff7a5da12007-07-28 23:10:27 +00003549
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003550/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003551/// property, find the underlying property reference expression.
3552const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3553 const Expr *E = this;
3554 while (true) {
3555 assert((E->getValueKind() == VK_LValue &&
3556 E->getObjectKind() == OK_ObjCProperty) &&
3557 "expression is not a property reference");
3558 E = E->IgnoreParenCasts();
3559 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3560 if (BO->getOpcode() == BO_Comma) {
3561 E = BO->getRHS();
3562 continue;
3563 }
3564 }
3565
3566 break;
3567 }
3568
3569 return cast<ObjCPropertyRefExpr>(E);
3570}
3571
Anna Zaks97c7ce32012-10-01 20:34:04 +00003572bool Expr::isObjCSelfExpr() const {
3573 const Expr *E = IgnoreParenImpCasts();
3574
3575 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3576 if (!DRE)
3577 return false;
3578
3579 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3580 if (!Param)
3581 return false;
3582
3583 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3584 if (!M)
3585 return false;
3586
3587 return M->getSelfDecl() == Param;
3588}
3589
John McCalld25db7e2013-05-06 21:39:12 +00003590FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003591 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003592
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003593 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003594 if (ICE->getCastKind() == CK_LValueToRValue ||
3595 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003596 E = ICE->getSubExpr()->IgnoreParens();
3597 else
3598 break;
3599 }
3600
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003601 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003602 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003603 if (Field->isBitField())
3604 return Field;
3605
George Burgess IV00f70bd2018-03-01 05:43:23 +00003606 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3607 FieldDecl *Ivar = IvarRef->getDecl();
3608 if (Ivar->isBitField())
3609 return Ivar;
3610 }
John McCalld25db7e2013-05-06 21:39:12 +00003611
Richard Smith7873de02016-08-11 22:25:46 +00003612 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003613 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3614 if (Field->isBitField())
3615 return Field;
3616
Richard Smith7873de02016-08-11 22:25:46 +00003617 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3618 if (Expr *E = BD->getBinding())
3619 return E->getSourceBitField();
3620 }
3621
Eli Friedman609ada22011-07-13 02:05:57 +00003622 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003623 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003624 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003625
Eli Friedman609ada22011-07-13 02:05:57 +00003626 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003627 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003628 }
3629
Richard Smith5b571672014-09-24 23:55:00 +00003630 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3631 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3632 return UnOp->getSubExpr()->getSourceBitField();
3633
Craig Topper36250ad2014-05-12 05:36:57 +00003634 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003635}
3636
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003637bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003638 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003639 const Expr *E = this->IgnoreParens();
Fangrui Song6907ce22018-07-30 19:24:48 +00003640
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003641 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003642 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003643 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003644 E = ICE->getSubExpr()->IgnoreParens();
3645 else
3646 break;
3647 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003648
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003649 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3650 return ASE->getBase()->getType()->isVectorType();
3651
3652 if (isa<ExtVectorElementExpr>(E))
3653 return true;
3654
Richard Smith7873de02016-08-11 22:25:46 +00003655 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3656 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3657 if (auto *E = BD->getBinding())
3658 return E->refersToVectorElement();
3659
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003660 return false;
3661}
3662
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003663bool Expr::refersToGlobalRegisterVar() const {
3664 const Expr *E = this->IgnoreParenImpCasts();
3665
3666 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3667 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3668 if (VD->getStorageClass() == SC_Register &&
3669 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3670 return true;
3671
3672 return false;
3673}
3674
Chris Lattnerb8211f62009-02-16 22:14:05 +00003675/// isArrow - Return true if the base expression is a pointer to vector,
3676/// return false if the base expression is a vector.
3677bool ExtVectorElementExpr::isArrow() const {
3678 return getBase()->getType()->isPointerType();
3679}
3680
Nate Begemance4d7fc2008-04-18 23:10:10 +00003681unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003682 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003683 return VT->getNumElements();
3684 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003685}
3686
Nate Begemanf322eab2008-05-09 06:41:27 +00003687/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003688bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003689 // FIXME: Refactor this code to an accessor on the AST node which returns the
3690 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003691 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003692
3693 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003694 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003695 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003696
Nate Begeman7e5185b2009-01-18 02:01:21 +00003697 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003698 if (Comp[0] == 's' || Comp[0] == 'S')
3699 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003700
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003701 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003702 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003703 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003704
Steve Naroff0d595ca2007-07-30 03:29:09 +00003705 return false;
3706}
Chris Lattner885b4952007-08-02 23:36:59 +00003707
Nate Begemanf322eab2008-05-09 06:41:27 +00003708/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003709void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003710 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003711 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003712 bool isNumericAccessor = false;
3713 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003714 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003715 isNumericAccessor = true;
3716 }
Mike Stump11289f42009-09-09 15:08:12 +00003717
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003718 bool isHi = Comp == "hi";
3719 bool isLo = Comp == "lo";
3720 bool isEven = Comp == "even";
3721 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003722
Nate Begemanf322eab2008-05-09 06:41:27 +00003723 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3724 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003725
Nate Begemanf322eab2008-05-09 06:41:27 +00003726 if (isHi)
3727 Index = e + i;
3728 else if (isLo)
3729 Index = i;
3730 else if (isEven)
3731 Index = 2 * i;
3732 else if (isOdd)
3733 Index = 2 * i + 1;
3734 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003735 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003736
Nate Begemand3862152008-05-13 21:03:02 +00003737 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003738 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003739}
3740
Craig Topper37932912013-08-18 10:09:15 +00003741ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003742 QualType Type, SourceLocation BLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00003743 SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003744 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3745 Type->isDependentType(), Type->isDependentType(),
3746 Type->isInstantiationDependentType(),
3747 Type->containsUnexpandedParameterPack()),
3748 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3749{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003750 SubExprs = new (C) Stmt*[args.size()];
3751 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003752 if (args[i]->isTypeDependent())
3753 ExprBits.TypeDependent = true;
3754 if (args[i]->isValueDependent())
3755 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003756 if (args[i]->isInstantiationDependent())
3757 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003758 if (args[i]->containsUnexpandedParameterPack())
3759 ExprBits.ContainsUnexpandedParameterPack = true;
3760
3761 SubExprs[i] = args[i];
3762 }
3763}
3764
Craig Topper37932912013-08-18 10:09:15 +00003765void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003766 if (SubExprs) C.Deallocate(SubExprs);
3767
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003768 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003769 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003770 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003771}
Nate Begeman48745922009-08-12 02:28:50 +00003772
Bruno Ricci94498c72019-01-26 13:58:15 +00003773GenericSelectionExpr::GenericSelectionExpr(
Bruno Riccidb076832019-01-26 14:15:10 +00003774 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
Bruno Ricci94498c72019-01-26 13:58:15 +00003775 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3776 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3777 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
3778 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
3779 AssocExprs[ResultIndex]->getValueKind(),
3780 AssocExprs[ResultIndex]->getObjectKind(),
3781 AssocExprs[ResultIndex]->isTypeDependent(),
3782 AssocExprs[ResultIndex]->isValueDependent(),
3783 AssocExprs[ResultIndex]->isInstantiationDependent(),
3784 ContainsUnexpandedParameterPack),
3785 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00003786 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00003787 assert(AssocTypes.size() == AssocExprs.size() &&
3788 "Must have the same number of association expressions"
3789 " and TypeSourceInfo!");
3790 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
3791
Bruno Riccidb076832019-01-26 14:15:10 +00003792 GenericSelectionExprBits.GenericLoc = GenericLoc;
3793 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00003794 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00003795 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
3796 std::copy(AssocTypes.begin(), AssocTypes.end(),
3797 getTrailingObjects<TypeSourceInfo *>());
Peter Collingbourne91147592011-04-15 00:35:48 +00003798}
3799
Bruno Ricci94498c72019-01-26 13:58:15 +00003800GenericSelectionExpr::GenericSelectionExpr(
3801 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3802 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3803 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3804 bool ContainsUnexpandedParameterPack)
3805 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
3806 OK_Ordinary,
3807 /*isTypeDependent=*/true,
3808 /*isValueDependent=*/true,
3809 /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
3810 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00003811 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00003812 assert(AssocTypes.size() == AssocExprs.size() &&
3813 "Must have the same number of association expressions"
3814 " and TypeSourceInfo!");
3815
Bruno Riccidb076832019-01-26 14:15:10 +00003816 GenericSelectionExprBits.GenericLoc = GenericLoc;
3817 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00003818 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00003819 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
3820 std::copy(AssocTypes.begin(), AssocTypes.end(),
3821 getTrailingObjects<TypeSourceInfo *>());
3822}
3823
3824GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
3825 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
3826
3827GenericSelectionExpr *GenericSelectionExpr::Create(
3828 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3829 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3830 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3831 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
3832 unsigned NumAssocs = AssocExprs.size();
3833 void *Mem = Context.Allocate(
3834 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3835 alignof(GenericSelectionExpr));
3836 return new (Mem) GenericSelectionExpr(
3837 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
3838 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
3839}
3840
3841GenericSelectionExpr *GenericSelectionExpr::Create(
3842 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3843 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3844 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3845 bool ContainsUnexpandedParameterPack) {
3846 unsigned NumAssocs = AssocExprs.size();
3847 void *Mem = Context.Allocate(
3848 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3849 alignof(GenericSelectionExpr));
3850 return new (Mem) GenericSelectionExpr(
3851 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
3852 RParenLoc, ContainsUnexpandedParameterPack);
3853}
3854
3855GenericSelectionExpr *
3856GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
3857 unsigned NumAssocs) {
3858 void *Mem = Context.Allocate(
3859 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3860 alignof(GenericSelectionExpr));
3861 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
Peter Collingbourne91147592011-04-15 00:35:48 +00003862}
3863
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003864//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003865// DesignatedInitExpr
3866//===----------------------------------------------------------------------===//
3867
Chandler Carruth631abd92011-06-16 06:47:06 +00003868IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003869 assert(Kind == FieldDesignator && "Only valid on a field designator");
3870 if (Field.NameOrField & 0x01)
3871 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3872 else
3873 return getField()->getIdentifier();
3874}
3875
Craig Topper37932912013-08-18 10:09:15 +00003876DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00003877 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003878 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003879 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003880 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003881 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003882 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003883 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003884 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003885 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003886 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003887 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00003888 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003889 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003890
3891 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003892 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003893 *Child++ = Init;
3894
3895 // Copy the designators and their subexpressions, computing
3896 // value-dependence along the way.
3897 unsigned IndexIdx = 0;
3898 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003899 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003900
3901 if (this->Designators[I].isArrayDesignator()) {
3902 // Compute type- and value-dependence.
3903 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003904 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003905 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003906 if (Index->isInstantiationDependent())
3907 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003908 // Propagate unexpanded parameter packs.
3909 if (Index->containsUnexpandedParameterPack())
3910 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003911
3912 // Copy the index expressions into permanent storage.
3913 *Child++ = IndexExprs[IndexIdx++];
3914 } else if (this->Designators[I].isArrayRangeDesignator()) {
3915 // Compute type- and value-dependence.
3916 Expr *Start = IndexExprs[IndexIdx];
3917 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003918 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003919 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00003920 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003921 ExprBits.InstantiationDependent = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003922 } else if (Start->isInstantiationDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003923 End->isInstantiationDependent()) {
3924 ExprBits.InstantiationDependent = true;
3925 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003926
Douglas Gregora6e053e2010-12-15 01:34:56 +00003927 // Propagate unexpanded parameter packs.
3928 if (Start->containsUnexpandedParameterPack() ||
3929 End->containsUnexpandedParameterPack())
3930 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003931
3932 // Copy the start/end expressions into permanent storage.
3933 *Child++ = IndexExprs[IndexIdx++];
3934 *Child++ = IndexExprs[IndexIdx++];
3935 }
3936 }
3937
Benjamin Kramerc215e762012-08-24 11:54:20 +00003938 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00003939}
3940
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003941DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00003942DesignatedInitExpr::Create(const ASTContext &C,
3943 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003944 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003945 SourceLocation ColonOrEqualLoc,
3946 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003947 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003948 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00003949 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003950 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003951 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003952}
3953
Craig Topper37932912013-08-18 10:09:15 +00003954DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00003955 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003956 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003957 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00003958 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3959}
3960
Craig Topper37932912013-08-18 10:09:15 +00003961void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003962 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00003963 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003964 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00003965 NumDesignators = NumDesigs;
3966 for (unsigned I = 0; I != NumDesigs; ++I)
3967 Designators[I] = Desigs[I];
3968}
3969
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003970SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3971 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3972 if (size() == 1)
3973 return DIE->getDesignator(0)->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003974 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003975 DIE->getDesignator(size() - 1)->getEndLoc());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003976}
3977
Stephen Kelly724e9e52018-08-09 20:05:03 +00003978SourceLocation DesignatedInitExpr::getBeginLoc() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003979 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00003980 auto *DIE = const_cast<DesignatedInitExpr *>(this);
3981 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003982 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00003983 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003984 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3985 else
3986 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3987 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00003988 StartLoc =
3989 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003990 return StartLoc;
3991}
3992
Stephen Kelly02a67ba2018-08-09 20:05:47 +00003993SourceLocation DesignatedInitExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003994 return getInit()->getEndLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003995}
3996
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003997Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003998 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003999 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004000}
4001
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004002Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004003 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004004 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004005 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004006}
4007
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004008Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004009 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004010 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004011 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004012}
4013
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004014/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00004015/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00004016void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00004017 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00004018 const Designator *Last) {
4019 unsigned NumNewDesignators = Last - First;
4020 if (NumNewDesignators == 0) {
4021 std::copy_backward(Designators + Idx + 1,
4022 Designators + NumDesignators,
4023 Designators + Idx);
4024 --NumNewDesignators;
4025 return;
4026 } else if (NumNewDesignators == 1) {
4027 Designators[Idx] = *First;
4028 return;
4029 }
4030
Mike Stump11289f42009-09-09 15:08:12 +00004031 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004032 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00004033 std::copy(Designators, Designators + Idx, NewDesignators);
4034 std::copy(First, Last, NewDesignators + Idx);
4035 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4036 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00004037 Designators = NewDesignators;
4038 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4039}
4040
Yunzhong Gaocb779302015-06-10 00:27:52 +00004041DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4042 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4043 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4044 OK_Ordinary, false, false, false, false) {
4045 BaseAndUpdaterExprs[0] = baseExpr;
4046
4047 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4048 ILE->setType(baseExpr->getType());
4049 BaseAndUpdaterExprs[1] = ILE;
4050}
4051
Stephen Kelly724e9e52018-08-09 20:05:03 +00004052SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004053 return getBase()->getBeginLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004054}
4055
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004056SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004057 return getBase()->getEndLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004058}
4059
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004060ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4061 SourceLocation RParenLoc)
4062 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4063 false, false),
4064 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4065 ParenListExprBits.NumExprs = Exprs.size();
4066
4067 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4068 if (Exprs[I]->isTypeDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004069 ExprBits.TypeDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004070 if (Exprs[I]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004071 ExprBits.ValueDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004072 if (Exprs[I]->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00004073 ExprBits.InstantiationDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004074 if (Exprs[I]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004075 ExprBits.ContainsUnexpandedParameterPack = true;
4076
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004077 getTrailingObjects<Stmt *>()[I] = Exprs[I];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004078 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004079}
4080
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004081ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4082 : Expr(ParenListExprClass, Empty) {
4083 ParenListExprBits.NumExprs = NumExprs;
4084}
4085
4086ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4087 SourceLocation LParenLoc,
4088 ArrayRef<Expr *> Exprs,
4089 SourceLocation RParenLoc) {
4090 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4091 alignof(ParenListExpr));
4092 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4093}
4094
4095ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4096 unsigned NumExprs) {
4097 void *Mem =
4098 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4099 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4100}
4101
John McCall1bf58462011-02-16 08:02:54 +00004102const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4103 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4104 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00004105 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4106 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00004107 e = cast<CXXConstructExpr>(e)->getArg(0);
4108 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4109 e = ice->getSubExpr();
4110 return cast<OpaqueValueExpr>(e);
4111}
4112
Craig Topper37932912013-08-18 10:09:15 +00004113PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4114 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00004115 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004116 void *buffer =
4117 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004118 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004119 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4120}
4121
4122PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4123 : Expr(PseudoObjectExprClass, shell) {
4124 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4125}
4126
Craig Topper37932912013-08-18 10:09:15 +00004127PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00004128 ArrayRef<Expr*> semantics,
4129 unsigned resultIndex) {
4130 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004131 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00004132
4133 QualType type;
4134 ExprValueKind VK;
4135 if (resultIndex == NoResult) {
4136 type = C.VoidTy;
4137 VK = VK_RValue;
4138 } else {
4139 assert(resultIndex < semantics.size());
4140 type = semantics[resultIndex]->getType();
4141 VK = semantics[resultIndex]->getValueKind();
4142 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4143 }
4144
James Y Knighte00a67e2015-12-31 04:18:25 +00004145 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004146 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004147 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4148 resultIndex);
4149}
4150
4151PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4152 Expr *syntax, ArrayRef<Expr*> semantics,
4153 unsigned resultIndex)
4154 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4155 /*filled in at end of ctor*/ false, false, false, false) {
4156 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4157 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4158
4159 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4160 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4161 getSubExprsBuffer()[i] = E;
4162
4163 if (E->isTypeDependent())
4164 ExprBits.TypeDependent = true;
4165 if (E->isValueDependent())
4166 ExprBits.ValueDependent = true;
4167 if (E->isInstantiationDependent())
4168 ExprBits.InstantiationDependent = true;
4169 if (E->containsUnexpandedParameterPack())
4170 ExprBits.ContainsUnexpandedParameterPack = true;
4171
4172 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00004173 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00004174 "opaque-value semantic expressions for pseudo-object "
4175 "operations must have sources");
4176 }
4177}
4178
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004179//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004180// Child Iterators for iterating over subexpressions/substatements
4181//===----------------------------------------------------------------------===//
4182
Peter Collingbournee190dee2011-03-11 19:24:49 +00004183// UnaryExprOrTypeTraitExpr
4184Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004185 const_child_range CCR =
4186 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4187 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4188}
4189
4190Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00004191 // If this is of a type and the type is a VLA type (and not a typedef), the
4192 // size expression of the VLA needs to be treated as an executable expression.
4193 // Why isn't this weirdness documented better in StmtIterator?
4194 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004195 if (const VariableArrayType *T =
4196 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4197 return const_child_range(const_child_iterator(T), const_child_iterator());
4198 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00004199 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004200 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004201}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004202
Benjamin Kramerc215e762012-08-24 11:54:20 +00004203AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004204 QualType t, AtomicOp op, SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004205 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4206 false, false, false, false),
4207 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4208{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004209 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4210 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004211 if (args[i]->isTypeDependent())
4212 ExprBits.TypeDependent = true;
4213 if (args[i]->isValueDependent())
4214 ExprBits.ValueDependent = true;
4215 if (args[i]->isInstantiationDependent())
4216 ExprBits.InstantiationDependent = true;
4217 if (args[i]->containsUnexpandedParameterPack())
4218 ExprBits.ContainsUnexpandedParameterPack = true;
4219
4220 SubExprs[i] = args[i];
4221 }
4222}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004223
4224unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4225 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004226 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004227 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004228 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004229 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004230 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004231
Yaxun Liu30d652a2017-08-15 16:02:49 +00004232 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004233 case AO__c11_atomic_store:
4234 case AO__c11_atomic_exchange:
4235 case AO__atomic_load:
4236 case AO__atomic_store:
4237 case AO__atomic_store_n:
4238 case AO__atomic_exchange_n:
4239 case AO__c11_atomic_fetch_add:
4240 case AO__c11_atomic_fetch_sub:
4241 case AO__c11_atomic_fetch_and:
4242 case AO__c11_atomic_fetch_or:
4243 case AO__c11_atomic_fetch_xor:
4244 case AO__atomic_fetch_add:
4245 case AO__atomic_fetch_sub:
4246 case AO__atomic_fetch_and:
4247 case AO__atomic_fetch_or:
4248 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004249 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004250 case AO__atomic_add_fetch:
4251 case AO__atomic_sub_fetch:
4252 case AO__atomic_and_fetch:
4253 case AO__atomic_or_fetch:
4254 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004255 case AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004256 case AO__atomic_fetch_min:
4257 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004258 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004259
Yaxun Liu30d652a2017-08-15 16:02:49 +00004260 case AO__opencl_atomic_store:
4261 case AO__opencl_atomic_exchange:
4262 case AO__opencl_atomic_fetch_add:
4263 case AO__opencl_atomic_fetch_sub:
4264 case AO__opencl_atomic_fetch_and:
4265 case AO__opencl_atomic_fetch_or:
4266 case AO__opencl_atomic_fetch_xor:
4267 case AO__opencl_atomic_fetch_min:
4268 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004269 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004270 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004271
4272 case AO__c11_atomic_compare_exchange_strong:
4273 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004274 return 5;
4275
Yaxun Liu39195062017-08-04 18:16:31 +00004276 case AO__opencl_atomic_compare_exchange_strong:
4277 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004278 case AO__atomic_compare_exchange:
4279 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004280 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004281 }
4282 llvm_unreachable("unknown atomic op");
4283}
Alexey Bataeva1764212015-09-30 09:22:36 +00004284
Yaxun Liu39195062017-08-04 18:16:31 +00004285QualType AtomicExpr::getValueType() const {
4286 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4287 if (auto AT = T->getAs<AtomicType>())
4288 return AT->getValueType();
4289 return T;
4290}
4291
Alexey Bataev31300ed2016-02-04 11:27:03 +00004292QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004293 unsigned ArraySectionCount = 0;
4294 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4295 Base = OASE->getBase();
4296 ++ArraySectionCount;
4297 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004298 while (auto *ASE =
4299 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004300 Base = ASE->getBase();
4301 ++ArraySectionCount;
4302 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004303 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004304 auto OriginalTy = Base->getType();
4305 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4306 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4307 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4308
4309 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4310 if (OriginalTy->isAnyPointerType())
4311 OriginalTy = OriginalTy->getPointeeType();
4312 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004313 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004314 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4315 }
4316 }
4317 return OriginalTy;
4318}