blob: d2730d3e26d5601163d44474bd08bb9451be97b1 [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:
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000242 case APValue::Indeterminate:
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000243 return ConstantExpr::RSK_None;
244 case APValue::Int:
245 if (!Value.getInt().needsCleanup())
246 return ConstantExpr::RSK_Int64;
247 LLVM_FALLTHROUGH;
248 default:
249 return ConstantExpr::RSK_APValue;
250 }
251}
252
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000253ConstantExpr::ResultStorageKind
254ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
255 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
256 return ConstantExpr::RSK_Int64;
257 return ConstantExpr::RSK_APValue;
258}
259
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000260void ConstantExpr::DefaultInit(ResultStorageKind StorageKind) {
261 ConstantExprBits.ResultKind = StorageKind;
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000262 ConstantExprBits.APValueKind = APValue::None;
263 ConstantExprBits.HasCleanup = false;
264 if (StorageKind == ConstantExpr::RSK_APValue)
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000265 ::new (getTrailingObjects<APValue>()) APValue();
266}
267
268ConstantExpr::ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind)
269 : FullExpr(ConstantExprClass, subexpr) {
270 DefaultInit(StorageKind);
271}
272
273ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
274 ResultStorageKind StorageKind) {
275 assert(!isa<ConstantExpr>(E));
276 AssertResultStorageKind(StorageKind);
277 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
278 StorageKind == ConstantExpr::RSK_APValue,
279 StorageKind == ConstantExpr::RSK_Int64);
280 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
281 ConstantExpr *Self = new (Mem) ConstantExpr(E, StorageKind);
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000282 return Self;
283}
284
285ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
286 const APValue &Result) {
287 ResultStorageKind StorageKind = getStorageKind(Result);
288 ConstantExpr *Self = Create(Context, E, StorageKind);
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000289 Self->SetResult(Result, Context);
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000290 return Self;
291}
292
293ConstantExpr::ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty)
294 : FullExpr(ConstantExprClass, Empty) {
295 DefaultInit(StorageKind);
296}
297
298ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
299 ResultStorageKind StorageKind,
300 EmptyShell Empty) {
301 AssertResultStorageKind(StorageKind);
302 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
303 StorageKind == ConstantExpr::RSK_APValue,
304 StorageKind == ConstantExpr::RSK_Int64);
305 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
306 ConstantExpr *Self = new (Mem) ConstantExpr(StorageKind, Empty);
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000307 return Self;
308}
309
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000310void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000311 assert(getStorageKind(Value) == ConstantExprBits.ResultKind &&
312 "Invalid storage for this value kind");
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000313 ConstantExprBits.APValueKind = Value.getKind();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000314 switch (ConstantExprBits.ResultKind) {
315 case RSK_None:
316 return;
317 case RSK_Int64:
318 Int64Result() = *Value.getInt().getRawData();
319 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
320 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
321 return;
322 case RSK_APValue:
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000323 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
324 ConstantExprBits.HasCleanup = true;
325 Context.addDestruction(&APValueResult());
326 }
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000327 APValueResult() = std::move(Value);
328 return;
329 }
330 llvm_unreachable("Invalid ResultKind Bits");
331}
332
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000333llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
334 switch (ConstantExprBits.ResultKind) {
335 case ConstantExpr::RSK_APValue:
336 return APValueResult().getInt();
337 case ConstantExpr::RSK_Int64:
338 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
339 ConstantExprBits.IsUnsigned);
340 default:
341 llvm_unreachable("invalid Accessor");
342 }
343}
344
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000345APValue ConstantExpr::getAPValueResult() const {
346 switch (ConstantExprBits.ResultKind) {
347 case ConstantExpr::RSK_APValue:
348 return APValueResult();
349 case ConstantExpr::RSK_Int64:
350 return APValue(
351 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
352 ConstantExprBits.IsUnsigned));
353 case ConstantExpr::RSK_None:
354 return APValue();
355 }
356 llvm_unreachable("invalid ResultKind");
357}
358
Fangrui Song6907ce22018-07-30 19:24:48 +0000359/// Compute the type-, value-, and instantiation-dependence of a
Douglas Gregor678d76c2011-07-01 01:22:09 +0000360/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000361/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000362static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
363 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000364 bool &ValueDependent,
365 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000366 TypeDependent = false;
367 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000368 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000369
370 // (TD) C++ [temp.dep.expr]p3:
371 // An id-expression is type-dependent if it contains:
372 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000373 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000374 //
375 // (VD) C++ [temp.dep.constexpr]p2:
376 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000377
Douglas Gregored6c7442009-11-23 11:41:28 +0000378 // (TD) - an identifier that was declared with dependent type
379 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000380 if (T->isDependentType()) {
381 TypeDependent = true;
382 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000383 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000384 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000385 } else if (T->isInstantiationDependentType()) {
386 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000387 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000388
Douglas Gregored6c7442009-11-23 11:41:28 +0000389 // (TD) - a conversion-function-id that specifies a dependent type
Fangrui Song6907ce22018-07-30 19:24:48 +0000390 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000391 == DeclarationName::CXXConversionFunctionName) {
392 QualType T = D->getDeclName().getCXXNameType();
393 if (T->isDependentType()) {
394 TypeDependent = true;
395 ValueDependent = true;
396 InstantiationDependent = true;
397 return;
398 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000399
Douglas Gregor678d76c2011-07-01 01:22:09 +0000400 if (T->isInstantiationDependentType())
401 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000402 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000403
Douglas Gregored6c7442009-11-23 11:41:28 +0000404 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000405 if (isa<NonTypeTemplateParmDecl>(D)) {
406 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000407 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000408 return;
409 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000410
Douglas Gregored6c7442009-11-23 11:41:28 +0000411 // (VD) - a constant with integral or enumeration type and is
412 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000413 // (VD) - a constant with literal type and is initialized with an
414 // expression that is value-dependent [C++11].
415 // (VD) - FIXME: Missing from the standard:
416 // - an entity with reference type and is initialized with an
417 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000418 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000419 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000420 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000421 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000422 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000423 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000424 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000425 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000426 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000427 InstantiationDependent = true;
428 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000429 }
430
Fangrui Song6907ce22018-07-30 19:24:48 +0000431 // (VD) - FIXME: Missing from the standard:
432 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000433 // instantiation
Fangrui Song6907ce22018-07-30 19:24:48 +0000434 if (Var->isStaticDataMember() &&
Richard Smithec8dcd22011-11-08 01:31:09 +0000435 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000436 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000437 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000438 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
439 if (TInfo->getType()->isIncompleteArrayType())
440 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000441 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000442
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000443 return;
444 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000445
446 // (VD) - FIXME: Missing from the standard:
447 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000448 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000449 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
450 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000451 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000452 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000453}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000454
Craig Topperce7167c2013-08-22 04:58:56 +0000455void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000456 bool TypeDependent = false;
457 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000458 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000459 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
460 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000461
462 ExprBits.TypeDependent |= TypeDependent;
463 ExprBits.ValueDependent |= ValueDependent;
464 ExprBits.InstantiationDependent |= InstantiationDependent;
465
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000466 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000467 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000468 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000469}
470
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000471DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
472 bool RefersToEnclosingVariableOrCapture, QualType T,
473 ExprValueKind VK, SourceLocation L,
Richard Smith715f7a12019-06-11 17:50:32 +0000474 const DeclarationNameLoc &LocInfo,
475 NonOdrUseReason NOUR)
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000476 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
477 D(D), DNLoc(LocInfo) {
478 DeclRefExprBits.HasQualifier = false;
479 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
480 DeclRefExprBits.HasFoundDecl = false;
481 DeclRefExprBits.HadMultipleCandidates = false;
482 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
483 RefersToEnclosingVariableOrCapture;
Richard Smith715f7a12019-06-11 17:50:32 +0000484 DeclRefExprBits.NonOdrUseReason = NOUR;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000485 DeclRefExprBits.Loc = L;
486 computeDependence(Ctx);
487}
488
Craig Topperce7167c2013-08-22 04:58:56 +0000489DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000490 NestedNameSpecifierLoc QualifierLoc,
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000491 SourceLocation TemplateKWLoc, ValueDecl *D,
492 bool RefersToEnclosingVariableOrCapture,
493 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000494 const TemplateArgumentListInfo *TemplateArgs,
Richard Smith715f7a12019-06-11 17:50:32 +0000495 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000496 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
497 D(D), DNLoc(NameInfo.getInfo()) {
Bruno Riccia795e802018-11-13 17:56:44 +0000498 DeclRefExprBits.Loc = NameInfo.getLoc();
Chandler Carruth0e439962011-05-01 21:29:53 +0000499 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000500 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000501 new (getTrailingObjects<NestedNameSpecifierLoc>())
502 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000503 auto *NNS = QualifierLoc.getNestedNameSpecifier();
504 if (NNS->isInstantiationDependent())
505 ExprBits.InstantiationDependent = true;
506 if (NNS->containsUnexpandedParameterPack())
507 ExprBits.ContainsUnexpandedParameterPack = true;
508 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000509 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
510 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000511 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000512 DeclRefExprBits.HasTemplateKWAndArgsInfo
513 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000514 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
515 RefersToEnclosingVariableOrCapture;
Richard Smith715f7a12019-06-11 17:50:32 +0000516 DeclRefExprBits.NonOdrUseReason = NOUR;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000517 if (TemplateArgs) {
518 bool Dependent = false;
519 bool InstantiationDependent = false;
520 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000521 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
522 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
523 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000524 assert(!Dependent && "built a DeclRefExpr with dependent template args");
525 ExprBits.InstantiationDependent |= InstantiationDependent;
526 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000527 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000528 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
529 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000530 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000531 DeclRefExprBits.HadMultipleCandidates = 0;
532
Daniel Dunbar9d355812012-03-09 01:51:51 +0000533 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000534}
535
Craig Topperce7167c2013-08-22 04:58:56 +0000536DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000537 NestedNameSpecifierLoc QualifierLoc,
Richard Smith715f7a12019-06-11 17:50:32 +0000538 SourceLocation TemplateKWLoc, ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000539 bool RefersToEnclosingVariableOrCapture,
Richard Smith715f7a12019-06-11 17:50:32 +0000540 SourceLocation NameLoc, QualType T,
541 ExprValueKind VK, NamedDecl *FoundD,
542 const TemplateArgumentListInfo *TemplateArgs,
543 NonOdrUseReason NOUR) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000544 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000545 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000546 DeclarationNameInfo(D->getDeclName(), NameLoc),
Richard Smith715f7a12019-06-11 17:50:32 +0000547 T, VK, FoundD, TemplateArgs, NOUR);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000548}
549
Craig Topperce7167c2013-08-22 04:58:56 +0000550DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000551 NestedNameSpecifierLoc QualifierLoc,
Richard Smith715f7a12019-06-11 17:50:32 +0000552 SourceLocation TemplateKWLoc, ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000553 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000554 const DeclarationNameInfo &NameInfo,
Richard Smith715f7a12019-06-11 17:50:32 +0000555 QualType T, ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000556 NamedDecl *FoundD,
Richard Smith715f7a12019-06-11 17:50:32 +0000557 const TemplateArgumentListInfo *TemplateArgs,
558 NonOdrUseReason NOUR) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000559 // Filter out cases where the found Decl is the same as the value refenenced.
560 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000561 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000562
James Y Knighte7d82282015-12-29 18:15:14 +0000563 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
564 std::size_t Size =
565 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
566 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
567 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
568 HasTemplateKWAndArgsInfo ? 1 : 0,
569 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000570
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000571 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000572 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Richard Smith715f7a12019-06-11 17:50:32 +0000573 RefersToEnclosingVariableOrCapture, NameInfo,
574 FoundD, TemplateArgs, T, VK, NOUR);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000575}
576
Craig Topperce7167c2013-08-22 04:58:56 +0000577DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000578 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000579 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000580 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000581 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000582 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
583 std::size_t Size =
584 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
585 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
586 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
587 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000588 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000589 return new (Mem) DeclRefExpr(EmptyShell());
590}
591
Stephen Kelly724e9e52018-08-09 20:05:03 +0000592SourceLocation DeclRefExpr::getBeginLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000593 if (hasQualifier())
594 return getQualifierLoc().getBeginLoc();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000595 return getNameInfo().getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000596}
Stephen Kelly02a67ba2018-08-09 20:05:47 +0000597SourceLocation DeclRefExpr::getEndLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000598 if (hasExplicitTemplateArgs())
599 return getRAngleLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000600 return getNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000601}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000602
Bruno Ricci17ff0262018-10-27 19:21:19 +0000603PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
Alexey Bataevec474782014-10-09 08:45:04 +0000604 StringLiteral *SL)
605 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
606 FNTy->isDependentType(), FNTy->isDependentType(),
607 FNTy->isInstantiationDependentType(),
Bruno Ricci17ff0262018-10-27 19:21:19 +0000608 /*ContainsUnexpandedParameterPack=*/false) {
609 PredefinedExprBits.Kind = IK;
610 assert((getIdentKind() == IK) &&
611 "IdentKind do not fit in PredefinedExprBitfields!");
612 bool HasFunctionName = SL != nullptr;
613 PredefinedExprBits.HasFunctionName = HasFunctionName;
614 PredefinedExprBits.Loc = L;
615 if (HasFunctionName)
616 setFunctionName(SL);
Alexey Bataevec474782014-10-09 08:45:04 +0000617}
618
Bruno Ricci17ff0262018-10-27 19:21:19 +0000619PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
620 : Expr(PredefinedExprClass, Empty) {
621 PredefinedExprBits.HasFunctionName = HasFunctionName;
622}
623
624PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
625 QualType FNTy, IdentKind IK,
626 StringLiteral *SL) {
627 bool HasFunctionName = SL != nullptr;
628 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
629 alignof(PredefinedExpr));
630 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
631}
632
633PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
634 bool HasFunctionName) {
635 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
636 alignof(PredefinedExpr));
637 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
638}
639
640StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
641 switch (IK) {
Alexey Bataevec474782014-10-09 08:45:04 +0000642 case Func:
643 return "__func__";
644 case Function:
645 return "__FUNCTION__";
646 case FuncDName:
647 return "__FUNCDNAME__";
648 case LFunction:
649 return "L__FUNCTION__";
650 case PrettyFunction:
651 return "__PRETTY_FUNCTION__";
652 case FuncSig:
653 return "__FUNCSIG__";
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000654 case LFuncSig:
655 return "L__FUNCSIG__";
Alexey Bataevec474782014-10-09 08:45:04 +0000656 case PrettyFunctionNoVirtual:
657 break;
658 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000659 llvm_unreachable("Unknown ident kind for PredefinedExpr");
Alexey Bataevec474782014-10-09 08:45:04 +0000660}
661
Anders Carlsson2fb08242009-09-08 18:24:21 +0000662// FIXME: Maybe this should use DeclPrinter with a special "print predefined
663// expr" policy instead.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000664std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000665 ASTContext &Context = CurrentDecl->getASTContext();
666
Bruno Ricci17ff0262018-10-27 19:21:19 +0000667 if (IK == PredefinedExpr::FuncDName) {
David Majnemerbed356a2013-11-06 23:31:56 +0000668 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000669 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000670 MC.reset(Context.createMangleContext());
671
672 if (MC->shouldMangleDeclName(ND)) {
673 SmallString<256> Buffer;
674 llvm::raw_svector_ostream Out(Buffer);
675 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
676 MC->mangleCXXCtor(CD, Ctor_Base, Out);
677 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
678 MC->mangleCXXDtor(DD, Dtor_Base, Out);
679 else
680 MC->mangleName(ND, Out);
681
David Majnemerbed356a2013-11-06 23:31:56 +0000682 if (!Buffer.empty() && Buffer.front() == '\01')
683 return Buffer.substr(1);
684 return Buffer.str();
685 } else
686 return ND->getIdentifier()->getName();
687 }
688 return "";
689 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000690 if (isa<BlockDecl>(CurrentDecl)) {
691 // For blocks we only emit something if it is enclosed in a function
692 // For top-level block we'd like to include the name of variable, but we
693 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000694 auto DC = CurrentDecl->getDeclContext();
695 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000696 return "";
697
698 SmallString<256> Buffer;
699 llvm::raw_svector_ostream Out(Buffer);
700 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
701 // For nested blocks, propagate up to the parent.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000702 Out << ComputeName(IK, DCBlock);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000703 else if (auto *DCDecl = dyn_cast<Decl>(DC))
Bruno Ricci17ff0262018-10-27 19:21:19 +0000704 Out << ComputeName(IK, DCDecl) << "_block_invoke";
Alexey Bataevec474782014-10-09 08:45:04 +0000705 return Out.str();
706 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000707 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000708 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
709 IK != FuncSig && IK != LFuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000710 return FD->getNameAsString();
711
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000712 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000713 llvm::raw_svector_ostream Out(Name);
714
715 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000716 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000717 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000718 if (MD->isStatic())
719 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000720 }
721
David Blaikiebbafb8a2012-03-11 07:00:24 +0000722 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000723 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000724 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000725
Douglas Gregor11a434a2012-04-10 20:14:15 +0000726 const FunctionDecl *Decl = FD;
727 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
728 Decl = Pattern;
729 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000730 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000731 if (FD->hasWrittenPrototype())
732 FT = dyn_cast<FunctionProtoType>(AFT);
733
Bruno Ricci17ff0262018-10-27 19:21:19 +0000734 if (IK == FuncSig || IK == LFuncSig) {
Richard Smith2f63d462017-01-09 21:40:40 +0000735 switch (AFT->getCallConv()) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000736 case CC_C: POut << "__cdecl "; break;
737 case CC_X86StdCall: POut << "__stdcall "; break;
738 case CC_X86FastCall: POut << "__fastcall "; break;
739 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000740 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000741 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000742 // Only bother printing the conventions that MSVC knows about.
743 default: break;
744 }
745 }
746
747 FD->printQualifiedName(POut, Policy);
748
Douglas Gregor11a434a2012-04-10 20:14:15 +0000749 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000750 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000751 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000752 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000753 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000754 }
755
756 if (FT->isVariadic()) {
757 if (FD->getNumParams()) POut << ", ";
758 POut << "...";
Bruno Ricci17ff0262018-10-27 19:21:19 +0000759 } else if ((IK == FuncSig || IK == LFuncSig ||
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000760 !Context.getLangOpts().CPlusPlus) &&
Richard Smithcf63b842017-01-09 22:16:16 +0000761 !Decl->getNumParams()) {
762 POut << "void";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000763 }
764 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000765 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000766
Sam Weinig4e83bd22009-12-27 01:38:20 +0000767 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Richard Smith2f63d462017-01-09 21:40:40 +0000768 assert(FT && "We must have a written prototype in this case.");
David Blaikief5697e52012-08-10 00:55:35 +0000769 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000770 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000771 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000772 POut << " volatile";
773 RefQualifierKind Ref = MD->getRefQualifier();
774 if (Ref == RQ_LValue)
775 POut << " &";
776 else if (Ref == RQ_RValue)
777 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000778 }
779
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000780 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000781 SpecsTy Specs;
782 const DeclContext *Ctx = FD->getDeclContext();
783 while (Ctx && isa<NamedDecl>(Ctx)) {
784 const ClassTemplateSpecializationDecl *Spec
785 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
786 if (Spec && !Spec->isExplicitSpecialization())
787 Specs.push_back(Spec);
788 Ctx = Ctx->getParent();
789 }
790
791 std::string TemplateParams;
792 llvm::raw_string_ostream TOut(TemplateParams);
793 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
794 I != E; ++I) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000795 const TemplateParameterList *Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000796 = (*I)->getSpecializedTemplate()->getTemplateParameters();
797 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
798 assert(Params->size() == Args.size());
799 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
800 StringRef Param = Params->getParam(i)->getName();
801 if (Param.empty()) continue;
802 TOut << Param << " = ";
803 Args.get(i).print(Policy, TOut);
804 TOut << ", ";
805 }
806 }
807
Fangrui Song6907ce22018-07-30 19:24:48 +0000808 FunctionTemplateSpecializationInfo *FSI
Douglas Gregor11a434a2012-04-10 20:14:15 +0000809 = FD->getTemplateSpecializationInfo();
810 if (FSI && !FSI->isExplicitSpecialization()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000811 const TemplateParameterList* Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000812 = FSI->getTemplate()->getTemplateParameters();
813 const TemplateArgumentList* Args = FSI->TemplateArguments;
814 assert(Params->size() == Args->size());
815 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
816 StringRef Param = Params->getParam(i)->getName();
817 if (Param.empty()) continue;
818 TOut << Param << " = ";
819 Args->get(i).print(Policy, TOut);
820 TOut << ", ";
821 }
822 }
823
824 TOut.flush();
825 if (!TemplateParams.empty()) {
826 // remove the trailing comma and space
827 TemplateParams.resize(TemplateParams.size() - 2);
828 POut << " [" << TemplateParams << "]";
829 }
830
831 POut.flush();
832
Benjamin Kramer90f54222013-08-21 11:45:27 +0000833 // Print "auto" for all deduced return types. This includes C++1y return
834 // type deduction and lambdas. For trailing return types resolve the
835 // decltype expression. Otherwise print the real type when this is
836 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000837 if (isa<CXXMethodDecl>(FD) &&
838 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000839 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000840 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
841 FT->getReturnType()
842 ->getAs<DecltypeType>()
843 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000844 .getAsStringInternal(Proto, Policy);
845 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000846 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000847
848 Out << Proto;
849
Anders Carlsson2fb08242009-09-08 18:24:21 +0000850 return Name.str().str();
851 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000852 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
853 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
854 // Skip to its enclosing function or method, but not its enclosing
855 // CapturedDecl.
856 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
857 const Decl *D = Decl::castFromDeclContext(DC);
Bruno Ricci17ff0262018-10-27 19:21:19 +0000858 return ComputeName(IK, D);
Wei Pan8d6b19a2013-08-26 14:27:34 +0000859 }
860 llvm_unreachable("CapturedDecl not inside a function or method");
861 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000862 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000863 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000864 llvm::raw_svector_ostream Out(Name);
865 Out << (MD->isInstanceMethod() ? '-' : '+');
866 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000867
868 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
869 // a null check to avoid a crash.
870 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000871 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000872
Anders Carlsson2fb08242009-09-08 18:24:21 +0000873 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000874 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000875 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000876
Anders Carlsson2fb08242009-09-08 18:24:21 +0000877 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000878 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000879 Out << ']';
880
Anders Carlsson2fb08242009-09-08 18:24:21 +0000881 return Name.str().str();
882 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000883 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000884 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
885 return "top level";
886 }
887 return "";
888}
889
Craig Topper37932912013-08-18 10:09:15 +0000890void APNumericStorage::setIntValue(const ASTContext &C,
891 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000892 if (hasAllocation())
893 C.Deallocate(pVal);
894
895 BitWidth = Val.getBitWidth();
896 unsigned NumWords = Val.getNumWords();
897 const uint64_t* Words = Val.getRawData();
898 if (NumWords > 1) {
899 pVal = new (C) uint64_t[NumWords];
900 std::copy(Words, Words + NumWords, pVal);
901 } else if (NumWords == 1)
902 VAL = Words[0];
903 else
904 VAL = 0;
905}
906
Craig Topper37932912013-08-18 10:09:15 +0000907IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000908 QualType type, SourceLocation l)
909 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
910 false, false),
911 Loc(l) {
912 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
913 assert(V.getBitWidth() == C.getIntWidth(type) &&
914 "Integer type is not the correct size for constant.");
915 setValue(C, V);
916}
917
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000918IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000919IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000920 QualType type, SourceLocation l) {
921 return new (C) IntegerLiteral(C, V, type, l);
922}
923
924IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000925IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000926 return new (C) IntegerLiteral(Empty);
927}
928
Leonard Chandb01c3a2018-06-20 17:19:40 +0000929FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
930 QualType type, SourceLocation l,
931 unsigned Scale)
932 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
933 false, false),
934 Loc(l), Scale(Scale) {
935 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
936 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
937 "Fixed point type is not the correct size for constant.");
938 setValue(C, V);
939}
940
941FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
942 const llvm::APInt &V,
943 QualType type,
944 SourceLocation l,
945 unsigned Scale) {
946 return new (C) FixedPointLiteral(C, V, type, l, Scale);
947}
948
949std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
950 // Currently the longest decimal number that can be printed is the max for an
951 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
952 // which is 43 characters.
953 SmallString<64> S;
954 FixedPointValueToString(
Leonard Chanc03642e2018-08-06 16:05:08 +0000955 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
Leonard Chandb01c3a2018-06-20 17:19:40 +0000956 return S.str();
957}
958
Craig Topper37932912013-08-18 10:09:15 +0000959FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000960 bool isexact, QualType Type, SourceLocation L)
961 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
962 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000963 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000964 FloatingLiteralBits.IsExact = isexact;
965 setValue(C, V);
966}
967
Craig Topper37932912013-08-18 10:09:15 +0000968FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000969 : Expr(FloatingLiteralClass, Empty) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000970 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000971 FloatingLiteralBits.IsExact = false;
972}
973
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000974FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000975FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000976 bool isexact, QualType Type, SourceLocation L) {
977 return new (C) FloatingLiteral(C, V, isexact, Type, L);
978}
979
980FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000981FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000982 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000983}
984
Chris Lattnera0173132008-06-07 22:13:43 +0000985/// getValueAsApproximateDouble - This returns the value as an inaccurate
986/// double. Note that this may cause loss of precision, but is useful for
987/// debugging dumps, etc.
988double FloatingLiteral::getValueAsApproximateDouble() const {
989 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000990 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000991 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
Dale Johannesenc48814b2008-10-09 23:02:32 +0000992 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000993 return V.convertToDouble();
994}
995
Bruno Ricciaf214882018-11-15 16:42:14 +0000996unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
997 StringKind SK) {
998 unsigned CharByteWidth = 0;
999 switch (SK) {
1000 case Ascii:
1001 case UTF8:
1002 CharByteWidth = Target.getCharWidth();
1003 break;
1004 case Wide:
1005 CharByteWidth = Target.getWCharWidth();
1006 break;
1007 case UTF16:
1008 CharByteWidth = Target.getChar16Width();
1009 break;
1010 case UTF32:
1011 CharByteWidth = Target.getChar32Width();
1012 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001013 }
1014 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1015 CharByteWidth /= 8;
Bruno Ricciaf214882018-11-15 16:42:14 +00001016 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1017 "The only supported character byte widths are 1,2 and 4!");
Eli Friedmanfcec6302011-11-01 02:23:42 +00001018 return CharByteWidth;
1019}
1020
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001021StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1022 StringKind Kind, bool Pascal, QualType Ty,
1023 const SourceLocation *Loc,
1024 unsigned NumConcatenated)
1025 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1026 false) {
1027 assert(Ctx.getAsConstantArrayType(Ty) &&
Benjamin Kramercdac7612014-02-25 12:26:20 +00001028 "StringLiteral must be of constant array type!");
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001029 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1030 unsigned ByteLength = Str.size();
1031 assert((ByteLength % CharByteWidth == 0) &&
1032 "The size of the data must be a multiple of CharByteWidth!");
Benjamin Kramercdac7612014-02-25 12:26:20 +00001033
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001034 // Avoid the expensive division. The compiler should be able to figure it
1035 // out by itself. However as of clang 7, even with the appropriate
1036 // llvm_unreachable added just here, it is not able to do so.
1037 unsigned Length;
1038 switch (CharByteWidth) {
1039 case 1:
1040 Length = ByteLength;
1041 break;
1042 case 2:
1043 Length = ByteLength / 2;
1044 break;
1045 case 4:
1046 Length = ByteLength / 4;
1047 break;
1048 default:
1049 llvm_unreachable("Unsupported character width!");
1050 }
Mike Stump11289f42009-09-09 15:08:12 +00001051
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001052 StringLiteralBits.Kind = Kind;
1053 StringLiteralBits.CharByteWidth = CharByteWidth;
1054 StringLiteralBits.IsPascal = Pascal;
1055 StringLiteralBits.NumConcatenated = NumConcatenated;
1056 *getTrailingObjects<unsigned>() = Length;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001057
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001058 // Initialize the trailing array of SourceLocation.
1059 // This is safe since SourceLocation is POD-like.
1060 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1061 NumConcatenated * sizeof(SourceLocation));
Chris Lattnerd3e98952006-10-06 05:22:26 +00001062
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001063 // Initialize the trailing array of char holding the string data.
1064 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
Chris Lattner630970d2009-02-18 05:49:11 +00001065}
1066
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001067StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1068 unsigned Length, unsigned CharByteWidth)
1069 : Expr(StringLiteralClass, Empty) {
1070 StringLiteralBits.CharByteWidth = CharByteWidth;
1071 StringLiteralBits.NumConcatenated = NumConcatenated;
1072 *getTrailingObjects<unsigned>() = Length;
1073}
1074
1075StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1076 StringKind Kind, bool Pascal, QualType Ty,
1077 const SourceLocation *Loc,
1078 unsigned NumConcatenated) {
1079 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1080 1, NumConcatenated, Str.size()),
1081 alignof(StringLiteral));
1082 return new (Mem)
1083 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1084}
1085
1086StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1087 unsigned NumConcatenated,
1088 unsigned Length,
1089 unsigned CharByteWidth) {
1090 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1091 1, NumConcatenated, Length * CharByteWidth),
1092 alignof(StringLiteral));
1093 return new (Mem)
1094 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
Douglas Gregor958dfc92009-04-15 16:35:07 +00001095}
1096
Alexander Kornienko540bacb2013-02-01 12:35:51 +00001097void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +00001098 switch (getKind()) {
1099 case Ascii: break; // no prefix.
1100 case Wide: OS << 'L'; break;
1101 case UTF8: OS << "u8"; break;
1102 case UTF16: OS << 'u'; break;
1103 case UTF32: OS << 'U'; break;
1104 }
1105 OS << '"';
1106 static const char Hex[] = "0123456789ABCDEF";
1107
1108 unsigned LastSlashX = getLength();
1109 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1110 switch (uint32_t Char = getCodeUnit(I)) {
1111 default:
1112 // FIXME: Convert UTF-8 back to codepoints before rendering.
1113
1114 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1115 // Leave invalid surrogates alone; we'll use \x for those.
Fangrui Song6907ce22018-07-30 19:24:48 +00001116 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
Richard Trieudc355912012-06-13 20:25:24 +00001117 Char <= 0xdbff) {
1118 uint32_t Trail = getCodeUnit(I + 1);
1119 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1120 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1121 ++I;
1122 }
1123 }
1124
1125 if (Char > 0xff) {
1126 // If this is a wide string, output characters over 0xff using \x
1127 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1128 // codepoint: use \x escapes for invalid codepoints.
1129 if (getKind() == Wide ||
1130 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1131 // FIXME: Is this the best way to print wchar_t?
1132 OS << "\\x";
1133 int Shift = 28;
1134 while ((Char >> Shift) == 0)
1135 Shift -= 4;
1136 for (/**/; Shift >= 0; Shift -= 4)
1137 OS << Hex[(Char >> Shift) & 15];
1138 LastSlashX = I;
1139 break;
1140 }
1141
1142 if (Char > 0xffff)
1143 OS << "\\U00"
1144 << Hex[(Char >> 20) & 15]
1145 << Hex[(Char >> 16) & 15];
1146 else
1147 OS << "\\u";
1148 OS << Hex[(Char >> 12) & 15]
1149 << Hex[(Char >> 8) & 15]
1150 << Hex[(Char >> 4) & 15]
1151 << Hex[(Char >> 0) & 15];
1152 break;
1153 }
1154
1155 // If we used \x... for the previous character, and this character is a
1156 // hexadecimal digit, prevent it being slurped as part of the \x.
1157 if (LastSlashX + 1 == I) {
1158 switch (Char) {
1159 case '0': case '1': case '2': case '3': case '4':
1160 case '5': case '6': case '7': case '8': case '9':
1161 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1162 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1163 OS << "\"\"";
1164 }
1165 }
1166
1167 assert(Char <= 0xff &&
1168 "Characters above 0xff should already have been handled.");
1169
Jordan Rosea7d03842013-02-08 22:30:41 +00001170 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +00001171 OS << (char)Char;
1172 else // Output anything hard as an octal escape.
1173 OS << '\\'
1174 << (char)('0' + ((Char >> 6) & 7))
1175 << (char)('0' + ((Char >> 3) & 7))
1176 << (char)('0' + ((Char >> 0) & 7));
1177 break;
1178 // Handle some common non-printable cases to make dumps prettier.
1179 case '\\': OS << "\\\\"; break;
1180 case '"': OS << "\\\""; break;
Richard Trieudc355912012-06-13 20:25:24 +00001181 case '\a': OS << "\\a"; break;
1182 case '\b': OS << "\\b"; break;
Benjamin Kramer60a53d52016-11-24 09:41:33 +00001183 case '\f': OS << "\\f"; break;
1184 case '\n': OS << "\\n"; break;
1185 case '\r': OS << "\\r"; break;
1186 case '\t': OS << "\\t"; break;
1187 case '\v': OS << "\\v"; break;
Richard Trieudc355912012-06-13 20:25:24 +00001188 }
1189 }
1190 OS << '"';
1191}
1192
Chris Lattnere925d612010-11-17 07:37:15 +00001193/// getLocationOfByte - Return a source location that points to the specified
1194/// byte of this string literal.
1195///
1196/// Strings are amazingly complex. They can be formed from multiple tokens and
1197/// can have escape sequences in them in addition to the usual trigraph and
1198/// escaped newline business. This routine handles this complexity.
1199///
Richard Smithefb116f2015-12-10 01:11:47 +00001200/// The *StartToken sets the first token to be searched in this function and
1201/// the *StartTokenByteOffset is the byte offset of the first token. Before
1202/// returning, it updates the *StartToken to the TokNo of the token being found
1203/// and sets *StartTokenByteOffset to the byte offset of the token in the
1204/// string.
1205/// Using these two parameters can reduce the time complexity from O(n^2) to
1206/// O(n) if one wants to get the location of byte for all the tokens in a
1207/// string.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001208///
Richard Smithefb116f2015-12-10 01:11:47 +00001209SourceLocation
1210StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1211 const LangOptions &Features,
1212 const TargetInfo &Target, unsigned *StartToken,
1213 unsigned *StartTokenByteOffset) const {
Bruno Ricciaf214882018-11-15 16:42:14 +00001214 assert((getKind() == StringLiteral::Ascii ||
1215 getKind() == StringLiteral::UTF8) &&
Richard Smith4060f772012-06-13 05:37:23 +00001216 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001217
Chris Lattnere925d612010-11-17 07:37:15 +00001218 // Loop over all of the tokens in this string until we find the one that
1219 // contains the byte we're looking for.
1220 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001221 unsigned StringOffset = 0;
1222 if (StartToken)
1223 TokNo = *StartToken;
1224 if (StartTokenByteOffset) {
1225 StringOffset = *StartTokenByteOffset;
1226 ByteNo -= StringOffset;
1227 }
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001228 while (1) {
Chris Lattnere925d612010-11-17 07:37:15 +00001229 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1230 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
Fangrui Song6907ce22018-07-30 19:24:48 +00001231
Chris Lattnere925d612010-11-17 07:37:15 +00001232 // Get the spelling of the string so that we can get the data that makes up
1233 // the string literal, not the identifier for the macro it is potentially
1234 // expanded through.
1235 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001236
Chris Lattnere925d612010-11-17 07:37:15 +00001237 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001238 std::pair<FileID, unsigned> LocInfo =
1239 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001240 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001241 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001242 if (Invalid) {
1243 if (StartTokenByteOffset != nullptr)
1244 *StartTokenByteOffset = StringOffset;
1245 if (StartToken != nullptr)
1246 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001247 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001248 }
1249
Chris Lattnere925d612010-11-17 07:37:15 +00001250 const char *StrData = Buffer.data()+LocInfo.second;
Fangrui Song6907ce22018-07-30 19:24:48 +00001251
Chris Lattnere925d612010-11-17 07:37:15 +00001252 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001253 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1254 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001255 Token TheTok;
1256 TheLexer.LexFromRawLexer(TheTok);
Fangrui Song6907ce22018-07-30 19:24:48 +00001257
Chris Lattnere925d612010-11-17 07:37:15 +00001258 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001259 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001260 unsigned TokNumBytes = SLP.GetStringLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00001261
Chris Lattnere925d612010-11-17 07:37:15 +00001262 // If the byte is in this token, return the location of the byte.
1263 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001264 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001265 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1266
Chris Lattnere925d612010-11-17 07:37:15 +00001267 // Now that we know the offset of the token in the spelling, use the
1268 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001269 if (StartTokenByteOffset != nullptr)
1270 *StartTokenByteOffset = StringOffset;
1271 if (StartToken != nullptr)
1272 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001273 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1274 }
Richard Smithefb116f2015-12-10 01:11:47 +00001275
Chris Lattnere925d612010-11-17 07:37:15 +00001276 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001277 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001278 ++TokNo;
1279 ByteNo -= TokNumBytes;
1280 }
1281}
1282
Chris Lattner1b926492006-08-23 06:42:10 +00001283/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1284/// corresponds to, e.g. "sizeof" or "[pre]++".
Bruno Ricci3dfcb842018-11-13 21:33:22 +00001285StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1286 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001287#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1288#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001289 }
David Blaikief47fa302012-01-17 02:30:50 +00001290 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001291}
1292
John McCalle3027922010-08-25 11:45:40 +00001293UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001294UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1295 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001296 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001297 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1298 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1299 case OO_Amp: return UO_AddrOf;
1300 case OO_Star: return UO_Deref;
1301 case OO_Plus: return UO_Plus;
1302 case OO_Minus: return UO_Minus;
1303 case OO_Tilde: return UO_Not;
1304 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001305 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001306 }
1307}
1308
1309OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1310 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001311 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1312 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1313 case UO_AddrOf: return OO_Amp;
1314 case UO_Deref: return OO_Star;
1315 case UO_Plus: return OO_Plus;
1316 case UO_Minus: return OO_Minus;
1317 case UO_Not: return OO_Tilde;
1318 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001319 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001320 default: return OO_None;
1321 }
1322}
1323
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001324
Chris Lattner0eedafe2006-08-24 04:56:27 +00001325//===----------------------------------------------------------------------===//
1326// Postfix Operators.
1327//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001328
Bruno Riccic5885cf2018-12-21 15:20:32 +00001329CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1330 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1331 SourceLocation RParenLoc, unsigned MinNumArgs,
1332 ADLCallKind UsesADL)
1333 : Expr(SC, Ty, VK, OK_Ordinary, Fn->isTypeDependent(),
1334 Fn->isValueDependent(), Fn->isInstantiationDependent(),
1335 Fn->containsUnexpandedParameterPack()),
1336 RParenLoc(RParenLoc) {
1337 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1338 unsigned NumPreArgs = PreArgs.size();
1339 CallExprBits.NumPreArgs = NumPreArgs;
1340 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1341
1342 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1343 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1344 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1345 "OffsetToTrailingObjects overflow!");
1346
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001347 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1348
Bruno Riccic5885cf2018-12-21 15:20:32 +00001349 setCallee(Fn);
1350 for (unsigned I = 0; I != NumPreArgs; ++I) {
1351 updateDependenciesFromArg(PreArgs[I]);
1352 setPreArg(I, PreArgs[I]);
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001353 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00001354 for (unsigned I = 0; I != Args.size(); ++I) {
1355 updateDependenciesFromArg(Args[I]);
1356 setArg(I, Args[I]);
Douglas Gregora6e053e2010-12-15 01:34:56 +00001357 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00001358 for (unsigned I = Args.size(); I != NumArgs; ++I) {
1359 setArg(I, nullptr);
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001360 }
Douglas Gregor993603d2008-11-14 16:09:21 +00001361}
Nate Begeman1e36a852008-01-17 17:46:27 +00001362
Bruno Riccic5885cf2018-12-21 15:20:32 +00001363CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1364 EmptyShell Empty)
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001365 : Expr(SC, Empty), NumArgs(NumArgs) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001366 CallExprBits.NumPreArgs = NumPreArgs;
Bruno Riccic5885cf2018-12-21 15:20:32 +00001367 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1368
1369 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1370 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1371 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1372 "OffsetToTrailingObjects overflow!");
Douglas Gregore20a2e52009-04-15 17:43:59 +00001373}
1374
Bruno Riccic5885cf2018-12-21 15:20:32 +00001375CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1376 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1377 SourceLocation RParenLoc, unsigned MinNumArgs,
1378 ADLCallKind UsesADL) {
1379 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1380 unsigned SizeOfTrailingObjects =
1381 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1382 void *Mem =
1383 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1384 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1385 RParenLoc, MinNumArgs, UsesADL);
1386}
1387
1388CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1389 ExprValueKind VK, SourceLocation RParenLoc,
1390 ADLCallKind UsesADL) {
1391 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1392 "Misaligned memory in CallExpr::CreateTemporary!");
1393 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1394 VK, RParenLoc, /*MinNumArgs=*/0, UsesADL);
1395}
1396
1397CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1398 EmptyShell Empty) {
1399 unsigned SizeOfTrailingObjects =
1400 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1401 void *Mem =
1402 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1403 return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1404}
1405
1406unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1407 switch (SC) {
1408 case CallExprClass:
1409 return sizeof(CallExpr);
1410 case CXXOperatorCallExprClass:
1411 return sizeof(CXXOperatorCallExpr);
1412 case CXXMemberCallExprClass:
1413 return sizeof(CXXMemberCallExpr);
1414 case UserDefinedLiteralClass:
1415 return sizeof(UserDefinedLiteral);
1416 case CUDAKernelCallExprClass:
1417 return sizeof(CUDAKernelCallExpr);
1418 default:
1419 llvm_unreachable("unexpected class deriving from CallExpr!");
1420 }
1421}
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001422
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001423void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1424 if (Arg->isTypeDependent())
1425 ExprBits.TypeDependent = true;
1426 if (Arg->isValueDependent())
1427 ExprBits.ValueDependent = true;
1428 if (Arg->isInstantiationDependent())
1429 ExprBits.InstantiationDependent = true;
1430 if (Arg->containsUnexpandedParameterPack())
1431 ExprBits.ContainsUnexpandedParameterPack = true;
1432}
1433
John McCallb92ab1a2016-10-26 23:46:34 +00001434Decl *Expr::getReferencedDeclOfCallee() {
1435 Expr *CEE = IgnoreParenImpCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00001436
Douglas Gregore0e96302011-09-06 21:41:04 +00001437 while (SubstNonTypeTemplateParmExpr *NTTP
1438 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1439 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1440 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001441
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001442 // If we're calling a dereference, look at the pointer instead.
1443 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1444 if (BO->isPtrMemOp())
1445 CEE = BO->getRHS()->IgnoreParenCasts();
1446 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1447 if (UO->getOpcode() == UO_Deref)
1448 CEE = UO->getSubExpr()->IgnoreParenCasts();
1449 }
Chris Lattner52301912009-07-17 15:46:27 +00001450 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001451 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001452 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1453 return ME->getMemberDecl();
Yaxun Liud83c7402019-02-26 16:20:41 +00001454 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1455 return BE->getBlockDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001456
Craig Topper36250ad2014-05-12 05:36:57 +00001457 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001458}
1459
Alp Tokera724cff2013-12-28 21:59:02 +00001460/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001461/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001462unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001463 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001464 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001465 // ImplicitCastExpr.
1466 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1467 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001468 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001469
Steve Narofff6e3b3292008-01-31 01:07:12 +00001470 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1471 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001472 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001473
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001474 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1475 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001476 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001477
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001478 if (!FDecl->getIdentifier())
1479 return 0;
1480
Douglas Gregor15fc9562009-09-12 00:22:50 +00001481 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001482}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001483
Scott Douglass503fc392015-06-10 13:53:15 +00001484bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001485 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001486 return Ctx.BuiltinInfo.isUnevaluated(BI);
1487 return false;
1488}
1489
David Majnemerced8bdf2015-02-25 17:36:15 +00001490QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1491 const Expr *Callee = getCallee();
1492 QualType CalleeType = Callee->getType();
1493 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001494 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001495 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001496 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001497 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1498 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1499 return Ctx.VoidTy;
1500
John McCall0009fcc2011-04-26 20:42:42 +00001501 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001502 CalleeType = Expr::findBoundMemberType(Callee);
1503 }
1504
John McCall0009fcc2011-04-26 20:42:42 +00001505 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001506 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001507}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001508
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00001509const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1510 // If the return type is a struct, union, or enum that is marked nodiscard,
1511 // then return the return type attribute.
1512 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1513 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1514 return A;
1515
1516 // Otherwise, see if the callee is marked nodiscard and return that attribute
1517 // instead.
1518 const Decl *D = getCalleeDecl();
1519 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1520}
1521
Stephen Kelly724e9e52018-08-09 20:05:03 +00001522SourceLocation CallExpr::getBeginLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001523 if (isa<CXXOperatorCallExpr>(this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001524 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001525
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001526 SourceLocation begin = getCallee()->getBeginLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001527 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001528 begin = getArg(0)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001529 return begin;
1530}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001531SourceLocation CallExpr::getEndLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001532 if (isa<CXXOperatorCallExpr>(this))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001533 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001534
1535 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001536 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001537 end = getArg(getNumArgs() - 1)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001538 return end;
1539}
John McCall701417a2011-02-21 06:23:05 +00001540
Craig Topper37932912013-08-18 10:09:15 +00001541OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001542 SourceLocation OperatorLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001543 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001544 ArrayRef<OffsetOfNode> comps,
1545 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001546 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001547 void *Mem = C.Allocate(
1548 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001549
Benjamin Kramerc215e762012-08-24 11:54:20 +00001550 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1551 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001552}
1553
Craig Topper37932912013-08-18 10:09:15 +00001554OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001555 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001556 void *Mem =
1557 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001558 return new (Mem) OffsetOfExpr(numComps, numExprs);
1559}
1560
Craig Topper37932912013-08-18 10:09:15 +00001561OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001562 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001563 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001564 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001565 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
Fangrui Song6907ce22018-07-30 19:24:48 +00001566 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001567 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001568 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001569 tsi->getType()->containsUnexpandedParameterPack()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001570 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001571 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001572{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001573 for (unsigned i = 0; i != comps.size(); ++i) {
1574 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001575 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001576
Benjamin Kramerc215e762012-08-24 11:54:20 +00001577 for (unsigned i = 0; i != exprs.size(); ++i) {
1578 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001579 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001580 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001581 ExprBits.ContainsUnexpandedParameterPack = true;
1582
Benjamin Kramerc215e762012-08-24 11:54:20 +00001583 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001584 }
1585}
1586
James Y Knight7281c352015-12-29 22:31:18 +00001587IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001588 assert(getKind() == Field || getKind() == Identifier);
1589 if (getKind() == Field)
1590 return getField()->getIdentifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00001591
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001592 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001593}
1594
David Majnemer10fd83d2015-01-15 10:04:14 +00001595UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1596 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1597 SourceLocation op, SourceLocation rp)
1598 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1599 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1600 // Value-dependent if the argument is type-dependent.
1601 E->isTypeDependent(), E->isInstantiationDependent(),
1602 E->containsUnexpandedParameterPack()),
1603 OpLoc(op), RParenLoc(rp) {
1604 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1605 UnaryExprOrTypeTraitExprBits.IsType = false;
1606 Argument.Ex = E;
1607
1608 // Check to see if we are in the situation where alignof(decl) should be
1609 // dependent because decl's alignment is dependent.
Richard Smith6822bd72018-10-26 19:26:45 +00001610 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
David Majnemer10fd83d2015-01-15 10:04:14 +00001611 if (!isValueDependent() || !isInstantiationDependent()) {
1612 E = E->IgnoreParens();
1613
1614 const ValueDecl *D = nullptr;
1615 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1616 D = DRE->getDecl();
1617 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1618 D = ME->getMemberDecl();
1619
1620 if (D) {
1621 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1622 if (I->isAlignmentDependent()) {
1623 setValueDependent(true);
1624 setInstantiationDependent(true);
1625 break;
1626 }
1627 }
1628 }
1629 }
1630 }
1631}
1632
Richard Smithdcf17de2019-06-06 23:24:15 +00001633MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1634 ValueDecl *MemberDecl,
1635 const DeclarationNameInfo &NameInfo, QualType T,
Richard Smith1bbad592019-06-11 17:50:36 +00001636 ExprValueKind VK, ExprObjectKind OK,
1637 NonOdrUseReason NOUR)
Richard Smithdcf17de2019-06-06 23:24:15 +00001638 : Expr(MemberExprClass, T, VK, OK, Base->isTypeDependent(),
1639 Base->isValueDependent(), Base->isInstantiationDependent(),
1640 Base->containsUnexpandedParameterPack()),
1641 Base(Base), MemberDecl(MemberDecl), MemberDNLoc(NameInfo.getInfo()),
1642 MemberLoc(NameInfo.getLoc()) {
1643 assert(!NameInfo.getName() ||
1644 MemberDecl->getDeclName() == NameInfo.getName());
1645 MemberExprBits.IsArrow = IsArrow;
1646 MemberExprBits.HasQualifierOrFoundDecl = false;
1647 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1648 MemberExprBits.HadMultipleCandidates = false;
Richard Smith1bbad592019-06-11 17:50:36 +00001649 MemberExprBits.NonOdrUseReason = NOUR;
Richard Smithdcf17de2019-06-06 23:24:15 +00001650 MemberExprBits.OperatorLoc = OperatorLoc;
1651}
1652
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001653MemberExpr *MemberExpr::Create(
Richard Smithdcf17de2019-06-06 23:24:15 +00001654 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001655 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
Richard Smithdcf17de2019-06-06 23:24:15 +00001656 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1657 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
Richard Smith1bbad592019-06-11 17:50:36 +00001658 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
Richard Smithdcf17de2019-06-06 23:24:15 +00001659 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1660 FoundDecl.getAccess() != MemberDecl->getAccess();
1661 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
James Y Knighte7d82282015-12-29 18:15:14 +00001662 std::size_t Size =
1663 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
Richard Smithdcf17de2019-06-06 23:24:15 +00001664 TemplateArgumentLoc>(
1665 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1666 TemplateArgs ? TemplateArgs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001667
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001668 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Richard Smith1bbad592019-06-11 17:50:36 +00001669 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1670 NameInfo, T, VK, OK, NOUR);
John McCall16df1e52010-03-30 21:47:33 +00001671
Richard Smithdcf17de2019-06-06 23:24:15 +00001672 if (HasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001673 // FIXME: Wrong. We should be looking at the member declaration we found.
1674 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001675 E->setValueDependent(true);
1676 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001677 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001678 }
1679 else if (QualifierLoc &&
1680 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001681 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001682
Bruno Ricci4c742532018-11-15 13:56:22 +00001683 E->MemberExprBits.HasQualifierOrFoundDecl = true;
John McCall16df1e52010-03-30 21:47:33 +00001684
James Y Knighte7d82282015-12-29 18:15:14 +00001685 MemberExprNameQualifier *NQ =
1686 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001687 NQ->QualifierLoc = QualifierLoc;
Richard Smithdcf17de2019-06-06 23:24:15 +00001688 NQ->FoundDecl = FoundDecl;
John McCall16df1e52010-03-30 21:47:33 +00001689 }
1690
Bruno Ricci4c742532018-11-15 13:56:22 +00001691 E->MemberExprBits.HasTemplateKWAndArgsInfo =
Richard Smithdcf17de2019-06-06 23:24:15 +00001692 TemplateArgs || TemplateKWLoc.isValid();
Abramo Bagnara7945c982012-01-27 09:46:47 +00001693
Richard Smithdcf17de2019-06-06 23:24:15 +00001694 if (TemplateArgs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001695 bool Dependent = false;
1696 bool InstantiationDependent = false;
1697 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001698 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
Richard Smithdcf17de2019-06-06 23:24:15 +00001699 TemplateKWLoc, *TemplateArgs,
1700 E->getTrailingObjects<TemplateArgumentLoc>(), Dependent,
1701 InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001702 if (InstantiationDependent)
1703 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001704 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001705 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1706 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001707 }
1708
1709 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001710}
1711
Richard Smithdcf17de2019-06-06 23:24:15 +00001712MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1713 bool HasQualifier, bool HasFoundDecl,
1714 bool HasTemplateKWAndArgsInfo,
1715 unsigned NumTemplateArgs) {
1716 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1717 "template args but no template arg info?");
1718 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1719 std::size_t Size =
1720 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1721 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1722 HasTemplateKWAndArgsInfo ? 1 : 0,
1723 NumTemplateArgs);
1724 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1725 return new (Mem) MemberExpr(EmptyShell());
1726}
1727
Stephen Kelly724e9e52018-08-09 20:05:03 +00001728SourceLocation MemberExpr::getBeginLoc() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001729 if (isImplicitAccess()) {
1730 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001731 return getQualifierLoc().getBeginLoc();
1732 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001733 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001734
Daniel Dunbarb507f272012-03-09 15:39:15 +00001735 // FIXME: We don't want this to happen. Rather, we should be able to
1736 // detect all kinds of implicit accesses more cleanly.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001737 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001738 if (BaseStartLoc.isValid())
1739 return BaseStartLoc;
1740 return MemberLoc;
1741}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001742SourceLocation MemberExpr::getEndLoc() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001743 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001744 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001745 EndLoc = getRAngleLoc();
1746 else if (EndLoc.isInvalid())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001747 EndLoc = getBase()->getEndLoc();
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001748 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001749}
1750
Alp Tokerc1086762013-12-07 13:51:35 +00001751bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001752 switch (getCastKind()) {
1753 case CK_DerivedToBase:
1754 case CK_UncheckedDerivedToBase:
1755 case CK_DerivedToBaseMemberPointer:
1756 case CK_BaseToDerived:
1757 case CK_BaseToDerivedMemberPointer:
1758 assert(!path_empty() && "Cast kind should have a base path!");
1759 break;
1760
1761 case CK_CPointerToObjCPointerCast:
1762 assert(getType()->isObjCObjectPointerType());
1763 assert(getSubExpr()->getType()->isPointerType());
1764 goto CheckNoBasePath;
1765
1766 case CK_BlockPointerToObjCPointerCast:
1767 assert(getType()->isObjCObjectPointerType());
1768 assert(getSubExpr()->getType()->isBlockPointerType());
1769 goto CheckNoBasePath;
1770
John McCallc62bb392012-02-15 01:22:51 +00001771 case CK_ReinterpretMemberPointer:
1772 assert(getType()->isMemberPointerType());
1773 assert(getSubExpr()->getType()->isMemberPointerType());
1774 goto CheckNoBasePath;
1775
John McCall9320b872011-09-09 05:25:32 +00001776 case CK_BitCast:
1777 // Arbitrary casts to C pointer types count as bitcasts.
1778 // Otherwise, we should only have block and ObjC pointer casts
1779 // here if they stay within the type kind.
1780 if (!getType()->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001781 assert(getType()->isObjCObjectPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001782 getSubExpr()->getType()->isObjCObjectPointerType());
Fangrui Song6907ce22018-07-30 19:24:48 +00001783 assert(getType()->isBlockPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001784 getSubExpr()->getType()->isBlockPointerType());
1785 }
1786 goto CheckNoBasePath;
1787
1788 case CK_AnyPointerToBlockPointerCast:
1789 assert(getType()->isBlockPointerType());
1790 assert(getSubExpr()->getType()->isAnyPointerType() &&
1791 !getSubExpr()->getType()->isBlockPointerType());
1792 goto CheckNoBasePath;
1793
Douglas Gregored90df32012-02-22 05:02:47 +00001794 case CK_CopyAndAutoreleaseBlockObject:
1795 assert(getType()->isBlockPointerType());
1796 assert(getSubExpr()->getType()->isBlockPointerType());
1797 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001798
1799 case CK_FunctionToPointerDecay:
1800 assert(getType()->isPointerType());
1801 assert(getSubExpr()->getType()->isFunctionType());
1802 goto CheckNoBasePath;
1803
Anastasia Stulova04307942018-11-16 16:22:56 +00001804 case CK_AddressSpaceConversion: {
1805 auto Ty = getType();
1806 auto SETy = getSubExpr()->getType();
1807 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
Anastasia Stulova094c7262019-04-04 10:48:36 +00001808 if (/*isRValue()*/ !Ty->getPointeeType().isNull()) {
Anastasia Stulova04307942018-11-16 16:22:56 +00001809 Ty = Ty->getPointeeType();
Anastasia Stulova04307942018-11-16 16:22:56 +00001810 SETy = SETy->getPointeeType();
Anastasia Stulovad1986d12019-01-14 11:44:22 +00001811 }
Anastasia Stulova04307942018-11-16 16:22:56 +00001812 assert(!Ty.isNull() && !SETy.isNull() &&
1813 Ty.getAddressSpace() != SETy.getAddressSpace());
1814 goto CheckNoBasePath;
1815 }
John McCall9320b872011-09-09 05:25:32 +00001816 // These should not have an inheritance path.
1817 case CK_Dynamic:
1818 case CK_ToUnion:
1819 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001820 case CK_NullToMemberPointer:
1821 case CK_NullToPointer:
1822 case CK_ConstructorConversion:
1823 case CK_IntegralToPointer:
1824 case CK_PointerToIntegral:
1825 case CK_ToVoid:
1826 case CK_VectorSplat:
1827 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001828 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001829 case CK_IntegralToFloating:
1830 case CK_FloatingToIntegral:
1831 case CK_FloatingCast:
1832 case CK_ObjCObjectLValueCast:
1833 case CK_FloatingRealToComplex:
1834 case CK_FloatingComplexToReal:
1835 case CK_FloatingComplexCast:
1836 case CK_FloatingComplexToIntegralComplex:
1837 case CK_IntegralRealToComplex:
1838 case CK_IntegralComplexToReal:
1839 case CK_IntegralComplexCast:
1840 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001841 case CK_ARCProduceObject:
1842 case CK_ARCConsumeObject:
1843 case CK_ARCReclaimReturnedObject:
1844 case CK_ARCExtendBlockObject:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001845 case CK_ZeroToOCLOpaqueType:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001846 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00001847 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +00001848 case CK_FixedPointToIntegral:
1849 case CK_IntegralToFixedPoint:
John McCall9320b872011-09-09 05:25:32 +00001850 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1851 goto CheckNoBasePath;
1852
1853 case CK_Dependent:
1854 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001855 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001856 case CK_AtomicToNonAtomic:
1857 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001858 case CK_PointerToBoolean:
1859 case CK_IntegralToBoolean:
1860 case CK_FloatingToBoolean:
1861 case CK_MemberPointerToBoolean:
1862 case CK_FloatingComplexToBoolean:
1863 case CK_IntegralComplexToBoolean:
1864 case CK_LValueBitCast: // -> bool&
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00001865 case CK_LValueToRValueBitCast:
John McCall9320b872011-09-09 05:25:32 +00001866 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001867 case CK_BuiltinFnToFnPtr:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001868 case CK_FixedPointToBoolean:
John McCall9320b872011-09-09 05:25:32 +00001869 CheckNoBasePath:
1870 assert(path_empty() && "Cast kind should not have a base path!");
1871 break;
1872 }
Alp Tokerc1086762013-12-07 13:51:35 +00001873 return true;
John McCall9320b872011-09-09 05:25:32 +00001874}
1875
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001876const char *CastExpr::getCastKindName(CastKind CK) {
1877 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001878#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1879#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001880 }
John McCallc5e62b42010-11-13 09:02:35 +00001881 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001882}
1883
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001884namespace {
Richard Smith1ef75542018-06-27 20:30:34 +00001885 const Expr *skipImplicitTemporary(const Expr *E) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001886 // Skip through reference binding to temporary.
Richard Smith1ef75542018-06-27 20:30:34 +00001887 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1888 E = Materialize->GetTemporaryExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001889
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001890 // Skip any temporary bindings; they're implicit.
Richard Smith1ef75542018-06-27 20:30:34 +00001891 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1892 E = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001893
Richard Smith1ef75542018-06-27 20:30:34 +00001894 return E;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001895 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001896}
1897
Douglas Gregord196a582009-12-14 19:27:10 +00001898Expr *CastExpr::getSubExprAsWritten() {
Richard Smith1ef75542018-06-27 20:30:34 +00001899 const Expr *SubExpr = nullptr;
1900 const CastExpr *E = this;
Douglas Gregord196a582009-12-14 19:27:10 +00001901 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001902 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001903
Douglas Gregord196a582009-12-14 19:27:10 +00001904 // Conversions by constructor and conversion functions have a
1905 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001906 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001907 SubExpr =
1908 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001909 else if (E->getCastKind() == CK_UserDefinedConversion) {
1910 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1911 isa<BlockExpr>(SubExpr)) &&
1912 "Unexpected SubExpr for CK_UserDefinedConversion.");
Richard Smith1ef75542018-06-27 20:30:34 +00001913 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1914 SubExpr = MCE->getImplicitObjectArgument();
Manman Ren8abc2e52016-02-02 22:23:03 +00001915 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001916
Douglas Gregord196a582009-12-14 19:27:10 +00001917 // If the subexpression we're left with is an implicit cast, look
1918 // through that, too.
Fangrui Song6907ce22018-07-30 19:24:48 +00001919 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1920
Richard Smith1ef75542018-06-27 20:30:34 +00001921 return const_cast<Expr*>(SubExpr);
1922}
1923
1924NamedDecl *CastExpr::getConversionFunction() const {
1925 const Expr *SubExpr = nullptr;
1926
1927 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1928 SubExpr = skipImplicitTemporary(E->getSubExpr());
1929
1930 if (E->getCastKind() == CK_ConstructorConversion)
1931 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1932
1933 if (E->getCastKind() == CK_UserDefinedConversion) {
1934 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1935 return MCE->getMethodDecl();
1936 }
1937 }
1938
1939 return nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001940}
1941
John McCallcf142162010-08-07 06:22:56 +00001942CXXBaseSpecifier **CastExpr::path_buffer() {
1943 switch (getStmtClass()) {
1944#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001945#define CASTEXPR(Type, Base) \
1946 case Stmt::Type##Class: \
1947 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001948#define STMT(Type, Base)
1949#include "clang/AST/StmtNodes.inc"
1950 default:
1951 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001952 }
1953}
1954
John McCallf1ef7962017-08-15 21:42:47 +00001955const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1956 QualType opType) {
1957 auto RD = unionType->castAs<RecordType>()->getDecl();
1958 return getTargetFieldForToUnionCast(RD, opType);
1959}
1960
1961const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1962 QualType OpType) {
1963 auto &Ctx = RD->getASTContext();
1964 RecordDecl::field_iterator Field, FieldEnd;
1965 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1966 Field != FieldEnd; ++Field) {
1967 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1968 !Field->isUnnamedBitfield()) {
1969 return *Field;
1970 }
1971 }
1972 return nullptr;
1973}
1974
Craig Topper37932912013-08-18 10:09:15 +00001975ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001976 CastKind Kind, Expr *Operand,
1977 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001978 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001979 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001980 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
Richard Smith27252a12019-06-14 17:46:38 +00001981 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
1982 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
1983 assert((Kind != CK_LValueToRValue ||
1984 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
1985 "invalid type for lvalue-to-rvalue conversion");
John McCallcf142162010-08-07 06:22:56 +00001986 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001987 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001988 if (PathSize)
1989 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1990 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001991 return E;
1992}
1993
Craig Topper37932912013-08-18 10:09:15 +00001994ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001995 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001996 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001997 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1998}
1999
2000
Craig Topper37932912013-08-18 10:09:15 +00002001CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00002002 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00002003 const CXXCastPath *BasePath,
2004 TypeSourceInfo *WrittenTy,
2005 SourceLocation L, SourceLocation R) {
2006 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00002007 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00002008 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00002009 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00002010 if (PathSize)
2011 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2012 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00002013 return E;
2014}
2015
Craig Topper37932912013-08-18 10:09:15 +00002016CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2017 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00002018 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00002019 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
2020}
2021
Chris Lattner1b926492006-08-23 06:42:10 +00002022/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2023/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00002024StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00002025 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00002026#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2027#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00002028 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002029 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00002030}
Steve Naroff47500512007-04-19 23:00:49 +00002031
John McCalle3027922010-08-25 11:45:40 +00002032BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002033BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2034 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00002035 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00002036 case OO_Plus: return BO_Add;
2037 case OO_Minus: return BO_Sub;
2038 case OO_Star: return BO_Mul;
2039 case OO_Slash: return BO_Div;
2040 case OO_Percent: return BO_Rem;
2041 case OO_Caret: return BO_Xor;
2042 case OO_Amp: return BO_And;
2043 case OO_Pipe: return BO_Or;
2044 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00002045 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00002046 case OO_Less: return BO_LT;
2047 case OO_Greater: return BO_GT;
2048 case OO_PlusEqual: return BO_AddAssign;
2049 case OO_MinusEqual: return BO_SubAssign;
2050 case OO_StarEqual: return BO_MulAssign;
2051 case OO_SlashEqual: return BO_DivAssign;
2052 case OO_PercentEqual: return BO_RemAssign;
2053 case OO_CaretEqual: return BO_XorAssign;
2054 case OO_AmpEqual: return BO_AndAssign;
2055 case OO_PipeEqual: return BO_OrAssign;
2056 case OO_LessLess: return BO_Shl;
2057 case OO_GreaterGreater: return BO_Shr;
2058 case OO_LessLessEqual: return BO_ShlAssign;
2059 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2060 case OO_EqualEqual: return BO_EQ;
2061 case OO_ExclaimEqual: return BO_NE;
2062 case OO_LessEqual: return BO_LE;
2063 case OO_GreaterEqual: return BO_GE;
2064 case OO_AmpAmp: return BO_LAnd;
2065 case OO_PipePipe: return BO_LOr;
2066 case OO_Comma: return BO_Comma;
2067 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002068 }
2069}
2070
2071OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2072 static const OverloadedOperatorKind OverOps[] = {
2073 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2074 OO_Star, OO_Slash, OO_Percent,
2075 OO_Plus, OO_Minus,
2076 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00002077 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002078 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2079 OO_EqualEqual, OO_ExclaimEqual,
2080 OO_Amp,
2081 OO_Caret,
2082 OO_Pipe,
2083 OO_AmpAmp,
2084 OO_PipePipe,
2085 OO_Equal, OO_StarEqual,
2086 OO_SlashEqual, OO_PercentEqual,
2087 OO_PlusEqual, OO_MinusEqual,
2088 OO_LessLessEqual, OO_GreaterGreaterEqual,
2089 OO_AmpEqual, OO_CaretEqual,
2090 OO_PipeEqual,
2091 OO_Comma
2092 };
2093 return OverOps[Opc];
2094}
2095
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002096bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2097 Opcode Opc,
2098 Expr *LHS, Expr *RHS) {
2099 if (Opc != BO_Add)
2100 return false;
2101
2102 // Check that we have one pointer and one integer operand.
2103 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002104 if (LHS->getType()->isPointerType()) {
2105 if (!RHS->getType()->isIntegerType())
2106 return false;
2107 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002108 } else if (RHS->getType()->isPointerType()) {
2109 if (!LHS->getType()->isIntegerType())
2110 return false;
2111 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002112 } else {
2113 return false;
2114 }
2115
2116 // Check that the pointer is a nullptr.
2117 if (!PExp->IgnoreParenCasts()
2118 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2119 return false;
2120
2121 // Check that the pointee type is char-sized.
2122 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2123 if (!PTy || !PTy->getPointeeType()->isCharType())
2124 return false;
2125
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002126 return true;
2127}
Eric Fiselier708afb52019-05-16 21:04:15 +00002128
2129static QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
2130 SourceLocExpr::IdentKind Kind) {
2131 switch (Kind) {
2132 case SourceLocExpr::File:
2133 case SourceLocExpr::Function: {
2134 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2135 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2136 }
2137 case SourceLocExpr::Line:
2138 case SourceLocExpr::Column:
2139 return Ctx.UnsignedIntTy;
2140 }
2141 llvm_unreachable("unhandled case");
2142}
2143
2144SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2145 SourceLocation BLoc, SourceLocation RParenLoc,
2146 DeclContext *ParentContext)
2147 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2148 VK_RValue, OK_Ordinary, false, false, false, false),
2149 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2150 SourceLocExprBits.Kind = Kind;
2151}
2152
2153StringRef SourceLocExpr::getBuiltinStr() const {
2154 switch (getIdentKind()) {
2155 case File:
2156 return "__builtin_FILE";
2157 case Function:
2158 return "__builtin_FUNCTION";
2159 case Line:
2160 return "__builtin_LINE";
2161 case Column:
2162 return "__builtin_COLUMN";
2163 }
2164 llvm_unreachable("unexpected IdentKind!");
2165}
2166
2167APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2168 const Expr *DefaultExpr) const {
2169 SourceLocation Loc;
2170 const DeclContext *Context;
2171
2172 std::tie(Loc,
2173 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2174 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2175 return {DIE->getUsedLocation(), DIE->getUsedContext()};
2176 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2177 return {DAE->getUsedLocation(), DAE->getUsedContext()};
2178 return {this->getLocation(), this->getParentContext()};
2179 }();
2180
2181 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2182 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2183
2184 auto MakeStringLiteral = [&](StringRef Tmp) {
2185 using LValuePathEntry = APValue::LValuePathEntry;
2186 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2187 // Decay the string to a pointer to the first character.
2188 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2189 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2190 };
2191
2192 switch (getIdentKind()) {
2193 case SourceLocExpr::File:
2194 return MakeStringLiteral(PLoc.getFilename());
2195 case SourceLocExpr::Function: {
2196 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2197 return MakeStringLiteral(
2198 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2199 : std::string(""));
2200 }
2201 case SourceLocExpr::Line:
2202 case SourceLocExpr::Column: {
2203 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002204 /*isUnsigned=*/true);
Eric Fiselier708afb52019-05-16 21:04:15 +00002205 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2206 : PLoc.getColumn();
2207 return APValue(IntVal);
2208 }
2209 }
2210 llvm_unreachable("unhandled case");
2211}
2212
Craig Topper37932912013-08-18 10:09:15 +00002213InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002214 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002215 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
2216 false, false),
2217 InitExprs(C, initExprs.size()),
2218 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
2219{
Sebastian Redlc83ed822012-02-17 08:42:25 +00002220 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00002221 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002222 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00002223 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00002224 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00002225 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002226 if (initExprs[I]->isInstantiationDependent())
2227 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00002228 if (initExprs[I]->containsUnexpandedParameterPack())
2229 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00002230 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002231
Benjamin Kramerc215e762012-08-24 11:54:20 +00002232 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00002233}
Chris Lattner1ec5f562007-06-27 05:38:08 +00002234
Craig Topper37932912013-08-18 10:09:15 +00002235void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002236 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00002237 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002238}
2239
Craig Topper37932912013-08-18 10:09:15 +00002240void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00002241 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002242}
2243
Craig Topper37932912013-08-18 10:09:15 +00002244Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002245 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00002246 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00002247 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00002248 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002249 }
Mike Stump11289f42009-09-09 15:08:12 +00002250
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002251 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00002252 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002253 return Result;
2254}
2255
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002256void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00002257 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002258 ArrayFillerOrUnionFieldInit = filler;
2259 // Fill out any "holes" in the array due to designated initializers.
2260 Expr **inits = getInits();
2261 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00002262 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002263 inits[i] = filler;
2264}
2265
Richard Smith9ec1e482012-04-15 02:50:59 +00002266bool InitListExpr::isStringLiteralInit() const {
2267 if (getNumInits() != 1)
2268 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00002269 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2270 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00002271 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00002272 // It is possible for getInit() to return null.
2273 const Expr *Init = getInit(0);
2274 if (!Init)
2275 return false;
2276 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00002277 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2278}
2279
Richard Smith122f88d2016-12-06 23:52:28 +00002280bool InitListExpr::isTransparent() const {
2281 assert(isSemanticForm() && "syntactic form never semantically transparent");
2282
2283 // A glvalue InitListExpr is always just sugar.
2284 if (isGLValue()) {
2285 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2286 return true;
2287 }
2288
2289 // Otherwise, we're sugar if and only if we have exactly one initializer that
2290 // is of the same type.
2291 if (getNumInits() != 1 || !getInit(0))
2292 return false;
2293
Richard Smith382bc512017-02-23 22:41:47 +00002294 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2295 // transparent struct copy.
2296 if (!getInit(0)->isRValue() && getType()->isRecordType())
2297 return false;
2298
Richard Smith122f88d2016-12-06 23:52:28 +00002299 return getType().getCanonicalType() ==
2300 getInit(0)->getType().getCanonicalType();
2301}
2302
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002303bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2304 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2305
Peter Wufa52e002019-07-16 01:13:36 +00002306 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002307 return false;
2308 }
2309
Peter Wufa52e002019-07-16 01:13:36 +00002310 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002311 return Lit && Lit->getValue() == 0;
2312}
2313
Stephen Kelly724e9e52018-08-09 20:05:03 +00002314SourceLocation InitListExpr::getBeginLoc() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00002315 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002316 return SyntacticForm->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002317 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002318 if (Beg.isInvalid()) {
2319 // Find the first non-null initializer.
2320 for (InitExprsTy::const_iterator I = InitExprs.begin(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002321 E = InitExprs.end();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002322 I != E; ++I) {
2323 if (Stmt *S = *I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002324 Beg = S->getBeginLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002325 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002326 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002327 }
2328 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002329 return Beg;
2330}
2331
Stephen Kelly02a67ba2018-08-09 20:05:47 +00002332SourceLocation InitListExpr::getEndLoc() const {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002333 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002334 return SyntacticForm->getEndLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002335 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002336 if (End.isInvalid()) {
2337 // Find the first non-null initializer from the end.
2338 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002339 E = InitExprs.rend();
2340 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002341 if (Stmt *S = *I) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002342 End = S->getEndLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002343 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002344 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002345 }
2346 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002347 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002348}
2349
Steve Naroff991e99d2008-09-04 15:31:07 +00002350/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002351///
John McCallc833dea2012-02-17 03:32:35 +00002352const FunctionProtoType *BlockExpr::getFunctionType() const {
2353 // The block pointer is never sugared, but the function type might be.
2354 return cast<BlockPointerType>(getType())
2355 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002356}
2357
Mike Stump11289f42009-09-09 15:08:12 +00002358SourceLocation BlockExpr::getCaretLocation() const {
2359 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002360}
Mike Stump11289f42009-09-09 15:08:12 +00002361const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002362 return TheBlock->getBody();
2363}
Mike Stump11289f42009-09-09 15:08:12 +00002364Stmt *BlockExpr::getBody() {
2365 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002366}
Steve Naroff415d3d52008-10-08 17:01:13 +00002367
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002368
Chris Lattner1ec5f562007-06-27 05:38:08 +00002369//===----------------------------------------------------------------------===//
2370// Generic Expression Routines
2371//===----------------------------------------------------------------------===//
2372
Chris Lattner237f2752009-02-14 07:37:35 +00002373/// isUnusedResultAWarning - Return true if this immediate expression should
2374/// be warned about if the result is unused. If so, fill in Loc and Ranges
2375/// with location to warn on and the source range[s] to report with the
2376/// warning.
Fangrui Song6907ce22018-07-30 19:24:48 +00002377bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
Eli Friedmanc11535c2012-05-24 00:47:05 +00002378 SourceRange &R1, SourceRange &R2,
2379 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002380 // Don't warn if the expr is type dependent. The type could end up
2381 // instantiating to void.
2382 if (isTypeDependent())
2383 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002384
Chris Lattner1ec5f562007-06-27 05:38:08 +00002385 switch (getStmtClass()) {
2386 default:
John McCallc493a732010-03-12 07:11:26 +00002387 if (getType()->isVoidType())
2388 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002389 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002390 Loc = getExprLoc();
2391 R1 = getSourceRange();
2392 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002393 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002394 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002395 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002396 case GenericSelectionExprClass:
2397 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002398 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002399 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002400 case CoyieldExprClass:
2401 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002402 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002403 case ChooseExprClass:
2404 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2405 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002406 case UnaryOperatorClass: {
2407 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002408
Chris Lattner1ec5f562007-06-27 05:38:08 +00002409 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002410 case UO_Plus:
2411 case UO_Minus:
2412 case UO_AddrOf:
2413 case UO_Not:
2414 case UO_LNot:
2415 case UO_Deref:
2416 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002417 case UO_Coawait:
2418 // This is just the 'operator co_await' call inside the guts of a
2419 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002420 case UO_PostInc:
2421 case UO_PostDec:
2422 case UO_PreInc:
2423 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002424 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002425 case UO_Real:
2426 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002427 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002428 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2429 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002430 return false;
2431 break;
John McCalle3027922010-08-25 11:45:40 +00002432 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002433 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002434 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002435 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002436 Loc = UO->getOperatorLoc();
2437 R1 = UO->getSubExpr()->getSourceRange();
2438 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002439 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002440 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002441 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002442 switch (BO->getOpcode()) {
2443 default:
2444 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002445 // Consider the RHS of comma for side effects. LHS was checked by
2446 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002447 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002448 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2449 // lvalue-ness) of an assignment written in a macro.
2450 if (IntegerLiteral *IE =
2451 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2452 if (IE->getValue() == 0)
2453 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002454 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002455 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002456 case BO_LAnd:
2457 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002458 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2459 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002460 return false;
2461 break;
John McCall1e3715a2010-02-16 04:10:53 +00002462 }
Chris Lattner237f2752009-02-14 07:37:35 +00002463 if (BO->isAssignmentOp())
2464 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002465 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002466 Loc = BO->getOperatorLoc();
2467 R1 = BO->getLHS()->getSourceRange();
2468 R2 = BO->getRHS()->getSourceRange();
2469 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002470 }
Chris Lattner86928112007-08-25 02:00:02 +00002471 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002472 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002473 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002474 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002475
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002476 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002477 // If only one of the LHS or RHS is a warning, the operator might
2478 // be being used for control flow. Only warn if both the LHS and
2479 // RHS are warnings.
Nathan Huckleberry321f9022019-06-19 18:37:01 +00002480 const auto *Exp = cast<ConditionalOperator>(this);
2481 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2482 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2483 }
2484 case BinaryConditionalOperatorClass: {
2485 const auto *Exp = cast<BinaryConditionalOperator>(this);
2486 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002487 }
2488
Chris Lattnera44d1162007-06-27 05:58:59 +00002489 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002490 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002491 Loc = cast<MemberExpr>(this)->getMemberLoc();
2492 R1 = SourceRange(Loc, Loc);
2493 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2494 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002495
Chris Lattner1ec5f562007-06-27 05:38:08 +00002496 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002497 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002498 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2499 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2500 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2501 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002502
Chandler Carruth46339472011-08-17 09:49:44 +00002503 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002504 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002505 // overloads as there is no reasonable way to define these such that they
2506 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002507 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002508 // provides additional value as well. If this list is updated,
2509 // DiagnoseUnusedComparison should be as well.
2510 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002511 switch (Op->getOperator()) {
2512 default:
2513 break;
2514 case OO_EqualEqual:
2515 case OO_ExclaimEqual:
2516 case OO_Less:
2517 case OO_Greater:
2518 case OO_GreaterEqual:
2519 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002520 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2521 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002522 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002523 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002524 Loc = Op->getOperatorLoc();
2525 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002526 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002527 }
Chandler Carruth46339472011-08-17 09:49:44 +00002528
2529 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002530 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002531 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002532 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002533 case CXXMemberCallExprClass:
2534 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002535 // If this is a direct call, get the callee.
2536 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002537 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner237f2752009-02-14 07:37:35 +00002538 // If the callee has attribute pure, const, or warn_unused_result, warn
2539 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002540 //
2541 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2542 // updated to match for QoI.
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00002543 if (CE->hasUnusedResultAttr(Ctx) ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002544 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002545 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002546 Loc = CE->getCallee()->getBeginLoc();
Chris Lattner1a6babf2009-10-13 04:53:48 +00002547 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002548
Chris Lattner1a6babf2009-10-13 04:53:48 +00002549 if (unsigned NumArgs = CE->getNumArgs())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002550 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002551 CE->getArg(NumArgs - 1)->getEndLoc());
Chris Lattner1a6babf2009-10-13 04:53:48 +00002552 return true;
2553 }
Chris Lattner237f2752009-02-14 07:37:35 +00002554 }
2555 return false;
2556 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002557
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002558 // If we don't know precisely what we're looking at, let's not warn.
2559 case UnresolvedLookupExprClass:
2560 case CXXUnresolvedConstructExprClass:
2561 return false;
2562
Anders Carlsson6aa50392009-11-17 17:11:23 +00002563 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002564 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002565 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
Erich Keane46441fd2019-07-25 15:10:56 +00002566 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2567 if (Type->hasAttr<WarnUnusedAttr>() ||
2568 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002569 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002570 Loc = getBeginLoc();
Lubos Lunak1f490f32013-07-21 13:15:58 +00002571 R1 = getSourceRange();
2572 return true;
2573 }
2574 }
Erich Keane46441fd2019-07-25 15:10:56 +00002575
2576 const auto *CE = cast<CXXConstructExpr>(this);
2577 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2578 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2579 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2580 WarnE = this;
2581 Loc = getBeginLoc();
2582 R1 = getSourceRange();
2583
2584 if (unsigned NumArgs = CE->getNumArgs())
2585 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2586 CE->getArg(NumArgs - 1)->getEndLoc());
2587 return true;
2588 }
2589 }
2590
Anders Carlsson6aa50392009-11-17 17:11:23 +00002591 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002592 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002593
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002594 case ObjCMessageExprClass: {
2595 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002596 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002597 ME->isInstanceMessage() &&
2598 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002599 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002600 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002601 Loc = getExprLoc();
2602 R1 = ME->getSourceRange();
2603 return true;
2604 }
2605
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002606 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002607 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002608 WarnE = this;
2609 Loc = getExprLoc();
2610 return true;
2611 }
2612
Chris Lattner237f2752009-02-14 07:37:35 +00002613 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002614 }
Mike Stump11289f42009-09-09 15:08:12 +00002615
John McCallb7bd14f2010-12-02 01:19:52 +00002616 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002617 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002618 Loc = getExprLoc();
2619 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002620 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002621
John McCallfe96e0b2011-11-06 09:01:30 +00002622 case PseudoObjectExprClass: {
2623 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2624
2625 // Only complain about things that have the form of a getter.
2626 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2627 isa<BinaryOperator>(PO->getSyntacticForm()))
2628 return false;
2629
Eli Friedmanc11535c2012-05-24 00:47:05 +00002630 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002631 Loc = getExprLoc();
2632 R1 = getSourceRange();
2633 return true;
2634 }
2635
Chris Lattner944d3062008-07-26 19:51:01 +00002636 case StmtExprClass: {
2637 // Statement exprs don't logically have side effects themselves, but are
2638 // sometimes used in macros in ways that give them a type that is unused.
2639 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2640 // however, if the result of the stmt expr is dead, we don't want to emit a
2641 // warning.
2642 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002643 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002644 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002645 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002646 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2647 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002648 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002649 }
Mike Stump11289f42009-09-09 15:08:12 +00002650
John McCallc493a732010-03-12 07:11:26 +00002651 if (getType()->isVoidType())
2652 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002653 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002654 Loc = cast<StmtExpr>(this)->getLParenLoc();
2655 R1 = getSourceRange();
2656 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002657 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002658 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002659 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002660 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002661 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002662 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002663 if (CE->getCastKind() == CK_ToVoid) {
2664 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002665 CE->getSubExpr()->getType().isVolatileQualified()) {
2666 const DeclRefExpr *DRE =
2667 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2668 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002669 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2670 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002671 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2672 R1, R2, Ctx);
2673 }
2674 }
Chris Lattner2706a552009-07-28 18:25:28 +00002675 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002676 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002677
Eli Friedmanc11535c2012-05-24 00:47:05 +00002678 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002679 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002680 if (CE->getCastKind() == CK_ConstructorConversion)
2681 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002682
Eli Friedmanc11535c2012-05-24 00:47:05 +00002683 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002684 if (const CXXFunctionalCastExpr *CXXCE =
2685 dyn_cast<CXXFunctionalCastExpr>(this)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002686 Loc = CXXCE->getBeginLoc();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002687 R1 = CXXCE->getSubExpr()->getSourceRange();
2688 } else {
2689 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2690 Loc = CStyleCE->getLParenLoc();
2691 R1 = CStyleCE->getSubExpr()->getSourceRange();
2692 }
Chris Lattner237f2752009-02-14 07:37:35 +00002693 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002694 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002695 case ImplicitCastExprClass: {
2696 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002697
Eli Friedmanc11535c2012-05-24 00:47:05 +00002698 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2699 if (ICE->getCastKind() == CK_LValueToRValue &&
2700 ICE->getSubExpr()->getType().isVolatileQualified())
2701 return false;
2702
2703 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2704 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002705 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002706 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002707 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002708 case CXXDefaultInitExprClass:
2709 return (cast<CXXDefaultInitExpr>(this)
2710 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002711
2712 case CXXNewExprClass:
2713 // FIXME: In theory, there might be new expressions that don't have side
2714 // effects (e.g. a placement new with an uninitialized POD).
2715 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002716 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002717 case MaterializeTemporaryExprClass:
2718 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2719 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002720 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002721 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2722 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002723 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002724 return cast<ExprWithCleanups>(this)->getSubExpr()
2725 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002726 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002727}
2728
Fariborz Jahanian07735332009-02-22 18:40:18 +00002729/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002730/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002731bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002732 const Expr *E = IgnoreParens();
2733 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002734 default:
2735 return false;
2736 case ObjCIvarRefExprClass:
2737 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002738 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002739 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002740 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002741 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002742 case MaterializeTemporaryExprClass:
2743 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2744 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002745 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002746 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002747 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002748 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002749
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002750 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2751 if (VD->hasGlobalStorage())
2752 return true;
2753 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002754 // dereferencing to a pointer is always a gc'able candidate,
2755 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002756 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002757 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002758 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002759 return false;
2760 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002761 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002762 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002763 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002764 }
2765 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002766 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002767 }
2768}
Sebastian Redlce354af2010-09-10 20:55:33 +00002769
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002770bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2771 if (isTypeDependent())
2772 return false;
John McCall086a4642010-11-24 05:12:34 +00002773 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002774}
2775
John McCall0009fcc2011-04-26 20:42:42 +00002776QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002777 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002778
2779 // Bound member expressions are always one of these possibilities:
2780 // x->m x.m x->*y x.*y
2781 // (possibly parenthesized)
2782
2783 expr = expr->IgnoreParens();
2784 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2785 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2786 return mem->getMemberDecl()->getType();
2787 }
2788
2789 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2790 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2791 ->getPointeeType();
2792 assert(type->isFunctionType());
2793 return type;
2794 }
2795
David Majnemerced8bdf2015-02-25 17:36:15 +00002796 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002797 return QualType();
2798}
2799
Bruno Ricci46148f22019-02-17 18:50:51 +00002800static Expr *IgnoreImpCastsSingleStep(Expr *E) {
2801 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2802 return ICE->getSubExpr();
2803
2804 if (auto *FE = dyn_cast<FullExpr>(E))
2805 return FE->getSubExpr();
2806
Bruno Riccid4038002019-02-17 13:47:29 +00002807 return E;
Ted Kremenek6f375e52014-04-16 07:26:09 +00002808}
2809
Bruno Ricci46148f22019-02-17 18:50:51 +00002810static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
2811 // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2812 // addition to what IgnoreImpCasts() skips to account for the current
2813 // behaviour of IgnoreParenImpCasts().
2814 Expr *SubE = IgnoreImpCastsSingleStep(E);
2815 if (SubE != E)
2816 return SubE;
2817
2818 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2819 return MTE->GetTemporaryExpr();
2820
2821 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2822 return NTTP->getReplacement();
2823
2824 return E;
2825}
2826
2827static Expr *IgnoreCastsSingleStep(Expr *E) {
2828 if (auto *CE = dyn_cast<CastExpr>(E))
2829 return CE->getSubExpr();
2830
2831 if (auto *FE = dyn_cast<FullExpr>(E))
2832 return FE->getSubExpr();
2833
2834 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2835 return MTE->GetTemporaryExpr();
2836
2837 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2838 return NTTP->getReplacement();
2839
2840 return E;
2841}
2842
2843static Expr *IgnoreLValueCastsSingleStep(Expr *E) {
2844 // Skip what IgnoreCastsSingleStep skips, except that only
2845 // lvalue-to-rvalue casts are skipped.
2846 if (auto *CE = dyn_cast<CastExpr>(E))
2847 if (CE->getCastKind() != CK_LValueToRValue)
2848 return E;
2849
2850 return IgnoreCastsSingleStep(E);
2851}
2852
2853static Expr *IgnoreBaseCastsSingleStep(Expr *E) {
2854 if (auto *CE = dyn_cast<CastExpr>(E))
2855 if (CE->getCastKind() == CK_DerivedToBase ||
2856 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2857 CE->getCastKind() == CK_NoOp)
2858 return CE->getSubExpr();
2859
2860 return E;
2861}
2862
2863static Expr *IgnoreImplicitSingleStep(Expr *E) {
2864 Expr *SubE = IgnoreImpCastsSingleStep(E);
2865 if (SubE != E)
2866 return SubE;
2867
2868 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2869 return MTE->GetTemporaryExpr();
2870
2871 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2872 return BTE->getSubExpr();
2873
2874 return E;
2875}
2876
2877static Expr *IgnoreParensSingleStep(Expr *E) {
2878 if (auto *PE = dyn_cast<ParenExpr>(E))
2879 return PE->getSubExpr();
2880
2881 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2882 if (UO->getOpcode() == UO_Extension)
2883 return UO->getSubExpr();
2884 }
2885
2886 else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2887 if (!GSE->isResultDependent())
2888 return GSE->getResultExpr();
2889 }
2890
2891 else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2892 if (!CE->isConditionDependent())
2893 return CE->getChosenSubExpr();
2894 }
2895
2896 else if (auto *CE = dyn_cast<ConstantExpr>(E))
2897 return CE->getSubExpr();
2898
2899 return E;
2900}
2901
2902static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
2903 if (auto *CE = dyn_cast<CastExpr>(E)) {
2904 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2905 // ptr<->int casts of the same width. We also ignore all identity casts.
2906 Expr *SubExpr = CE->getSubExpr();
2907 bool IsIdentityCast =
2908 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2909 bool IsSameWidthCast =
2910 (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2911 (SubExpr->getType()->isPointerType() ||
2912 SubExpr->getType()->isIntegralType(Ctx)) &&
2913 (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2914
2915 if (IsIdentityCast || IsSameWidthCast)
2916 return SubExpr;
2917 }
2918
2919 else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2920 return NTTP->getReplacement();
2921
2922 return E;
2923}
2924
2925static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2926template <typename FnTy, typename... FnTys>
2927static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2928 return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2929}
2930
2931/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2932/// Recursively apply each of the functions to E until reaching a fixed point.
2933/// Note that a null E is valid; in this case nothing is done.
2934template <typename... FnTys>
2935static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
Bruno Riccid4038002019-02-17 13:47:29 +00002936 Expr *LastE = nullptr;
2937 while (E != LastE) {
2938 LastE = E;
Bruno Ricci46148f22019-02-17 18:50:51 +00002939 E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
Bruno Riccid4038002019-02-17 13:47:29 +00002940 }
2941 return E;
John McCall34376a62010-12-04 03:47:34 +00002942}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002943
Bruno Ricci46148f22019-02-17 18:50:51 +00002944Expr *Expr::IgnoreImpCasts() {
2945 return IgnoreExprNodes(this, IgnoreImpCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002946}
2947
2948Expr *Expr::IgnoreCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002949 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002950}
2951
Bruno Ricci46148f22019-02-17 18:50:51 +00002952Expr *Expr::IgnoreImplicit() {
2953 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002954}
2955
Bruno Ricci46148f22019-02-17 18:50:51 +00002956Expr *Expr::IgnoreParens() {
2957 return IgnoreExprNodes(this, IgnoreParensSingleStep);
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002958}
2959
John McCalleebc8322010-05-05 22:59:52 +00002960Expr *Expr::IgnoreParenImpCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002961 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2962 IgnoreImpCastsExtraSingleStep);
2963}
2964
2965Expr *Expr::IgnoreParenCasts() {
2966 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
John McCalleebc8322010-05-05 22:59:52 +00002967}
2968
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002969Expr *Expr::IgnoreConversionOperator() {
Bruno Riccie64aee82019-02-03 19:50:56 +00002970 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002971 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002972 return MCE->getImplicitObjectArgument();
2973 }
2974 return this;
2975}
2976
Bruno Ricci46148f22019-02-17 18:50:51 +00002977Expr *Expr::IgnoreParenLValueCasts() {
2978 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2979 IgnoreLValueCastsSingleStep);
2980}
2981
2982Expr *Expr::ignoreParenBaseCasts() {
2983 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2984 IgnoreBaseCastsSingleStep);
2985}
2986
Bruno Riccie64aee82019-02-03 19:50:56 +00002987Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
Bruno Ricci46148f22019-02-17 18:50:51 +00002988 return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2989 return IgnoreNoopCastsSingleStep(Ctx, E);
2990 });
Chris Lattneref26c772009-03-13 17:28:01 +00002991}
2992
Douglas Gregord196a582009-12-14 19:27:10 +00002993bool Expr::isDefaultArgument() const {
2994 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002995 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2996 E = M->GetTemporaryExpr();
2997
Douglas Gregord196a582009-12-14 19:27:10 +00002998 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2999 E = ICE->getSubExprAsWritten();
Fangrui Song6907ce22018-07-30 19:24:48 +00003000
Douglas Gregord196a582009-12-14 19:27:10 +00003001 return isa<CXXDefaultArgExpr>(E);
3002}
Chris Lattneref26c772009-03-13 17:28:01 +00003003
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003004/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003005/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00003006static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00003007 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3008 E = M->GetTemporaryExpr();
3009
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003010 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00003011 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003012 E = ICE->getSubExpr();
3013 else
3014 break;
3015 }
3016
3017 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3018 E = BE->getSubExpr();
3019
3020 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00003021 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003022 E = ICE->getSubExpr();
3023 else
3024 break;
3025 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00003026
3027 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003028}
3029
John McCall7a626f62010-09-15 10:14:12 +00003030/// isTemporaryObject - Determines if this expression produces a
3031/// temporary of the given class type.
3032bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3033 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3034 return false;
3035
Anders Carlsson66bbf502010-11-28 16:40:49 +00003036 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003037
John McCall02dc8c72010-09-15 20:59:13 +00003038 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00003039 if (!E->Classify(C).isPRValue()) {
3040 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00003041 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00003042 return false;
3043 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003044
John McCallf4ee1dd2010-09-16 06:57:56 +00003045 // Black-list a few cases which yield pr-values of class type that don't
3046 // refer to temporaries of that type:
3047
3048 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00003049 if (isa<ImplicitCastExpr>(E)) {
3050 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3051 case CK_DerivedToBase:
3052 case CK_UncheckedDerivedToBase:
3053 return false;
3054 default:
3055 break;
3056 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003057 }
3058
John McCallf4ee1dd2010-09-16 06:57:56 +00003059 // - member expressions (all)
3060 if (isa<MemberExpr>(E))
3061 return false;
3062
Eli Friedman13ffdd82012-06-15 23:51:06 +00003063 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3064 if (BO->isPtrMemOp())
3065 return false;
3066
John McCallc07a0c72011-02-17 10:25:35 +00003067 // - opaque values (all)
3068 if (isa<OpaqueValueExpr>(E))
3069 return false;
3070
John McCall7a626f62010-09-15 10:14:12 +00003071 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003072}
3073
Douglas Gregor25b7e052011-03-02 21:06:53 +00003074bool Expr::isImplicitCXXThis() const {
3075 const Expr *E = this;
Fangrui Song6907ce22018-07-30 19:24:48 +00003076
Douglas Gregor25b7e052011-03-02 21:06:53 +00003077 // Strip away parentheses and casts we don't care about.
3078 while (true) {
3079 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3080 E = Paren->getSubExpr();
3081 continue;
3082 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003083
Douglas Gregor25b7e052011-03-02 21:06:53 +00003084 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3085 if (ICE->getCastKind() == CK_NoOp ||
3086 ICE->getCastKind() == CK_LValueToRValue ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003087 ICE->getCastKind() == CK_DerivedToBase ||
Douglas Gregor25b7e052011-03-02 21:06:53 +00003088 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3089 E = ICE->getSubExpr();
3090 continue;
3091 }
3092 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003093
Douglas Gregor25b7e052011-03-02 21:06:53 +00003094 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3095 if (UnOp->getOpcode() == UO_Extension) {
3096 E = UnOp->getSubExpr();
3097 continue;
3098 }
3099 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003100
Douglas Gregorfe314812011-06-21 17:03:29 +00003101 if (const MaterializeTemporaryExpr *M
3102 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3103 E = M->GetTemporaryExpr();
3104 continue;
3105 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003106
Douglas Gregor25b7e052011-03-02 21:06:53 +00003107 break;
3108 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003109
Douglas Gregor25b7e052011-03-02 21:06:53 +00003110 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3111 return This->isImplicit();
Fangrui Song6907ce22018-07-30 19:24:48 +00003112
Douglas Gregor25b7e052011-03-02 21:06:53 +00003113 return false;
3114}
3115
Douglas Gregor4619e432008-12-05 23:32:09 +00003116/// hasAnyTypeDependentArguments - Determines if any of the expressions
3117/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003118bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003119 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00003120 if (Exprs[I]->isTypeDependent())
3121 return true;
3122
3123 return false;
3124}
3125
Abramo Bagnara847c6602014-05-22 19:20:46 +00003126bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3127 const Expr **Culprit) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +00003128 assert(!isValueDependent() &&
3129 "Expression evaluator can't be called on a dependent expression.");
3130
Eli Friedman384da272009-01-25 03:12:18 +00003131 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00003132 // which can be evaluated at compile-time. It very closely parallels
3133 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3134 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3135 // to isEvaluatable most of the time.
3136 //
John McCall8b0f4ff2010-08-02 21:13:48 +00003137 // If we ever capture reference-binding directly in the AST, we can
3138 // kill the second parameter.
3139
3140 if (IsForRef) {
3141 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003142 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3143 return true;
3144 if (Culprit)
3145 *Culprit = this;
3146 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00003147 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00003148
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003149 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00003150 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003151 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00003152 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003153 return true;
John McCall81c9cea2010-08-01 21:51:45 +00003154 case CXXTemporaryObjectExprClass:
3155 case CXXConstructExprClass: {
3156 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00003157
Eli Friedman4c27ac22013-07-16 22:40:53 +00003158 if (CE->getConstructor()->isTrivial() &&
3159 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3160 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00003161 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00003162
Eli Friedman4c27ac22013-07-16 22:40:53 +00003163 // Trivial copy constructor
3164 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00003165 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00003166 }
3167
Richard Smithd62306a2011-11-10 06:34:14 +00003168 break;
John McCall81c9cea2010-08-01 21:51:45 +00003169 }
Fangrui Song407659a2018-11-30 23:41:18 +00003170 case ConstantExprClass: {
3171 // FIXME: We should be able to return "true" here, but it can lead to extra
3172 // error messages. E.g. in Sema/array-init.c.
3173 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3174 return Exp->isConstantInitializer(Ctx, false, Culprit);
3175 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003176 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00003177 // This handles gcc's extension that allows global initializers like
3178 // "struct x {int x;} x = (struct x) {};".
3179 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003180 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00003181 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003182 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00003183 case DesignatedInitUpdateExprClass: {
3184 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3185 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3186 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3187 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003188 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00003189 const InitListExpr *ILE = cast<InitListExpr>(this);
Dmitri Gribenkoc5f25442019-05-10 06:39:20 +00003190 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
Eli Friedman4c27ac22013-07-16 22:40:53 +00003191 if (ILE->getType()->isArrayType()) {
3192 unsigned numInits = ILE->getNumInits();
3193 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00003194 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00003195 return false;
3196 }
3197 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003198 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00003199
3200 if (ILE->getType()->isRecordType()) {
3201 unsigned ElementNo = 0;
3202 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00003203 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00003204 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00003205 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00003206 continue;
3207
3208 // Don't emit anonymous bitfields, they just affect layout.
3209 if (Field->isUnnamedBitfield())
3210 continue;
3211
3212 if (ElementNo < ILE->getNumInits()) {
3213 const Expr *Elt = ILE->getInit(ElementNo++);
3214 if (Field->isBitField()) {
3215 // Bitfields have to evaluate to an integer.
Fangrui Song407659a2018-11-30 23:41:18 +00003216 EvalResult Result;
3217 if (!Elt->EvaluateAsInt(Result, Ctx)) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00003218 if (Culprit)
3219 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00003220 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003221 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00003222 } else {
3223 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00003224 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00003225 return false;
3226 }
3227 }
3228 }
3229 return true;
3230 }
3231
3232 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003233 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00003234 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003235 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00003236 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00003237 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00003238 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003239 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00003240 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00003241 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003242 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00003243 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00003244 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3245 if (Culprit)
3246 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00003247 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003248 }
Eli Friedman75807f22013-07-20 00:40:58 +00003249 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003250 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003251 case UnaryOperatorClass: {
3252 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00003253 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003254 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003255 break;
3256 }
John McCall8b0f4ff2010-08-02 21:13:48 +00003257 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00003258 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00003259 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00003260 case CStyleCastExprClass:
3261 case ObjCBridgedCastExprClass:
3262 case CXXDynamicCastExprClass:
3263 case CXXReinterpretCastExprClass:
3264 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00003265 const CastExpr *CE = cast<CastExpr>(this);
3266
Eli Friedman13ec75b2011-12-21 00:43:02 +00003267 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00003268 if (CE->getCastKind() == CK_NoOp ||
3269 CE->getCastKind() == CK_LValueToRValue ||
3270 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00003271 CE->getCastKind() == CK_ConstructorConversion ||
3272 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003273 CE->getCastKind() == CK_AtomicToNonAtomic ||
3274 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003275 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00003276
Eli Friedman384da272009-01-25 03:12:18 +00003277 break;
Richard Smith161f09a2011-12-06 22:44:34 +00003278 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003279 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003280 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003281 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003282
Eli Friedman4c27ac22013-07-16 22:40:53 +00003283 case SubstNonTypeTemplateParmExprClass:
3284 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003285 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003286 case CXXDefaultArgExprClass:
3287 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003288 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003289 case CXXDefaultInitExprClass:
3290 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003291 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003292 }
Richard Smithce8eca52015-12-08 03:21:47 +00003293 // Allow certain forms of UB in constant initializers: signed integer
3294 // overflow and floating-point division by zero. We'll give a warning on
3295 // these, but they're common enough that we have to accept them.
3296 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00003297 return true;
3298 if (Culprit)
3299 *Culprit = this;
3300 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00003301}
3302
Nico Weber758fbac2018-02-13 21:31:47 +00003303bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3304 const FunctionDecl* FD = getDirectCallee();
3305 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3306 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3307 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003308
Nico Weber758fbac2018-02-13 21:31:47 +00003309 const Expr* Arg = getArg(0);
3310 bool ArgVal;
3311 return !Arg->isValueDependent() &&
3312 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3313}
3314
Scott Douglasscc013592015-06-10 15:18:23 +00003315namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003316 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00003317 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003318 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00003319 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003320 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00003321
3322 public:
3323 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003324 : Inherited(Context),
3325 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00003326
3327 bool hasSideEffects() const { return HasSideEffects; }
3328
3329 void VisitExpr(const Expr *E) {
3330 if (!HasSideEffects &&
3331 E->HasSideEffects(Context, IncludePossibleEffects))
3332 HasSideEffects = true;
3333 }
3334 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003335}
Scott Douglasscc013592015-06-10 15:18:23 +00003336
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003337bool Expr::HasSideEffects(const ASTContext &Ctx,
3338 bool IncludePossibleEffects) const {
3339 // In circumstances where we care about definite side effects instead of
3340 // potential side effects, we want to ignore expressions that are part of a
3341 // macro expansion as a potential side effect.
3342 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3343 return false;
3344
Richard Smith0421ce72012-08-07 04:16:51 +00003345 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003346 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00003347
3348 switch (getStmtClass()) {
3349 case NoStmtClass:
3350 #define ABSTRACT_STMT(Type)
3351 #define STMT(Type, Base) case Type##Class:
3352 #define EXPR(Type, Base)
3353 #include "clang/AST/StmtNodes.inc"
3354 llvm_unreachable("unexpected Expr kind");
3355
3356 case DependentScopeDeclRefExprClass:
3357 case CXXUnresolvedConstructExprClass:
3358 case CXXDependentScopeMemberExprClass:
3359 case UnresolvedLookupExprClass:
3360 case UnresolvedMemberExprClass:
3361 case PackExpansionExprClass:
3362 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00003363 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003364 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00003365 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003366 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3367
Richard Smitha33e4fe2012-08-07 05:18:29 +00003368 case DeclRefExprClass:
3369 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003370 case PredefinedExprClass:
3371 case IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003372 case FixedPointLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003373 case FloatingLiteralClass:
3374 case ImaginaryLiteralClass:
3375 case StringLiteralClass:
3376 case CharacterLiteralClass:
3377 case OffsetOfExprClass:
3378 case ImplicitValueInitExprClass:
3379 case UnaryExprOrTypeTraitExprClass:
3380 case AddrLabelExprClass:
3381 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003382 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003383 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003384 case CXXBoolLiteralExprClass:
3385 case CXXNullPtrLiteralExprClass:
3386 case CXXThisExprClass:
3387 case CXXScalarValueInitExprClass:
3388 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003389 case ArrayTypeTraitExprClass:
3390 case ExpressionTraitExprClass:
3391 case CXXNoexceptExprClass:
3392 case SizeOfPackExprClass:
3393 case ObjCStringLiteralClass:
3394 case ObjCEncodeExprClass:
3395 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003396 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003397 case CXXUuidofExprClass:
3398 case OpaqueValueExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +00003399 case SourceLocExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003400 // These never have a side-effect.
3401 return false;
3402
Bill Wendling7c44da22018-10-31 03:48:47 +00003403 case ConstantExprClass:
3404 // FIXME: Move this into the "return false;" block above.
3405 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3406 Ctx, IncludePossibleEffects);
3407
Richard Smith0421ce72012-08-07 04:16:51 +00003408 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003409 case CXXOperatorCallExprClass:
3410 case CXXMemberCallExprClass:
3411 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003412 case UserDefinedLiteralClass: {
3413 // We don't know a call definitely has side effects, except for calls
3414 // to pure/const functions that definitely don't.
3415 // If the call itself is considered side-effect free, check the operands.
3416 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3417 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3418 if (IsPure || !IncludePossibleEffects)
3419 break;
3420 return true;
3421 }
3422
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003423 case BlockExprClass:
3424 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003425 if (!IncludePossibleEffects)
3426 break;
3427 return true;
3428
John McCall5e77d762013-04-16 07:28:30 +00003429 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003430 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003431 case CompoundAssignOperatorClass:
3432 case VAArgExprClass:
3433 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003434 case CXXThrowExprClass:
3435 case CXXNewExprClass:
3436 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003437 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003438 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003439 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003440 // These always have a side-effect.
3441 return true;
3442
Scott Douglasscc013592015-06-10 15:18:23 +00003443 case StmtExprClass: {
3444 // StmtExprs have a side-effect if any substatement does.
3445 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3446 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3447 return Finder.hasSideEffects();
3448 }
3449
Tim Shen4a05bb82016-06-21 20:29:17 +00003450 case ExprWithCleanupsClass:
3451 if (IncludePossibleEffects)
3452 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3453 return true;
3454 break;
3455
Richard Smith0421ce72012-08-07 04:16:51 +00003456 case ParenExprClass:
3457 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003458 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003459 case MemberExprClass:
3460 case ConditionalOperatorClass:
3461 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003462 case CompoundLiteralExprClass:
3463 case ExtVectorElementExprClass:
3464 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003465 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003466 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003467 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003468 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003469 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003470 case SubstNonTypeTemplateParmExprClass:
3471 case MaterializeTemporaryExprClass:
3472 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003473 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003474 case AsTypeExprClass:
3475 // These have a side-effect if any subexpression does.
3476 break;
3477
Richard Smitha33e4fe2012-08-07 05:18:29 +00003478 case UnaryOperatorClass:
3479 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003480 return true;
3481 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003482
3483 case BinaryOperatorClass:
3484 if (cast<BinaryOperator>(this)->isAssignmentOp())
3485 return true;
3486 break;
3487
Richard Smith0421ce72012-08-07 04:16:51 +00003488 case InitListExprClass:
3489 // FIXME: The children for an InitListExpr doesn't include the array filler.
3490 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003491 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003492 return true;
3493 break;
3494
3495 case GenericSelectionExprClass:
3496 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003497 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003498
3499 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003500 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3501 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003502
3503 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003504 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3505 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003506
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003507 case CXXDefaultInitExprClass: {
3508 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3509 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003510 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003511 // If we've not yet parsed the initializer, assume it has side-effects.
3512 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003513 }
Richard Smith852c9db2013-04-20 22:23:05 +00003514
Richard Smith0421ce72012-08-07 04:16:51 +00003515 case CXXDynamicCastExprClass: {
3516 // A dynamic_cast expression has side-effects if it can throw.
3517 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3518 if (DCE->getTypeAsWritten()->isReferenceType() &&
3519 DCE->getCastKind() == CK_Dynamic)
3520 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003521 }
3522 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003523 case ImplicitCastExprClass:
3524 case CStyleCastExprClass:
3525 case CXXStaticCastExprClass:
3526 case CXXReinterpretCastExprClass:
3527 case CXXConstCastExprClass:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00003528 case CXXFunctionalCastExprClass:
3529 case BuiltinBitCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003530 // While volatile reads are side-effecting in both C and C++, we treat them
3531 // as having possible (not definite) side-effects. This allows idiomatic
3532 // code to behave without warning, such as sizeof(*v) for a volatile-
3533 // qualified pointer.
3534 if (!IncludePossibleEffects)
3535 break;
3536
Richard Smitha33e4fe2012-08-07 05:18:29 +00003537 const CastExpr *CE = cast<CastExpr>(this);
3538 if (CE->getCastKind() == CK_LValueToRValue &&
3539 CE->getSubExpr()->getType().isVolatileQualified())
3540 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003541 break;
3542 }
3543
Richard Smithef8bf432012-08-13 20:08:14 +00003544 case CXXTypeidExprClass:
3545 // typeid might throw if its subexpression is potentially-evaluated, so has
3546 // side-effects in that case whether or not its subexpression does.
3547 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003548
3549 case CXXConstructExprClass:
3550 case CXXTemporaryObjectExprClass: {
3551 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003552 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003553 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003554 // A trivial constructor does not add any side-effects of its own. Just look
3555 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003556 break;
3557 }
3558
Richard Smith5179eb72016-06-28 19:03:57 +00003559 case CXXInheritedCtorInitExprClass: {
3560 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3561 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3562 return true;
3563 break;
3564 }
3565
Richard Smith0421ce72012-08-07 04:16:51 +00003566 case LambdaExprClass: {
3567 const LambdaExpr *LE = cast<LambdaExpr>(this);
Richard Smithb3d203f2018-10-19 19:01:34 +00003568 for (Expr *E : LE->capture_inits())
3569 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003570 return true;
3571 return false;
3572 }
3573
3574 case PseudoObjectExprClass: {
3575 // Only look for side-effects in the semantic form, and look past
3576 // OpaqueValueExpr bindings in that form.
3577 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3578 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3579 E = PO->semantics_end();
3580 I != E; ++I) {
3581 const Expr *Subexpr = *I;
3582 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3583 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003584 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003585 return true;
3586 }
3587 return false;
3588 }
3589
3590 case ObjCBoxedExprClass:
3591 case ObjCArrayLiteralClass:
3592 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003593 case ObjCSelectorExprClass:
3594 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003595 case ObjCIsaExprClass:
3596 case ObjCIndirectCopyRestoreExprClass:
3597 case ObjCSubscriptRefExprClass:
3598 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003599 case ObjCMessageExprClass:
3600 case ObjCPropertyRefExprClass:
3601 // FIXME: Classify these cases better.
3602 if (IncludePossibleEffects)
3603 return true;
3604 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003605 }
3606
3607 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003608 for (const Stmt *SubStmt : children())
3609 if (SubStmt &&
3610 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3611 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003612
3613 return false;
3614}
3615
Douglas Gregor1be329d2012-02-23 07:33:15 +00003616namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003617 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003618 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3619 {
3620 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003621
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003622 bool NonTrivial;
Fangrui Song6907ce22018-07-30 19:24:48 +00003623
Douglas Gregor1be329d2012-02-23 07:33:15 +00003624 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003625 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003626 : Inherited(Context), NonTrivial(false) { }
Fangrui Song6907ce22018-07-30 19:24:48 +00003627
Douglas Gregor1be329d2012-02-23 07:33:15 +00003628 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003629
3630 void VisitCallExpr(const CallExpr *E) {
3631 if (const CXXMethodDecl *Method
3632 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003633 if (Method->isTrivial()) {
3634 // Recurse to children of the call.
3635 Inherited::VisitStmt(E);
3636 return;
3637 }
3638 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003639
Douglas Gregor1be329d2012-02-23 07:33:15 +00003640 NonTrivial = true;
3641 }
Scott Douglass503fc392015-06-10 13:53:15 +00003642
3643 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003644 if (E->getConstructor()->isTrivial()) {
3645 // Recurse to children of the call.
3646 Inherited::VisitStmt(E);
3647 return;
3648 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003649
Douglas Gregor1be329d2012-02-23 07:33:15 +00003650 NonTrivial = true;
3651 }
Scott Douglass503fc392015-06-10 13:53:15 +00003652
3653 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003654 if (E->getTemporary()->getDestructor()->isTrivial()) {
3655 Inherited::VisitStmt(E);
3656 return;
3657 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003658
Douglas Gregor1be329d2012-02-23 07:33:15 +00003659 NonTrivial = true;
3660 }
3661 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003662}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003663
Scott Douglass503fc392015-06-10 13:53:15 +00003664bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003665 NonTrivialCallFinder Finder(Ctx);
3666 Finder.Visit(this);
Fangrui Song6907ce22018-07-30 19:24:48 +00003667 return Finder.hasNonTrivialCall();
Douglas Gregor1be329d2012-02-23 07:33:15 +00003668}
3669
Fangrui Song6907ce22018-07-30 19:24:48 +00003670/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003671/// pointer constant or not, as well as the specific kind of constant detected.
3672/// Null pointer constants can be integer constant expressions with the
3673/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3674/// (a GNU extension).
3675Expr::NullPointerConstantKind
3676Expr::isNullPointerConstant(ASTContext &Ctx,
3677 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003678 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003679 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003680 switch (NPC) {
3681 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003682 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003683 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003684 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003685 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003686 else
3687 return NPCK_NotNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003688
Douglas Gregor56751b52009-09-25 04:25:58 +00003689 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003690 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003691 }
3692 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003693
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003694 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003695 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003696 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003697 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003698 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003699 QualType Pointee = PT->getPointeeType();
Richard Smithdab73ce2018-11-28 06:25:06 +00003700 Qualifiers Qs = Pointee.getQualifiers();
Yaxun Liub7318e02017-10-13 03:37:48 +00003701 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3702 // has non-default address space it is not treated as nullptr.
3703 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3704 // since it cannot be assigned to a pointer to constant address space.
Richard Smithdab73ce2018-11-28 06:25:06 +00003705 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
Yaxun Liub7318e02017-10-13 03:37:48 +00003706 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3707 (Ctx.getLangOpts().OpenCL &&
3708 Ctx.getLangOpts().OpenCLVersion < 200 &&
Richard Smithdab73ce2018-11-28 06:25:06 +00003709 Pointee.getAddressSpace() == LangAS::opencl_private))
3710 Qs.removeAddressSpace();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003711
Richard Smithdab73ce2018-11-28 06:25:06 +00003712 if (Pointee->isVoidType() && Qs.empty() && // to void*
3713 CE->getSubExpr()->getType()->isIntegerType()) // from int
Douglas Gregor56751b52009-09-25 04:25:58 +00003714 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003715 }
Steve Naroffada7d422007-05-20 17:54:12 +00003716 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003717 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3718 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003719 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003720 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3721 // Accept ((void*)0) as a null pointer constant, as many other
3722 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003723 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003724 } else if (const GenericSelectionExpr *GE =
3725 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003726 if (GE->isResultDependent())
3727 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003728 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003729 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3730 if (CE->isConditionDependent())
3731 return NPCK_NotNull;
3732 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003733 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003734 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003735 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003736 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003737 } else if (const CXXDefaultInitExpr *DefaultInit
3738 = dyn_cast<CXXDefaultInitExpr>(this)) {
3739 // See through default initializer expressions.
3740 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003741 } else if (isa<GNUNullExpr>(this)) {
3742 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003743 return NPCK_GNUNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003744 } else if (const MaterializeTemporaryExpr *M
Douglas Gregorfe314812011-06-21 17:03:29 +00003745 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3746 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003747 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3748 if (const Expr *Source = OVE->getSourceExpr())
3749 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003750 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003751
Richard Smith89645bc2013-01-02 12:01:23 +00003752 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003753 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003754 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003755
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003756 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003757 if (!Ctx.getLangOpts().CPlusPlus11 &&
3758 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003759 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3760 const Expr *InitExpr = CLE->getInitializer();
3761 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3762 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3763 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003764 // This expression must be an integer type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003765 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003766 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003767 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003768
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003769 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003770 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3771 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003772 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003773 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003774 if (Lit && !Lit->getValue())
3775 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003776 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003777 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003778 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003779 // If we have an integer constant expression, we need to *evaluate* it and
3780 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003781 if (!isIntegerConstantExpr(Ctx))
3782 return NPCK_NotNull;
3783 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003784
David Blaikie1c7c8f72012-08-08 17:33:31 +00003785 if (EvaluateKnownConstInt(Ctx) != 0)
3786 return NPCK_NotNull;
3787
3788 if (isa<IntegerLiteral>(this))
3789 return NPCK_ZeroLiteral;
3790 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003791}
Steve Narofff7a5da12007-07-28 23:10:27 +00003792
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003793/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003794/// property, find the underlying property reference expression.
3795const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3796 const Expr *E = this;
3797 while (true) {
3798 assert((E->getValueKind() == VK_LValue &&
3799 E->getObjectKind() == OK_ObjCProperty) &&
3800 "expression is not a property reference");
3801 E = E->IgnoreParenCasts();
3802 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3803 if (BO->getOpcode() == BO_Comma) {
3804 E = BO->getRHS();
3805 continue;
3806 }
3807 }
3808
3809 break;
3810 }
3811
3812 return cast<ObjCPropertyRefExpr>(E);
3813}
3814
Anna Zaks97c7ce32012-10-01 20:34:04 +00003815bool Expr::isObjCSelfExpr() const {
3816 const Expr *E = IgnoreParenImpCasts();
3817
3818 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3819 if (!DRE)
3820 return false;
3821
3822 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3823 if (!Param)
3824 return false;
3825
3826 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3827 if (!M)
3828 return false;
3829
3830 return M->getSelfDecl() == Param;
3831}
3832
John McCalld25db7e2013-05-06 21:39:12 +00003833FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003834 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003835
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003836 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003837 if (ICE->getCastKind() == CK_LValueToRValue ||
3838 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003839 E = ICE->getSubExpr()->IgnoreParens();
3840 else
3841 break;
3842 }
3843
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003844 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003845 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003846 if (Field->isBitField())
3847 return Field;
3848
George Burgess IV00f70bd2018-03-01 05:43:23 +00003849 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3850 FieldDecl *Ivar = IvarRef->getDecl();
3851 if (Ivar->isBitField())
3852 return Ivar;
3853 }
John McCalld25db7e2013-05-06 21:39:12 +00003854
Richard Smith7873de02016-08-11 22:25:46 +00003855 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003856 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3857 if (Field->isBitField())
3858 return Field;
3859
Richard Smith7873de02016-08-11 22:25:46 +00003860 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3861 if (Expr *E = BD->getBinding())
3862 return E->getSourceBitField();
3863 }
3864
Eli Friedman609ada22011-07-13 02:05:57 +00003865 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003866 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003867 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003868
Eli Friedman609ada22011-07-13 02:05:57 +00003869 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003870 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003871 }
3872
Richard Smith5b571672014-09-24 23:55:00 +00003873 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3874 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3875 return UnOp->getSubExpr()->getSourceBitField();
3876
Craig Topper36250ad2014-05-12 05:36:57 +00003877 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003878}
3879
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003880bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003881 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003882 const Expr *E = this->IgnoreParens();
Fangrui Song6907ce22018-07-30 19:24:48 +00003883
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003884 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003885 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003886 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003887 E = ICE->getSubExpr()->IgnoreParens();
3888 else
3889 break;
3890 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003891
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003892 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3893 return ASE->getBase()->getType()->isVectorType();
3894
3895 if (isa<ExtVectorElementExpr>(E))
3896 return true;
3897
Richard Smith7873de02016-08-11 22:25:46 +00003898 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3899 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3900 if (auto *E = BD->getBinding())
3901 return E->refersToVectorElement();
3902
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003903 return false;
3904}
3905
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003906bool Expr::refersToGlobalRegisterVar() const {
3907 const Expr *E = this->IgnoreParenImpCasts();
3908
3909 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3910 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3911 if (VD->getStorageClass() == SC_Register &&
3912 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3913 return true;
3914
3915 return false;
3916}
3917
Chris Lattnerb8211f62009-02-16 22:14:05 +00003918/// isArrow - Return true if the base expression is a pointer to vector,
3919/// return false if the base expression is a vector.
3920bool ExtVectorElementExpr::isArrow() const {
3921 return getBase()->getType()->isPointerType();
3922}
3923
Nate Begemance4d7fc2008-04-18 23:10:10 +00003924unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003925 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003926 return VT->getNumElements();
3927 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003928}
3929
Nate Begemanf322eab2008-05-09 06:41:27 +00003930/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003931bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003932 // FIXME: Refactor this code to an accessor on the AST node which returns the
3933 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003934 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003935
3936 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003937 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003938 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003939
Nate Begeman7e5185b2009-01-18 02:01:21 +00003940 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003941 if (Comp[0] == 's' || Comp[0] == 'S')
3942 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003943
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003944 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003945 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003946 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003947
Steve Naroff0d595ca2007-07-30 03:29:09 +00003948 return false;
3949}
Chris Lattner885b4952007-08-02 23:36:59 +00003950
Nate Begemanf322eab2008-05-09 06:41:27 +00003951/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003952void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003953 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003954 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003955 bool isNumericAccessor = false;
3956 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003957 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003958 isNumericAccessor = true;
3959 }
Mike Stump11289f42009-09-09 15:08:12 +00003960
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003961 bool isHi = Comp == "hi";
3962 bool isLo = Comp == "lo";
3963 bool isEven = Comp == "even";
3964 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003965
Nate Begemanf322eab2008-05-09 06:41:27 +00003966 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3967 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003968
Nate Begemanf322eab2008-05-09 06:41:27 +00003969 if (isHi)
3970 Index = e + i;
3971 else if (isLo)
3972 Index = i;
3973 else if (isEven)
3974 Index = 2 * i;
3975 else if (isOdd)
3976 Index = 2 * i + 1;
3977 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003978 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003979
Nate Begemand3862152008-05-13 21:03:02 +00003980 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003981 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003982}
3983
Craig Topper37932912013-08-18 10:09:15 +00003984ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003985 QualType Type, SourceLocation BLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00003986 SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003987 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3988 Type->isDependentType(), Type->isDependentType(),
3989 Type->isInstantiationDependentType(),
3990 Type->containsUnexpandedParameterPack()),
3991 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3992{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003993 SubExprs = new (C) Stmt*[args.size()];
3994 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003995 if (args[i]->isTypeDependent())
3996 ExprBits.TypeDependent = true;
3997 if (args[i]->isValueDependent())
3998 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003999 if (args[i]->isInstantiationDependent())
4000 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00004001 if (args[i]->containsUnexpandedParameterPack())
4002 ExprBits.ContainsUnexpandedParameterPack = true;
4003
4004 SubExprs[i] = args[i];
4005 }
4006}
4007
Craig Topper37932912013-08-18 10:09:15 +00004008void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00004009 if (SubExprs) C.Deallocate(SubExprs);
4010
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00004011 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00004012 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00004013 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00004014}
Nate Begeman48745922009-08-12 02:28:50 +00004015
Bruno Ricci94498c72019-01-26 13:58:15 +00004016GenericSelectionExpr::GenericSelectionExpr(
Bruno Riccidb076832019-01-26 14:15:10 +00004017 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
Bruno Ricci94498c72019-01-26 13:58:15 +00004018 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4019 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4020 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4021 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4022 AssocExprs[ResultIndex]->getValueKind(),
4023 AssocExprs[ResultIndex]->getObjectKind(),
4024 AssocExprs[ResultIndex]->isTypeDependent(),
4025 AssocExprs[ResultIndex]->isValueDependent(),
4026 AssocExprs[ResultIndex]->isInstantiationDependent(),
4027 ContainsUnexpandedParameterPack),
4028 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00004029 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00004030 assert(AssocTypes.size() == AssocExprs.size() &&
4031 "Must have the same number of association expressions"
4032 " and TypeSourceInfo!");
4033 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4034
Bruno Riccidb076832019-01-26 14:15:10 +00004035 GenericSelectionExprBits.GenericLoc = GenericLoc;
4036 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00004037 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00004038 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4039 std::copy(AssocTypes.begin(), AssocTypes.end(),
4040 getTrailingObjects<TypeSourceInfo *>());
Peter Collingbourne91147592011-04-15 00:35:48 +00004041}
4042
Bruno Ricci94498c72019-01-26 13:58:15 +00004043GenericSelectionExpr::GenericSelectionExpr(
4044 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4045 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4046 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4047 bool ContainsUnexpandedParameterPack)
4048 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
4049 OK_Ordinary,
4050 /*isTypeDependent=*/true,
4051 /*isValueDependent=*/true,
4052 /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
4053 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00004054 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00004055 assert(AssocTypes.size() == AssocExprs.size() &&
4056 "Must have the same number of association expressions"
4057 " and TypeSourceInfo!");
4058
Bruno Riccidb076832019-01-26 14:15:10 +00004059 GenericSelectionExprBits.GenericLoc = GenericLoc;
4060 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00004061 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00004062 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4063 std::copy(AssocTypes.begin(), AssocTypes.end(),
4064 getTrailingObjects<TypeSourceInfo *>());
4065}
4066
4067GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4068 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4069
4070GenericSelectionExpr *GenericSelectionExpr::Create(
4071 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4072 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4073 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4074 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4075 unsigned NumAssocs = AssocExprs.size();
4076 void *Mem = Context.Allocate(
4077 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4078 alignof(GenericSelectionExpr));
4079 return new (Mem) GenericSelectionExpr(
4080 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4081 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4082}
4083
4084GenericSelectionExpr *GenericSelectionExpr::Create(
4085 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4086 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4087 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4088 bool ContainsUnexpandedParameterPack) {
4089 unsigned NumAssocs = AssocExprs.size();
4090 void *Mem = Context.Allocate(
4091 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4092 alignof(GenericSelectionExpr));
4093 return new (Mem) GenericSelectionExpr(
4094 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4095 RParenLoc, ContainsUnexpandedParameterPack);
4096}
4097
4098GenericSelectionExpr *
4099GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4100 unsigned NumAssocs) {
4101 void *Mem = Context.Allocate(
4102 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4103 alignof(GenericSelectionExpr));
4104 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
Peter Collingbourne91147592011-04-15 00:35:48 +00004105}
4106
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004107//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004108// DesignatedInitExpr
4109//===----------------------------------------------------------------------===//
4110
Chandler Carruth631abd92011-06-16 06:47:06 +00004111IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004112 assert(Kind == FieldDesignator && "Only valid on a field designator");
4113 if (Field.NameOrField & 0x01)
4114 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
4115 else
4116 return getField()->getIdentifier();
4117}
4118
Craig Topper37932912013-08-18 10:09:15 +00004119DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00004120 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00004121 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00004122 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004123 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004124 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00004125 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00004126 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00004127 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00004128 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00004129 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00004130 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00004131 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004132 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004133
4134 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004135 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004136 *Child++ = Init;
4137
4138 // Copy the designators and their subexpressions, computing
4139 // value-dependence along the way.
4140 unsigned IndexIdx = 0;
4141 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00004142 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004143
4144 if (this->Designators[I].isArrayDesignator()) {
4145 // Compute type- and value-dependence.
4146 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004147 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00004148 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00004149 if (Index->isInstantiationDependent())
4150 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00004151 // Propagate unexpanded parameter packs.
4152 if (Index->containsUnexpandedParameterPack())
4153 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004154
4155 // Copy the index expressions into permanent storage.
4156 *Child++ = IndexExprs[IndexIdx++];
4157 } else if (this->Designators[I].isArrayRangeDesignator()) {
4158 // Compute type- and value-dependence.
4159 Expr *Start = IndexExprs[IndexIdx];
4160 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004161 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00004162 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00004163 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00004164 ExprBits.InstantiationDependent = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004165 } else if (Start->isInstantiationDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00004166 End->isInstantiationDependent()) {
4167 ExprBits.InstantiationDependent = true;
4168 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004169
Douglas Gregora6e053e2010-12-15 01:34:56 +00004170 // Propagate unexpanded parameter packs.
4171 if (Start->containsUnexpandedParameterPack() ||
4172 End->containsUnexpandedParameterPack())
4173 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004174
4175 // Copy the start/end expressions into permanent storage.
4176 *Child++ = IndexExprs[IndexIdx++];
4177 *Child++ = IndexExprs[IndexIdx++];
4178 }
4179 }
4180
Benjamin Kramerc215e762012-08-24 11:54:20 +00004181 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00004182}
4183
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004184DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00004185DesignatedInitExpr::Create(const ASTContext &C,
4186 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004187 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004188 SourceLocation ColonOrEqualLoc,
4189 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004190 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004191 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00004192 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004193 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004194 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004195}
4196
Craig Topper37932912013-08-18 10:09:15 +00004197DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00004198 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004199 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004200 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00004201 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4202}
4203
Craig Topper37932912013-08-18 10:09:15 +00004204void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004205 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00004206 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004207 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00004208 NumDesignators = NumDesigs;
4209 for (unsigned I = 0; I != NumDesigs; ++I)
4210 Designators[I] = Desigs[I];
4211}
4212
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00004213SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4214 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4215 if (size() == 1)
4216 return DIE->getDesignator(0)->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004217 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004218 DIE->getDesignator(size() - 1)->getEndLoc());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00004219}
4220
Stephen Kelly724e9e52018-08-09 20:05:03 +00004221SourceLocation DesignatedInitExpr::getBeginLoc() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004222 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00004223 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4224 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004225 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00004226 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004227 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
4228 else
4229 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
4230 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00004231 StartLoc =
4232 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00004233 return StartLoc;
4234}
4235
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004236SourceLocation DesignatedInitExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004237 return getInit()->getEndLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004238}
4239
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004240Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004241 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004242 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004243}
4244
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004245Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004246 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004247 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004248 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004249}
4250
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004251Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004252 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004253 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004254 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004255}
4256
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004257/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00004258/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00004259void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00004260 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00004261 const Designator *Last) {
4262 unsigned NumNewDesignators = Last - First;
4263 if (NumNewDesignators == 0) {
4264 std::copy_backward(Designators + Idx + 1,
4265 Designators + NumDesignators,
4266 Designators + Idx);
4267 --NumNewDesignators;
4268 return;
4269 } else if (NumNewDesignators == 1) {
4270 Designators[Idx] = *First;
4271 return;
4272 }
4273
Mike Stump11289f42009-09-09 15:08:12 +00004274 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004275 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00004276 std::copy(Designators, Designators + Idx, NewDesignators);
4277 std::copy(First, Last, NewDesignators + Idx);
4278 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4279 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00004280 Designators = NewDesignators;
4281 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4282}
4283
Yunzhong Gaocb779302015-06-10 00:27:52 +00004284DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4285 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4286 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4287 OK_Ordinary, false, false, false, false) {
4288 BaseAndUpdaterExprs[0] = baseExpr;
4289
4290 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4291 ILE->setType(baseExpr->getType());
4292 BaseAndUpdaterExprs[1] = ILE;
4293}
4294
Stephen Kelly724e9e52018-08-09 20:05:03 +00004295SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004296 return getBase()->getBeginLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004297}
4298
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004299SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004300 return getBase()->getEndLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004301}
4302
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004303ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4304 SourceLocation RParenLoc)
4305 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4306 false, false),
4307 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4308 ParenListExprBits.NumExprs = Exprs.size();
4309
4310 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4311 if (Exprs[I]->isTypeDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004312 ExprBits.TypeDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004313 if (Exprs[I]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004314 ExprBits.ValueDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004315 if (Exprs[I]->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00004316 ExprBits.InstantiationDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004317 if (Exprs[I]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004318 ExprBits.ContainsUnexpandedParameterPack = true;
4319
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004320 getTrailingObjects<Stmt *>()[I] = Exprs[I];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004321 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004322}
4323
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004324ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4325 : Expr(ParenListExprClass, Empty) {
4326 ParenListExprBits.NumExprs = NumExprs;
4327}
4328
4329ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4330 SourceLocation LParenLoc,
4331 ArrayRef<Expr *> Exprs,
4332 SourceLocation RParenLoc) {
4333 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4334 alignof(ParenListExpr));
4335 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4336}
4337
4338ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4339 unsigned NumExprs) {
4340 void *Mem =
4341 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4342 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4343}
4344
John McCall1bf58462011-02-16 08:02:54 +00004345const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4346 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4347 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00004348 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4349 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00004350 e = cast<CXXConstructExpr>(e)->getArg(0);
4351 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4352 e = ice->getSubExpr();
4353 return cast<OpaqueValueExpr>(e);
4354}
4355
Craig Topper37932912013-08-18 10:09:15 +00004356PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4357 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00004358 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004359 void *buffer =
4360 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004361 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004362 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4363}
4364
4365PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4366 : Expr(PseudoObjectExprClass, shell) {
4367 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4368}
4369
Craig Topper37932912013-08-18 10:09:15 +00004370PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00004371 ArrayRef<Expr*> semantics,
4372 unsigned resultIndex) {
4373 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004374 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00004375
4376 QualType type;
4377 ExprValueKind VK;
4378 if (resultIndex == NoResult) {
4379 type = C.VoidTy;
4380 VK = VK_RValue;
4381 } else {
4382 assert(resultIndex < semantics.size());
4383 type = semantics[resultIndex]->getType();
4384 VK = semantics[resultIndex]->getValueKind();
4385 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4386 }
4387
James Y Knighte00a67e2015-12-31 04:18:25 +00004388 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004389 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004390 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4391 resultIndex);
4392}
4393
4394PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4395 Expr *syntax, ArrayRef<Expr*> semantics,
4396 unsigned resultIndex)
4397 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4398 /*filled in at end of ctor*/ false, false, false, false) {
4399 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4400 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4401
4402 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4403 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4404 getSubExprsBuffer()[i] = E;
4405
4406 if (E->isTypeDependent())
4407 ExprBits.TypeDependent = true;
4408 if (E->isValueDependent())
4409 ExprBits.ValueDependent = true;
4410 if (E->isInstantiationDependent())
4411 ExprBits.InstantiationDependent = true;
4412 if (E->containsUnexpandedParameterPack())
4413 ExprBits.ContainsUnexpandedParameterPack = true;
4414
4415 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00004416 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00004417 "opaque-value semantic expressions for pseudo-object "
4418 "operations must have sources");
4419 }
4420}
4421
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004422//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004423// Child Iterators for iterating over subexpressions/substatements
4424//===----------------------------------------------------------------------===//
4425
Peter Collingbournee190dee2011-03-11 19:24:49 +00004426// UnaryExprOrTypeTraitExpr
4427Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004428 const_child_range CCR =
4429 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4430 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4431}
4432
4433Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00004434 // If this is of a type and the type is a VLA type (and not a typedef), the
4435 // size expression of the VLA needs to be treated as an executable expression.
4436 // Why isn't this weirdness documented better in StmtIterator?
4437 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004438 if (const VariableArrayType *T =
4439 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4440 return const_child_range(const_child_iterator(T), const_child_iterator());
4441 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00004442 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004443 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004444}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004445
Benjamin Kramerc215e762012-08-24 11:54:20 +00004446AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004447 QualType t, AtomicOp op, SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004448 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4449 false, false, false, false),
4450 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4451{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004452 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4453 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004454 if (args[i]->isTypeDependent())
4455 ExprBits.TypeDependent = true;
4456 if (args[i]->isValueDependent())
4457 ExprBits.ValueDependent = true;
4458 if (args[i]->isInstantiationDependent())
4459 ExprBits.InstantiationDependent = true;
4460 if (args[i]->containsUnexpandedParameterPack())
4461 ExprBits.ContainsUnexpandedParameterPack = true;
4462
4463 SubExprs[i] = args[i];
4464 }
4465}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004466
4467unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4468 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004469 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004470 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004471 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004472 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004473 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004474
Yaxun Liu30d652a2017-08-15 16:02:49 +00004475 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004476 case AO__c11_atomic_store:
4477 case AO__c11_atomic_exchange:
4478 case AO__atomic_load:
4479 case AO__atomic_store:
4480 case AO__atomic_store_n:
4481 case AO__atomic_exchange_n:
4482 case AO__c11_atomic_fetch_add:
4483 case AO__c11_atomic_fetch_sub:
4484 case AO__c11_atomic_fetch_and:
4485 case AO__c11_atomic_fetch_or:
4486 case AO__c11_atomic_fetch_xor:
4487 case AO__atomic_fetch_add:
4488 case AO__atomic_fetch_sub:
4489 case AO__atomic_fetch_and:
4490 case AO__atomic_fetch_or:
4491 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004492 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004493 case AO__atomic_add_fetch:
4494 case AO__atomic_sub_fetch:
4495 case AO__atomic_and_fetch:
4496 case AO__atomic_or_fetch:
4497 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004498 case AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004499 case AO__atomic_fetch_min:
4500 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004501 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004502
Yaxun Liu30d652a2017-08-15 16:02:49 +00004503 case AO__opencl_atomic_store:
4504 case AO__opencl_atomic_exchange:
4505 case AO__opencl_atomic_fetch_add:
4506 case AO__opencl_atomic_fetch_sub:
4507 case AO__opencl_atomic_fetch_and:
4508 case AO__opencl_atomic_fetch_or:
4509 case AO__opencl_atomic_fetch_xor:
4510 case AO__opencl_atomic_fetch_min:
4511 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004512 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004513 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004514
4515 case AO__c11_atomic_compare_exchange_strong:
4516 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004517 return 5;
4518
Yaxun Liu39195062017-08-04 18:16:31 +00004519 case AO__opencl_atomic_compare_exchange_strong:
4520 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004521 case AO__atomic_compare_exchange:
4522 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004523 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004524 }
4525 llvm_unreachable("unknown atomic op");
4526}
Alexey Bataeva1764212015-09-30 09:22:36 +00004527
Yaxun Liu39195062017-08-04 18:16:31 +00004528QualType AtomicExpr::getValueType() const {
4529 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4530 if (auto AT = T->getAs<AtomicType>())
4531 return AT->getValueType();
4532 return T;
4533}
4534
Alexey Bataev31300ed2016-02-04 11:27:03 +00004535QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004536 unsigned ArraySectionCount = 0;
4537 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4538 Base = OASE->getBase();
4539 ++ArraySectionCount;
4540 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004541 while (auto *ASE =
4542 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004543 Base = ASE->getBase();
4544 ++ArraySectionCount;
4545 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004546 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004547 auto OriginalTy = Base->getType();
4548 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4549 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4550 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4551
4552 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4553 if (OriginalTy->isAnyPointerType())
4554 OriginalTy = OriginalTy->getPointeeType();
4555 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004556 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004557 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4558 }
4559 }
4560 return OriginalTy;
4561}