blob: cc92689cb922c1ad5d69f3a7ec8f2a82f874f6be [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
Eric Fiselier708afb52019-05-16 21:04:15 +000013#include "clang/AST/Expr.h"
14#include "clang/AST/APValue.h"
Chris Lattner5c4664e2007-07-15 23:32:58 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Douglas Gregor9a657932008-10-21 23:43:52 +000017#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor1be329d2012-02-23 07:33:15 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/AST/ExprCXX.h"
David Majnemerbed356a2013-11-06 23:31:56 +000022#include "clang/AST/Mangle.h"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000023#include "clang/AST/RecordLayout.h"
24#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000026#include "clang/Basic/CharInfo.h"
Chris Lattnere925d612010-11-17 07:37:15 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnera7944d82007-11-27 18:22:04 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/Lex/Lexer.h"
30#include "clang/Lex/LiteralSupport.h"
Douglas Gregor0840cc02009-11-01 20:32:48 +000031#include "llvm/Support/ErrorHandling.h"
Anders Carlsson2fb08242009-09-08 18:24:21 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregord5846a12009-04-15 06:41:24 +000033#include <algorithm>
Eli Friedmanfcec6302011-11-01 02:23:42 +000034#include <cstring>
Chris Lattner1b926492006-08-23 06:42:10 +000035using namespace clang;
36
Richard Smith018ac392016-11-03 18:55:18 +000037const Expr *Expr::getBestDynamicClassTypeExpr() const {
38 const Expr *E = this;
39 while (true) {
40 E = E->ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000041
Richard Smith018ac392016-11-03 18:55:18 +000042 // Follow the RHS of a comma operator.
43 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
44 if (BO->getOpcode() == BO_Comma) {
45 E = BO->getRHS();
46 continue;
47 }
48 }
49
50 // Step into initializer for materialized temporaries.
51 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
52 E = MTE->GetTemporaryExpr();
53 continue;
54 }
55
56 break;
57 }
58
59 return E;
60}
61
62const CXXRecordDecl *Expr::getBestDynamicClassType() const {
63 const Expr *E = getBestDynamicClassTypeExpr();
Rafael Espindola49e860b2012-06-26 17:45:31 +000064 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000065 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
66 DerivedType = PTy->getPointeeType();
67
Rafael Espindola60a2bba2012-07-17 20:24:05 +000068 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000069 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000070
Rafael Espindola49e860b2012-06-26 17:45:31 +000071 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000072 Decl *D = Ty->getDecl();
73 return cast<CXXRecordDecl>(D);
74}
75
Richard Smithf3fabd22013-06-03 00:17:11 +000076const Expr *Expr::skipRValueSubobjectAdjustments(
77 SmallVectorImpl<const Expr *> &CommaLHSs,
78 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000079 const Expr *E = this;
80 while (true) {
81 E = E->IgnoreParens();
82
83 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
84 if ((CE->getCastKind() == CK_DerivedToBase ||
85 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
86 E->getType()->isRecordType()) {
87 E = CE->getSubExpr();
88 CXXRecordDecl *Derived
89 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
90 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
91 continue;
92 }
93
94 if (CE->getCastKind() == CK_NoOp) {
95 E = CE->getSubExpr();
96 continue;
97 }
98 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +000099 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +0000100 assert(ME->getBase()->getType()->isRecordType());
101 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000102 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +0000103 E = ME->getBase();
104 Adjustments.push_back(SubobjectAdjustment(Field));
105 continue;
106 }
Rafael Espindola9c006de2012-10-27 01:03:43 +0000107 }
108 }
109 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Richard Smitha3fd1162018-07-24 21:18:30 +0000110 if (BO->getOpcode() == BO_PtrMemD) {
Rafael Espindola973aa202012-11-01 14:32:20 +0000111 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +0000112 E = BO->getLHS();
113 const MemberPointerType *MPT =
114 BO->getRHS()->getType()->getAs<MemberPointerType>();
115 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +0000116 continue;
117 } else if (BO->getOpcode() == BO_Comma) {
118 CommaLHSs.push_back(BO->getLHS());
119 E = BO->getRHS();
120 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000121 }
122 }
123
124 // Nothing changed.
125 break;
126 }
127 return E;
128}
129
Chris Lattner4ebae652010-04-16 23:34:13 +0000130/// isKnownToHaveBooleanValue - Return true if this is an integer expression
131/// that is known to return 0 or 1. This happens for _Bool/bool expressions
132/// but also int expressions which are produced by things like comparisons in
133/// C.
134bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000135 const Expr *E = IgnoreParens();
136
Chris Lattner4ebae652010-04-16 23:34:13 +0000137 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000138 if (E->getType()->isBooleanType()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000139 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000140 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000141
Peter Collingbourne91147592011-04-15 00:35:48 +0000142 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000143 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000144 case UO_Plus:
Chris Lattner4ebae652010-04-16 23:34:13 +0000145 return UO->getSubExpr()->isKnownToHaveBooleanValue();
Richard Trieu0f097742014-04-04 04:13:47 +0000146 case UO_LNot:
147 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000148 default:
149 return false;
150 }
151 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000152
John McCall45d30c32010-06-12 01:56:02 +0000153 // Only look through implicit casts. If the user writes
154 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbourne91147592011-04-15 00:35:48 +0000155 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000156 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000157
Peter Collingbourne91147592011-04-15 00:35:48 +0000158 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000159 switch (BO->getOpcode()) {
160 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000161 case BO_LT: // Relational operators.
162 case BO_GT:
163 case BO_LE:
164 case BO_GE:
165 case BO_EQ: // Equality operators.
166 case BO_NE:
167 case BO_LAnd: // AND operator.
168 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000169 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000170
John McCalle3027922010-08-25 11:45:40 +0000171 case BO_And: // Bitwise AND operator.
172 case BO_Xor: // Bitwise XOR operator.
173 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000174 // Handle things like (x==2)|(y==12).
175 return BO->getLHS()->isKnownToHaveBooleanValue() &&
176 BO->getRHS()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000177
John McCalle3027922010-08-25 11:45:40 +0000178 case BO_Comma:
179 case BO_Assign:
Chris Lattner4ebae652010-04-16 23:34:13 +0000180 return BO->getRHS()->isKnownToHaveBooleanValue();
181 }
182 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000183
Peter Collingbourne91147592011-04-15 00:35:48 +0000184 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000185 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
186 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000187
Chris Lattner4ebae652010-04-16 23:34:13 +0000188 return false;
189}
190
John McCallbd066782011-02-09 08:16:59 +0000191// Amusing macro metaprogramming hack: check whether a class provides
192// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000193//
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000194// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000195namespace {
196 /// This implementation is used when a class provides a custom
197 /// implementation of getExprLoc.
198 template <class E, class T>
199 SourceLocation getExprLocImpl(const Expr *expr,
200 SourceLocation (T::*v)() const) {
201 return static_cast<const E*>(expr)->getExprLoc();
202 }
John McCallbd066782011-02-09 08:16:59 +0000203
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000204 /// This implementation is used when a class doesn't provide
205 /// a custom implementation of getExprLoc. Overload resolution
206 /// should pick it over the implementation above because it's
207 /// more specialized according to function template partial ordering.
208 template <class E>
209 SourceLocation getExprLocImpl(const Expr *expr,
210 SourceLocation (Expr::*v)() const) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000211 return static_cast<const E *>(expr)->getBeginLoc();
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000212 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000213}
John McCallbd066782011-02-09 08:16:59 +0000214
215SourceLocation Expr::getExprLoc() const {
216 switch (getStmtClass()) {
217 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
218#define ABSTRACT_STMT(type)
219#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000220 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000221#define EXPR(type, base) \
222 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
223#include "clang/AST/StmtNodes.inc"
224 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000225 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000226}
227
Chris Lattner0eedafe2006-08-24 04:56:27 +0000228//===----------------------------------------------------------------------===//
229// Primary Expressions.
230//===----------------------------------------------------------------------===//
231
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000232static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
233 assert((Kind == ConstantExpr::RSK_APValue ||
234 Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&
235 "Invalid StorageKind Value");
236}
237
238ConstantExpr::ResultStorageKind
239ConstantExpr::getStorageKind(const APValue &Value) {
240 switch (Value.getKind()) {
241 case APValue::None:
242 return ConstantExpr::RSK_None;
243 case APValue::Int:
244 if (!Value.getInt().needsCleanup())
245 return ConstantExpr::RSK_Int64;
246 LLVM_FALLTHROUGH;
247 default:
248 return ConstantExpr::RSK_APValue;
249 }
250}
251
252void ConstantExpr::DefaultInit(ResultStorageKind StorageKind) {
253 ConstantExprBits.ResultKind = StorageKind;
254 if (StorageKind == RSK_APValue)
255 ::new (getTrailingObjects<APValue>()) APValue();
256}
257
258ConstantExpr::ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind)
259 : FullExpr(ConstantExprClass, subexpr) {
260 DefaultInit(StorageKind);
261}
262
263ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
264 ResultStorageKind StorageKind) {
265 assert(!isa<ConstantExpr>(E));
266 AssertResultStorageKind(StorageKind);
267 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
268 StorageKind == ConstantExpr::RSK_APValue,
269 StorageKind == ConstantExpr::RSK_Int64);
270 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
271 ConstantExpr *Self = new (Mem) ConstantExpr(E, StorageKind);
272 if (StorageKind == ConstantExpr::RSK_APValue)
273 Context.AddAPValueCleanup(&Self->APValueResult());
274 return Self;
275}
276
277ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
278 const APValue &Result) {
279 ResultStorageKind StorageKind = getStorageKind(Result);
280 ConstantExpr *Self = Create(Context, E, StorageKind);
281 Self->SetResult(Result);
282 return Self;
283}
284
285ConstantExpr::ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty)
286 : FullExpr(ConstantExprClass, Empty) {
287 DefaultInit(StorageKind);
288}
289
290ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
291 ResultStorageKind StorageKind,
292 EmptyShell Empty) {
293 AssertResultStorageKind(StorageKind);
294 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
295 StorageKind == ConstantExpr::RSK_APValue,
296 StorageKind == ConstantExpr::RSK_Int64);
297 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
298 ConstantExpr *Self = new (Mem) ConstantExpr(StorageKind, Empty);
299 if (StorageKind == ConstantExpr::RSK_APValue)
300 Context.AddAPValueCleanup(&Self->APValueResult());
301 return Self;
302}
303
304void ConstantExpr::MoveIntoResult(APValue &Value) {
305 assert(getStorageKind(Value) == ConstantExprBits.ResultKind &&
306 "Invalid storage for this value kind");
307 switch (ConstantExprBits.ResultKind) {
308 case RSK_None:
309 return;
310 case RSK_Int64:
311 Int64Result() = *Value.getInt().getRawData();
312 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
313 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
314 return;
315 case RSK_APValue:
316 APValueResult() = std::move(Value);
317 return;
318 }
319 llvm_unreachable("Invalid ResultKind Bits");
320}
321
322APValue ConstantExpr::getAPValueResult() const {
323 switch (ConstantExprBits.ResultKind) {
324 case ConstantExpr::RSK_APValue:
325 return APValueResult();
326 case ConstantExpr::RSK_Int64:
327 return APValue(
328 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
329 ConstantExprBits.IsUnsigned));
330 case ConstantExpr::RSK_None:
331 return APValue();
332 }
333 llvm_unreachable("invalid ResultKind");
334}
335
Fangrui Song6907ce22018-07-30 19:24:48 +0000336/// Compute the type-, value-, and instantiation-dependence of a
Douglas Gregor678d76c2011-07-01 01:22:09 +0000337/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000338/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000339static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
340 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000341 bool &ValueDependent,
342 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000343 TypeDependent = false;
344 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000345 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000346
347 // (TD) C++ [temp.dep.expr]p3:
348 // An id-expression is type-dependent if it contains:
349 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000350 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000351 //
352 // (VD) C++ [temp.dep.constexpr]p2:
353 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000354
Douglas Gregored6c7442009-11-23 11:41:28 +0000355 // (TD) - an identifier that was declared with dependent type
356 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000357 if (T->isDependentType()) {
358 TypeDependent = true;
359 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000360 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000361 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000362 } else if (T->isInstantiationDependentType()) {
363 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000364 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000365
Douglas Gregored6c7442009-11-23 11:41:28 +0000366 // (TD) - a conversion-function-id that specifies a dependent type
Fangrui Song6907ce22018-07-30 19:24:48 +0000367 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000368 == DeclarationName::CXXConversionFunctionName) {
369 QualType T = D->getDeclName().getCXXNameType();
370 if (T->isDependentType()) {
371 TypeDependent = true;
372 ValueDependent = true;
373 InstantiationDependent = true;
374 return;
375 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000376
Douglas Gregor678d76c2011-07-01 01:22:09 +0000377 if (T->isInstantiationDependentType())
378 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000379 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000380
Douglas Gregored6c7442009-11-23 11:41:28 +0000381 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000382 if (isa<NonTypeTemplateParmDecl>(D)) {
383 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000384 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000385 return;
386 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000387
Douglas Gregored6c7442009-11-23 11:41:28 +0000388 // (VD) - a constant with integral or enumeration type and is
389 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000390 // (VD) - a constant with literal type and is initialized with an
391 // expression that is value-dependent [C++11].
392 // (VD) - FIXME: Missing from the standard:
393 // - an entity with reference type and is initialized with an
394 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000395 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000396 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000397 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000398 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000399 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000400 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000401 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000402 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000403 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000404 InstantiationDependent = true;
405 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000406 }
407
Fangrui Song6907ce22018-07-30 19:24:48 +0000408 // (VD) - FIXME: Missing from the standard:
409 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000410 // instantiation
Fangrui Song6907ce22018-07-30 19:24:48 +0000411 if (Var->isStaticDataMember() &&
Richard Smithec8dcd22011-11-08 01:31:09 +0000412 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000413 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000414 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000415 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
416 if (TInfo->getType()->isIncompleteArrayType())
417 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000418 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000419
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000420 return;
421 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000422
423 // (VD) - FIXME: Missing from the standard:
424 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000425 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000426 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
427 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000428 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000429 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000430}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000431
Craig Topperce7167c2013-08-22 04:58:56 +0000432void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000433 bool TypeDependent = false;
434 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000435 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000436 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
437 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000438
439 ExprBits.TypeDependent |= TypeDependent;
440 ExprBits.ValueDependent |= ValueDependent;
441 ExprBits.InstantiationDependent |= InstantiationDependent;
442
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000443 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000444 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000445 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000446}
447
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000448DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
449 bool RefersToEnclosingVariableOrCapture, QualType T,
450 ExprValueKind VK, SourceLocation L,
Richard Smith715f7a12019-06-11 17:50:32 +0000451 const DeclarationNameLoc &LocInfo,
452 NonOdrUseReason NOUR)
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000453 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
454 D(D), DNLoc(LocInfo) {
455 DeclRefExprBits.HasQualifier = false;
456 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
457 DeclRefExprBits.HasFoundDecl = false;
458 DeclRefExprBits.HadMultipleCandidates = false;
459 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
460 RefersToEnclosingVariableOrCapture;
Richard Smith715f7a12019-06-11 17:50:32 +0000461 DeclRefExprBits.NonOdrUseReason = NOUR;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000462 DeclRefExprBits.Loc = L;
463 computeDependence(Ctx);
464}
465
Craig Topperce7167c2013-08-22 04:58:56 +0000466DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000467 NestedNameSpecifierLoc QualifierLoc,
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000468 SourceLocation TemplateKWLoc, ValueDecl *D,
469 bool RefersToEnclosingVariableOrCapture,
470 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000471 const TemplateArgumentListInfo *TemplateArgs,
Richard Smith715f7a12019-06-11 17:50:32 +0000472 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000473 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
474 D(D), DNLoc(NameInfo.getInfo()) {
Bruno Riccia795e802018-11-13 17:56:44 +0000475 DeclRefExprBits.Loc = NameInfo.getLoc();
Chandler Carruth0e439962011-05-01 21:29:53 +0000476 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000477 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000478 new (getTrailingObjects<NestedNameSpecifierLoc>())
479 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000480 auto *NNS = QualifierLoc.getNestedNameSpecifier();
481 if (NNS->isInstantiationDependent())
482 ExprBits.InstantiationDependent = true;
483 if (NNS->containsUnexpandedParameterPack())
484 ExprBits.ContainsUnexpandedParameterPack = true;
485 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000486 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
487 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000488 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000489 DeclRefExprBits.HasTemplateKWAndArgsInfo
490 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000491 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
492 RefersToEnclosingVariableOrCapture;
Richard Smith715f7a12019-06-11 17:50:32 +0000493 DeclRefExprBits.NonOdrUseReason = NOUR;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000494 if (TemplateArgs) {
495 bool Dependent = false;
496 bool InstantiationDependent = false;
497 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000498 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
499 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
500 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000501 assert(!Dependent && "built a DeclRefExpr with dependent template args");
502 ExprBits.InstantiationDependent |= InstantiationDependent;
503 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000504 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000505 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
506 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000507 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000508 DeclRefExprBits.HadMultipleCandidates = 0;
509
Daniel Dunbar9d355812012-03-09 01:51:51 +0000510 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000511}
512
Craig Topperce7167c2013-08-22 04:58:56 +0000513DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000514 NestedNameSpecifierLoc QualifierLoc,
Richard Smith715f7a12019-06-11 17:50:32 +0000515 SourceLocation TemplateKWLoc, ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000516 bool RefersToEnclosingVariableOrCapture,
Richard Smith715f7a12019-06-11 17:50:32 +0000517 SourceLocation NameLoc, QualType T,
518 ExprValueKind VK, NamedDecl *FoundD,
519 const TemplateArgumentListInfo *TemplateArgs,
520 NonOdrUseReason NOUR) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000521 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000522 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000523 DeclarationNameInfo(D->getDeclName(), NameLoc),
Richard Smith715f7a12019-06-11 17:50:32 +0000524 T, VK, FoundD, TemplateArgs, NOUR);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000525}
526
Craig Topperce7167c2013-08-22 04:58:56 +0000527DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000528 NestedNameSpecifierLoc QualifierLoc,
Richard Smith715f7a12019-06-11 17:50:32 +0000529 SourceLocation TemplateKWLoc, ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000530 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000531 const DeclarationNameInfo &NameInfo,
Richard Smith715f7a12019-06-11 17:50:32 +0000532 QualType T, ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000533 NamedDecl *FoundD,
Richard Smith715f7a12019-06-11 17:50:32 +0000534 const TemplateArgumentListInfo *TemplateArgs,
535 NonOdrUseReason NOUR) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000536 // Filter out cases where the found Decl is the same as the value refenenced.
537 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000538 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000539
James Y Knighte7d82282015-12-29 18:15:14 +0000540 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
541 std::size_t Size =
542 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
543 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
544 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
545 HasTemplateKWAndArgsInfo ? 1 : 0,
546 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000547
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000548 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000549 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Richard Smith715f7a12019-06-11 17:50:32 +0000550 RefersToEnclosingVariableOrCapture, NameInfo,
551 FoundD, TemplateArgs, T, VK, NOUR);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000552}
553
Craig Topperce7167c2013-08-22 04:58:56 +0000554DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000555 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000556 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000557 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000558 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000559 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
560 std::size_t Size =
561 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
562 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
563 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
564 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000565 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000566 return new (Mem) DeclRefExpr(EmptyShell());
567}
568
Stephen Kelly724e9e52018-08-09 20:05:03 +0000569SourceLocation DeclRefExpr::getBeginLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000570 if (hasQualifier())
571 return getQualifierLoc().getBeginLoc();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000572 return getNameInfo().getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000573}
Stephen Kelly02a67ba2018-08-09 20:05:47 +0000574SourceLocation DeclRefExpr::getEndLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000575 if (hasExplicitTemplateArgs())
576 return getRAngleLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000577 return getNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000578}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000579
Bruno Ricci17ff0262018-10-27 19:21:19 +0000580PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
Alexey Bataevec474782014-10-09 08:45:04 +0000581 StringLiteral *SL)
582 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
583 FNTy->isDependentType(), FNTy->isDependentType(),
584 FNTy->isInstantiationDependentType(),
Bruno Ricci17ff0262018-10-27 19:21:19 +0000585 /*ContainsUnexpandedParameterPack=*/false) {
586 PredefinedExprBits.Kind = IK;
587 assert((getIdentKind() == IK) &&
588 "IdentKind do not fit in PredefinedExprBitfields!");
589 bool HasFunctionName = SL != nullptr;
590 PredefinedExprBits.HasFunctionName = HasFunctionName;
591 PredefinedExprBits.Loc = L;
592 if (HasFunctionName)
593 setFunctionName(SL);
Alexey Bataevec474782014-10-09 08:45:04 +0000594}
595
Bruno Ricci17ff0262018-10-27 19:21:19 +0000596PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
597 : Expr(PredefinedExprClass, Empty) {
598 PredefinedExprBits.HasFunctionName = HasFunctionName;
599}
600
601PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
602 QualType FNTy, IdentKind IK,
603 StringLiteral *SL) {
604 bool HasFunctionName = SL != nullptr;
605 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
606 alignof(PredefinedExpr));
607 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
608}
609
610PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
611 bool HasFunctionName) {
612 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
613 alignof(PredefinedExpr));
614 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
615}
616
617StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
618 switch (IK) {
Alexey Bataevec474782014-10-09 08:45:04 +0000619 case Func:
620 return "__func__";
621 case Function:
622 return "__FUNCTION__";
623 case FuncDName:
624 return "__FUNCDNAME__";
625 case LFunction:
626 return "L__FUNCTION__";
627 case PrettyFunction:
628 return "__PRETTY_FUNCTION__";
629 case FuncSig:
630 return "__FUNCSIG__";
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000631 case LFuncSig:
632 return "L__FUNCSIG__";
Alexey Bataevec474782014-10-09 08:45:04 +0000633 case PrettyFunctionNoVirtual:
634 break;
635 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000636 llvm_unreachable("Unknown ident kind for PredefinedExpr");
Alexey Bataevec474782014-10-09 08:45:04 +0000637}
638
Anders Carlsson2fb08242009-09-08 18:24:21 +0000639// FIXME: Maybe this should use DeclPrinter with a special "print predefined
640// expr" policy instead.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000641std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000642 ASTContext &Context = CurrentDecl->getASTContext();
643
Bruno Ricci17ff0262018-10-27 19:21:19 +0000644 if (IK == PredefinedExpr::FuncDName) {
David Majnemerbed356a2013-11-06 23:31:56 +0000645 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000646 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000647 MC.reset(Context.createMangleContext());
648
649 if (MC->shouldMangleDeclName(ND)) {
650 SmallString<256> Buffer;
651 llvm::raw_svector_ostream Out(Buffer);
652 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
653 MC->mangleCXXCtor(CD, Ctor_Base, Out);
654 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
655 MC->mangleCXXDtor(DD, Dtor_Base, Out);
656 else
657 MC->mangleName(ND, Out);
658
David Majnemerbed356a2013-11-06 23:31:56 +0000659 if (!Buffer.empty() && Buffer.front() == '\01')
660 return Buffer.substr(1);
661 return Buffer.str();
662 } else
663 return ND->getIdentifier()->getName();
664 }
665 return "";
666 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000667 if (isa<BlockDecl>(CurrentDecl)) {
668 // For blocks we only emit something if it is enclosed in a function
669 // For top-level block we'd like to include the name of variable, but we
670 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000671 auto DC = CurrentDecl->getDeclContext();
672 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000673 return "";
674
675 SmallString<256> Buffer;
676 llvm::raw_svector_ostream Out(Buffer);
677 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
678 // For nested blocks, propagate up to the parent.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000679 Out << ComputeName(IK, DCBlock);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000680 else if (auto *DCDecl = dyn_cast<Decl>(DC))
Bruno Ricci17ff0262018-10-27 19:21:19 +0000681 Out << ComputeName(IK, DCDecl) << "_block_invoke";
Alexey Bataevec474782014-10-09 08:45:04 +0000682 return Out.str();
683 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000684 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000685 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
686 IK != FuncSig && IK != LFuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000687 return FD->getNameAsString();
688
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000689 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000690 llvm::raw_svector_ostream Out(Name);
691
692 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000693 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000694 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000695 if (MD->isStatic())
696 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000697 }
698
David Blaikiebbafb8a2012-03-11 07:00:24 +0000699 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000700 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000701 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000702
Douglas Gregor11a434a2012-04-10 20:14:15 +0000703 const FunctionDecl *Decl = FD;
704 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
705 Decl = Pattern;
706 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000707 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000708 if (FD->hasWrittenPrototype())
709 FT = dyn_cast<FunctionProtoType>(AFT);
710
Bruno Ricci17ff0262018-10-27 19:21:19 +0000711 if (IK == FuncSig || IK == LFuncSig) {
Richard Smith2f63d462017-01-09 21:40:40 +0000712 switch (AFT->getCallConv()) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000713 case CC_C: POut << "__cdecl "; break;
714 case CC_X86StdCall: POut << "__stdcall "; break;
715 case CC_X86FastCall: POut << "__fastcall "; break;
716 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000717 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000718 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000719 // Only bother printing the conventions that MSVC knows about.
720 default: break;
721 }
722 }
723
724 FD->printQualifiedName(POut, Policy);
725
Douglas Gregor11a434a2012-04-10 20:14:15 +0000726 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000727 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000728 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000729 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000730 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000731 }
732
733 if (FT->isVariadic()) {
734 if (FD->getNumParams()) POut << ", ";
735 POut << "...";
Bruno Ricci17ff0262018-10-27 19:21:19 +0000736 } else if ((IK == FuncSig || IK == LFuncSig ||
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000737 !Context.getLangOpts().CPlusPlus) &&
Richard Smithcf63b842017-01-09 22:16:16 +0000738 !Decl->getNumParams()) {
739 POut << "void";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000740 }
741 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000742 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000743
Sam Weinig4e83bd22009-12-27 01:38:20 +0000744 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Richard Smith2f63d462017-01-09 21:40:40 +0000745 assert(FT && "We must have a written prototype in this case.");
David Blaikief5697e52012-08-10 00:55:35 +0000746 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000747 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000748 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000749 POut << " volatile";
750 RefQualifierKind Ref = MD->getRefQualifier();
751 if (Ref == RQ_LValue)
752 POut << " &";
753 else if (Ref == RQ_RValue)
754 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000755 }
756
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000757 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000758 SpecsTy Specs;
759 const DeclContext *Ctx = FD->getDeclContext();
760 while (Ctx && isa<NamedDecl>(Ctx)) {
761 const ClassTemplateSpecializationDecl *Spec
762 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
763 if (Spec && !Spec->isExplicitSpecialization())
764 Specs.push_back(Spec);
765 Ctx = Ctx->getParent();
766 }
767
768 std::string TemplateParams;
769 llvm::raw_string_ostream TOut(TemplateParams);
770 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
771 I != E; ++I) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000772 const TemplateParameterList *Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000773 = (*I)->getSpecializedTemplate()->getTemplateParameters();
774 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
775 assert(Params->size() == Args.size());
776 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
777 StringRef Param = Params->getParam(i)->getName();
778 if (Param.empty()) continue;
779 TOut << Param << " = ";
780 Args.get(i).print(Policy, TOut);
781 TOut << ", ";
782 }
783 }
784
Fangrui Song6907ce22018-07-30 19:24:48 +0000785 FunctionTemplateSpecializationInfo *FSI
Douglas Gregor11a434a2012-04-10 20:14:15 +0000786 = FD->getTemplateSpecializationInfo();
787 if (FSI && !FSI->isExplicitSpecialization()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000788 const TemplateParameterList* Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000789 = FSI->getTemplate()->getTemplateParameters();
790 const TemplateArgumentList* Args = FSI->TemplateArguments;
791 assert(Params->size() == Args->size());
792 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
793 StringRef Param = Params->getParam(i)->getName();
794 if (Param.empty()) continue;
795 TOut << Param << " = ";
796 Args->get(i).print(Policy, TOut);
797 TOut << ", ";
798 }
799 }
800
801 TOut.flush();
802 if (!TemplateParams.empty()) {
803 // remove the trailing comma and space
804 TemplateParams.resize(TemplateParams.size() - 2);
805 POut << " [" << TemplateParams << "]";
806 }
807
808 POut.flush();
809
Benjamin Kramer90f54222013-08-21 11:45:27 +0000810 // Print "auto" for all deduced return types. This includes C++1y return
811 // type deduction and lambdas. For trailing return types resolve the
812 // decltype expression. Otherwise print the real type when this is
813 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000814 if (isa<CXXMethodDecl>(FD) &&
815 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000816 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000817 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
818 FT->getReturnType()
819 ->getAs<DecltypeType>()
820 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000821 .getAsStringInternal(Proto, Policy);
822 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000823 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000824
825 Out << Proto;
826
Anders Carlsson2fb08242009-09-08 18:24:21 +0000827 return Name.str().str();
828 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000829 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
830 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
831 // Skip to its enclosing function or method, but not its enclosing
832 // CapturedDecl.
833 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
834 const Decl *D = Decl::castFromDeclContext(DC);
Bruno Ricci17ff0262018-10-27 19:21:19 +0000835 return ComputeName(IK, D);
Wei Pan8d6b19a2013-08-26 14:27:34 +0000836 }
837 llvm_unreachable("CapturedDecl not inside a function or method");
838 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000839 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000840 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000841 llvm::raw_svector_ostream Out(Name);
842 Out << (MD->isInstanceMethod() ? '-' : '+');
843 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000844
845 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
846 // a null check to avoid a crash.
847 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000848 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000849
Anders Carlsson2fb08242009-09-08 18:24:21 +0000850 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000851 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000852 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000853
Anders Carlsson2fb08242009-09-08 18:24:21 +0000854 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000855 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000856 Out << ']';
857
Anders Carlsson2fb08242009-09-08 18:24:21 +0000858 return Name.str().str();
859 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000860 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000861 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
862 return "top level";
863 }
864 return "";
865}
866
Craig Topper37932912013-08-18 10:09:15 +0000867void APNumericStorage::setIntValue(const ASTContext &C,
868 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000869 if (hasAllocation())
870 C.Deallocate(pVal);
871
872 BitWidth = Val.getBitWidth();
873 unsigned NumWords = Val.getNumWords();
874 const uint64_t* Words = Val.getRawData();
875 if (NumWords > 1) {
876 pVal = new (C) uint64_t[NumWords];
877 std::copy(Words, Words + NumWords, pVal);
878 } else if (NumWords == 1)
879 VAL = Words[0];
880 else
881 VAL = 0;
882}
883
Craig Topper37932912013-08-18 10:09:15 +0000884IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000885 QualType type, SourceLocation l)
886 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
887 false, false),
888 Loc(l) {
889 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
890 assert(V.getBitWidth() == C.getIntWidth(type) &&
891 "Integer type is not the correct size for constant.");
892 setValue(C, V);
893}
894
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000895IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000896IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000897 QualType type, SourceLocation l) {
898 return new (C) IntegerLiteral(C, V, type, l);
899}
900
901IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000902IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000903 return new (C) IntegerLiteral(Empty);
904}
905
Leonard Chandb01c3a2018-06-20 17:19:40 +0000906FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
907 QualType type, SourceLocation l,
908 unsigned Scale)
909 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
910 false, false),
911 Loc(l), Scale(Scale) {
912 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
913 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
914 "Fixed point type is not the correct size for constant.");
915 setValue(C, V);
916}
917
918FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
919 const llvm::APInt &V,
920 QualType type,
921 SourceLocation l,
922 unsigned Scale) {
923 return new (C) FixedPointLiteral(C, V, type, l, Scale);
924}
925
926std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
927 // Currently the longest decimal number that can be printed is the max for an
928 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
929 // which is 43 characters.
930 SmallString<64> S;
931 FixedPointValueToString(
Leonard Chanc03642e2018-08-06 16:05:08 +0000932 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
Leonard Chandb01c3a2018-06-20 17:19:40 +0000933 return S.str();
934}
935
Craig Topper37932912013-08-18 10:09:15 +0000936FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000937 bool isexact, QualType Type, SourceLocation L)
938 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
939 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000940 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000941 FloatingLiteralBits.IsExact = isexact;
942 setValue(C, V);
943}
944
Craig Topper37932912013-08-18 10:09:15 +0000945FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000946 : Expr(FloatingLiteralClass, Empty) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000947 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000948 FloatingLiteralBits.IsExact = false;
949}
950
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000951FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000952FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000953 bool isexact, QualType Type, SourceLocation L) {
954 return new (C) FloatingLiteral(C, V, isexact, Type, L);
955}
956
957FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000958FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000959 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000960}
961
Chris Lattnera0173132008-06-07 22:13:43 +0000962/// getValueAsApproximateDouble - This returns the value as an inaccurate
963/// double. Note that this may cause loss of precision, but is useful for
964/// debugging dumps, etc.
965double FloatingLiteral::getValueAsApproximateDouble() const {
966 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000967 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000968 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
Dale Johannesenc48814b2008-10-09 23:02:32 +0000969 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000970 return V.convertToDouble();
971}
972
Bruno Ricciaf214882018-11-15 16:42:14 +0000973unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
974 StringKind SK) {
975 unsigned CharByteWidth = 0;
976 switch (SK) {
977 case Ascii:
978 case UTF8:
979 CharByteWidth = Target.getCharWidth();
980 break;
981 case Wide:
982 CharByteWidth = Target.getWCharWidth();
983 break;
984 case UTF16:
985 CharByteWidth = Target.getChar16Width();
986 break;
987 case UTF32:
988 CharByteWidth = Target.getChar32Width();
989 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000990 }
991 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
992 CharByteWidth /= 8;
Bruno Ricciaf214882018-11-15 16:42:14 +0000993 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
994 "The only supported character byte widths are 1,2 and 4!");
Eli Friedmanfcec6302011-11-01 02:23:42 +0000995 return CharByteWidth;
996}
997
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000998StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
999 StringKind Kind, bool Pascal, QualType Ty,
1000 const SourceLocation *Loc,
1001 unsigned NumConcatenated)
1002 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1003 false) {
1004 assert(Ctx.getAsConstantArrayType(Ty) &&
Benjamin Kramercdac7612014-02-25 12:26:20 +00001005 "StringLiteral must be of constant array type!");
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001006 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1007 unsigned ByteLength = Str.size();
1008 assert((ByteLength % CharByteWidth == 0) &&
1009 "The size of the data must be a multiple of CharByteWidth!");
Benjamin Kramercdac7612014-02-25 12:26:20 +00001010
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001011 // Avoid the expensive division. The compiler should be able to figure it
1012 // out by itself. However as of clang 7, even with the appropriate
1013 // llvm_unreachable added just here, it is not able to do so.
1014 unsigned Length;
1015 switch (CharByteWidth) {
1016 case 1:
1017 Length = ByteLength;
1018 break;
1019 case 2:
1020 Length = ByteLength / 2;
1021 break;
1022 case 4:
1023 Length = ByteLength / 4;
1024 break;
1025 default:
1026 llvm_unreachable("Unsupported character width!");
1027 }
Mike Stump11289f42009-09-09 15:08:12 +00001028
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001029 StringLiteralBits.Kind = Kind;
1030 StringLiteralBits.CharByteWidth = CharByteWidth;
1031 StringLiteralBits.IsPascal = Pascal;
1032 StringLiteralBits.NumConcatenated = NumConcatenated;
1033 *getTrailingObjects<unsigned>() = Length;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001034
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001035 // Initialize the trailing array of SourceLocation.
1036 // This is safe since SourceLocation is POD-like.
1037 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1038 NumConcatenated * sizeof(SourceLocation));
Chris Lattnerd3e98952006-10-06 05:22:26 +00001039
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001040 // Initialize the trailing array of char holding the string data.
1041 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
Chris Lattner630970d2009-02-18 05:49:11 +00001042}
1043
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001044StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1045 unsigned Length, unsigned CharByteWidth)
1046 : Expr(StringLiteralClass, Empty) {
1047 StringLiteralBits.CharByteWidth = CharByteWidth;
1048 StringLiteralBits.NumConcatenated = NumConcatenated;
1049 *getTrailingObjects<unsigned>() = Length;
1050}
1051
1052StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1053 StringKind Kind, bool Pascal, QualType Ty,
1054 const SourceLocation *Loc,
1055 unsigned NumConcatenated) {
1056 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1057 1, NumConcatenated, Str.size()),
1058 alignof(StringLiteral));
1059 return new (Mem)
1060 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1061}
1062
1063StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1064 unsigned NumConcatenated,
1065 unsigned Length,
1066 unsigned CharByteWidth) {
1067 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1068 1, NumConcatenated, Length * CharByteWidth),
1069 alignof(StringLiteral));
1070 return new (Mem)
1071 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
Douglas Gregor958dfc92009-04-15 16:35:07 +00001072}
1073
Alexander Kornienko540bacb2013-02-01 12:35:51 +00001074void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +00001075 switch (getKind()) {
1076 case Ascii: break; // no prefix.
1077 case Wide: OS << 'L'; break;
1078 case UTF8: OS << "u8"; break;
1079 case UTF16: OS << 'u'; break;
1080 case UTF32: OS << 'U'; break;
1081 }
1082 OS << '"';
1083 static const char Hex[] = "0123456789ABCDEF";
1084
1085 unsigned LastSlashX = getLength();
1086 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1087 switch (uint32_t Char = getCodeUnit(I)) {
1088 default:
1089 // FIXME: Convert UTF-8 back to codepoints before rendering.
1090
1091 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1092 // Leave invalid surrogates alone; we'll use \x for those.
Fangrui Song6907ce22018-07-30 19:24:48 +00001093 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
Richard Trieudc355912012-06-13 20:25:24 +00001094 Char <= 0xdbff) {
1095 uint32_t Trail = getCodeUnit(I + 1);
1096 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1097 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1098 ++I;
1099 }
1100 }
1101
1102 if (Char > 0xff) {
1103 // If this is a wide string, output characters over 0xff using \x
1104 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1105 // codepoint: use \x escapes for invalid codepoints.
1106 if (getKind() == Wide ||
1107 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1108 // FIXME: Is this the best way to print wchar_t?
1109 OS << "\\x";
1110 int Shift = 28;
1111 while ((Char >> Shift) == 0)
1112 Shift -= 4;
1113 for (/**/; Shift >= 0; Shift -= 4)
1114 OS << Hex[(Char >> Shift) & 15];
1115 LastSlashX = I;
1116 break;
1117 }
1118
1119 if (Char > 0xffff)
1120 OS << "\\U00"
1121 << Hex[(Char >> 20) & 15]
1122 << Hex[(Char >> 16) & 15];
1123 else
1124 OS << "\\u";
1125 OS << Hex[(Char >> 12) & 15]
1126 << Hex[(Char >> 8) & 15]
1127 << Hex[(Char >> 4) & 15]
1128 << Hex[(Char >> 0) & 15];
1129 break;
1130 }
1131
1132 // If we used \x... for the previous character, and this character is a
1133 // hexadecimal digit, prevent it being slurped as part of the \x.
1134 if (LastSlashX + 1 == I) {
1135 switch (Char) {
1136 case '0': case '1': case '2': case '3': case '4':
1137 case '5': case '6': case '7': case '8': case '9':
1138 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1139 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1140 OS << "\"\"";
1141 }
1142 }
1143
1144 assert(Char <= 0xff &&
1145 "Characters above 0xff should already have been handled.");
1146
Jordan Rosea7d03842013-02-08 22:30:41 +00001147 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +00001148 OS << (char)Char;
1149 else // Output anything hard as an octal escape.
1150 OS << '\\'
1151 << (char)('0' + ((Char >> 6) & 7))
1152 << (char)('0' + ((Char >> 3) & 7))
1153 << (char)('0' + ((Char >> 0) & 7));
1154 break;
1155 // Handle some common non-printable cases to make dumps prettier.
1156 case '\\': OS << "\\\\"; break;
1157 case '"': OS << "\\\""; break;
Richard Trieudc355912012-06-13 20:25:24 +00001158 case '\a': OS << "\\a"; break;
1159 case '\b': OS << "\\b"; break;
Benjamin Kramer60a53d52016-11-24 09:41:33 +00001160 case '\f': OS << "\\f"; break;
1161 case '\n': OS << "\\n"; break;
1162 case '\r': OS << "\\r"; break;
1163 case '\t': OS << "\\t"; break;
1164 case '\v': OS << "\\v"; break;
Richard Trieudc355912012-06-13 20:25:24 +00001165 }
1166 }
1167 OS << '"';
1168}
1169
Chris Lattnere925d612010-11-17 07:37:15 +00001170/// getLocationOfByte - Return a source location that points to the specified
1171/// byte of this string literal.
1172///
1173/// Strings are amazingly complex. They can be formed from multiple tokens and
1174/// can have escape sequences in them in addition to the usual trigraph and
1175/// escaped newline business. This routine handles this complexity.
1176///
Richard Smithefb116f2015-12-10 01:11:47 +00001177/// The *StartToken sets the first token to be searched in this function and
1178/// the *StartTokenByteOffset is the byte offset of the first token. Before
1179/// returning, it updates the *StartToken to the TokNo of the token being found
1180/// and sets *StartTokenByteOffset to the byte offset of the token in the
1181/// string.
1182/// Using these two parameters can reduce the time complexity from O(n^2) to
1183/// O(n) if one wants to get the location of byte for all the tokens in a
1184/// string.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001185///
Richard Smithefb116f2015-12-10 01:11:47 +00001186SourceLocation
1187StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1188 const LangOptions &Features,
1189 const TargetInfo &Target, unsigned *StartToken,
1190 unsigned *StartTokenByteOffset) const {
Bruno Ricciaf214882018-11-15 16:42:14 +00001191 assert((getKind() == StringLiteral::Ascii ||
1192 getKind() == StringLiteral::UTF8) &&
Richard Smith4060f772012-06-13 05:37:23 +00001193 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001194
Chris Lattnere925d612010-11-17 07:37:15 +00001195 // Loop over all of the tokens in this string until we find the one that
1196 // contains the byte we're looking for.
1197 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001198 unsigned StringOffset = 0;
1199 if (StartToken)
1200 TokNo = *StartToken;
1201 if (StartTokenByteOffset) {
1202 StringOffset = *StartTokenByteOffset;
1203 ByteNo -= StringOffset;
1204 }
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001205 while (1) {
Chris Lattnere925d612010-11-17 07:37:15 +00001206 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1207 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
Fangrui Song6907ce22018-07-30 19:24:48 +00001208
Chris Lattnere925d612010-11-17 07:37:15 +00001209 // Get the spelling of the string so that we can get the data that makes up
1210 // the string literal, not the identifier for the macro it is potentially
1211 // expanded through.
1212 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001213
Chris Lattnere925d612010-11-17 07:37:15 +00001214 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001215 std::pair<FileID, unsigned> LocInfo =
1216 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001217 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001218 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001219 if (Invalid) {
1220 if (StartTokenByteOffset != nullptr)
1221 *StartTokenByteOffset = StringOffset;
1222 if (StartToken != nullptr)
1223 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001224 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001225 }
1226
Chris Lattnere925d612010-11-17 07:37:15 +00001227 const char *StrData = Buffer.data()+LocInfo.second;
Fangrui Song6907ce22018-07-30 19:24:48 +00001228
Chris Lattnere925d612010-11-17 07:37:15 +00001229 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001230 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1231 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001232 Token TheTok;
1233 TheLexer.LexFromRawLexer(TheTok);
Fangrui Song6907ce22018-07-30 19:24:48 +00001234
Chris Lattnere925d612010-11-17 07:37:15 +00001235 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001236 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001237 unsigned TokNumBytes = SLP.GetStringLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00001238
Chris Lattnere925d612010-11-17 07:37:15 +00001239 // If the byte is in this token, return the location of the byte.
1240 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001241 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001242 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1243
Chris Lattnere925d612010-11-17 07:37:15 +00001244 // Now that we know the offset of the token in the spelling, use the
1245 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001246 if (StartTokenByteOffset != nullptr)
1247 *StartTokenByteOffset = StringOffset;
1248 if (StartToken != nullptr)
1249 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001250 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1251 }
Richard Smithefb116f2015-12-10 01:11:47 +00001252
Chris Lattnere925d612010-11-17 07:37:15 +00001253 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001254 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001255 ++TokNo;
1256 ByteNo -= TokNumBytes;
1257 }
1258}
1259
Chris Lattner1b926492006-08-23 06:42:10 +00001260/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1261/// corresponds to, e.g. "sizeof" or "[pre]++".
Bruno Ricci3dfcb842018-11-13 21:33:22 +00001262StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1263 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001264#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1265#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001266 }
David Blaikief47fa302012-01-17 02:30:50 +00001267 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001268}
1269
John McCalle3027922010-08-25 11:45:40 +00001270UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001271UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1272 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001273 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001274 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1275 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1276 case OO_Amp: return UO_AddrOf;
1277 case OO_Star: return UO_Deref;
1278 case OO_Plus: return UO_Plus;
1279 case OO_Minus: return UO_Minus;
1280 case OO_Tilde: return UO_Not;
1281 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001282 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001283 }
1284}
1285
1286OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1287 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001288 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1289 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1290 case UO_AddrOf: return OO_Amp;
1291 case UO_Deref: return OO_Star;
1292 case UO_Plus: return OO_Plus;
1293 case UO_Minus: return OO_Minus;
1294 case UO_Not: return OO_Tilde;
1295 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001296 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001297 default: return OO_None;
1298 }
1299}
1300
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001301
Chris Lattner0eedafe2006-08-24 04:56:27 +00001302//===----------------------------------------------------------------------===//
1303// Postfix Operators.
1304//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001305
Bruno Riccic5885cf2018-12-21 15:20:32 +00001306CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1307 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1308 SourceLocation RParenLoc, unsigned MinNumArgs,
1309 ADLCallKind UsesADL)
1310 : Expr(SC, Ty, VK, OK_Ordinary, Fn->isTypeDependent(),
1311 Fn->isValueDependent(), Fn->isInstantiationDependent(),
1312 Fn->containsUnexpandedParameterPack()),
1313 RParenLoc(RParenLoc) {
1314 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1315 unsigned NumPreArgs = PreArgs.size();
1316 CallExprBits.NumPreArgs = NumPreArgs;
1317 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1318
1319 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1320 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1321 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1322 "OffsetToTrailingObjects overflow!");
1323
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001324 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1325
Bruno Riccic5885cf2018-12-21 15:20:32 +00001326 setCallee(Fn);
1327 for (unsigned I = 0; I != NumPreArgs; ++I) {
1328 updateDependenciesFromArg(PreArgs[I]);
1329 setPreArg(I, PreArgs[I]);
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001330 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00001331 for (unsigned I = 0; I != Args.size(); ++I) {
1332 updateDependenciesFromArg(Args[I]);
1333 setArg(I, Args[I]);
Douglas Gregora6e053e2010-12-15 01:34:56 +00001334 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00001335 for (unsigned I = Args.size(); I != NumArgs; ++I) {
1336 setArg(I, nullptr);
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001337 }
Douglas Gregor993603d2008-11-14 16:09:21 +00001338}
Nate Begeman1e36a852008-01-17 17:46:27 +00001339
Bruno Riccic5885cf2018-12-21 15:20:32 +00001340CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1341 EmptyShell Empty)
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001342 : Expr(SC, Empty), NumArgs(NumArgs) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001343 CallExprBits.NumPreArgs = NumPreArgs;
Bruno Riccic5885cf2018-12-21 15:20:32 +00001344 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1345
1346 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1347 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1348 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1349 "OffsetToTrailingObjects overflow!");
Douglas Gregore20a2e52009-04-15 17:43:59 +00001350}
1351
Bruno Riccic5885cf2018-12-21 15:20:32 +00001352CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1353 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1354 SourceLocation RParenLoc, unsigned MinNumArgs,
1355 ADLCallKind UsesADL) {
1356 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1357 unsigned SizeOfTrailingObjects =
1358 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1359 void *Mem =
1360 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1361 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1362 RParenLoc, MinNumArgs, UsesADL);
1363}
1364
1365CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1366 ExprValueKind VK, SourceLocation RParenLoc,
1367 ADLCallKind UsesADL) {
1368 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1369 "Misaligned memory in CallExpr::CreateTemporary!");
1370 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1371 VK, RParenLoc, /*MinNumArgs=*/0, UsesADL);
1372}
1373
1374CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1375 EmptyShell Empty) {
1376 unsigned SizeOfTrailingObjects =
1377 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1378 void *Mem =
1379 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1380 return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1381}
1382
1383unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1384 switch (SC) {
1385 case CallExprClass:
1386 return sizeof(CallExpr);
1387 case CXXOperatorCallExprClass:
1388 return sizeof(CXXOperatorCallExpr);
1389 case CXXMemberCallExprClass:
1390 return sizeof(CXXMemberCallExpr);
1391 case UserDefinedLiteralClass:
1392 return sizeof(UserDefinedLiteral);
1393 case CUDAKernelCallExprClass:
1394 return sizeof(CUDAKernelCallExpr);
1395 default:
1396 llvm_unreachable("unexpected class deriving from CallExpr!");
1397 }
1398}
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001399
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001400void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1401 if (Arg->isTypeDependent())
1402 ExprBits.TypeDependent = true;
1403 if (Arg->isValueDependent())
1404 ExprBits.ValueDependent = true;
1405 if (Arg->isInstantiationDependent())
1406 ExprBits.InstantiationDependent = true;
1407 if (Arg->containsUnexpandedParameterPack())
1408 ExprBits.ContainsUnexpandedParameterPack = true;
1409}
1410
John McCallb92ab1a2016-10-26 23:46:34 +00001411Decl *Expr::getReferencedDeclOfCallee() {
1412 Expr *CEE = IgnoreParenImpCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00001413
Douglas Gregore0e96302011-09-06 21:41:04 +00001414 while (SubstNonTypeTemplateParmExpr *NTTP
1415 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1416 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1417 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001418
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001419 // If we're calling a dereference, look at the pointer instead.
1420 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1421 if (BO->isPtrMemOp())
1422 CEE = BO->getRHS()->IgnoreParenCasts();
1423 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1424 if (UO->getOpcode() == UO_Deref)
1425 CEE = UO->getSubExpr()->IgnoreParenCasts();
1426 }
Chris Lattner52301912009-07-17 15:46:27 +00001427 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001428 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001429 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1430 return ME->getMemberDecl();
Yaxun Liud83c7402019-02-26 16:20:41 +00001431 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1432 return BE->getBlockDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001433
Craig Topper36250ad2014-05-12 05:36:57 +00001434 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001435}
1436
Alp Tokera724cff2013-12-28 21:59:02 +00001437/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001438/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001439unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001440 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001441 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001442 // ImplicitCastExpr.
1443 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1444 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001445 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001446
Steve Narofff6e3b3292008-01-31 01:07:12 +00001447 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1448 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001449 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001450
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001451 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1452 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001453 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001454
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001455 if (!FDecl->getIdentifier())
1456 return 0;
1457
Douglas Gregor15fc9562009-09-12 00:22:50 +00001458 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001459}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001460
Scott Douglass503fc392015-06-10 13:53:15 +00001461bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001462 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001463 return Ctx.BuiltinInfo.isUnevaluated(BI);
1464 return false;
1465}
1466
David Majnemerced8bdf2015-02-25 17:36:15 +00001467QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1468 const Expr *Callee = getCallee();
1469 QualType CalleeType = Callee->getType();
1470 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001471 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001472 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001473 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001474 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1475 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1476 return Ctx.VoidTy;
1477
John McCall0009fcc2011-04-26 20:42:42 +00001478 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001479 CalleeType = Expr::findBoundMemberType(Callee);
1480 }
1481
John McCall0009fcc2011-04-26 20:42:42 +00001482 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001483 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001484}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001485
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00001486const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1487 // If the return type is a struct, union, or enum that is marked nodiscard,
1488 // then return the return type attribute.
1489 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1490 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1491 return A;
1492
1493 // Otherwise, see if the callee is marked nodiscard and return that attribute
1494 // instead.
1495 const Decl *D = getCalleeDecl();
1496 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1497}
1498
Stephen Kelly724e9e52018-08-09 20:05:03 +00001499SourceLocation CallExpr::getBeginLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001500 if (isa<CXXOperatorCallExpr>(this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001501 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001502
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001503 SourceLocation begin = getCallee()->getBeginLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001504 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001505 begin = getArg(0)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001506 return begin;
1507}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001508SourceLocation CallExpr::getEndLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001509 if (isa<CXXOperatorCallExpr>(this))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001510 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001511
1512 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001513 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001514 end = getArg(getNumArgs() - 1)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001515 return end;
1516}
John McCall701417a2011-02-21 06:23:05 +00001517
Craig Topper37932912013-08-18 10:09:15 +00001518OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001519 SourceLocation OperatorLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001520 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001521 ArrayRef<OffsetOfNode> comps,
1522 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001523 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001524 void *Mem = C.Allocate(
1525 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001526
Benjamin Kramerc215e762012-08-24 11:54:20 +00001527 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1528 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001529}
1530
Craig Topper37932912013-08-18 10:09:15 +00001531OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001532 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001533 void *Mem =
1534 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001535 return new (Mem) OffsetOfExpr(numComps, numExprs);
1536}
1537
Craig Topper37932912013-08-18 10:09:15 +00001538OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001539 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001540 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001541 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001542 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
Fangrui Song6907ce22018-07-30 19:24:48 +00001543 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001544 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001545 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001546 tsi->getType()->containsUnexpandedParameterPack()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001547 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001548 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001549{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001550 for (unsigned i = 0; i != comps.size(); ++i) {
1551 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001552 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001553
Benjamin Kramerc215e762012-08-24 11:54:20 +00001554 for (unsigned i = 0; i != exprs.size(); ++i) {
1555 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001556 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001557 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001558 ExprBits.ContainsUnexpandedParameterPack = true;
1559
Benjamin Kramerc215e762012-08-24 11:54:20 +00001560 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001561 }
1562}
1563
James Y Knight7281c352015-12-29 22:31:18 +00001564IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001565 assert(getKind() == Field || getKind() == Identifier);
1566 if (getKind() == Field)
1567 return getField()->getIdentifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00001568
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001569 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001570}
1571
David Majnemer10fd83d2015-01-15 10:04:14 +00001572UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1573 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1574 SourceLocation op, SourceLocation rp)
1575 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1576 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1577 // Value-dependent if the argument is type-dependent.
1578 E->isTypeDependent(), E->isInstantiationDependent(),
1579 E->containsUnexpandedParameterPack()),
1580 OpLoc(op), RParenLoc(rp) {
1581 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1582 UnaryExprOrTypeTraitExprBits.IsType = false;
1583 Argument.Ex = E;
1584
1585 // Check to see if we are in the situation where alignof(decl) should be
1586 // dependent because decl's alignment is dependent.
Richard Smith6822bd72018-10-26 19:26:45 +00001587 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
David Majnemer10fd83d2015-01-15 10:04:14 +00001588 if (!isValueDependent() || !isInstantiationDependent()) {
1589 E = E->IgnoreParens();
1590
1591 const ValueDecl *D = nullptr;
1592 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1593 D = DRE->getDecl();
1594 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1595 D = ME->getMemberDecl();
1596
1597 if (D) {
1598 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1599 if (I->isAlignmentDependent()) {
1600 setValueDependent(true);
1601 setInstantiationDependent(true);
1602 break;
1603 }
1604 }
1605 }
1606 }
1607 }
1608}
1609
Richard Smithdcf17de2019-06-06 23:24:15 +00001610MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1611 ValueDecl *MemberDecl,
1612 const DeclarationNameInfo &NameInfo, QualType T,
Richard Smith1bbad592019-06-11 17:50:36 +00001613 ExprValueKind VK, ExprObjectKind OK,
1614 NonOdrUseReason NOUR)
Richard Smithdcf17de2019-06-06 23:24:15 +00001615 : Expr(MemberExprClass, T, VK, OK, Base->isTypeDependent(),
1616 Base->isValueDependent(), Base->isInstantiationDependent(),
1617 Base->containsUnexpandedParameterPack()),
1618 Base(Base), MemberDecl(MemberDecl), MemberDNLoc(NameInfo.getInfo()),
1619 MemberLoc(NameInfo.getLoc()) {
1620 assert(!NameInfo.getName() ||
1621 MemberDecl->getDeclName() == NameInfo.getName());
1622 MemberExprBits.IsArrow = IsArrow;
1623 MemberExprBits.HasQualifierOrFoundDecl = false;
1624 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1625 MemberExprBits.HadMultipleCandidates = false;
Richard Smith1bbad592019-06-11 17:50:36 +00001626 MemberExprBits.NonOdrUseReason = NOUR;
Richard Smithdcf17de2019-06-06 23:24:15 +00001627 MemberExprBits.OperatorLoc = OperatorLoc;
1628}
1629
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001630MemberExpr *MemberExpr::Create(
Richard Smithdcf17de2019-06-06 23:24:15 +00001631 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001632 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
Richard Smithdcf17de2019-06-06 23:24:15 +00001633 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1634 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
Richard Smith1bbad592019-06-11 17:50:36 +00001635 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
Richard Smithdcf17de2019-06-06 23:24:15 +00001636 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1637 FoundDecl.getAccess() != MemberDecl->getAccess();
1638 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
James Y Knighte7d82282015-12-29 18:15:14 +00001639 std::size_t Size =
1640 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
Richard Smithdcf17de2019-06-06 23:24:15 +00001641 TemplateArgumentLoc>(
1642 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1643 TemplateArgs ? TemplateArgs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001644
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001645 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Richard Smith1bbad592019-06-11 17:50:36 +00001646 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1647 NameInfo, T, VK, OK, NOUR);
John McCall16df1e52010-03-30 21:47:33 +00001648
Richard Smithdcf17de2019-06-06 23:24:15 +00001649 if (HasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001650 // FIXME: Wrong. We should be looking at the member declaration we found.
1651 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001652 E->setValueDependent(true);
1653 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001654 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001655 }
1656 else if (QualifierLoc &&
1657 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001658 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001659
Bruno Ricci4c742532018-11-15 13:56:22 +00001660 E->MemberExprBits.HasQualifierOrFoundDecl = true;
John McCall16df1e52010-03-30 21:47:33 +00001661
James Y Knighte7d82282015-12-29 18:15:14 +00001662 MemberExprNameQualifier *NQ =
1663 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001664 NQ->QualifierLoc = QualifierLoc;
Richard Smithdcf17de2019-06-06 23:24:15 +00001665 NQ->FoundDecl = FoundDecl;
John McCall16df1e52010-03-30 21:47:33 +00001666 }
1667
Bruno Ricci4c742532018-11-15 13:56:22 +00001668 E->MemberExprBits.HasTemplateKWAndArgsInfo =
Richard Smithdcf17de2019-06-06 23:24:15 +00001669 TemplateArgs || TemplateKWLoc.isValid();
Abramo Bagnara7945c982012-01-27 09:46:47 +00001670
Richard Smithdcf17de2019-06-06 23:24:15 +00001671 if (TemplateArgs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001672 bool Dependent = false;
1673 bool InstantiationDependent = false;
1674 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001675 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
Richard Smithdcf17de2019-06-06 23:24:15 +00001676 TemplateKWLoc, *TemplateArgs,
1677 E->getTrailingObjects<TemplateArgumentLoc>(), Dependent,
1678 InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001679 if (InstantiationDependent)
1680 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001681 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001682 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1683 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001684 }
1685
1686 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001687}
1688
Richard Smithdcf17de2019-06-06 23:24:15 +00001689MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1690 bool HasQualifier, bool HasFoundDecl,
1691 bool HasTemplateKWAndArgsInfo,
1692 unsigned NumTemplateArgs) {
1693 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1694 "template args but no template arg info?");
1695 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1696 std::size_t Size =
1697 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1698 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1699 HasTemplateKWAndArgsInfo ? 1 : 0,
1700 NumTemplateArgs);
1701 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1702 return new (Mem) MemberExpr(EmptyShell());
1703}
1704
Stephen Kelly724e9e52018-08-09 20:05:03 +00001705SourceLocation MemberExpr::getBeginLoc() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001706 if (isImplicitAccess()) {
1707 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001708 return getQualifierLoc().getBeginLoc();
1709 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001710 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001711
Daniel Dunbarb507f272012-03-09 15:39:15 +00001712 // FIXME: We don't want this to happen. Rather, we should be able to
1713 // detect all kinds of implicit accesses more cleanly.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001714 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001715 if (BaseStartLoc.isValid())
1716 return BaseStartLoc;
1717 return MemberLoc;
1718}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001719SourceLocation MemberExpr::getEndLoc() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001720 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001721 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001722 EndLoc = getRAngleLoc();
1723 else if (EndLoc.isInvalid())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001724 EndLoc = getBase()->getEndLoc();
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001725 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001726}
1727
Alp Tokerc1086762013-12-07 13:51:35 +00001728bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001729 switch (getCastKind()) {
1730 case CK_DerivedToBase:
1731 case CK_UncheckedDerivedToBase:
1732 case CK_DerivedToBaseMemberPointer:
1733 case CK_BaseToDerived:
1734 case CK_BaseToDerivedMemberPointer:
1735 assert(!path_empty() && "Cast kind should have a base path!");
1736 break;
1737
1738 case CK_CPointerToObjCPointerCast:
1739 assert(getType()->isObjCObjectPointerType());
1740 assert(getSubExpr()->getType()->isPointerType());
1741 goto CheckNoBasePath;
1742
1743 case CK_BlockPointerToObjCPointerCast:
1744 assert(getType()->isObjCObjectPointerType());
1745 assert(getSubExpr()->getType()->isBlockPointerType());
1746 goto CheckNoBasePath;
1747
John McCallc62bb392012-02-15 01:22:51 +00001748 case CK_ReinterpretMemberPointer:
1749 assert(getType()->isMemberPointerType());
1750 assert(getSubExpr()->getType()->isMemberPointerType());
1751 goto CheckNoBasePath;
1752
John McCall9320b872011-09-09 05:25:32 +00001753 case CK_BitCast:
1754 // Arbitrary casts to C pointer types count as bitcasts.
1755 // Otherwise, we should only have block and ObjC pointer casts
1756 // here if they stay within the type kind.
1757 if (!getType()->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001758 assert(getType()->isObjCObjectPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001759 getSubExpr()->getType()->isObjCObjectPointerType());
Fangrui Song6907ce22018-07-30 19:24:48 +00001760 assert(getType()->isBlockPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001761 getSubExpr()->getType()->isBlockPointerType());
1762 }
1763 goto CheckNoBasePath;
1764
1765 case CK_AnyPointerToBlockPointerCast:
1766 assert(getType()->isBlockPointerType());
1767 assert(getSubExpr()->getType()->isAnyPointerType() &&
1768 !getSubExpr()->getType()->isBlockPointerType());
1769 goto CheckNoBasePath;
1770
Douglas Gregored90df32012-02-22 05:02:47 +00001771 case CK_CopyAndAutoreleaseBlockObject:
1772 assert(getType()->isBlockPointerType());
1773 assert(getSubExpr()->getType()->isBlockPointerType());
1774 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001775
1776 case CK_FunctionToPointerDecay:
1777 assert(getType()->isPointerType());
1778 assert(getSubExpr()->getType()->isFunctionType());
1779 goto CheckNoBasePath;
1780
Anastasia Stulova04307942018-11-16 16:22:56 +00001781 case CK_AddressSpaceConversion: {
1782 auto Ty = getType();
1783 auto SETy = getSubExpr()->getType();
1784 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
Anastasia Stulova094c7262019-04-04 10:48:36 +00001785 if (/*isRValue()*/ !Ty->getPointeeType().isNull()) {
Anastasia Stulova04307942018-11-16 16:22:56 +00001786 Ty = Ty->getPointeeType();
Anastasia Stulova04307942018-11-16 16:22:56 +00001787 SETy = SETy->getPointeeType();
Anastasia Stulovad1986d12019-01-14 11:44:22 +00001788 }
Anastasia Stulova04307942018-11-16 16:22:56 +00001789 assert(!Ty.isNull() && !SETy.isNull() &&
1790 Ty.getAddressSpace() != SETy.getAddressSpace());
1791 goto CheckNoBasePath;
1792 }
John McCall9320b872011-09-09 05:25:32 +00001793 // These should not have an inheritance path.
1794 case CK_Dynamic:
1795 case CK_ToUnion:
1796 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001797 case CK_NullToMemberPointer:
1798 case CK_NullToPointer:
1799 case CK_ConstructorConversion:
1800 case CK_IntegralToPointer:
1801 case CK_PointerToIntegral:
1802 case CK_ToVoid:
1803 case CK_VectorSplat:
1804 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001805 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001806 case CK_IntegralToFloating:
1807 case CK_FloatingToIntegral:
1808 case CK_FloatingCast:
1809 case CK_ObjCObjectLValueCast:
1810 case CK_FloatingRealToComplex:
1811 case CK_FloatingComplexToReal:
1812 case CK_FloatingComplexCast:
1813 case CK_FloatingComplexToIntegralComplex:
1814 case CK_IntegralRealToComplex:
1815 case CK_IntegralComplexToReal:
1816 case CK_IntegralComplexCast:
1817 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001818 case CK_ARCProduceObject:
1819 case CK_ARCConsumeObject:
1820 case CK_ARCReclaimReturnedObject:
1821 case CK_ARCExtendBlockObject:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001822 case CK_ZeroToOCLOpaqueType:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001823 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00001824 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +00001825 case CK_FixedPointToIntegral:
1826 case CK_IntegralToFixedPoint:
John McCall9320b872011-09-09 05:25:32 +00001827 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1828 goto CheckNoBasePath;
1829
1830 case CK_Dependent:
1831 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001832 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001833 case CK_AtomicToNonAtomic:
1834 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001835 case CK_PointerToBoolean:
1836 case CK_IntegralToBoolean:
1837 case CK_FloatingToBoolean:
1838 case CK_MemberPointerToBoolean:
1839 case CK_FloatingComplexToBoolean:
1840 case CK_IntegralComplexToBoolean:
1841 case CK_LValueBitCast: // -> bool&
1842 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001843 case CK_BuiltinFnToFnPtr:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001844 case CK_FixedPointToBoolean:
John McCall9320b872011-09-09 05:25:32 +00001845 CheckNoBasePath:
1846 assert(path_empty() && "Cast kind should not have a base path!");
1847 break;
1848 }
Alp Tokerc1086762013-12-07 13:51:35 +00001849 return true;
John McCall9320b872011-09-09 05:25:32 +00001850}
1851
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001852const char *CastExpr::getCastKindName(CastKind CK) {
1853 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001854#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1855#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001856 }
John McCallc5e62b42010-11-13 09:02:35 +00001857 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001858}
1859
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001860namespace {
Richard Smith1ef75542018-06-27 20:30:34 +00001861 const Expr *skipImplicitTemporary(const Expr *E) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001862 // Skip through reference binding to temporary.
Richard Smith1ef75542018-06-27 20:30:34 +00001863 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1864 E = Materialize->GetTemporaryExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001865
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001866 // Skip any temporary bindings; they're implicit.
Richard Smith1ef75542018-06-27 20:30:34 +00001867 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1868 E = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001869
Richard Smith1ef75542018-06-27 20:30:34 +00001870 return E;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001871 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001872}
1873
Douglas Gregord196a582009-12-14 19:27:10 +00001874Expr *CastExpr::getSubExprAsWritten() {
Richard Smith1ef75542018-06-27 20:30:34 +00001875 const Expr *SubExpr = nullptr;
1876 const CastExpr *E = this;
Douglas Gregord196a582009-12-14 19:27:10 +00001877 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001878 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001879
Douglas Gregord196a582009-12-14 19:27:10 +00001880 // Conversions by constructor and conversion functions have a
1881 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001882 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001883 SubExpr =
1884 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001885 else if (E->getCastKind() == CK_UserDefinedConversion) {
1886 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1887 isa<BlockExpr>(SubExpr)) &&
1888 "Unexpected SubExpr for CK_UserDefinedConversion.");
Richard Smith1ef75542018-06-27 20:30:34 +00001889 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1890 SubExpr = MCE->getImplicitObjectArgument();
Manman Ren8abc2e52016-02-02 22:23:03 +00001891 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001892
Douglas Gregord196a582009-12-14 19:27:10 +00001893 // If the subexpression we're left with is an implicit cast, look
1894 // through that, too.
Fangrui Song6907ce22018-07-30 19:24:48 +00001895 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1896
Richard Smith1ef75542018-06-27 20:30:34 +00001897 return const_cast<Expr*>(SubExpr);
1898}
1899
1900NamedDecl *CastExpr::getConversionFunction() const {
1901 const Expr *SubExpr = nullptr;
1902
1903 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1904 SubExpr = skipImplicitTemporary(E->getSubExpr());
1905
1906 if (E->getCastKind() == CK_ConstructorConversion)
1907 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1908
1909 if (E->getCastKind() == CK_UserDefinedConversion) {
1910 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1911 return MCE->getMethodDecl();
1912 }
1913 }
1914
1915 return nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001916}
1917
John McCallcf142162010-08-07 06:22:56 +00001918CXXBaseSpecifier **CastExpr::path_buffer() {
1919 switch (getStmtClass()) {
1920#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001921#define CASTEXPR(Type, Base) \
1922 case Stmt::Type##Class: \
1923 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001924#define STMT(Type, Base)
1925#include "clang/AST/StmtNodes.inc"
1926 default:
1927 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001928 }
1929}
1930
John McCallf1ef7962017-08-15 21:42:47 +00001931const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1932 QualType opType) {
1933 auto RD = unionType->castAs<RecordType>()->getDecl();
1934 return getTargetFieldForToUnionCast(RD, opType);
1935}
1936
1937const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1938 QualType OpType) {
1939 auto &Ctx = RD->getASTContext();
1940 RecordDecl::field_iterator Field, FieldEnd;
1941 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1942 Field != FieldEnd; ++Field) {
1943 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1944 !Field->isUnnamedBitfield()) {
1945 return *Field;
1946 }
1947 }
1948 return nullptr;
1949}
1950
Craig Topper37932912013-08-18 10:09:15 +00001951ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001952 CastKind Kind, Expr *Operand,
1953 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001954 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001955 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001956 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
Richard Smith27252a12019-06-14 17:46:38 +00001957 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
1958 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
1959 assert((Kind != CK_LValueToRValue ||
1960 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
1961 "invalid type for lvalue-to-rvalue conversion");
John McCallcf142162010-08-07 06:22:56 +00001962 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001963 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001964 if (PathSize)
1965 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1966 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001967 return E;
1968}
1969
Craig Topper37932912013-08-18 10:09:15 +00001970ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001971 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001972 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001973 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1974}
1975
1976
Craig Topper37932912013-08-18 10:09:15 +00001977CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001978 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001979 const CXXCastPath *BasePath,
1980 TypeSourceInfo *WrittenTy,
1981 SourceLocation L, SourceLocation R) {
1982 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001983 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001984 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001985 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001986 if (PathSize)
1987 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1988 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001989 return E;
1990}
1991
Craig Topper37932912013-08-18 10:09:15 +00001992CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1993 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001994 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001995 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1996}
1997
Chris Lattner1b926492006-08-23 06:42:10 +00001998/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1999/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00002000StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00002001 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00002002#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2003#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00002004 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002005 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00002006}
Steve Naroff47500512007-04-19 23:00:49 +00002007
John McCalle3027922010-08-25 11:45:40 +00002008BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002009BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2010 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00002011 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00002012 case OO_Plus: return BO_Add;
2013 case OO_Minus: return BO_Sub;
2014 case OO_Star: return BO_Mul;
2015 case OO_Slash: return BO_Div;
2016 case OO_Percent: return BO_Rem;
2017 case OO_Caret: return BO_Xor;
2018 case OO_Amp: return BO_And;
2019 case OO_Pipe: return BO_Or;
2020 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00002021 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00002022 case OO_Less: return BO_LT;
2023 case OO_Greater: return BO_GT;
2024 case OO_PlusEqual: return BO_AddAssign;
2025 case OO_MinusEqual: return BO_SubAssign;
2026 case OO_StarEqual: return BO_MulAssign;
2027 case OO_SlashEqual: return BO_DivAssign;
2028 case OO_PercentEqual: return BO_RemAssign;
2029 case OO_CaretEqual: return BO_XorAssign;
2030 case OO_AmpEqual: return BO_AndAssign;
2031 case OO_PipeEqual: return BO_OrAssign;
2032 case OO_LessLess: return BO_Shl;
2033 case OO_GreaterGreater: return BO_Shr;
2034 case OO_LessLessEqual: return BO_ShlAssign;
2035 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2036 case OO_EqualEqual: return BO_EQ;
2037 case OO_ExclaimEqual: return BO_NE;
2038 case OO_LessEqual: return BO_LE;
2039 case OO_GreaterEqual: return BO_GE;
2040 case OO_AmpAmp: return BO_LAnd;
2041 case OO_PipePipe: return BO_LOr;
2042 case OO_Comma: return BO_Comma;
2043 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002044 }
2045}
2046
2047OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2048 static const OverloadedOperatorKind OverOps[] = {
2049 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2050 OO_Star, OO_Slash, OO_Percent,
2051 OO_Plus, OO_Minus,
2052 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00002053 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002054 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2055 OO_EqualEqual, OO_ExclaimEqual,
2056 OO_Amp,
2057 OO_Caret,
2058 OO_Pipe,
2059 OO_AmpAmp,
2060 OO_PipePipe,
2061 OO_Equal, OO_StarEqual,
2062 OO_SlashEqual, OO_PercentEqual,
2063 OO_PlusEqual, OO_MinusEqual,
2064 OO_LessLessEqual, OO_GreaterGreaterEqual,
2065 OO_AmpEqual, OO_CaretEqual,
2066 OO_PipeEqual,
2067 OO_Comma
2068 };
2069 return OverOps[Opc];
2070}
2071
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002072bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2073 Opcode Opc,
2074 Expr *LHS, Expr *RHS) {
2075 if (Opc != BO_Add)
2076 return false;
2077
2078 // Check that we have one pointer and one integer operand.
2079 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002080 if (LHS->getType()->isPointerType()) {
2081 if (!RHS->getType()->isIntegerType())
2082 return false;
2083 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002084 } else if (RHS->getType()->isPointerType()) {
2085 if (!LHS->getType()->isIntegerType())
2086 return false;
2087 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002088 } else {
2089 return false;
2090 }
2091
2092 // Check that the pointer is a nullptr.
2093 if (!PExp->IgnoreParenCasts()
2094 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2095 return false;
2096
2097 // Check that the pointee type is char-sized.
2098 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2099 if (!PTy || !PTy->getPointeeType()->isCharType())
2100 return false;
2101
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002102 return true;
2103}
Eric Fiselier708afb52019-05-16 21:04:15 +00002104
2105static QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
2106 SourceLocExpr::IdentKind Kind) {
2107 switch (Kind) {
2108 case SourceLocExpr::File:
2109 case SourceLocExpr::Function: {
2110 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2111 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2112 }
2113 case SourceLocExpr::Line:
2114 case SourceLocExpr::Column:
2115 return Ctx.UnsignedIntTy;
2116 }
2117 llvm_unreachable("unhandled case");
2118}
2119
2120SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2121 SourceLocation BLoc, SourceLocation RParenLoc,
2122 DeclContext *ParentContext)
2123 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2124 VK_RValue, OK_Ordinary, false, false, false, false),
2125 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2126 SourceLocExprBits.Kind = Kind;
2127}
2128
2129StringRef SourceLocExpr::getBuiltinStr() const {
2130 switch (getIdentKind()) {
2131 case File:
2132 return "__builtin_FILE";
2133 case Function:
2134 return "__builtin_FUNCTION";
2135 case Line:
2136 return "__builtin_LINE";
2137 case Column:
2138 return "__builtin_COLUMN";
2139 }
2140 llvm_unreachable("unexpected IdentKind!");
2141}
2142
2143APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2144 const Expr *DefaultExpr) const {
2145 SourceLocation Loc;
2146 const DeclContext *Context;
2147
2148 std::tie(Loc,
2149 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2150 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2151 return {DIE->getUsedLocation(), DIE->getUsedContext()};
2152 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2153 return {DAE->getUsedLocation(), DAE->getUsedContext()};
2154 return {this->getLocation(), this->getParentContext()};
2155 }();
2156
2157 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2158 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2159
2160 auto MakeStringLiteral = [&](StringRef Tmp) {
2161 using LValuePathEntry = APValue::LValuePathEntry;
2162 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2163 // Decay the string to a pointer to the first character.
2164 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2165 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2166 };
2167
2168 switch (getIdentKind()) {
2169 case SourceLocExpr::File:
2170 return MakeStringLiteral(PLoc.getFilename());
2171 case SourceLocExpr::Function: {
2172 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2173 return MakeStringLiteral(
2174 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2175 : std::string(""));
2176 }
2177 case SourceLocExpr::Line:
2178 case SourceLocExpr::Column: {
2179 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2180 /*IsUnsigned=*/true);
2181 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2182 : PLoc.getColumn();
2183 return APValue(IntVal);
2184 }
2185 }
2186 llvm_unreachable("unhandled case");
2187}
2188
Craig Topper37932912013-08-18 10:09:15 +00002189InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002190 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002191 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
2192 false, false),
2193 InitExprs(C, initExprs.size()),
2194 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
2195{
Sebastian Redlc83ed822012-02-17 08:42:25 +00002196 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00002197 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002198 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00002199 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00002200 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00002201 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002202 if (initExprs[I]->isInstantiationDependent())
2203 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00002204 if (initExprs[I]->containsUnexpandedParameterPack())
2205 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00002206 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002207
Benjamin Kramerc215e762012-08-24 11:54:20 +00002208 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00002209}
Chris Lattner1ec5f562007-06-27 05:38:08 +00002210
Craig Topper37932912013-08-18 10:09:15 +00002211void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002212 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00002213 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002214}
2215
Craig Topper37932912013-08-18 10:09:15 +00002216void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00002217 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002218}
2219
Craig Topper37932912013-08-18 10:09:15 +00002220Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002221 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00002222 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00002223 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00002224 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002227 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00002228 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002229 return Result;
2230}
2231
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002232void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00002233 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002234 ArrayFillerOrUnionFieldInit = filler;
2235 // Fill out any "holes" in the array due to designated initializers.
2236 Expr **inits = getInits();
2237 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00002238 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002239 inits[i] = filler;
2240}
2241
Richard Smith9ec1e482012-04-15 02:50:59 +00002242bool InitListExpr::isStringLiteralInit() const {
2243 if (getNumInits() != 1)
2244 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00002245 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2246 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00002247 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00002248 // It is possible for getInit() to return null.
2249 const Expr *Init = getInit(0);
2250 if (!Init)
2251 return false;
2252 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00002253 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2254}
2255
Richard Smith122f88d2016-12-06 23:52:28 +00002256bool InitListExpr::isTransparent() const {
2257 assert(isSemanticForm() && "syntactic form never semantically transparent");
2258
2259 // A glvalue InitListExpr is always just sugar.
2260 if (isGLValue()) {
2261 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2262 return true;
2263 }
2264
2265 // Otherwise, we're sugar if and only if we have exactly one initializer that
2266 // is of the same type.
2267 if (getNumInits() != 1 || !getInit(0))
2268 return false;
2269
Richard Smith382bc512017-02-23 22:41:47 +00002270 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2271 // transparent struct copy.
2272 if (!getInit(0)->isRValue() && getType()->isRecordType())
2273 return false;
2274
Richard Smith122f88d2016-12-06 23:52:28 +00002275 return getType().getCanonicalType() ==
2276 getInit(0)->getType().getCanonicalType();
2277}
2278
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002279bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2280 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2281
2282 if (LangOpts.CPlusPlus || getNumInits() != 1) {
2283 return false;
2284 }
2285
2286 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
2287 return Lit && Lit->getValue() == 0;
2288}
2289
Stephen Kelly724e9e52018-08-09 20:05:03 +00002290SourceLocation InitListExpr::getBeginLoc() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00002291 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002292 return SyntacticForm->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002293 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002294 if (Beg.isInvalid()) {
2295 // Find the first non-null initializer.
2296 for (InitExprsTy::const_iterator I = InitExprs.begin(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002297 E = InitExprs.end();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002298 I != E; ++I) {
2299 if (Stmt *S = *I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002300 Beg = S->getBeginLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002301 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002302 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002303 }
2304 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002305 return Beg;
2306}
2307
Stephen Kelly02a67ba2018-08-09 20:05:47 +00002308SourceLocation InitListExpr::getEndLoc() const {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002309 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002310 return SyntacticForm->getEndLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002311 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002312 if (End.isInvalid()) {
2313 // Find the first non-null initializer from the end.
2314 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002315 E = InitExprs.rend();
2316 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002317 if (Stmt *S = *I) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002318 End = S->getEndLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002319 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002320 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002321 }
2322 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002323 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002324}
2325
Steve Naroff991e99d2008-09-04 15:31:07 +00002326/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002327///
John McCallc833dea2012-02-17 03:32:35 +00002328const FunctionProtoType *BlockExpr::getFunctionType() const {
2329 // The block pointer is never sugared, but the function type might be.
2330 return cast<BlockPointerType>(getType())
2331 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002332}
2333
Mike Stump11289f42009-09-09 15:08:12 +00002334SourceLocation BlockExpr::getCaretLocation() const {
2335 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002336}
Mike Stump11289f42009-09-09 15:08:12 +00002337const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002338 return TheBlock->getBody();
2339}
Mike Stump11289f42009-09-09 15:08:12 +00002340Stmt *BlockExpr::getBody() {
2341 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002342}
Steve Naroff415d3d52008-10-08 17:01:13 +00002343
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002344
Chris Lattner1ec5f562007-06-27 05:38:08 +00002345//===----------------------------------------------------------------------===//
2346// Generic Expression Routines
2347//===----------------------------------------------------------------------===//
2348
Chris Lattner237f2752009-02-14 07:37:35 +00002349/// isUnusedResultAWarning - Return true if this immediate expression should
2350/// be warned about if the result is unused. If so, fill in Loc and Ranges
2351/// with location to warn on and the source range[s] to report with the
2352/// warning.
Fangrui Song6907ce22018-07-30 19:24:48 +00002353bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
Eli Friedmanc11535c2012-05-24 00:47:05 +00002354 SourceRange &R1, SourceRange &R2,
2355 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002356 // Don't warn if the expr is type dependent. The type could end up
2357 // instantiating to void.
2358 if (isTypeDependent())
2359 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002360
Chris Lattner1ec5f562007-06-27 05:38:08 +00002361 switch (getStmtClass()) {
2362 default:
John McCallc493a732010-03-12 07:11:26 +00002363 if (getType()->isVoidType())
2364 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002365 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002366 Loc = getExprLoc();
2367 R1 = getSourceRange();
2368 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002369 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002370 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002371 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002372 case GenericSelectionExprClass:
2373 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002374 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002375 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002376 case CoyieldExprClass:
2377 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002378 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002379 case ChooseExprClass:
2380 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2381 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002382 case UnaryOperatorClass: {
2383 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002384
Chris Lattner1ec5f562007-06-27 05:38:08 +00002385 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002386 case UO_Plus:
2387 case UO_Minus:
2388 case UO_AddrOf:
2389 case UO_Not:
2390 case UO_LNot:
2391 case UO_Deref:
2392 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002393 case UO_Coawait:
2394 // This is just the 'operator co_await' call inside the guts of a
2395 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002396 case UO_PostInc:
2397 case UO_PostDec:
2398 case UO_PreInc:
2399 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002400 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002401 case UO_Real:
2402 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002403 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002404 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2405 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002406 return false;
2407 break;
John McCalle3027922010-08-25 11:45:40 +00002408 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002409 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002410 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002411 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002412 Loc = UO->getOperatorLoc();
2413 R1 = UO->getSubExpr()->getSourceRange();
2414 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002415 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002416 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002417 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002418 switch (BO->getOpcode()) {
2419 default:
2420 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002421 // Consider the RHS of comma for side effects. LHS was checked by
2422 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002423 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002424 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2425 // lvalue-ness) of an assignment written in a macro.
2426 if (IntegerLiteral *IE =
2427 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2428 if (IE->getValue() == 0)
2429 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002430 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002431 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002432 case BO_LAnd:
2433 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002434 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2435 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002436 return false;
2437 break;
John McCall1e3715a2010-02-16 04:10:53 +00002438 }
Chris Lattner237f2752009-02-14 07:37:35 +00002439 if (BO->isAssignmentOp())
2440 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002441 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002442 Loc = BO->getOperatorLoc();
2443 R1 = BO->getLHS()->getSourceRange();
2444 R2 = BO->getRHS()->getSourceRange();
2445 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002446 }
Chris Lattner86928112007-08-25 02:00:02 +00002447 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002448 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002449 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002450 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002451
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002452 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002453 // If only one of the LHS or RHS is a warning, the operator might
2454 // be being used for control flow. Only warn if both the LHS and
2455 // RHS are warnings.
Nathan Huckleberry321f9022019-06-19 18:37:01 +00002456 const auto *Exp = cast<ConditionalOperator>(this);
2457 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2458 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2459 }
2460 case BinaryConditionalOperatorClass: {
2461 const auto *Exp = cast<BinaryConditionalOperator>(this);
2462 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002463 }
2464
Chris Lattnera44d1162007-06-27 05:58:59 +00002465 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002466 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002467 Loc = cast<MemberExpr>(this)->getMemberLoc();
2468 R1 = SourceRange(Loc, Loc);
2469 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2470 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002471
Chris Lattner1ec5f562007-06-27 05:38:08 +00002472 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002473 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002474 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2475 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2476 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2477 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002478
Chandler Carruth46339472011-08-17 09:49:44 +00002479 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002480 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002481 // overloads as there is no reasonable way to define these such that they
2482 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002483 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002484 // provides additional value as well. If this list is updated,
2485 // DiagnoseUnusedComparison should be as well.
2486 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002487 switch (Op->getOperator()) {
2488 default:
2489 break;
2490 case OO_EqualEqual:
2491 case OO_ExclaimEqual:
2492 case OO_Less:
2493 case OO_Greater:
2494 case OO_GreaterEqual:
2495 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002496 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2497 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002498 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002499 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002500 Loc = Op->getOperatorLoc();
2501 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002502 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002503 }
Chandler Carruth46339472011-08-17 09:49:44 +00002504
2505 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002506 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002507 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002508 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002509 case CXXMemberCallExprClass:
2510 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002511 // If this is a direct call, get the callee.
2512 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002513 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner237f2752009-02-14 07:37:35 +00002514 // If the callee has attribute pure, const, or warn_unused_result, warn
2515 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002516 //
2517 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2518 // updated to match for QoI.
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00002519 if (CE->hasUnusedResultAttr(Ctx) ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002520 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002521 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002522 Loc = CE->getCallee()->getBeginLoc();
Chris Lattner1a6babf2009-10-13 04:53:48 +00002523 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002524
Chris Lattner1a6babf2009-10-13 04:53:48 +00002525 if (unsigned NumArgs = CE->getNumArgs())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002526 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002527 CE->getArg(NumArgs - 1)->getEndLoc());
Chris Lattner1a6babf2009-10-13 04:53:48 +00002528 return true;
2529 }
Chris Lattner237f2752009-02-14 07:37:35 +00002530 }
2531 return false;
2532 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002533
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002534 // If we don't know precisely what we're looking at, let's not warn.
2535 case UnresolvedLookupExprClass:
2536 case CXXUnresolvedConstructExprClass:
2537 return false;
2538
Anders Carlsson6aa50392009-11-17 17:11:23 +00002539 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002540 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002541 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2542 if (Type->hasAttr<WarnUnusedAttr>()) {
2543 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002544 Loc = getBeginLoc();
Lubos Lunak1f490f32013-07-21 13:15:58 +00002545 R1 = getSourceRange();
2546 return true;
2547 }
2548 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002549 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002550 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002551
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002552 case ObjCMessageExprClass: {
2553 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002554 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002555 ME->isInstanceMessage() &&
2556 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002557 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002558 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002559 Loc = getExprLoc();
2560 R1 = ME->getSourceRange();
2561 return true;
2562 }
2563
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002564 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002565 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002566 WarnE = this;
2567 Loc = getExprLoc();
2568 return true;
2569 }
2570
Chris Lattner237f2752009-02-14 07:37:35 +00002571 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002572 }
Mike Stump11289f42009-09-09 15:08:12 +00002573
John McCallb7bd14f2010-12-02 01:19:52 +00002574 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002575 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002576 Loc = getExprLoc();
2577 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002578 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002579
John McCallfe96e0b2011-11-06 09:01:30 +00002580 case PseudoObjectExprClass: {
2581 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2582
2583 // Only complain about things that have the form of a getter.
2584 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2585 isa<BinaryOperator>(PO->getSyntacticForm()))
2586 return false;
2587
Eli Friedmanc11535c2012-05-24 00:47:05 +00002588 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002589 Loc = getExprLoc();
2590 R1 = getSourceRange();
2591 return true;
2592 }
2593
Chris Lattner944d3062008-07-26 19:51:01 +00002594 case StmtExprClass: {
2595 // Statement exprs don't logically have side effects themselves, but are
2596 // sometimes used in macros in ways that give them a type that is unused.
2597 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2598 // however, if the result of the stmt expr is dead, we don't want to emit a
2599 // warning.
2600 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002601 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002602 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002603 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002604 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2605 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002606 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002607 }
Mike Stump11289f42009-09-09 15:08:12 +00002608
John McCallc493a732010-03-12 07:11:26 +00002609 if (getType()->isVoidType())
2610 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002611 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002612 Loc = cast<StmtExpr>(this)->getLParenLoc();
2613 R1 = getSourceRange();
2614 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002615 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002616 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002617 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002618 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002619 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002620 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002621 if (CE->getCastKind() == CK_ToVoid) {
2622 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002623 CE->getSubExpr()->getType().isVolatileQualified()) {
2624 const DeclRefExpr *DRE =
2625 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2626 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002627 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2628 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002629 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2630 R1, R2, Ctx);
2631 }
2632 }
Chris Lattner2706a552009-07-28 18:25:28 +00002633 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002634 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002635
Eli Friedmanc11535c2012-05-24 00:47:05 +00002636 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002637 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002638 if (CE->getCastKind() == CK_ConstructorConversion)
2639 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002640
Eli Friedmanc11535c2012-05-24 00:47:05 +00002641 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002642 if (const CXXFunctionalCastExpr *CXXCE =
2643 dyn_cast<CXXFunctionalCastExpr>(this)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002644 Loc = CXXCE->getBeginLoc();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002645 R1 = CXXCE->getSubExpr()->getSourceRange();
2646 } else {
2647 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2648 Loc = CStyleCE->getLParenLoc();
2649 R1 = CStyleCE->getSubExpr()->getSourceRange();
2650 }
Chris Lattner237f2752009-02-14 07:37:35 +00002651 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002652 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002653 case ImplicitCastExprClass: {
2654 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002655
Eli Friedmanc11535c2012-05-24 00:47:05 +00002656 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2657 if (ICE->getCastKind() == CK_LValueToRValue &&
2658 ICE->getSubExpr()->getType().isVolatileQualified())
2659 return false;
2660
2661 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2662 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002663 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002664 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002665 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002666 case CXXDefaultInitExprClass:
2667 return (cast<CXXDefaultInitExpr>(this)
2668 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002669
2670 case CXXNewExprClass:
2671 // FIXME: In theory, there might be new expressions that don't have side
2672 // effects (e.g. a placement new with an uninitialized POD).
2673 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002674 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002675 case MaterializeTemporaryExprClass:
2676 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2677 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002678 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002679 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2680 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002681 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002682 return cast<ExprWithCleanups>(this)->getSubExpr()
2683 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002684 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002685}
2686
Fariborz Jahanian07735332009-02-22 18:40:18 +00002687/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002688/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002689bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002690 const Expr *E = IgnoreParens();
2691 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002692 default:
2693 return false;
2694 case ObjCIvarRefExprClass:
2695 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002696 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002697 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002698 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002699 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002700 case MaterializeTemporaryExprClass:
2701 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2702 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002703 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002704 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002705 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002706 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002707
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002708 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2709 if (VD->hasGlobalStorage())
2710 return true;
2711 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002712 // dereferencing to a pointer is always a gc'able candidate,
2713 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002714 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002715 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002716 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002717 return false;
2718 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002719 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002720 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002721 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002722 }
2723 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002724 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002725 }
2726}
Sebastian Redlce354af2010-09-10 20:55:33 +00002727
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002728bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2729 if (isTypeDependent())
2730 return false;
John McCall086a4642010-11-24 05:12:34 +00002731 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002732}
2733
John McCall0009fcc2011-04-26 20:42:42 +00002734QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002735 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002736
2737 // Bound member expressions are always one of these possibilities:
2738 // x->m x.m x->*y x.*y
2739 // (possibly parenthesized)
2740
2741 expr = expr->IgnoreParens();
2742 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2743 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2744 return mem->getMemberDecl()->getType();
2745 }
2746
2747 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2748 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2749 ->getPointeeType();
2750 assert(type->isFunctionType());
2751 return type;
2752 }
2753
David Majnemerced8bdf2015-02-25 17:36:15 +00002754 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002755 return QualType();
2756}
2757
Bruno Ricci46148f22019-02-17 18:50:51 +00002758static Expr *IgnoreImpCastsSingleStep(Expr *E) {
2759 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2760 return ICE->getSubExpr();
2761
2762 if (auto *FE = dyn_cast<FullExpr>(E))
2763 return FE->getSubExpr();
2764
Bruno Riccid4038002019-02-17 13:47:29 +00002765 return E;
Ted Kremenek6f375e52014-04-16 07:26:09 +00002766}
2767
Bruno Ricci46148f22019-02-17 18:50:51 +00002768static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
2769 // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2770 // addition to what IgnoreImpCasts() skips to account for the current
2771 // behaviour of IgnoreParenImpCasts().
2772 Expr *SubE = IgnoreImpCastsSingleStep(E);
2773 if (SubE != E)
2774 return SubE;
2775
2776 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2777 return MTE->GetTemporaryExpr();
2778
2779 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2780 return NTTP->getReplacement();
2781
2782 return E;
2783}
2784
2785static Expr *IgnoreCastsSingleStep(Expr *E) {
2786 if (auto *CE = dyn_cast<CastExpr>(E))
2787 return CE->getSubExpr();
2788
2789 if (auto *FE = dyn_cast<FullExpr>(E))
2790 return FE->getSubExpr();
2791
2792 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2793 return MTE->GetTemporaryExpr();
2794
2795 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2796 return NTTP->getReplacement();
2797
2798 return E;
2799}
2800
2801static Expr *IgnoreLValueCastsSingleStep(Expr *E) {
2802 // Skip what IgnoreCastsSingleStep skips, except that only
2803 // lvalue-to-rvalue casts are skipped.
2804 if (auto *CE = dyn_cast<CastExpr>(E))
2805 if (CE->getCastKind() != CK_LValueToRValue)
2806 return E;
2807
2808 return IgnoreCastsSingleStep(E);
2809}
2810
2811static Expr *IgnoreBaseCastsSingleStep(Expr *E) {
2812 if (auto *CE = dyn_cast<CastExpr>(E))
2813 if (CE->getCastKind() == CK_DerivedToBase ||
2814 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2815 CE->getCastKind() == CK_NoOp)
2816 return CE->getSubExpr();
2817
2818 return E;
2819}
2820
2821static Expr *IgnoreImplicitSingleStep(Expr *E) {
2822 Expr *SubE = IgnoreImpCastsSingleStep(E);
2823 if (SubE != E)
2824 return SubE;
2825
2826 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2827 return MTE->GetTemporaryExpr();
2828
2829 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2830 return BTE->getSubExpr();
2831
2832 return E;
2833}
2834
2835static Expr *IgnoreParensSingleStep(Expr *E) {
2836 if (auto *PE = dyn_cast<ParenExpr>(E))
2837 return PE->getSubExpr();
2838
2839 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2840 if (UO->getOpcode() == UO_Extension)
2841 return UO->getSubExpr();
2842 }
2843
2844 else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2845 if (!GSE->isResultDependent())
2846 return GSE->getResultExpr();
2847 }
2848
2849 else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2850 if (!CE->isConditionDependent())
2851 return CE->getChosenSubExpr();
2852 }
2853
2854 else if (auto *CE = dyn_cast<ConstantExpr>(E))
2855 return CE->getSubExpr();
2856
2857 return E;
2858}
2859
2860static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
2861 if (auto *CE = dyn_cast<CastExpr>(E)) {
2862 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2863 // ptr<->int casts of the same width. We also ignore all identity casts.
2864 Expr *SubExpr = CE->getSubExpr();
2865 bool IsIdentityCast =
2866 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2867 bool IsSameWidthCast =
2868 (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2869 (SubExpr->getType()->isPointerType() ||
2870 SubExpr->getType()->isIntegralType(Ctx)) &&
2871 (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2872
2873 if (IsIdentityCast || IsSameWidthCast)
2874 return SubExpr;
2875 }
2876
2877 else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2878 return NTTP->getReplacement();
2879
2880 return E;
2881}
2882
2883static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2884template <typename FnTy, typename... FnTys>
2885static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2886 return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2887}
2888
2889/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2890/// Recursively apply each of the functions to E until reaching a fixed point.
2891/// Note that a null E is valid; in this case nothing is done.
2892template <typename... FnTys>
2893static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
Bruno Riccid4038002019-02-17 13:47:29 +00002894 Expr *LastE = nullptr;
2895 while (E != LastE) {
2896 LastE = E;
Bruno Ricci46148f22019-02-17 18:50:51 +00002897 E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
Bruno Riccid4038002019-02-17 13:47:29 +00002898 }
2899 return E;
John McCall34376a62010-12-04 03:47:34 +00002900}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002901
Bruno Ricci46148f22019-02-17 18:50:51 +00002902Expr *Expr::IgnoreImpCasts() {
2903 return IgnoreExprNodes(this, IgnoreImpCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002904}
2905
2906Expr *Expr::IgnoreCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002907 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002908}
2909
Bruno Ricci46148f22019-02-17 18:50:51 +00002910Expr *Expr::IgnoreImplicit() {
2911 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002912}
2913
Bruno Ricci46148f22019-02-17 18:50:51 +00002914Expr *Expr::IgnoreParens() {
2915 return IgnoreExprNodes(this, IgnoreParensSingleStep);
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002916}
2917
John McCalleebc8322010-05-05 22:59:52 +00002918Expr *Expr::IgnoreParenImpCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002919 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2920 IgnoreImpCastsExtraSingleStep);
2921}
2922
2923Expr *Expr::IgnoreParenCasts() {
2924 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
John McCalleebc8322010-05-05 22:59:52 +00002925}
2926
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002927Expr *Expr::IgnoreConversionOperator() {
Bruno Riccie64aee82019-02-03 19:50:56 +00002928 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002929 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002930 return MCE->getImplicitObjectArgument();
2931 }
2932 return this;
2933}
2934
Bruno Ricci46148f22019-02-17 18:50:51 +00002935Expr *Expr::IgnoreParenLValueCasts() {
2936 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2937 IgnoreLValueCastsSingleStep);
2938}
2939
2940Expr *Expr::ignoreParenBaseCasts() {
2941 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2942 IgnoreBaseCastsSingleStep);
2943}
2944
Bruno Riccie64aee82019-02-03 19:50:56 +00002945Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
Bruno Ricci46148f22019-02-17 18:50:51 +00002946 return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2947 return IgnoreNoopCastsSingleStep(Ctx, E);
2948 });
Chris Lattneref26c772009-03-13 17:28:01 +00002949}
2950
Douglas Gregord196a582009-12-14 19:27:10 +00002951bool Expr::isDefaultArgument() const {
2952 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002953 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2954 E = M->GetTemporaryExpr();
2955
Douglas Gregord196a582009-12-14 19:27:10 +00002956 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2957 E = ICE->getSubExprAsWritten();
Fangrui Song6907ce22018-07-30 19:24:48 +00002958
Douglas Gregord196a582009-12-14 19:27:10 +00002959 return isa<CXXDefaultArgExpr>(E);
2960}
Chris Lattneref26c772009-03-13 17:28:01 +00002961
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002962/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002963/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002964static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002965 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2966 E = M->GetTemporaryExpr();
2967
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002968 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002969 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002970 E = ICE->getSubExpr();
2971 else
2972 break;
2973 }
2974
2975 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2976 E = BE->getSubExpr();
2977
2978 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002979 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002980 E = ICE->getSubExpr();
2981 else
2982 break;
2983 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002984
2985 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002986}
2987
John McCall7a626f62010-09-15 10:14:12 +00002988/// isTemporaryObject - Determines if this expression produces a
2989/// temporary of the given class type.
2990bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2991 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2992 return false;
2993
Anders Carlsson66bbf502010-11-28 16:40:49 +00002994 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002995
John McCall02dc8c72010-09-15 20:59:13 +00002996 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002997 if (!E->Classify(C).isPRValue()) {
2998 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002999 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00003000 return false;
3001 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003002
John McCallf4ee1dd2010-09-16 06:57:56 +00003003 // Black-list a few cases which yield pr-values of class type that don't
3004 // refer to temporaries of that type:
3005
3006 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00003007 if (isa<ImplicitCastExpr>(E)) {
3008 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3009 case CK_DerivedToBase:
3010 case CK_UncheckedDerivedToBase:
3011 return false;
3012 default:
3013 break;
3014 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003015 }
3016
John McCallf4ee1dd2010-09-16 06:57:56 +00003017 // - member expressions (all)
3018 if (isa<MemberExpr>(E))
3019 return false;
3020
Eli Friedman13ffdd82012-06-15 23:51:06 +00003021 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3022 if (BO->isPtrMemOp())
3023 return false;
3024
John McCallc07a0c72011-02-17 10:25:35 +00003025 // - opaque values (all)
3026 if (isa<OpaqueValueExpr>(E))
3027 return false;
3028
John McCall7a626f62010-09-15 10:14:12 +00003029 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003030}
3031
Douglas Gregor25b7e052011-03-02 21:06:53 +00003032bool Expr::isImplicitCXXThis() const {
3033 const Expr *E = this;
Fangrui Song6907ce22018-07-30 19:24:48 +00003034
Douglas Gregor25b7e052011-03-02 21:06:53 +00003035 // Strip away parentheses and casts we don't care about.
3036 while (true) {
3037 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3038 E = Paren->getSubExpr();
3039 continue;
3040 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003041
Douglas Gregor25b7e052011-03-02 21:06:53 +00003042 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3043 if (ICE->getCastKind() == CK_NoOp ||
3044 ICE->getCastKind() == CK_LValueToRValue ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003045 ICE->getCastKind() == CK_DerivedToBase ||
Douglas Gregor25b7e052011-03-02 21:06:53 +00003046 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3047 E = ICE->getSubExpr();
3048 continue;
3049 }
3050 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003051
Douglas Gregor25b7e052011-03-02 21:06:53 +00003052 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3053 if (UnOp->getOpcode() == UO_Extension) {
3054 E = UnOp->getSubExpr();
3055 continue;
3056 }
3057 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003058
Douglas Gregorfe314812011-06-21 17:03:29 +00003059 if (const MaterializeTemporaryExpr *M
3060 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3061 E = M->GetTemporaryExpr();
3062 continue;
3063 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003064
Douglas Gregor25b7e052011-03-02 21:06:53 +00003065 break;
3066 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003067
Douglas Gregor25b7e052011-03-02 21:06:53 +00003068 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3069 return This->isImplicit();
Fangrui Song6907ce22018-07-30 19:24:48 +00003070
Douglas Gregor25b7e052011-03-02 21:06:53 +00003071 return false;
3072}
3073
Douglas Gregor4619e432008-12-05 23:32:09 +00003074/// hasAnyTypeDependentArguments - Determines if any of the expressions
3075/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003076bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003077 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00003078 if (Exprs[I]->isTypeDependent())
3079 return true;
3080
3081 return false;
3082}
3083
Abramo Bagnara847c6602014-05-22 19:20:46 +00003084bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3085 const Expr **Culprit) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +00003086 assert(!isValueDependent() &&
3087 "Expression evaluator can't be called on a dependent expression.");
3088
Eli Friedman384da272009-01-25 03:12:18 +00003089 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00003090 // which can be evaluated at compile-time. It very closely parallels
3091 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3092 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3093 // to isEvaluatable most of the time.
3094 //
John McCall8b0f4ff2010-08-02 21:13:48 +00003095 // If we ever capture reference-binding directly in the AST, we can
3096 // kill the second parameter.
3097
3098 if (IsForRef) {
3099 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003100 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3101 return true;
3102 if (Culprit)
3103 *Culprit = this;
3104 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00003105 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00003106
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003107 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00003108 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003109 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00003110 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003111 return true;
John McCall81c9cea2010-08-01 21:51:45 +00003112 case CXXTemporaryObjectExprClass:
3113 case CXXConstructExprClass: {
3114 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00003115
Eli Friedman4c27ac22013-07-16 22:40:53 +00003116 if (CE->getConstructor()->isTrivial() &&
3117 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3118 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00003119 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00003120
Eli Friedman4c27ac22013-07-16 22:40:53 +00003121 // Trivial copy constructor
3122 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00003123 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00003124 }
3125
Richard Smithd62306a2011-11-10 06:34:14 +00003126 break;
John McCall81c9cea2010-08-01 21:51:45 +00003127 }
Fangrui Song407659a2018-11-30 23:41:18 +00003128 case ConstantExprClass: {
3129 // FIXME: We should be able to return "true" here, but it can lead to extra
3130 // error messages. E.g. in Sema/array-init.c.
3131 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3132 return Exp->isConstantInitializer(Ctx, false, Culprit);
3133 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003134 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00003135 // This handles gcc's extension that allows global initializers like
3136 // "struct x {int x;} x = (struct x) {};".
3137 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003138 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00003139 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003140 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00003141 case DesignatedInitUpdateExprClass: {
3142 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3143 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3144 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3145 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003146 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00003147 const InitListExpr *ILE = cast<InitListExpr>(this);
Dmitri Gribenkoc5f25442019-05-10 06:39:20 +00003148 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
Eli Friedman4c27ac22013-07-16 22:40:53 +00003149 if (ILE->getType()->isArrayType()) {
3150 unsigned numInits = ILE->getNumInits();
3151 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00003152 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00003153 return false;
3154 }
3155 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003156 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00003157
3158 if (ILE->getType()->isRecordType()) {
3159 unsigned ElementNo = 0;
3160 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00003161 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00003162 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00003163 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00003164 continue;
3165
3166 // Don't emit anonymous bitfields, they just affect layout.
3167 if (Field->isUnnamedBitfield())
3168 continue;
3169
3170 if (ElementNo < ILE->getNumInits()) {
3171 const Expr *Elt = ILE->getInit(ElementNo++);
3172 if (Field->isBitField()) {
3173 // Bitfields have to evaluate to an integer.
Fangrui Song407659a2018-11-30 23:41:18 +00003174 EvalResult Result;
3175 if (!Elt->EvaluateAsInt(Result, Ctx)) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00003176 if (Culprit)
3177 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00003178 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003179 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00003180 } else {
3181 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00003182 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00003183 return false;
3184 }
3185 }
3186 }
3187 return true;
3188 }
3189
3190 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003191 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00003192 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003193 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00003194 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00003195 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00003196 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003197 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00003198 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00003199 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003200 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00003201 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00003202 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3203 if (Culprit)
3204 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00003205 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003206 }
Eli Friedman75807f22013-07-20 00:40:58 +00003207 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003208 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003209 case UnaryOperatorClass: {
3210 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00003211 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003212 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003213 break;
3214 }
John McCall8b0f4ff2010-08-02 21:13:48 +00003215 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00003216 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00003217 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00003218 case CStyleCastExprClass:
3219 case ObjCBridgedCastExprClass:
3220 case CXXDynamicCastExprClass:
3221 case CXXReinterpretCastExprClass:
3222 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00003223 const CastExpr *CE = cast<CastExpr>(this);
3224
Eli Friedman13ec75b2011-12-21 00:43:02 +00003225 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00003226 if (CE->getCastKind() == CK_NoOp ||
3227 CE->getCastKind() == CK_LValueToRValue ||
3228 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00003229 CE->getCastKind() == CK_ConstructorConversion ||
3230 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003231 CE->getCastKind() == CK_AtomicToNonAtomic ||
3232 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003233 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00003234
Eli Friedman384da272009-01-25 03:12:18 +00003235 break;
Richard Smith161f09a2011-12-06 22:44:34 +00003236 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003237 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003238 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003239 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003240
Eli Friedman4c27ac22013-07-16 22:40:53 +00003241 case SubstNonTypeTemplateParmExprClass:
3242 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003243 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003244 case CXXDefaultArgExprClass:
3245 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003246 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003247 case CXXDefaultInitExprClass:
3248 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003249 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003250 }
Richard Smithce8eca52015-12-08 03:21:47 +00003251 // Allow certain forms of UB in constant initializers: signed integer
3252 // overflow and floating-point division by zero. We'll give a warning on
3253 // these, but they're common enough that we have to accept them.
3254 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00003255 return true;
3256 if (Culprit)
3257 *Culprit = this;
3258 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00003259}
3260
Nico Weber758fbac2018-02-13 21:31:47 +00003261bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3262 const FunctionDecl* FD = getDirectCallee();
3263 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3264 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3265 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003266
Nico Weber758fbac2018-02-13 21:31:47 +00003267 const Expr* Arg = getArg(0);
3268 bool ArgVal;
3269 return !Arg->isValueDependent() &&
3270 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3271}
3272
Scott Douglasscc013592015-06-10 15:18:23 +00003273namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003274 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00003275 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003276 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00003277 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003278 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00003279
3280 public:
3281 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003282 : Inherited(Context),
3283 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00003284
3285 bool hasSideEffects() const { return HasSideEffects; }
3286
3287 void VisitExpr(const Expr *E) {
3288 if (!HasSideEffects &&
3289 E->HasSideEffects(Context, IncludePossibleEffects))
3290 HasSideEffects = true;
3291 }
3292 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003293}
Scott Douglasscc013592015-06-10 15:18:23 +00003294
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003295bool Expr::HasSideEffects(const ASTContext &Ctx,
3296 bool IncludePossibleEffects) const {
3297 // In circumstances where we care about definite side effects instead of
3298 // potential side effects, we want to ignore expressions that are part of a
3299 // macro expansion as a potential side effect.
3300 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3301 return false;
3302
Richard Smith0421ce72012-08-07 04:16:51 +00003303 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003304 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00003305
3306 switch (getStmtClass()) {
3307 case NoStmtClass:
3308 #define ABSTRACT_STMT(Type)
3309 #define STMT(Type, Base) case Type##Class:
3310 #define EXPR(Type, Base)
3311 #include "clang/AST/StmtNodes.inc"
3312 llvm_unreachable("unexpected Expr kind");
3313
3314 case DependentScopeDeclRefExprClass:
3315 case CXXUnresolvedConstructExprClass:
3316 case CXXDependentScopeMemberExprClass:
3317 case UnresolvedLookupExprClass:
3318 case UnresolvedMemberExprClass:
3319 case PackExpansionExprClass:
3320 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00003321 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003322 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00003323 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003324 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3325
Richard Smitha33e4fe2012-08-07 05:18:29 +00003326 case DeclRefExprClass:
3327 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003328 case PredefinedExprClass:
3329 case IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003330 case FixedPointLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003331 case FloatingLiteralClass:
3332 case ImaginaryLiteralClass:
3333 case StringLiteralClass:
3334 case CharacterLiteralClass:
3335 case OffsetOfExprClass:
3336 case ImplicitValueInitExprClass:
3337 case UnaryExprOrTypeTraitExprClass:
3338 case AddrLabelExprClass:
3339 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003340 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003341 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003342 case CXXBoolLiteralExprClass:
3343 case CXXNullPtrLiteralExprClass:
3344 case CXXThisExprClass:
3345 case CXXScalarValueInitExprClass:
3346 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003347 case ArrayTypeTraitExprClass:
3348 case ExpressionTraitExprClass:
3349 case CXXNoexceptExprClass:
3350 case SizeOfPackExprClass:
3351 case ObjCStringLiteralClass:
3352 case ObjCEncodeExprClass:
3353 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003354 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003355 case CXXUuidofExprClass:
3356 case OpaqueValueExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +00003357 case SourceLocExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003358 // These never have a side-effect.
3359 return false;
3360
Bill Wendling7c44da22018-10-31 03:48:47 +00003361 case ConstantExprClass:
3362 // FIXME: Move this into the "return false;" block above.
3363 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3364 Ctx, IncludePossibleEffects);
3365
Richard Smith0421ce72012-08-07 04:16:51 +00003366 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003367 case CXXOperatorCallExprClass:
3368 case CXXMemberCallExprClass:
3369 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003370 case UserDefinedLiteralClass: {
3371 // We don't know a call definitely has side effects, except for calls
3372 // to pure/const functions that definitely don't.
3373 // If the call itself is considered side-effect free, check the operands.
3374 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3375 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3376 if (IsPure || !IncludePossibleEffects)
3377 break;
3378 return true;
3379 }
3380
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003381 case BlockExprClass:
3382 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003383 if (!IncludePossibleEffects)
3384 break;
3385 return true;
3386
John McCall5e77d762013-04-16 07:28:30 +00003387 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003388 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003389 case CompoundAssignOperatorClass:
3390 case VAArgExprClass:
3391 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003392 case CXXThrowExprClass:
3393 case CXXNewExprClass:
3394 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003395 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003396 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003397 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003398 // These always have a side-effect.
3399 return true;
3400
Scott Douglasscc013592015-06-10 15:18:23 +00003401 case StmtExprClass: {
3402 // StmtExprs have a side-effect if any substatement does.
3403 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3404 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3405 return Finder.hasSideEffects();
3406 }
3407
Tim Shen4a05bb82016-06-21 20:29:17 +00003408 case ExprWithCleanupsClass:
3409 if (IncludePossibleEffects)
3410 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3411 return true;
3412 break;
3413
Richard Smith0421ce72012-08-07 04:16:51 +00003414 case ParenExprClass:
3415 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003416 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003417 case MemberExprClass:
3418 case ConditionalOperatorClass:
3419 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003420 case CompoundLiteralExprClass:
3421 case ExtVectorElementExprClass:
3422 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003423 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003424 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003425 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003426 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003427 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003428 case SubstNonTypeTemplateParmExprClass:
3429 case MaterializeTemporaryExprClass:
3430 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003431 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003432 case AsTypeExprClass:
3433 // These have a side-effect if any subexpression does.
3434 break;
3435
Richard Smitha33e4fe2012-08-07 05:18:29 +00003436 case UnaryOperatorClass:
3437 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003438 return true;
3439 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003440
3441 case BinaryOperatorClass:
3442 if (cast<BinaryOperator>(this)->isAssignmentOp())
3443 return true;
3444 break;
3445
Richard Smith0421ce72012-08-07 04:16:51 +00003446 case InitListExprClass:
3447 // FIXME: The children for an InitListExpr doesn't include the array filler.
3448 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003449 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003450 return true;
3451 break;
3452
3453 case GenericSelectionExprClass:
3454 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003455 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003456
3457 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003458 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3459 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003460
3461 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003462 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3463 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003464
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003465 case CXXDefaultInitExprClass: {
3466 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3467 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003468 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003469 // If we've not yet parsed the initializer, assume it has side-effects.
3470 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003471 }
Richard Smith852c9db2013-04-20 22:23:05 +00003472
Richard Smith0421ce72012-08-07 04:16:51 +00003473 case CXXDynamicCastExprClass: {
3474 // A dynamic_cast expression has side-effects if it can throw.
3475 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3476 if (DCE->getTypeAsWritten()->isReferenceType() &&
3477 DCE->getCastKind() == CK_Dynamic)
3478 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003479 }
3480 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003481 case ImplicitCastExprClass:
3482 case CStyleCastExprClass:
3483 case CXXStaticCastExprClass:
3484 case CXXReinterpretCastExprClass:
3485 case CXXConstCastExprClass:
3486 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003487 // While volatile reads are side-effecting in both C and C++, we treat them
3488 // as having possible (not definite) side-effects. This allows idiomatic
3489 // code to behave without warning, such as sizeof(*v) for a volatile-
3490 // qualified pointer.
3491 if (!IncludePossibleEffects)
3492 break;
3493
Richard Smitha33e4fe2012-08-07 05:18:29 +00003494 const CastExpr *CE = cast<CastExpr>(this);
3495 if (CE->getCastKind() == CK_LValueToRValue &&
3496 CE->getSubExpr()->getType().isVolatileQualified())
3497 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003498 break;
3499 }
3500
Richard Smithef8bf432012-08-13 20:08:14 +00003501 case CXXTypeidExprClass:
3502 // typeid might throw if its subexpression is potentially-evaluated, so has
3503 // side-effects in that case whether or not its subexpression does.
3504 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003505
3506 case CXXConstructExprClass:
3507 case CXXTemporaryObjectExprClass: {
3508 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003509 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003510 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003511 // A trivial constructor does not add any side-effects of its own. Just look
3512 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003513 break;
3514 }
3515
Richard Smith5179eb72016-06-28 19:03:57 +00003516 case CXXInheritedCtorInitExprClass: {
3517 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3518 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3519 return true;
3520 break;
3521 }
3522
Richard Smith0421ce72012-08-07 04:16:51 +00003523 case LambdaExprClass: {
3524 const LambdaExpr *LE = cast<LambdaExpr>(this);
Richard Smithb3d203f2018-10-19 19:01:34 +00003525 for (Expr *E : LE->capture_inits())
3526 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003527 return true;
3528 return false;
3529 }
3530
3531 case PseudoObjectExprClass: {
3532 // Only look for side-effects in the semantic form, and look past
3533 // OpaqueValueExpr bindings in that form.
3534 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3535 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3536 E = PO->semantics_end();
3537 I != E; ++I) {
3538 const Expr *Subexpr = *I;
3539 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3540 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003541 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003542 return true;
3543 }
3544 return false;
3545 }
3546
3547 case ObjCBoxedExprClass:
3548 case ObjCArrayLiteralClass:
3549 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003550 case ObjCSelectorExprClass:
3551 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003552 case ObjCIsaExprClass:
3553 case ObjCIndirectCopyRestoreExprClass:
3554 case ObjCSubscriptRefExprClass:
3555 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003556 case ObjCMessageExprClass:
3557 case ObjCPropertyRefExprClass:
3558 // FIXME: Classify these cases better.
3559 if (IncludePossibleEffects)
3560 return true;
3561 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003562 }
3563
3564 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003565 for (const Stmt *SubStmt : children())
3566 if (SubStmt &&
3567 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3568 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003569
3570 return false;
3571}
3572
Douglas Gregor1be329d2012-02-23 07:33:15 +00003573namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003574 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003575 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3576 {
3577 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003578
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003579 bool NonTrivial;
Fangrui Song6907ce22018-07-30 19:24:48 +00003580
Douglas Gregor1be329d2012-02-23 07:33:15 +00003581 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003582 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003583 : Inherited(Context), NonTrivial(false) { }
Fangrui Song6907ce22018-07-30 19:24:48 +00003584
Douglas Gregor1be329d2012-02-23 07:33:15 +00003585 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003586
3587 void VisitCallExpr(const CallExpr *E) {
3588 if (const CXXMethodDecl *Method
3589 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003590 if (Method->isTrivial()) {
3591 // Recurse to children of the call.
3592 Inherited::VisitStmt(E);
3593 return;
3594 }
3595 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003596
Douglas Gregor1be329d2012-02-23 07:33:15 +00003597 NonTrivial = true;
3598 }
Scott Douglass503fc392015-06-10 13:53:15 +00003599
3600 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003601 if (E->getConstructor()->isTrivial()) {
3602 // Recurse to children of the call.
3603 Inherited::VisitStmt(E);
3604 return;
3605 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003606
Douglas Gregor1be329d2012-02-23 07:33:15 +00003607 NonTrivial = true;
3608 }
Scott Douglass503fc392015-06-10 13:53:15 +00003609
3610 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003611 if (E->getTemporary()->getDestructor()->isTrivial()) {
3612 Inherited::VisitStmt(E);
3613 return;
3614 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003615
Douglas Gregor1be329d2012-02-23 07:33:15 +00003616 NonTrivial = true;
3617 }
3618 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003619}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003620
Scott Douglass503fc392015-06-10 13:53:15 +00003621bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003622 NonTrivialCallFinder Finder(Ctx);
3623 Finder.Visit(this);
Fangrui Song6907ce22018-07-30 19:24:48 +00003624 return Finder.hasNonTrivialCall();
Douglas Gregor1be329d2012-02-23 07:33:15 +00003625}
3626
Fangrui Song6907ce22018-07-30 19:24:48 +00003627/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003628/// pointer constant or not, as well as the specific kind of constant detected.
3629/// Null pointer constants can be integer constant expressions with the
3630/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3631/// (a GNU extension).
3632Expr::NullPointerConstantKind
3633Expr::isNullPointerConstant(ASTContext &Ctx,
3634 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003635 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003636 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003637 switch (NPC) {
3638 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003639 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003640 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003641 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003642 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003643 else
3644 return NPCK_NotNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003645
Douglas Gregor56751b52009-09-25 04:25:58 +00003646 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003647 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003648 }
3649 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003650
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003651 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003652 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003653 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003654 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003655 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003656 QualType Pointee = PT->getPointeeType();
Richard Smithdab73ce2018-11-28 06:25:06 +00003657 Qualifiers Qs = Pointee.getQualifiers();
Yaxun Liub7318e02017-10-13 03:37:48 +00003658 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3659 // has non-default address space it is not treated as nullptr.
3660 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3661 // since it cannot be assigned to a pointer to constant address space.
Richard Smithdab73ce2018-11-28 06:25:06 +00003662 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
Yaxun Liub7318e02017-10-13 03:37:48 +00003663 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3664 (Ctx.getLangOpts().OpenCL &&
3665 Ctx.getLangOpts().OpenCLVersion < 200 &&
Richard Smithdab73ce2018-11-28 06:25:06 +00003666 Pointee.getAddressSpace() == LangAS::opencl_private))
3667 Qs.removeAddressSpace();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003668
Richard Smithdab73ce2018-11-28 06:25:06 +00003669 if (Pointee->isVoidType() && Qs.empty() && // to void*
3670 CE->getSubExpr()->getType()->isIntegerType()) // from int
Douglas Gregor56751b52009-09-25 04:25:58 +00003671 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003672 }
Steve Naroffada7d422007-05-20 17:54:12 +00003673 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003674 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3675 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003676 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003677 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3678 // Accept ((void*)0) as a null pointer constant, as many other
3679 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003680 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003681 } else if (const GenericSelectionExpr *GE =
3682 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003683 if (GE->isResultDependent())
3684 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003685 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003686 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3687 if (CE->isConditionDependent())
3688 return NPCK_NotNull;
3689 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003690 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003691 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003692 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003693 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003694 } else if (const CXXDefaultInitExpr *DefaultInit
3695 = dyn_cast<CXXDefaultInitExpr>(this)) {
3696 // See through default initializer expressions.
3697 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003698 } else if (isa<GNUNullExpr>(this)) {
3699 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003700 return NPCK_GNUNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003701 } else if (const MaterializeTemporaryExpr *M
Douglas Gregorfe314812011-06-21 17:03:29 +00003702 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3703 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003704 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3705 if (const Expr *Source = OVE->getSourceExpr())
3706 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003707 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003708
Richard Smith89645bc2013-01-02 12:01:23 +00003709 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003710 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003711 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003712
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003713 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003714 if (!Ctx.getLangOpts().CPlusPlus11 &&
3715 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003716 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3717 const Expr *InitExpr = CLE->getInitializer();
3718 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3719 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3720 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003721 // This expression must be an integer type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003722 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003723 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003724 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003725
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003726 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003727 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3728 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003729 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003730 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003731 if (Lit && !Lit->getValue())
3732 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003733 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003734 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003735 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003736 // If we have an integer constant expression, we need to *evaluate* it and
3737 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003738 if (!isIntegerConstantExpr(Ctx))
3739 return NPCK_NotNull;
3740 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003741
David Blaikie1c7c8f72012-08-08 17:33:31 +00003742 if (EvaluateKnownConstInt(Ctx) != 0)
3743 return NPCK_NotNull;
3744
3745 if (isa<IntegerLiteral>(this))
3746 return NPCK_ZeroLiteral;
3747 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003748}
Steve Narofff7a5da12007-07-28 23:10:27 +00003749
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003750/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003751/// property, find the underlying property reference expression.
3752const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3753 const Expr *E = this;
3754 while (true) {
3755 assert((E->getValueKind() == VK_LValue &&
3756 E->getObjectKind() == OK_ObjCProperty) &&
3757 "expression is not a property reference");
3758 E = E->IgnoreParenCasts();
3759 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3760 if (BO->getOpcode() == BO_Comma) {
3761 E = BO->getRHS();
3762 continue;
3763 }
3764 }
3765
3766 break;
3767 }
3768
3769 return cast<ObjCPropertyRefExpr>(E);
3770}
3771
Anna Zaks97c7ce32012-10-01 20:34:04 +00003772bool Expr::isObjCSelfExpr() const {
3773 const Expr *E = IgnoreParenImpCasts();
3774
3775 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3776 if (!DRE)
3777 return false;
3778
3779 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3780 if (!Param)
3781 return false;
3782
3783 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3784 if (!M)
3785 return false;
3786
3787 return M->getSelfDecl() == Param;
3788}
3789
John McCalld25db7e2013-05-06 21:39:12 +00003790FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003791 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003792
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003793 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003794 if (ICE->getCastKind() == CK_LValueToRValue ||
3795 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003796 E = ICE->getSubExpr()->IgnoreParens();
3797 else
3798 break;
3799 }
3800
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003801 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003802 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003803 if (Field->isBitField())
3804 return Field;
3805
George Burgess IV00f70bd2018-03-01 05:43:23 +00003806 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3807 FieldDecl *Ivar = IvarRef->getDecl();
3808 if (Ivar->isBitField())
3809 return Ivar;
3810 }
John McCalld25db7e2013-05-06 21:39:12 +00003811
Richard Smith7873de02016-08-11 22:25:46 +00003812 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003813 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3814 if (Field->isBitField())
3815 return Field;
3816
Richard Smith7873de02016-08-11 22:25:46 +00003817 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3818 if (Expr *E = BD->getBinding())
3819 return E->getSourceBitField();
3820 }
3821
Eli Friedman609ada22011-07-13 02:05:57 +00003822 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003823 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003824 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003825
Eli Friedman609ada22011-07-13 02:05:57 +00003826 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003827 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003828 }
3829
Richard Smith5b571672014-09-24 23:55:00 +00003830 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3831 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3832 return UnOp->getSubExpr()->getSourceBitField();
3833
Craig Topper36250ad2014-05-12 05:36:57 +00003834 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003835}
3836
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003837bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003838 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003839 const Expr *E = this->IgnoreParens();
Fangrui Song6907ce22018-07-30 19:24:48 +00003840
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003841 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003842 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003843 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003844 E = ICE->getSubExpr()->IgnoreParens();
3845 else
3846 break;
3847 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003848
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003849 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3850 return ASE->getBase()->getType()->isVectorType();
3851
3852 if (isa<ExtVectorElementExpr>(E))
3853 return true;
3854
Richard Smith7873de02016-08-11 22:25:46 +00003855 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3856 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3857 if (auto *E = BD->getBinding())
3858 return E->refersToVectorElement();
3859
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003860 return false;
3861}
3862
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003863bool Expr::refersToGlobalRegisterVar() const {
3864 const Expr *E = this->IgnoreParenImpCasts();
3865
3866 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3867 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3868 if (VD->getStorageClass() == SC_Register &&
3869 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3870 return true;
3871
3872 return false;
3873}
3874
Chris Lattnerb8211f62009-02-16 22:14:05 +00003875/// isArrow - Return true if the base expression is a pointer to vector,
3876/// return false if the base expression is a vector.
3877bool ExtVectorElementExpr::isArrow() const {
3878 return getBase()->getType()->isPointerType();
3879}
3880
Nate Begemance4d7fc2008-04-18 23:10:10 +00003881unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003882 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003883 return VT->getNumElements();
3884 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003885}
3886
Nate Begemanf322eab2008-05-09 06:41:27 +00003887/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003888bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003889 // FIXME: Refactor this code to an accessor on the AST node which returns the
3890 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003891 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003892
3893 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003894 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003895 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003896
Nate Begeman7e5185b2009-01-18 02:01:21 +00003897 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003898 if (Comp[0] == 's' || Comp[0] == 'S')
3899 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003900
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003901 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003902 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003903 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003904
Steve Naroff0d595ca2007-07-30 03:29:09 +00003905 return false;
3906}
Chris Lattner885b4952007-08-02 23:36:59 +00003907
Nate Begemanf322eab2008-05-09 06:41:27 +00003908/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003909void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003910 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003911 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003912 bool isNumericAccessor = false;
3913 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003914 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003915 isNumericAccessor = true;
3916 }
Mike Stump11289f42009-09-09 15:08:12 +00003917
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003918 bool isHi = Comp == "hi";
3919 bool isLo = Comp == "lo";
3920 bool isEven = Comp == "even";
3921 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003922
Nate Begemanf322eab2008-05-09 06:41:27 +00003923 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3924 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003925
Nate Begemanf322eab2008-05-09 06:41:27 +00003926 if (isHi)
3927 Index = e + i;
3928 else if (isLo)
3929 Index = i;
3930 else if (isEven)
3931 Index = 2 * i;
3932 else if (isOdd)
3933 Index = 2 * i + 1;
3934 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003935 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003936
Nate Begemand3862152008-05-13 21:03:02 +00003937 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003938 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003939}
3940
Craig Topper37932912013-08-18 10:09:15 +00003941ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003942 QualType Type, SourceLocation BLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00003943 SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003944 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3945 Type->isDependentType(), Type->isDependentType(),
3946 Type->isInstantiationDependentType(),
3947 Type->containsUnexpandedParameterPack()),
3948 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3949{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003950 SubExprs = new (C) Stmt*[args.size()];
3951 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003952 if (args[i]->isTypeDependent())
3953 ExprBits.TypeDependent = true;
3954 if (args[i]->isValueDependent())
3955 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003956 if (args[i]->isInstantiationDependent())
3957 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003958 if (args[i]->containsUnexpandedParameterPack())
3959 ExprBits.ContainsUnexpandedParameterPack = true;
3960
3961 SubExprs[i] = args[i];
3962 }
3963}
3964
Craig Topper37932912013-08-18 10:09:15 +00003965void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003966 if (SubExprs) C.Deallocate(SubExprs);
3967
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003968 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003969 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003970 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003971}
Nate Begeman48745922009-08-12 02:28:50 +00003972
Bruno Ricci94498c72019-01-26 13:58:15 +00003973GenericSelectionExpr::GenericSelectionExpr(
Bruno Riccidb076832019-01-26 14:15:10 +00003974 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
Bruno Ricci94498c72019-01-26 13:58:15 +00003975 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3976 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3977 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
3978 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
3979 AssocExprs[ResultIndex]->getValueKind(),
3980 AssocExprs[ResultIndex]->getObjectKind(),
3981 AssocExprs[ResultIndex]->isTypeDependent(),
3982 AssocExprs[ResultIndex]->isValueDependent(),
3983 AssocExprs[ResultIndex]->isInstantiationDependent(),
3984 ContainsUnexpandedParameterPack),
3985 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00003986 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00003987 assert(AssocTypes.size() == AssocExprs.size() &&
3988 "Must have the same number of association expressions"
3989 " and TypeSourceInfo!");
3990 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
3991
Bruno Riccidb076832019-01-26 14:15:10 +00003992 GenericSelectionExprBits.GenericLoc = GenericLoc;
3993 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00003994 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00003995 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
3996 std::copy(AssocTypes.begin(), AssocTypes.end(),
3997 getTrailingObjects<TypeSourceInfo *>());
Peter Collingbourne91147592011-04-15 00:35:48 +00003998}
3999
Bruno Ricci94498c72019-01-26 13:58:15 +00004000GenericSelectionExpr::GenericSelectionExpr(
4001 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4002 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4003 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4004 bool ContainsUnexpandedParameterPack)
4005 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
4006 OK_Ordinary,
4007 /*isTypeDependent=*/true,
4008 /*isValueDependent=*/true,
4009 /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
4010 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00004011 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00004012 assert(AssocTypes.size() == AssocExprs.size() &&
4013 "Must have the same number of association expressions"
4014 " and TypeSourceInfo!");
4015
Bruno Riccidb076832019-01-26 14:15:10 +00004016 GenericSelectionExprBits.GenericLoc = GenericLoc;
4017 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00004018 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00004019 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4020 std::copy(AssocTypes.begin(), AssocTypes.end(),
4021 getTrailingObjects<TypeSourceInfo *>());
4022}
4023
4024GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4025 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4026
4027GenericSelectionExpr *GenericSelectionExpr::Create(
4028 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4029 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4030 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4031 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4032 unsigned NumAssocs = AssocExprs.size();
4033 void *Mem = Context.Allocate(
4034 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4035 alignof(GenericSelectionExpr));
4036 return new (Mem) GenericSelectionExpr(
4037 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4038 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4039}
4040
4041GenericSelectionExpr *GenericSelectionExpr::Create(
4042 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4043 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4044 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4045 bool ContainsUnexpandedParameterPack) {
4046 unsigned NumAssocs = AssocExprs.size();
4047 void *Mem = Context.Allocate(
4048 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4049 alignof(GenericSelectionExpr));
4050 return new (Mem) GenericSelectionExpr(
4051 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4052 RParenLoc, ContainsUnexpandedParameterPack);
4053}
4054
4055GenericSelectionExpr *
4056GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4057 unsigned NumAssocs) {
4058 void *Mem = Context.Allocate(
4059 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4060 alignof(GenericSelectionExpr));
4061 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
Peter Collingbourne91147592011-04-15 00:35:48 +00004062}
4063
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004064//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004065// DesignatedInitExpr
4066//===----------------------------------------------------------------------===//
4067
Chandler Carruth631abd92011-06-16 06:47:06 +00004068IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004069 assert(Kind == FieldDesignator && "Only valid on a field designator");
4070 if (Field.NameOrField & 0x01)
4071 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
4072 else
4073 return getField()->getIdentifier();
4074}
4075
Craig Topper37932912013-08-18 10:09:15 +00004076DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00004077 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00004078 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00004079 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004080 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004081 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00004082 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00004083 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00004084 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00004085 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00004086 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00004087 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00004088 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004089 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004090
4091 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004092 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004093 *Child++ = Init;
4094
4095 // Copy the designators and their subexpressions, computing
4096 // value-dependence along the way.
4097 unsigned IndexIdx = 0;
4098 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00004099 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004100
4101 if (this->Designators[I].isArrayDesignator()) {
4102 // Compute type- and value-dependence.
4103 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004104 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00004105 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00004106 if (Index->isInstantiationDependent())
4107 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00004108 // Propagate unexpanded parameter packs.
4109 if (Index->containsUnexpandedParameterPack())
4110 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004111
4112 // Copy the index expressions into permanent storage.
4113 *Child++ = IndexExprs[IndexIdx++];
4114 } else if (this->Designators[I].isArrayRangeDesignator()) {
4115 // Compute type- and value-dependence.
4116 Expr *Start = IndexExprs[IndexIdx];
4117 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004118 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00004119 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00004120 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00004121 ExprBits.InstantiationDependent = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004122 } else if (Start->isInstantiationDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00004123 End->isInstantiationDependent()) {
4124 ExprBits.InstantiationDependent = true;
4125 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004126
Douglas Gregora6e053e2010-12-15 01:34:56 +00004127 // Propagate unexpanded parameter packs.
4128 if (Start->containsUnexpandedParameterPack() ||
4129 End->containsUnexpandedParameterPack())
4130 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004131
4132 // Copy the start/end expressions into permanent storage.
4133 *Child++ = IndexExprs[IndexIdx++];
4134 *Child++ = IndexExprs[IndexIdx++];
4135 }
4136 }
4137
Benjamin Kramerc215e762012-08-24 11:54:20 +00004138 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00004139}
4140
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004141DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00004142DesignatedInitExpr::Create(const ASTContext &C,
4143 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004144 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004145 SourceLocation ColonOrEqualLoc,
4146 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004147 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004148 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00004149 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004150 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004151 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004152}
4153
Craig Topper37932912013-08-18 10:09:15 +00004154DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00004155 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004156 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004157 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00004158 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4159}
4160
Craig Topper37932912013-08-18 10:09:15 +00004161void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004162 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00004163 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004164 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00004165 NumDesignators = NumDesigs;
4166 for (unsigned I = 0; I != NumDesigs; ++I)
4167 Designators[I] = Desigs[I];
4168}
4169
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00004170SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4171 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4172 if (size() == 1)
4173 return DIE->getDesignator(0)->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004174 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004175 DIE->getDesignator(size() - 1)->getEndLoc());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00004176}
4177
Stephen Kelly724e9e52018-08-09 20:05:03 +00004178SourceLocation DesignatedInitExpr::getBeginLoc() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004179 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00004180 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4181 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004182 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00004183 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004184 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
4185 else
4186 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
4187 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00004188 StartLoc =
4189 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00004190 return StartLoc;
4191}
4192
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004193SourceLocation DesignatedInitExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004194 return getInit()->getEndLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004195}
4196
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004197Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004198 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004199 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004200}
4201
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004202Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004203 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004204 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004205 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004206}
4207
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004208Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004209 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004210 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004211 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004212}
4213
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004214/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00004215/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00004216void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00004217 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00004218 const Designator *Last) {
4219 unsigned NumNewDesignators = Last - First;
4220 if (NumNewDesignators == 0) {
4221 std::copy_backward(Designators + Idx + 1,
4222 Designators + NumDesignators,
4223 Designators + Idx);
4224 --NumNewDesignators;
4225 return;
4226 } else if (NumNewDesignators == 1) {
4227 Designators[Idx] = *First;
4228 return;
4229 }
4230
Mike Stump11289f42009-09-09 15:08:12 +00004231 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004232 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00004233 std::copy(Designators, Designators + Idx, NewDesignators);
4234 std::copy(First, Last, NewDesignators + Idx);
4235 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4236 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00004237 Designators = NewDesignators;
4238 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4239}
4240
Yunzhong Gaocb779302015-06-10 00:27:52 +00004241DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4242 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4243 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4244 OK_Ordinary, false, false, false, false) {
4245 BaseAndUpdaterExprs[0] = baseExpr;
4246
4247 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4248 ILE->setType(baseExpr->getType());
4249 BaseAndUpdaterExprs[1] = ILE;
4250}
4251
Stephen Kelly724e9e52018-08-09 20:05:03 +00004252SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004253 return getBase()->getBeginLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004254}
4255
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004256SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004257 return getBase()->getEndLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004258}
4259
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004260ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4261 SourceLocation RParenLoc)
4262 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4263 false, false),
4264 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4265 ParenListExprBits.NumExprs = Exprs.size();
4266
4267 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4268 if (Exprs[I]->isTypeDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004269 ExprBits.TypeDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004270 if (Exprs[I]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004271 ExprBits.ValueDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004272 if (Exprs[I]->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00004273 ExprBits.InstantiationDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004274 if (Exprs[I]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004275 ExprBits.ContainsUnexpandedParameterPack = true;
4276
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004277 getTrailingObjects<Stmt *>()[I] = Exprs[I];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004278 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004279}
4280
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004281ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4282 : Expr(ParenListExprClass, Empty) {
4283 ParenListExprBits.NumExprs = NumExprs;
4284}
4285
4286ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4287 SourceLocation LParenLoc,
4288 ArrayRef<Expr *> Exprs,
4289 SourceLocation RParenLoc) {
4290 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4291 alignof(ParenListExpr));
4292 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4293}
4294
4295ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4296 unsigned NumExprs) {
4297 void *Mem =
4298 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4299 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4300}
4301
John McCall1bf58462011-02-16 08:02:54 +00004302const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4303 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4304 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00004305 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4306 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00004307 e = cast<CXXConstructExpr>(e)->getArg(0);
4308 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4309 e = ice->getSubExpr();
4310 return cast<OpaqueValueExpr>(e);
4311}
4312
Craig Topper37932912013-08-18 10:09:15 +00004313PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4314 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00004315 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004316 void *buffer =
4317 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004318 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004319 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4320}
4321
4322PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4323 : Expr(PseudoObjectExprClass, shell) {
4324 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4325}
4326
Craig Topper37932912013-08-18 10:09:15 +00004327PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00004328 ArrayRef<Expr*> semantics,
4329 unsigned resultIndex) {
4330 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004331 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00004332
4333 QualType type;
4334 ExprValueKind VK;
4335 if (resultIndex == NoResult) {
4336 type = C.VoidTy;
4337 VK = VK_RValue;
4338 } else {
4339 assert(resultIndex < semantics.size());
4340 type = semantics[resultIndex]->getType();
4341 VK = semantics[resultIndex]->getValueKind();
4342 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4343 }
4344
James Y Knighte00a67e2015-12-31 04:18:25 +00004345 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004346 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004347 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4348 resultIndex);
4349}
4350
4351PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4352 Expr *syntax, ArrayRef<Expr*> semantics,
4353 unsigned resultIndex)
4354 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4355 /*filled in at end of ctor*/ false, false, false, false) {
4356 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4357 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4358
4359 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4360 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4361 getSubExprsBuffer()[i] = E;
4362
4363 if (E->isTypeDependent())
4364 ExprBits.TypeDependent = true;
4365 if (E->isValueDependent())
4366 ExprBits.ValueDependent = true;
4367 if (E->isInstantiationDependent())
4368 ExprBits.InstantiationDependent = true;
4369 if (E->containsUnexpandedParameterPack())
4370 ExprBits.ContainsUnexpandedParameterPack = true;
4371
4372 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00004373 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00004374 "opaque-value semantic expressions for pseudo-object "
4375 "operations must have sources");
4376 }
4377}
4378
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004379//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004380// Child Iterators for iterating over subexpressions/substatements
4381//===----------------------------------------------------------------------===//
4382
Peter Collingbournee190dee2011-03-11 19:24:49 +00004383// UnaryExprOrTypeTraitExpr
4384Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004385 const_child_range CCR =
4386 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4387 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4388}
4389
4390Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00004391 // If this is of a type and the type is a VLA type (and not a typedef), the
4392 // size expression of the VLA needs to be treated as an executable expression.
4393 // Why isn't this weirdness documented better in StmtIterator?
4394 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004395 if (const VariableArrayType *T =
4396 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4397 return const_child_range(const_child_iterator(T), const_child_iterator());
4398 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00004399 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004400 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004401}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004402
Benjamin Kramerc215e762012-08-24 11:54:20 +00004403AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004404 QualType t, AtomicOp op, SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004405 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4406 false, false, false, false),
4407 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4408{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004409 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4410 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004411 if (args[i]->isTypeDependent())
4412 ExprBits.TypeDependent = true;
4413 if (args[i]->isValueDependent())
4414 ExprBits.ValueDependent = true;
4415 if (args[i]->isInstantiationDependent())
4416 ExprBits.InstantiationDependent = true;
4417 if (args[i]->containsUnexpandedParameterPack())
4418 ExprBits.ContainsUnexpandedParameterPack = true;
4419
4420 SubExprs[i] = args[i];
4421 }
4422}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004423
4424unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4425 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004426 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004427 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004428 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004429 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004430 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004431
Yaxun Liu30d652a2017-08-15 16:02:49 +00004432 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004433 case AO__c11_atomic_store:
4434 case AO__c11_atomic_exchange:
4435 case AO__atomic_load:
4436 case AO__atomic_store:
4437 case AO__atomic_store_n:
4438 case AO__atomic_exchange_n:
4439 case AO__c11_atomic_fetch_add:
4440 case AO__c11_atomic_fetch_sub:
4441 case AO__c11_atomic_fetch_and:
4442 case AO__c11_atomic_fetch_or:
4443 case AO__c11_atomic_fetch_xor:
4444 case AO__atomic_fetch_add:
4445 case AO__atomic_fetch_sub:
4446 case AO__atomic_fetch_and:
4447 case AO__atomic_fetch_or:
4448 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004449 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004450 case AO__atomic_add_fetch:
4451 case AO__atomic_sub_fetch:
4452 case AO__atomic_and_fetch:
4453 case AO__atomic_or_fetch:
4454 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004455 case AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004456 case AO__atomic_fetch_min:
4457 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004458 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004459
Yaxun Liu30d652a2017-08-15 16:02:49 +00004460 case AO__opencl_atomic_store:
4461 case AO__opencl_atomic_exchange:
4462 case AO__opencl_atomic_fetch_add:
4463 case AO__opencl_atomic_fetch_sub:
4464 case AO__opencl_atomic_fetch_and:
4465 case AO__opencl_atomic_fetch_or:
4466 case AO__opencl_atomic_fetch_xor:
4467 case AO__opencl_atomic_fetch_min:
4468 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004469 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004470 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004471
4472 case AO__c11_atomic_compare_exchange_strong:
4473 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004474 return 5;
4475
Yaxun Liu39195062017-08-04 18:16:31 +00004476 case AO__opencl_atomic_compare_exchange_strong:
4477 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004478 case AO__atomic_compare_exchange:
4479 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004480 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004481 }
4482 llvm_unreachable("unknown atomic op");
4483}
Alexey Bataeva1764212015-09-30 09:22:36 +00004484
Yaxun Liu39195062017-08-04 18:16:31 +00004485QualType AtomicExpr::getValueType() const {
4486 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4487 if (auto AT = T->getAs<AtomicType>())
4488 return AT->getValueType();
4489 return T;
4490}
4491
Alexey Bataev31300ed2016-02-04 11:27:03 +00004492QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004493 unsigned ArraySectionCount = 0;
4494 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4495 Base = OASE->getBase();
4496 ++ArraySectionCount;
4497 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004498 while (auto *ASE =
4499 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004500 Base = ASE->getBase();
4501 ++ArraySectionCount;
4502 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004503 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004504 auto OriginalTy = Base->getType();
4505 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4506 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4507 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4508
4509 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4510 if (OriginalTy->isAnyPointerType())
4511 OriginalTy = OriginalTy->getPointeeType();
4512 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004513 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004514 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4515 }
4516 }
4517 return OriginalTy;
4518}