blob: a2a024a3c2be14bb603a5ee9322e7bab1e74f572 [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"
Haojian Wu876bb862020-03-17 08:33:37 +010017#include "clang/AST/ComputeDependence.h"
Douglas Gregor9a657932008-10-21 23:43:52 +000018#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000020#include "clang/AST/DeclTemplate.h"
Haojian Wu67d25912020-03-16 13:43:40 +010021#include "clang/AST/DependenceFlags.h"
Douglas Gregor1be329d2012-02-23 07:33:15 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000023#include "clang/AST/ExprCXX.h"
David Majnemerbed356a2013-11-06 23:31:56 +000024#include "clang/AST/Mangle.h"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000025#include "clang/AST/RecordLayout.h"
26#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Chris Lattnere925d612010-11-17 07:37:15 +000029#include "clang/Basic/SourceManager.h"
Chris Lattnera7944d82007-11-27 18:22:04 +000030#include "clang/Basic/TargetInfo.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/Lex/Lexer.h"
32#include "clang/Lex/LiteralSupport.h"
Douglas Gregor0840cc02009-11-01 20:32:48 +000033#include "llvm/Support/ErrorHandling.h"
Anders Carlsson2fb08242009-09-08 18:24:21 +000034#include "llvm/Support/raw_ostream.h"
Douglas Gregord5846a12009-04-15 06:41:24 +000035#include <algorithm>
Eli Friedmanfcec6302011-11-01 02:23:42 +000036#include <cstring>
Chris Lattner1b926492006-08-23 06:42:10 +000037using namespace clang;
38
Richard Smith018ac392016-11-03 18:55:18 +000039const Expr *Expr::getBestDynamicClassTypeExpr() const {
40 const Expr *E = this;
41 while (true) {
42 E = E->ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000043
Richard Smith018ac392016-11-03 18:55:18 +000044 // Follow the RHS of a comma operator.
45 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
46 if (BO->getOpcode() == BO_Comma) {
47 E = BO->getRHS();
48 continue;
49 }
50 }
51
52 // Step into initializer for materialized temporaries.
53 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
Tykerb0561b32019-11-17 11:41:55 +010054 E = MTE->getSubExpr();
Richard Smith018ac392016-11-03 18:55:18 +000055 continue;
56 }
57
58 break;
59 }
60
61 return E;
62}
63
64const CXXRecordDecl *Expr::getBestDynamicClassType() const {
65 const Expr *E = getBestDynamicClassTypeExpr();
Rafael Espindola49e860b2012-06-26 17:45:31 +000066 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000067 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
68 DerivedType = PTy->getPointeeType();
69
Rafael Espindola60a2bba2012-07-17 20:24:05 +000070 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000071 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000072
Rafael Espindola49e860b2012-06-26 17:45:31 +000073 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000074 Decl *D = Ty->getDecl();
75 return cast<CXXRecordDecl>(D);
76}
77
Richard Smithf3fabd22013-06-03 00:17:11 +000078const Expr *Expr::skipRValueSubobjectAdjustments(
79 SmallVectorImpl<const Expr *> &CommaLHSs,
80 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000081 const Expr *E = this;
82 while (true) {
83 E = E->IgnoreParens();
84
85 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
86 if ((CE->getCastKind() == CK_DerivedToBase ||
87 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
88 E->getType()->isRecordType()) {
89 E = CE->getSubExpr();
Simon Pilgrim1cd399c2019-10-03 11:22:48 +000090 auto *Derived =
91 cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
Rafael Espindola9c006de2012-10-27 01:03:43 +000092 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
93 continue;
94 }
95
96 if (CE->getCastKind() == CK_NoOp) {
97 E = CE->getSubExpr();
98 continue;
99 }
100 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000101 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +0000102 assert(ME->getBase()->getType()->isRecordType());
103 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000104 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +0000105 E = ME->getBase();
106 Adjustments.push_back(SubobjectAdjustment(Field));
107 continue;
108 }
Rafael Espindola9c006de2012-10-27 01:03:43 +0000109 }
110 }
111 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Richard Smitha3fd1162018-07-24 21:18:30 +0000112 if (BO->getOpcode() == BO_PtrMemD) {
Rafael Espindola973aa202012-11-01 14:32:20 +0000113 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +0000114 E = BO->getLHS();
115 const MemberPointerType *MPT =
116 BO->getRHS()->getType()->getAs<MemberPointerType>();
117 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +0000118 continue;
119 } else if (BO->getOpcode() == BO_Comma) {
120 CommaLHSs.push_back(BO->getLHS());
121 E = BO->getRHS();
122 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000123 }
124 }
125
126 // Nothing changed.
127 break;
128 }
129 return E;
130}
131
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800132bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000133 const Expr *E = IgnoreParens();
134
Chris Lattner4ebae652010-04-16 23:34:13 +0000135 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000136 if (E->getType()->isBooleanType()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000137 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000138 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000139
Peter Collingbourne91147592011-04-15 00:35:48 +0000140 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000141 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000142 case UO_Plus:
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800143 return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
Richard Trieu0f097742014-04-04 04:13:47 +0000144 case UO_LNot:
145 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000146 default:
147 return false;
148 }
149 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000150
John McCall45d30c32010-06-12 01:56:02 +0000151 // Only look through implicit casts. If the user writes
152 // '(int) (a && b)' treat it as an arbitrary int.
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800153 // FIXME: Should we look through any cast expression in !Semantic mode?
Peter Collingbourne91147592011-04-15 00:35:48 +0000154 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800155 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
Fangrui Song6907ce22018-07-30 19:24:48 +0000156
Peter Collingbourne91147592011-04-15 00:35:48 +0000157 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000158 switch (BO->getOpcode()) {
159 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000160 case BO_LT: // Relational operators.
161 case BO_GT:
162 case BO_LE:
163 case BO_GE:
164 case BO_EQ: // Equality operators.
165 case BO_NE:
166 case BO_LAnd: // AND operator.
167 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000168 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000169
John McCalle3027922010-08-25 11:45:40 +0000170 case BO_And: // Bitwise AND operator.
171 case BO_Xor: // Bitwise XOR operator.
172 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000173 // Handle things like (x==2)|(y==12).
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800174 return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
175 BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
Fangrui Song6907ce22018-07-30 19:24:48 +0000176
John McCalle3027922010-08-25 11:45:40 +0000177 case BO_Comma:
178 case BO_Assign:
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800179 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
Chris Lattner4ebae652010-04-16 23:34:13 +0000180 }
181 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000182
Peter Collingbourne91147592011-04-15 00:35:48 +0000183 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800184 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
185 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
Fangrui Song6907ce22018-07-30 19:24:48 +0000186
Erik Pilkington5c621522019-09-17 21:11:51 +0000187 if (isa<ObjCBoolLiteralExpr>(E))
188 return true;
189
190 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800191 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
Erik Pilkington5c621522019-09-17 21:11:51 +0000192
Erik Pilkington8bfb3532019-11-18 10:56:05 -0800193 if (const FieldDecl *FD = E->getSourceBitField())
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800194 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
Erik Pilkington8bfb3532019-11-18 10:56:05 -0800195 !FD->getBitWidth()->isValueDependent() &&
196 FD->getBitWidthValue(FD->getASTContext()) == 1)
197 return true;
198
Chris Lattner4ebae652010-04-16 23:34:13 +0000199 return false;
200}
201
John McCallbd066782011-02-09 08:16:59 +0000202// Amusing macro metaprogramming hack: check whether a class provides
203// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000204//
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000205// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000206namespace {
207 /// This implementation is used when a class provides a custom
208 /// implementation of getExprLoc.
209 template <class E, class T>
210 SourceLocation getExprLocImpl(const Expr *expr,
211 SourceLocation (T::*v)() const) {
212 return static_cast<const E*>(expr)->getExprLoc();
213 }
John McCallbd066782011-02-09 08:16:59 +0000214
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000215 /// This implementation is used when a class doesn't provide
216 /// a custom implementation of getExprLoc. Overload resolution
217 /// should pick it over the implementation above because it's
218 /// more specialized according to function template partial ordering.
219 template <class E>
220 SourceLocation getExprLocImpl(const Expr *expr,
221 SourceLocation (Expr::*v)() const) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000222 return static_cast<const E *>(expr)->getBeginLoc();
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000223 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000224}
John McCallbd066782011-02-09 08:16:59 +0000225
226SourceLocation Expr::getExprLoc() const {
227 switch (getStmtClass()) {
228 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
229#define ABSTRACT_STMT(type)
230#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000231 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000232#define EXPR(type, base) \
233 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
234#include "clang/AST/StmtNodes.inc"
235 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000236 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000237}
238
Chris Lattner0eedafe2006-08-24 04:56:27 +0000239//===----------------------------------------------------------------------===//
240// Primary Expressions.
241//===----------------------------------------------------------------------===//
242
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000243static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
244 assert((Kind == ConstantExpr::RSK_APValue ||
245 Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&
246 "Invalid StorageKind Value");
247}
248
249ConstantExpr::ResultStorageKind
250ConstantExpr::getStorageKind(const APValue &Value) {
251 switch (Value.getKind()) {
252 case APValue::None:
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000253 case APValue::Indeterminate:
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000254 return ConstantExpr::RSK_None;
255 case APValue::Int:
256 if (!Value.getInt().needsCleanup())
257 return ConstantExpr::RSK_Int64;
258 LLVM_FALLTHROUGH;
259 default:
260 return ConstantExpr::RSK_APValue;
261 }
262}
263
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000264ConstantExpr::ResultStorageKind
265ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
266 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
267 return ConstantExpr::RSK_Int64;
268 return ConstantExpr::RSK_APValue;
269}
270
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000271void ConstantExpr::DefaultInit(ResultStorageKind StorageKind) {
272 ConstantExprBits.ResultKind = StorageKind;
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000273 ConstantExprBits.APValueKind = APValue::None;
274 ConstantExprBits.HasCleanup = false;
275 if (StorageKind == ConstantExpr::RSK_APValue)
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000276 ::new (getTrailingObjects<APValue>()) APValue();
277}
278
279ConstantExpr::ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind)
280 : FullExpr(ConstantExprClass, subexpr) {
281 DefaultInit(StorageKind);
282}
283
284ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
Tyker008e7bf2020-02-04 19:23:33 +0100285 ResultStorageKind StorageKind,
286 bool IsImmediateInvocation) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000287 assert(!isa<ConstantExpr>(E));
288 AssertResultStorageKind(StorageKind);
289 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
290 StorageKind == ConstantExpr::RSK_APValue,
291 StorageKind == ConstantExpr::RSK_Int64);
292 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
293 ConstantExpr *Self = new (Mem) ConstantExpr(E, StorageKind);
Tyker008e7bf2020-02-04 19:23:33 +0100294 Self->ConstantExprBits.IsImmediateInvocation =
295 IsImmediateInvocation;
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000296 return Self;
297}
298
299ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
300 const APValue &Result) {
301 ResultStorageKind StorageKind = getStorageKind(Result);
302 ConstantExpr *Self = Create(Context, E, StorageKind);
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000303 Self->SetResult(Result, Context);
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000304 return Self;
305}
306
307ConstantExpr::ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty)
308 : FullExpr(ConstantExprClass, Empty) {
309 DefaultInit(StorageKind);
310}
311
312ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
313 ResultStorageKind StorageKind,
314 EmptyShell Empty) {
315 AssertResultStorageKind(StorageKind);
316 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
317 StorageKind == ConstantExpr::RSK_APValue,
318 StorageKind == ConstantExpr::RSK_Int64);
319 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
320 ConstantExpr *Self = new (Mem) ConstantExpr(StorageKind, Empty);
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000321 return Self;
322}
323
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000324void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
Simon Pilgrim6198e1c2020-02-05 10:49:43 +0000325 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000326 "Invalid storage for this value kind");
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000327 ConstantExprBits.APValueKind = Value.getKind();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000328 switch (ConstantExprBits.ResultKind) {
329 case RSK_None:
330 return;
331 case RSK_Int64:
332 Int64Result() = *Value.getInt().getRawData();
333 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
334 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
335 return;
336 case RSK_APValue:
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000337 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
338 ConstantExprBits.HasCleanup = true;
339 Context.addDestruction(&APValueResult());
340 }
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000341 APValueResult() = std::move(Value);
342 return;
343 }
344 llvm_unreachable("Invalid ResultKind Bits");
345}
346
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000347llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
348 switch (ConstantExprBits.ResultKind) {
349 case ConstantExpr::RSK_APValue:
350 return APValueResult().getInt();
351 case ConstantExpr::RSK_Int64:
352 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
353 ConstantExprBits.IsUnsigned);
354 default:
355 llvm_unreachable("invalid Accessor");
356 }
357}
358
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000359APValue ConstantExpr::getAPValueResult() const {
Wyatt Childersbe10b7e2020-03-20 14:57:56 -0700360 assert(hasAPValueResult());
361
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000362 switch (ConstantExprBits.ResultKind) {
363 case ConstantExpr::RSK_APValue:
364 return APValueResult();
365 case ConstantExpr::RSK_Int64:
366 return APValue(
367 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
368 ConstantExprBits.IsUnsigned));
369 case ConstantExpr::RSK_None:
370 return APValue();
371 }
372 llvm_unreachable("invalid ResultKind");
373}
374
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000375DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
376 bool RefersToEnclosingVariableOrCapture, QualType T,
377 ExprValueKind VK, SourceLocation L,
Richard Smith715f7a12019-06-11 17:50:32 +0000378 const DeclarationNameLoc &LocInfo,
379 NonOdrUseReason NOUR)
Haojian Wu876bb862020-03-17 08:33:37 +0100380 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000381 DeclRefExprBits.HasQualifier = false;
382 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
383 DeclRefExprBits.HasFoundDecl = false;
384 DeclRefExprBits.HadMultipleCandidates = false;
385 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
386 RefersToEnclosingVariableOrCapture;
Richard Smith715f7a12019-06-11 17:50:32 +0000387 DeclRefExprBits.NonOdrUseReason = NOUR;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000388 DeclRefExprBits.Loc = L;
Haojian Wu876bb862020-03-17 08:33:37 +0100389 setDependence(computeDependence(this, Ctx));
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000390}
391
Craig Topperce7167c2013-08-22 04:58:56 +0000392DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000393 NestedNameSpecifierLoc QualifierLoc,
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000394 SourceLocation TemplateKWLoc, ValueDecl *D,
395 bool RefersToEnclosingVariableOrCapture,
396 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000397 const TemplateArgumentListInfo *TemplateArgs,
Richard Smith715f7a12019-06-11 17:50:32 +0000398 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
Haojian Wu876bb862020-03-17 08:33:37 +0100399 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
400 DNLoc(NameInfo.getInfo()) {
Bruno Riccia795e802018-11-13 17:56:44 +0000401 DeclRefExprBits.Loc = NameInfo.getLoc();
Chandler Carruth0e439962011-05-01 21:29:53 +0000402 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Haojian Wu876bb862020-03-17 08:33:37 +0100403 if (QualifierLoc)
James Y Knighte7d82282015-12-29 18:15:14 +0000404 new (getTrailingObjects<NestedNameSpecifierLoc>())
405 NestedNameSpecifierLoc(QualifierLoc);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000406 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
407 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000408 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000409 DeclRefExprBits.HasTemplateKWAndArgsInfo
410 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000411 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
412 RefersToEnclosingVariableOrCapture;
Richard Smith715f7a12019-06-11 17:50:32 +0000413 DeclRefExprBits.NonOdrUseReason = NOUR;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000414 if (TemplateArgs) {
Ilya Biryukovec3060c2020-03-02 16:07:09 +0100415 auto Deps = TemplateArgumentDependence::None;
James Y Knighte7d82282015-12-29 18:15:14 +0000416 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
417 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
Ilya Biryukovec3060c2020-03-02 16:07:09 +0100418 Deps);
419 assert(!(Deps & TemplateArgumentDependence::Dependent) &&
420 "built a DeclRefExpr with dependent template args");
Abramo Bagnara7945c982012-01-27 09:46:47 +0000421 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000422 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
423 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000424 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000425 DeclRefExprBits.HadMultipleCandidates = 0;
Haojian Wu876bb862020-03-17 08:33:37 +0100426 setDependence(computeDependence(this, Ctx));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000427}
428
Craig Topperce7167c2013-08-22 04:58:56 +0000429DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000430 NestedNameSpecifierLoc QualifierLoc,
Richard Smith715f7a12019-06-11 17:50:32 +0000431 SourceLocation TemplateKWLoc, ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000432 bool RefersToEnclosingVariableOrCapture,
Richard Smith715f7a12019-06-11 17:50:32 +0000433 SourceLocation NameLoc, QualType T,
434 ExprValueKind VK, NamedDecl *FoundD,
435 const TemplateArgumentListInfo *TemplateArgs,
436 NonOdrUseReason NOUR) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000437 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000438 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000439 DeclarationNameInfo(D->getDeclName(), NameLoc),
Richard Smith715f7a12019-06-11 17:50:32 +0000440 T, VK, FoundD, TemplateArgs, NOUR);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000441}
442
Craig Topperce7167c2013-08-22 04:58:56 +0000443DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000444 NestedNameSpecifierLoc QualifierLoc,
Richard Smith715f7a12019-06-11 17:50:32 +0000445 SourceLocation TemplateKWLoc, ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000446 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000447 const DeclarationNameInfo &NameInfo,
Richard Smith715f7a12019-06-11 17:50:32 +0000448 QualType T, ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000449 NamedDecl *FoundD,
Richard Smith715f7a12019-06-11 17:50:32 +0000450 const TemplateArgumentListInfo *TemplateArgs,
451 NonOdrUseReason NOUR) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000452 // Filter out cases where the found Decl is the same as the value refenenced.
453 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000454 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000455
James Y Knighte7d82282015-12-29 18:15:14 +0000456 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
457 std::size_t Size =
458 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
459 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
460 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
461 HasTemplateKWAndArgsInfo ? 1 : 0,
462 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000463
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000464 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000465 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Richard Smith715f7a12019-06-11 17:50:32 +0000466 RefersToEnclosingVariableOrCapture, NameInfo,
467 FoundD, TemplateArgs, T, VK, NOUR);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000468}
469
Craig Topperce7167c2013-08-22 04:58:56 +0000470DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000471 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000472 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000473 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000474 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000475 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
476 std::size_t Size =
477 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
478 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
479 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
480 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000481 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000482 return new (Mem) DeclRefExpr(EmptyShell());
483}
484
Stephen Kelly724e9e52018-08-09 20:05:03 +0000485SourceLocation DeclRefExpr::getBeginLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000486 if (hasQualifier())
487 return getQualifierLoc().getBeginLoc();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000488 return getNameInfo().getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000489}
Stephen Kelly02a67ba2018-08-09 20:05:47 +0000490SourceLocation DeclRefExpr::getEndLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000491 if (hasExplicitTemplateArgs())
492 return getRAngleLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000493 return getNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000494}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000495
Bruno Ricci17ff0262018-10-27 19:21:19 +0000496PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
Alexey Bataevec474782014-10-09 08:45:04 +0000497 StringLiteral *SL)
Haojian Wu876bb862020-03-17 08:33:37 +0100498 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000499 PredefinedExprBits.Kind = IK;
500 assert((getIdentKind() == IK) &&
501 "IdentKind do not fit in PredefinedExprBitfields!");
502 bool HasFunctionName = SL != nullptr;
503 PredefinedExprBits.HasFunctionName = HasFunctionName;
504 PredefinedExprBits.Loc = L;
505 if (HasFunctionName)
506 setFunctionName(SL);
Haojian Wu876bb862020-03-17 08:33:37 +0100507 setDependence(computeDependence(this));
Alexey Bataevec474782014-10-09 08:45:04 +0000508}
509
Bruno Ricci17ff0262018-10-27 19:21:19 +0000510PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
511 : Expr(PredefinedExprClass, Empty) {
512 PredefinedExprBits.HasFunctionName = HasFunctionName;
513}
514
515PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
516 QualType FNTy, IdentKind IK,
517 StringLiteral *SL) {
518 bool HasFunctionName = SL != nullptr;
519 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
520 alignof(PredefinedExpr));
521 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
522}
523
524PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
525 bool HasFunctionName) {
526 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
527 alignof(PredefinedExpr));
528 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
529}
530
531StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
532 switch (IK) {
Alexey Bataevec474782014-10-09 08:45:04 +0000533 case Func:
534 return "__func__";
535 case Function:
536 return "__FUNCTION__";
537 case FuncDName:
538 return "__FUNCDNAME__";
539 case LFunction:
540 return "L__FUNCTION__";
541 case PrettyFunction:
542 return "__PRETTY_FUNCTION__";
543 case FuncSig:
544 return "__FUNCSIG__";
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000545 case LFuncSig:
546 return "L__FUNCSIG__";
Alexey Bataevec474782014-10-09 08:45:04 +0000547 case PrettyFunctionNoVirtual:
548 break;
549 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000550 llvm_unreachable("Unknown ident kind for PredefinedExpr");
Alexey Bataevec474782014-10-09 08:45:04 +0000551}
552
Anders Carlsson2fb08242009-09-08 18:24:21 +0000553// FIXME: Maybe this should use DeclPrinter with a special "print predefined
554// expr" policy instead.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000555std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000556 ASTContext &Context = CurrentDecl->getASTContext();
557
Bruno Ricci17ff0262018-10-27 19:21:19 +0000558 if (IK == PredefinedExpr::FuncDName) {
David Majnemerbed356a2013-11-06 23:31:56 +0000559 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000560 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000561 MC.reset(Context.createMangleContext());
562
563 if (MC->shouldMangleDeclName(ND)) {
564 SmallString<256> Buffer;
565 llvm::raw_svector_ostream Out(Buffer);
Yaxun (Sam) Liu29e1a162020-03-05 12:02:13 -0500566 GlobalDecl GD;
David Majnemerbed356a2013-11-06 23:31:56 +0000567 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
Yaxun (Sam) Liu29e1a162020-03-05 12:02:13 -0500568 GD = GlobalDecl(CD, Ctor_Base);
David Majnemerbed356a2013-11-06 23:31:56 +0000569 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
Yaxun (Sam) Liu29e1a162020-03-05 12:02:13 -0500570 GD = GlobalDecl(DD, Dtor_Base);
Yaxun (Sam) Liu22c457a2020-03-05 12:59:33 -0500571 else if (ND->hasAttr<CUDAGlobalAttr>())
Michael Liao4cf01ed2020-03-18 01:43:20 -0400572 GD = GlobalDecl(cast<FunctionDecl>(ND));
David Majnemerbed356a2013-11-06 23:31:56 +0000573 else
Yaxun (Sam) Liu29e1a162020-03-05 12:02:13 -0500574 GD = GlobalDecl(ND);
575 MC->mangleName(GD, Out);
David Majnemerbed356a2013-11-06 23:31:56 +0000576
David Majnemerbed356a2013-11-06 23:31:56 +0000577 if (!Buffer.empty() && Buffer.front() == '\01')
Benjamin Krameradcd0262020-01-28 20:23:46 +0100578 return std::string(Buffer.substr(1));
579 return std::string(Buffer.str());
David Majnemerbed356a2013-11-06 23:31:56 +0000580 } else
Benjamin Krameradcd0262020-01-28 20:23:46 +0100581 return std::string(ND->getIdentifier()->getName());
David Majnemerbed356a2013-11-06 23:31:56 +0000582 }
583 return "";
584 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000585 if (isa<BlockDecl>(CurrentDecl)) {
586 // For blocks we only emit something if it is enclosed in a function
587 // For top-level block we'd like to include the name of variable, but we
588 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000589 auto DC = CurrentDecl->getDeclContext();
590 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000591 return "";
592
593 SmallString<256> Buffer;
594 llvm::raw_svector_ostream Out(Buffer);
595 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
596 // For nested blocks, propagate up to the parent.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000597 Out << ComputeName(IK, DCBlock);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000598 else if (auto *DCDecl = dyn_cast<Decl>(DC))
Bruno Ricci17ff0262018-10-27 19:21:19 +0000599 Out << ComputeName(IK, DCDecl) << "_block_invoke";
Benjamin Krameradcd0262020-01-28 20:23:46 +0100600 return std::string(Out.str());
Alexey Bataevec474782014-10-09 08:45:04 +0000601 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000602 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000603 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
604 IK != FuncSig && IK != LFuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000605 return FD->getNameAsString();
606
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000607 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000608 llvm::raw_svector_ostream Out(Name);
609
610 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000611 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000612 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000613 if (MD->isStatic())
614 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000615 }
616
David Blaikiebbafb8a2012-03-11 07:00:24 +0000617 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000618 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000619 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000620
Douglas Gregor11a434a2012-04-10 20:14:15 +0000621 const FunctionDecl *Decl = FD;
622 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
623 Decl = Pattern;
624 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000625 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000626 if (FD->hasWrittenPrototype())
627 FT = dyn_cast<FunctionProtoType>(AFT);
628
Bruno Ricci17ff0262018-10-27 19:21:19 +0000629 if (IK == FuncSig || IK == LFuncSig) {
Richard Smith2f63d462017-01-09 21:40:40 +0000630 switch (AFT->getCallConv()) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000631 case CC_C: POut << "__cdecl "; break;
632 case CC_X86StdCall: POut << "__stdcall "; break;
633 case CC_X86FastCall: POut << "__fastcall "; break;
634 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000635 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000636 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000637 // Only bother printing the conventions that MSVC knows about.
638 default: break;
639 }
640 }
641
642 FD->printQualifiedName(POut, Policy);
643
Douglas Gregor11a434a2012-04-10 20:14:15 +0000644 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000645 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000646 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000647 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000648 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000649 }
650
651 if (FT->isVariadic()) {
652 if (FD->getNumParams()) POut << ", ";
653 POut << "...";
Bruno Ricci17ff0262018-10-27 19:21:19 +0000654 } else if ((IK == FuncSig || IK == LFuncSig ||
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000655 !Context.getLangOpts().CPlusPlus) &&
Richard Smithcf63b842017-01-09 22:16:16 +0000656 !Decl->getNumParams()) {
657 POut << "void";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000658 }
659 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000660 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000661
Sam Weinig4e83bd22009-12-27 01:38:20 +0000662 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Richard Smith2f63d462017-01-09 21:40:40 +0000663 assert(FT && "We must have a written prototype in this case.");
David Blaikief5697e52012-08-10 00:55:35 +0000664 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000665 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000666 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000667 POut << " volatile";
668 RefQualifierKind Ref = MD->getRefQualifier();
669 if (Ref == RQ_LValue)
670 POut << " &";
671 else if (Ref == RQ_RValue)
672 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000673 }
674
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000675 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000676 SpecsTy Specs;
677 const DeclContext *Ctx = FD->getDeclContext();
678 while (Ctx && isa<NamedDecl>(Ctx)) {
679 const ClassTemplateSpecializationDecl *Spec
680 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
681 if (Spec && !Spec->isExplicitSpecialization())
682 Specs.push_back(Spec);
683 Ctx = Ctx->getParent();
684 }
685
686 std::string TemplateParams;
687 llvm::raw_string_ostream TOut(TemplateParams);
688 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
689 I != E; ++I) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000690 const TemplateParameterList *Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000691 = (*I)->getSpecializedTemplate()->getTemplateParameters();
692 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
693 assert(Params->size() == Args.size());
694 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
695 StringRef Param = Params->getParam(i)->getName();
696 if (Param.empty()) continue;
697 TOut << Param << " = ";
698 Args.get(i).print(Policy, TOut);
699 TOut << ", ";
700 }
701 }
702
Fangrui Song6907ce22018-07-30 19:24:48 +0000703 FunctionTemplateSpecializationInfo *FSI
Douglas Gregor11a434a2012-04-10 20:14:15 +0000704 = FD->getTemplateSpecializationInfo();
705 if (FSI && !FSI->isExplicitSpecialization()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000706 const TemplateParameterList* Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000707 = FSI->getTemplate()->getTemplateParameters();
708 const TemplateArgumentList* Args = FSI->TemplateArguments;
709 assert(Params->size() == Args->size());
710 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
711 StringRef Param = Params->getParam(i)->getName();
712 if (Param.empty()) continue;
713 TOut << Param << " = ";
714 Args->get(i).print(Policy, TOut);
715 TOut << ", ";
716 }
717 }
718
719 TOut.flush();
720 if (!TemplateParams.empty()) {
721 // remove the trailing comma and space
722 TemplateParams.resize(TemplateParams.size() - 2);
723 POut << " [" << TemplateParams << "]";
724 }
725
726 POut.flush();
727
Benjamin Kramer90f54222013-08-21 11:45:27 +0000728 // Print "auto" for all deduced return types. This includes C++1y return
729 // type deduction and lambdas. For trailing return types resolve the
730 // decltype expression. Otherwise print the real type when this is
731 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000732 if (isa<CXXMethodDecl>(FD) &&
733 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000734 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000735 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
736 FT->getReturnType()
737 ->getAs<DecltypeType>()
738 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000739 .getAsStringInternal(Proto, Policy);
740 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000741 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000742
743 Out << Proto;
744
Jonas Devlieghere509e21a2020-01-29 21:27:46 -0800745 return std::string(Name);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000746 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000747 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
748 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
749 // Skip to its enclosing function or method, but not its enclosing
750 // CapturedDecl.
751 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
752 const Decl *D = Decl::castFromDeclContext(DC);
Bruno Ricci17ff0262018-10-27 19:21:19 +0000753 return ComputeName(IK, D);
Wei Pan8d6b19a2013-08-26 14:27:34 +0000754 }
755 llvm_unreachable("CapturedDecl not inside a function or method");
756 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000757 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000758 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000759 llvm::raw_svector_ostream Out(Name);
760 Out << (MD->isInstanceMethod() ? '-' : '+');
761 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000762
763 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
764 // a null check to avoid a crash.
765 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000766 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000767
Anders Carlsson2fb08242009-09-08 18:24:21 +0000768 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000769 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000770 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000771
Anders Carlsson2fb08242009-09-08 18:24:21 +0000772 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000773 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000774 Out << ']';
775
Jonas Devlieghere509e21a2020-01-29 21:27:46 -0800776 return std::string(Name);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000777 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000778 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000779 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
780 return "top level";
781 }
782 return "";
783}
784
Craig Topper37932912013-08-18 10:09:15 +0000785void APNumericStorage::setIntValue(const ASTContext &C,
786 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000787 if (hasAllocation())
788 C.Deallocate(pVal);
789
790 BitWidth = Val.getBitWidth();
791 unsigned NumWords = Val.getNumWords();
792 const uint64_t* Words = Val.getRawData();
793 if (NumWords > 1) {
794 pVal = new (C) uint64_t[NumWords];
795 std::copy(Words, Words + NumWords, pVal);
796 } else if (NumWords == 1)
797 VAL = Words[0];
798 else
799 VAL = 0;
800}
801
Craig Topper37932912013-08-18 10:09:15 +0000802IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000803 QualType type, SourceLocation l)
Haojian Wu876bb862020-03-17 08:33:37 +0100804 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary), Loc(l) {
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000805 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
806 assert(V.getBitWidth() == C.getIntWidth(type) &&
807 "Integer type is not the correct size for constant.");
808 setValue(C, V);
Haojian Wu876bb862020-03-17 08:33:37 +0100809 setDependence(ExprDependence::None);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000810}
811
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000812IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000813IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000814 QualType type, SourceLocation l) {
815 return new (C) IntegerLiteral(C, V, type, l);
816}
817
818IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000819IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000820 return new (C) IntegerLiteral(Empty);
821}
822
Leonard Chandb01c3a2018-06-20 17:19:40 +0000823FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
824 QualType type, SourceLocation l,
825 unsigned Scale)
Haojian Wu876bb862020-03-17 08:33:37 +0100826 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary), Loc(l),
827 Scale(Scale) {
Leonard Chandb01c3a2018-06-20 17:19:40 +0000828 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
829 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
830 "Fixed point type is not the correct size for constant.");
831 setValue(C, V);
Haojian Wu876bb862020-03-17 08:33:37 +0100832 setDependence(ExprDependence::None);
Leonard Chandb01c3a2018-06-20 17:19:40 +0000833}
834
835FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
836 const llvm::APInt &V,
837 QualType type,
838 SourceLocation l,
839 unsigned Scale) {
840 return new (C) FixedPointLiteral(C, V, type, l, Scale);
841}
842
843std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
844 // Currently the longest decimal number that can be printed is the max for an
845 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
846 // which is 43 characters.
847 SmallString<64> S;
848 FixedPointValueToString(
Leonard Chanc03642e2018-08-06 16:05:08 +0000849 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
Benjamin Krameradcd0262020-01-28 20:23:46 +0100850 return std::string(S.str());
Leonard Chandb01c3a2018-06-20 17:19:40 +0000851}
852
Craig Topper37932912013-08-18 10:09:15 +0000853FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000854 bool isexact, QualType Type, SourceLocation L)
Haojian Wu876bb862020-03-17 08:33:37 +0100855 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000856 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000857 FloatingLiteralBits.IsExact = isexact;
858 setValue(C, V);
Haojian Wu876bb862020-03-17 08:33:37 +0100859 setDependence(ExprDependence::None);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000860}
861
Craig Topper37932912013-08-18 10:09:15 +0000862FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000863 : Expr(FloatingLiteralClass, Empty) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000864 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000865 FloatingLiteralBits.IsExact = false;
866}
867
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000868FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000869FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000870 bool isexact, QualType Type, SourceLocation L) {
871 return new (C) FloatingLiteral(C, V, isexact, Type, L);
872}
873
874FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000875FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000876 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000877}
878
Chris Lattnera0173132008-06-07 22:13:43 +0000879/// getValueAsApproximateDouble - This returns the value as an inaccurate
880/// double. Note that this may cause loss of precision, but is useful for
881/// debugging dumps, etc.
882double FloatingLiteral::getValueAsApproximateDouble() const {
883 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000884 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000885 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
Dale Johannesenc48814b2008-10-09 23:02:32 +0000886 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000887 return V.convertToDouble();
888}
889
Bruno Ricciaf214882018-11-15 16:42:14 +0000890unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
891 StringKind SK) {
892 unsigned CharByteWidth = 0;
893 switch (SK) {
894 case Ascii:
895 case UTF8:
896 CharByteWidth = Target.getCharWidth();
897 break;
898 case Wide:
899 CharByteWidth = Target.getWCharWidth();
900 break;
901 case UTF16:
902 CharByteWidth = Target.getChar16Width();
903 break;
904 case UTF32:
905 CharByteWidth = Target.getChar32Width();
906 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000907 }
908 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
909 CharByteWidth /= 8;
Bruno Ricciaf214882018-11-15 16:42:14 +0000910 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
911 "The only supported character byte widths are 1,2 and 4!");
Eli Friedmanfcec6302011-11-01 02:23:42 +0000912 return CharByteWidth;
913}
914
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000915StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
916 StringKind Kind, bool Pascal, QualType Ty,
917 const SourceLocation *Loc,
918 unsigned NumConcatenated)
Haojian Wu876bb862020-03-17 08:33:37 +0100919 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000920 assert(Ctx.getAsConstantArrayType(Ty) &&
Benjamin Kramercdac7612014-02-25 12:26:20 +0000921 "StringLiteral must be of constant array type!");
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000922 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
923 unsigned ByteLength = Str.size();
924 assert((ByteLength % CharByteWidth == 0) &&
925 "The size of the data must be a multiple of CharByteWidth!");
Benjamin Kramercdac7612014-02-25 12:26:20 +0000926
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000927 // Avoid the expensive division. The compiler should be able to figure it
928 // out by itself. However as of clang 7, even with the appropriate
929 // llvm_unreachable added just here, it is not able to do so.
930 unsigned Length;
931 switch (CharByteWidth) {
932 case 1:
933 Length = ByteLength;
934 break;
935 case 2:
936 Length = ByteLength / 2;
937 break;
938 case 4:
939 Length = ByteLength / 4;
940 break;
941 default:
942 llvm_unreachable("Unsupported character width!");
943 }
Mike Stump11289f42009-09-09 15:08:12 +0000944
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000945 StringLiteralBits.Kind = Kind;
946 StringLiteralBits.CharByteWidth = CharByteWidth;
947 StringLiteralBits.IsPascal = Pascal;
948 StringLiteralBits.NumConcatenated = NumConcatenated;
949 *getTrailingObjects<unsigned>() = Length;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000950
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000951 // Initialize the trailing array of SourceLocation.
952 // This is safe since SourceLocation is POD-like.
953 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
954 NumConcatenated * sizeof(SourceLocation));
Chris Lattnerd3e98952006-10-06 05:22:26 +0000955
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000956 // Initialize the trailing array of char holding the string data.
957 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
Haojian Wu876bb862020-03-17 08:33:37 +0100958
959 setDependence(ExprDependence::None);
Chris Lattner630970d2009-02-18 05:49:11 +0000960}
961
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000962StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
963 unsigned Length, unsigned CharByteWidth)
964 : Expr(StringLiteralClass, Empty) {
965 StringLiteralBits.CharByteWidth = CharByteWidth;
966 StringLiteralBits.NumConcatenated = NumConcatenated;
967 *getTrailingObjects<unsigned>() = Length;
968}
969
970StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
971 StringKind Kind, bool Pascal, QualType Ty,
972 const SourceLocation *Loc,
973 unsigned NumConcatenated) {
974 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
975 1, NumConcatenated, Str.size()),
976 alignof(StringLiteral));
977 return new (Mem)
978 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
979}
980
981StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
982 unsigned NumConcatenated,
983 unsigned Length,
984 unsigned CharByteWidth) {
985 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
986 1, NumConcatenated, Length * CharByteWidth),
987 alignof(StringLiteral));
988 return new (Mem)
989 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
Douglas Gregor958dfc92009-04-15 16:35:07 +0000990}
991
Alexander Kornienko540bacb2013-02-01 12:35:51 +0000992void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +0000993 switch (getKind()) {
994 case Ascii: break; // no prefix.
995 case Wide: OS << 'L'; break;
996 case UTF8: OS << "u8"; break;
997 case UTF16: OS << 'u'; break;
998 case UTF32: OS << 'U'; break;
999 }
1000 OS << '"';
1001 static const char Hex[] = "0123456789ABCDEF";
1002
1003 unsigned LastSlashX = getLength();
1004 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1005 switch (uint32_t Char = getCodeUnit(I)) {
1006 default:
1007 // FIXME: Convert UTF-8 back to codepoints before rendering.
1008
1009 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1010 // Leave invalid surrogates alone; we'll use \x for those.
Fangrui Song6907ce22018-07-30 19:24:48 +00001011 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
Richard Trieudc355912012-06-13 20:25:24 +00001012 Char <= 0xdbff) {
1013 uint32_t Trail = getCodeUnit(I + 1);
1014 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1015 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1016 ++I;
1017 }
1018 }
1019
1020 if (Char > 0xff) {
1021 // If this is a wide string, output characters over 0xff using \x
1022 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1023 // codepoint: use \x escapes for invalid codepoints.
1024 if (getKind() == Wide ||
1025 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1026 // FIXME: Is this the best way to print wchar_t?
1027 OS << "\\x";
1028 int Shift = 28;
1029 while ((Char >> Shift) == 0)
1030 Shift -= 4;
1031 for (/**/; Shift >= 0; Shift -= 4)
1032 OS << Hex[(Char >> Shift) & 15];
1033 LastSlashX = I;
1034 break;
1035 }
1036
1037 if (Char > 0xffff)
1038 OS << "\\U00"
1039 << Hex[(Char >> 20) & 15]
1040 << Hex[(Char >> 16) & 15];
1041 else
1042 OS << "\\u";
1043 OS << Hex[(Char >> 12) & 15]
1044 << Hex[(Char >> 8) & 15]
1045 << Hex[(Char >> 4) & 15]
1046 << Hex[(Char >> 0) & 15];
1047 break;
1048 }
1049
1050 // If we used \x... for the previous character, and this character is a
1051 // hexadecimal digit, prevent it being slurped as part of the \x.
1052 if (LastSlashX + 1 == I) {
1053 switch (Char) {
1054 case '0': case '1': case '2': case '3': case '4':
1055 case '5': case '6': case '7': case '8': case '9':
1056 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1057 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1058 OS << "\"\"";
1059 }
1060 }
1061
1062 assert(Char <= 0xff &&
1063 "Characters above 0xff should already have been handled.");
1064
Jordan Rosea7d03842013-02-08 22:30:41 +00001065 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +00001066 OS << (char)Char;
1067 else // Output anything hard as an octal escape.
1068 OS << '\\'
1069 << (char)('0' + ((Char >> 6) & 7))
1070 << (char)('0' + ((Char >> 3) & 7))
1071 << (char)('0' + ((Char >> 0) & 7));
1072 break;
1073 // Handle some common non-printable cases to make dumps prettier.
1074 case '\\': OS << "\\\\"; break;
1075 case '"': OS << "\\\""; break;
Richard Trieudc355912012-06-13 20:25:24 +00001076 case '\a': OS << "\\a"; break;
1077 case '\b': OS << "\\b"; break;
Benjamin Kramer60a53d52016-11-24 09:41:33 +00001078 case '\f': OS << "\\f"; break;
1079 case '\n': OS << "\\n"; break;
1080 case '\r': OS << "\\r"; break;
1081 case '\t': OS << "\\t"; break;
1082 case '\v': OS << "\\v"; break;
Richard Trieudc355912012-06-13 20:25:24 +00001083 }
1084 }
1085 OS << '"';
1086}
1087
Chris Lattnere925d612010-11-17 07:37:15 +00001088/// getLocationOfByte - Return a source location that points to the specified
1089/// byte of this string literal.
1090///
1091/// Strings are amazingly complex. They can be formed from multiple tokens and
1092/// can have escape sequences in them in addition to the usual trigraph and
1093/// escaped newline business. This routine handles this complexity.
1094///
Richard Smithefb116f2015-12-10 01:11:47 +00001095/// The *StartToken sets the first token to be searched in this function and
1096/// the *StartTokenByteOffset is the byte offset of the first token. Before
1097/// returning, it updates the *StartToken to the TokNo of the token being found
1098/// and sets *StartTokenByteOffset to the byte offset of the token in the
1099/// string.
1100/// Using these two parameters can reduce the time complexity from O(n^2) to
1101/// O(n) if one wants to get the location of byte for all the tokens in a
1102/// string.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001103///
Richard Smithefb116f2015-12-10 01:11:47 +00001104SourceLocation
1105StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1106 const LangOptions &Features,
1107 const TargetInfo &Target, unsigned *StartToken,
1108 unsigned *StartTokenByteOffset) const {
Bruno Ricciaf214882018-11-15 16:42:14 +00001109 assert((getKind() == StringLiteral::Ascii ||
1110 getKind() == StringLiteral::UTF8) &&
Richard Smith4060f772012-06-13 05:37:23 +00001111 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001112
Chris Lattnere925d612010-11-17 07:37:15 +00001113 // Loop over all of the tokens in this string until we find the one that
1114 // contains the byte we're looking for.
1115 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001116 unsigned StringOffset = 0;
1117 if (StartToken)
1118 TokNo = *StartToken;
1119 if (StartTokenByteOffset) {
1120 StringOffset = *StartTokenByteOffset;
1121 ByteNo -= StringOffset;
1122 }
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001123 while (1) {
Chris Lattnere925d612010-11-17 07:37:15 +00001124 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1125 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
Fangrui Song6907ce22018-07-30 19:24:48 +00001126
Chris Lattnere925d612010-11-17 07:37:15 +00001127 // Get the spelling of the string so that we can get the data that makes up
1128 // the string literal, not the identifier for the macro it is potentially
1129 // expanded through.
1130 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001131
Chris Lattnere925d612010-11-17 07:37:15 +00001132 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001133 std::pair<FileID, unsigned> LocInfo =
1134 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001135 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001136 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001137 if (Invalid) {
1138 if (StartTokenByteOffset != nullptr)
1139 *StartTokenByteOffset = StringOffset;
1140 if (StartToken != nullptr)
1141 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001142 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001143 }
1144
Chris Lattnere925d612010-11-17 07:37:15 +00001145 const char *StrData = Buffer.data()+LocInfo.second;
Fangrui Song6907ce22018-07-30 19:24:48 +00001146
Chris Lattnere925d612010-11-17 07:37:15 +00001147 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001148 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1149 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001150 Token TheTok;
1151 TheLexer.LexFromRawLexer(TheTok);
Fangrui Song6907ce22018-07-30 19:24:48 +00001152
Chris Lattnere925d612010-11-17 07:37:15 +00001153 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001154 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001155 unsigned TokNumBytes = SLP.GetStringLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00001156
Chris Lattnere925d612010-11-17 07:37:15 +00001157 // If the byte is in this token, return the location of the byte.
1158 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001159 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001160 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1161
Chris Lattnere925d612010-11-17 07:37:15 +00001162 // Now that we know the offset of the token in the spelling, use the
1163 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001164 if (StartTokenByteOffset != nullptr)
1165 *StartTokenByteOffset = StringOffset;
1166 if (StartToken != nullptr)
1167 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001168 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1169 }
Richard Smithefb116f2015-12-10 01:11:47 +00001170
Chris Lattnere925d612010-11-17 07:37:15 +00001171 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001172 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001173 ++TokNo;
1174 ByteNo -= TokNumBytes;
1175 }
1176}
1177
Chris Lattner1b926492006-08-23 06:42:10 +00001178/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1179/// corresponds to, e.g. "sizeof" or "[pre]++".
Bruno Ricci3dfcb842018-11-13 21:33:22 +00001180StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1181 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001182#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1183#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001184 }
David Blaikief47fa302012-01-17 02:30:50 +00001185 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001186}
1187
John McCalle3027922010-08-25 11:45:40 +00001188UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001189UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1190 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001191 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001192 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1193 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1194 case OO_Amp: return UO_AddrOf;
1195 case OO_Star: return UO_Deref;
1196 case OO_Plus: return UO_Plus;
1197 case OO_Minus: return UO_Minus;
1198 case OO_Tilde: return UO_Not;
1199 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001200 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001201 }
1202}
1203
1204OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1205 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001206 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1207 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1208 case UO_AddrOf: return OO_Amp;
1209 case UO_Deref: return OO_Star;
1210 case UO_Plus: return OO_Plus;
1211 case UO_Minus: return OO_Minus;
1212 case UO_Not: return OO_Tilde;
1213 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001214 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001215 default: return OO_None;
1216 }
1217}
1218
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001219
Chris Lattner0eedafe2006-08-24 04:56:27 +00001220//===----------------------------------------------------------------------===//
1221// Postfix Operators.
1222//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001223
Bruno Riccic5885cf2018-12-21 15:20:32 +00001224CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1225 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1226 SourceLocation RParenLoc, unsigned MinNumArgs,
1227 ADLCallKind UsesADL)
Haojian Wu876bb862020-03-17 08:33:37 +01001228 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
Bruno Riccic5885cf2018-12-21 15:20:32 +00001229 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1230 unsigned NumPreArgs = PreArgs.size();
1231 CallExprBits.NumPreArgs = NumPreArgs;
1232 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1233
1234 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1235 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1236 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1237 "OffsetToTrailingObjects overflow!");
1238
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001239 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1240
Bruno Riccic5885cf2018-12-21 15:20:32 +00001241 setCallee(Fn);
Haojian Wu876bb862020-03-17 08:33:37 +01001242 for (unsigned I = 0; I != NumPreArgs; ++I)
Bruno Riccic5885cf2018-12-21 15:20:32 +00001243 setPreArg(I, PreArgs[I]);
Haojian Wu876bb862020-03-17 08:33:37 +01001244 for (unsigned I = 0; I != Args.size(); ++I)
Bruno Riccic5885cf2018-12-21 15:20:32 +00001245 setArg(I, Args[I]);
Haojian Wu876bb862020-03-17 08:33:37 +01001246 for (unsigned I = Args.size(); I != NumArgs; ++I)
Bruno Riccic5885cf2018-12-21 15:20:32 +00001247 setArg(I, nullptr);
Haojian Wu876bb862020-03-17 08:33:37 +01001248
1249 setDependence(computeDependence(this, PreArgs));
Douglas Gregor993603d2008-11-14 16:09:21 +00001250}
Nate Begeman1e36a852008-01-17 17:46:27 +00001251
Bruno Riccic5885cf2018-12-21 15:20:32 +00001252CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1253 EmptyShell Empty)
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001254 : Expr(SC, Empty), NumArgs(NumArgs) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001255 CallExprBits.NumPreArgs = NumPreArgs;
Bruno Riccic5885cf2018-12-21 15:20:32 +00001256 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1257
1258 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1259 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1260 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1261 "OffsetToTrailingObjects overflow!");
Douglas Gregore20a2e52009-04-15 17:43:59 +00001262}
1263
Bruno Riccic5885cf2018-12-21 15:20:32 +00001264CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1265 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1266 SourceLocation RParenLoc, unsigned MinNumArgs,
1267 ADLCallKind UsesADL) {
1268 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1269 unsigned SizeOfTrailingObjects =
1270 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1271 void *Mem =
1272 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1273 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1274 RParenLoc, MinNumArgs, UsesADL);
1275}
1276
1277CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1278 ExprValueKind VK, SourceLocation RParenLoc,
1279 ADLCallKind UsesADL) {
1280 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1281 "Misaligned memory in CallExpr::CreateTemporary!");
1282 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1283 VK, RParenLoc, /*MinNumArgs=*/0, UsesADL);
1284}
1285
1286CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1287 EmptyShell Empty) {
1288 unsigned SizeOfTrailingObjects =
1289 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1290 void *Mem =
1291 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1292 return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1293}
1294
1295unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1296 switch (SC) {
1297 case CallExprClass:
1298 return sizeof(CallExpr);
1299 case CXXOperatorCallExprClass:
1300 return sizeof(CXXOperatorCallExpr);
1301 case CXXMemberCallExprClass:
1302 return sizeof(CXXMemberCallExpr);
1303 case UserDefinedLiteralClass:
1304 return sizeof(UserDefinedLiteral);
1305 case CUDAKernelCallExprClass:
1306 return sizeof(CUDAKernelCallExpr);
1307 default:
1308 llvm_unreachable("unexpected class deriving from CallExpr!");
1309 }
1310}
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001311
John McCallb92ab1a2016-10-26 23:46:34 +00001312Decl *Expr::getReferencedDeclOfCallee() {
1313 Expr *CEE = IgnoreParenImpCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00001314
Richard Smithda3dc002020-02-05 19:01:33 -08001315 while (SubstNonTypeTemplateParmExpr *NTTP =
1316 dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1317 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
Douglas Gregore0e96302011-09-06 21:41:04 +00001318 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001319
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001320 // If we're calling a dereference, look at the pointer instead.
Richard Smithda3dc002020-02-05 19:01:33 -08001321 while (true) {
1322 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1323 if (BO->isPtrMemOp()) {
1324 CEE = BO->getRHS()->IgnoreParenImpCasts();
1325 continue;
1326 }
1327 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1328 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1329 UO->getOpcode() == UO_Plus) {
1330 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1331 continue;
1332 }
1333 }
1334 break;
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001335 }
Richard Smithda3dc002020-02-05 19:01:33 -08001336
Chris Lattner52301912009-07-17 15:46:27 +00001337 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001338 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001339 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1340 return ME->getMemberDecl();
Yaxun Liud83c7402019-02-26 16:20:41 +00001341 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1342 return BE->getBlockDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001343
Craig Topper36250ad2014-05-12 05:36:57 +00001344 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001345}
1346
Richard Smithda3dc002020-02-05 19:01:33 -08001347/// If this is a call to a builtin, return the builtin ID. If not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001348unsigned CallExpr::getBuiltinCallee() const {
Richard Smithda3dc002020-02-05 19:01:33 -08001349 auto *FDecl =
1350 dyn_cast_or_null<FunctionDecl>(getCallee()->getReferencedDeclOfCallee());
1351 return FDecl ? FDecl->getBuiltinID() : 0;
Chris Lattner01ff98a2008-10-06 05:00:53 +00001352}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001353
Scott Douglass503fc392015-06-10 13:53:15 +00001354bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001355 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001356 return Ctx.BuiltinInfo.isUnevaluated(BI);
1357 return false;
1358}
1359
David Majnemerced8bdf2015-02-25 17:36:15 +00001360QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1361 const Expr *Callee = getCallee();
1362 QualType CalleeType = Callee->getType();
1363 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001364 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001365 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001366 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001367 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1368 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1369 return Ctx.VoidTy;
1370
John McCall0009fcc2011-04-26 20:42:42 +00001371 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001372 CalleeType = Expr::findBoundMemberType(Callee);
1373 }
1374
John McCall0009fcc2011-04-26 20:42:42 +00001375 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001376 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001377}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001378
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00001379const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1380 // If the return type is a struct, union, or enum that is marked nodiscard,
1381 // then return the return type attribute.
1382 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1383 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1384 return A;
1385
1386 // Otherwise, see if the callee is marked nodiscard and return that attribute
1387 // instead.
1388 const Decl *D = getCalleeDecl();
1389 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1390}
1391
Stephen Kelly724e9e52018-08-09 20:05:03 +00001392SourceLocation CallExpr::getBeginLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001393 if (isa<CXXOperatorCallExpr>(this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001394 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001395
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001396 SourceLocation begin = getCallee()->getBeginLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001397 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001398 begin = getArg(0)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001399 return begin;
1400}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001401SourceLocation CallExpr::getEndLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001402 if (isa<CXXOperatorCallExpr>(this))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001403 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001404
1405 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001406 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001407 end = getArg(getNumArgs() - 1)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001408 return end;
1409}
John McCall701417a2011-02-21 06:23:05 +00001410
Craig Topper37932912013-08-18 10:09:15 +00001411OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001412 SourceLocation OperatorLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001413 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001414 ArrayRef<OffsetOfNode> comps,
1415 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001416 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001417 void *Mem = C.Allocate(
1418 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001419
Benjamin Kramerc215e762012-08-24 11:54:20 +00001420 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1421 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001422}
1423
Craig Topper37932912013-08-18 10:09:15 +00001424OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001425 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001426 void *Mem =
1427 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001428 return new (Mem) OffsetOfExpr(numComps, numExprs);
1429}
1430
Craig Topper37932912013-08-18 10:09:15 +00001431OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001432 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Haojian Wu876bb862020-03-17 08:33:37 +01001433 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001434 SourceLocation RParenLoc)
Haojian Wu876bb862020-03-17 08:33:37 +01001435 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary),
1436 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1437 NumComps(comps.size()), NumExprs(exprs.size()) {
1438 for (unsigned i = 0; i != comps.size(); ++i)
Benjamin Kramerc215e762012-08-24 11:54:20 +00001439 setComponent(i, comps[i]);
Haojian Wu876bb862020-03-17 08:33:37 +01001440 for (unsigned i = 0; i != exprs.size(); ++i)
Haojian Wu18c97662020-03-16 16:49:38 +01001441 setIndexExpr(i, exprs[i]);
Haojian Wu876bb862020-03-17 08:33:37 +01001442
1443 setDependence(computeDependence(this));
Douglas Gregor882211c2010-04-28 22:16:22 +00001444}
1445
James Y Knight7281c352015-12-29 22:31:18 +00001446IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001447 assert(getKind() == Field || getKind() == Identifier);
1448 if (getKind() == Field)
1449 return getField()->getIdentifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00001450
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001451 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001452}
1453
David Majnemer10fd83d2015-01-15 10:04:14 +00001454UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1455 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1456 SourceLocation op, SourceLocation rp)
Haojian Wu876bb862020-03-17 08:33:37 +01001457 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary),
David Majnemer10fd83d2015-01-15 10:04:14 +00001458 OpLoc(op), RParenLoc(rp) {
1459 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1460 UnaryExprOrTypeTraitExprBits.IsType = false;
1461 Argument.Ex = E;
Haojian Wu876bb862020-03-17 08:33:37 +01001462 setDependence(computeDependence(this));
David Majnemer10fd83d2015-01-15 10:04:14 +00001463}
1464
Richard Smithdcf17de2019-06-06 23:24:15 +00001465MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1466 ValueDecl *MemberDecl,
1467 const DeclarationNameInfo &NameInfo, QualType T,
Richard Smith1bbad592019-06-11 17:50:36 +00001468 ExprValueKind VK, ExprObjectKind OK,
1469 NonOdrUseReason NOUR)
Haojian Wu876bb862020-03-17 08:33:37 +01001470 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1471 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
Richard Smithdcf17de2019-06-06 23:24:15 +00001472 assert(!NameInfo.getName() ||
1473 MemberDecl->getDeclName() == NameInfo.getName());
1474 MemberExprBits.IsArrow = IsArrow;
1475 MemberExprBits.HasQualifierOrFoundDecl = false;
1476 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1477 MemberExprBits.HadMultipleCandidates = false;
Richard Smith1bbad592019-06-11 17:50:36 +00001478 MemberExprBits.NonOdrUseReason = NOUR;
Richard Smithdcf17de2019-06-06 23:24:15 +00001479 MemberExprBits.OperatorLoc = OperatorLoc;
Haojian Wu876bb862020-03-17 08:33:37 +01001480 setDependence(computeDependence(this));
Richard Smithdcf17de2019-06-06 23:24:15 +00001481}
1482
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001483MemberExpr *MemberExpr::Create(
Richard Smithdcf17de2019-06-06 23:24:15 +00001484 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001485 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
Richard Smithdcf17de2019-06-06 23:24:15 +00001486 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1487 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
Richard Smith1bbad592019-06-11 17:50:36 +00001488 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
Richard Smithdcf17de2019-06-06 23:24:15 +00001489 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1490 FoundDecl.getAccess() != MemberDecl->getAccess();
1491 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
James Y Knighte7d82282015-12-29 18:15:14 +00001492 std::size_t Size =
1493 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
Richard Smithdcf17de2019-06-06 23:24:15 +00001494 TemplateArgumentLoc>(
1495 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1496 TemplateArgs ? TemplateArgs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001497
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001498 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Richard Smith1bbad592019-06-11 17:50:36 +00001499 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1500 NameInfo, T, VK, OK, NOUR);
John McCall16df1e52010-03-30 21:47:33 +00001501
Sam McCallb4f02d82020-03-18 23:38:08 +01001502 // FIXME: remove remaining dependence computation to computeDependence().
1503 auto Deps = E->getDependence();
Richard Smithdcf17de2019-06-06 23:24:15 +00001504 if (HasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001505 // FIXME: Wrong. We should be looking at the member declaration we found.
Ilya Biryukovec3060c2020-03-02 16:07:09 +01001506 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent())
Sam McCallb4f02d82020-03-18 23:38:08 +01001507 Deps |= ExprDependence::TypeValueInstantiation;
Fangrui Song6907ce22018-07-30 19:24:48 +00001508 else if (QualifierLoc &&
1509 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
Sam McCallb4f02d82020-03-18 23:38:08 +01001510 Deps |= ExprDependence::Instantiation;
Fangrui Song6907ce22018-07-30 19:24:48 +00001511
Bruno Ricci4c742532018-11-15 13:56:22 +00001512 E->MemberExprBits.HasQualifierOrFoundDecl = true;
John McCall16df1e52010-03-30 21:47:33 +00001513
James Y Knighte7d82282015-12-29 18:15:14 +00001514 MemberExprNameQualifier *NQ =
1515 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001516 NQ->QualifierLoc = QualifierLoc;
Richard Smithdcf17de2019-06-06 23:24:15 +00001517 NQ->FoundDecl = FoundDecl;
John McCall16df1e52010-03-30 21:47:33 +00001518 }
1519
Bruno Ricci4c742532018-11-15 13:56:22 +00001520 E->MemberExprBits.HasTemplateKWAndArgsInfo =
Richard Smithdcf17de2019-06-06 23:24:15 +00001521 TemplateArgs || TemplateKWLoc.isValid();
Abramo Bagnara7945c982012-01-27 09:46:47 +00001522
Richard Smithdcf17de2019-06-06 23:24:15 +00001523 if (TemplateArgs) {
Sam McCallb4f02d82020-03-18 23:38:08 +01001524 auto TemplateArgDeps = TemplateArgumentDependence::None;
James Y Knighte7d82282015-12-29 18:15:14 +00001525 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
Richard Smithdcf17de2019-06-06 23:24:15 +00001526 TemplateKWLoc, *TemplateArgs,
Sam McCallb4f02d82020-03-18 23:38:08 +01001527 E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps);
1528 if (TemplateArgDeps & TemplateArgumentDependence::Instantiation)
1529 Deps |= ExprDependence::Instantiation;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001530 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001531 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1532 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001533 }
Sam McCallb4f02d82020-03-18 23:38:08 +01001534 E->setDependence(Deps);
John McCall16df1e52010-03-30 21:47:33 +00001535
1536 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001537}
1538
Richard Smithdcf17de2019-06-06 23:24:15 +00001539MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1540 bool HasQualifier, bool HasFoundDecl,
1541 bool HasTemplateKWAndArgsInfo,
1542 unsigned NumTemplateArgs) {
1543 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1544 "template args but no template arg info?");
1545 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1546 std::size_t Size =
1547 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1548 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1549 HasTemplateKWAndArgsInfo ? 1 : 0,
1550 NumTemplateArgs);
1551 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1552 return new (Mem) MemberExpr(EmptyShell());
1553}
1554
Stephen Kelly724e9e52018-08-09 20:05:03 +00001555SourceLocation MemberExpr::getBeginLoc() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001556 if (isImplicitAccess()) {
1557 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001558 return getQualifierLoc().getBeginLoc();
1559 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001560 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001561
Daniel Dunbarb507f272012-03-09 15:39:15 +00001562 // FIXME: We don't want this to happen. Rather, we should be able to
1563 // detect all kinds of implicit accesses more cleanly.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001564 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001565 if (BaseStartLoc.isValid())
1566 return BaseStartLoc;
1567 return MemberLoc;
1568}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001569SourceLocation MemberExpr::getEndLoc() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001570 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001571 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001572 EndLoc = getRAngleLoc();
1573 else if (EndLoc.isInvalid())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001574 EndLoc = getBase()->getEndLoc();
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001575 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001576}
1577
Alp Tokerc1086762013-12-07 13:51:35 +00001578bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001579 switch (getCastKind()) {
1580 case CK_DerivedToBase:
1581 case CK_UncheckedDerivedToBase:
1582 case CK_DerivedToBaseMemberPointer:
1583 case CK_BaseToDerived:
1584 case CK_BaseToDerivedMemberPointer:
1585 assert(!path_empty() && "Cast kind should have a base path!");
1586 break;
1587
1588 case CK_CPointerToObjCPointerCast:
1589 assert(getType()->isObjCObjectPointerType());
1590 assert(getSubExpr()->getType()->isPointerType());
1591 goto CheckNoBasePath;
1592
1593 case CK_BlockPointerToObjCPointerCast:
1594 assert(getType()->isObjCObjectPointerType());
1595 assert(getSubExpr()->getType()->isBlockPointerType());
1596 goto CheckNoBasePath;
1597
John McCallc62bb392012-02-15 01:22:51 +00001598 case CK_ReinterpretMemberPointer:
1599 assert(getType()->isMemberPointerType());
1600 assert(getSubExpr()->getType()->isMemberPointerType());
1601 goto CheckNoBasePath;
1602
John McCall9320b872011-09-09 05:25:32 +00001603 case CK_BitCast:
1604 // Arbitrary casts to C pointer types count as bitcasts.
1605 // Otherwise, we should only have block and ObjC pointer casts
1606 // here if they stay within the type kind.
1607 if (!getType()->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001608 assert(getType()->isObjCObjectPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001609 getSubExpr()->getType()->isObjCObjectPointerType());
Fangrui Song6907ce22018-07-30 19:24:48 +00001610 assert(getType()->isBlockPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001611 getSubExpr()->getType()->isBlockPointerType());
1612 }
1613 goto CheckNoBasePath;
1614
1615 case CK_AnyPointerToBlockPointerCast:
1616 assert(getType()->isBlockPointerType());
1617 assert(getSubExpr()->getType()->isAnyPointerType() &&
1618 !getSubExpr()->getType()->isBlockPointerType());
1619 goto CheckNoBasePath;
1620
Douglas Gregored90df32012-02-22 05:02:47 +00001621 case CK_CopyAndAutoreleaseBlockObject:
1622 assert(getType()->isBlockPointerType());
1623 assert(getSubExpr()->getType()->isBlockPointerType());
1624 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001625
1626 case CK_FunctionToPointerDecay:
1627 assert(getType()->isPointerType());
1628 assert(getSubExpr()->getType()->isFunctionType());
1629 goto CheckNoBasePath;
1630
Anastasia Stulova04307942018-11-16 16:22:56 +00001631 case CK_AddressSpaceConversion: {
1632 auto Ty = getType();
1633 auto SETy = getSubExpr()->getType();
1634 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
Anastasia Stulovaa29aa472019-11-27 11:03:11 +00001635 if (isRValue()) {
Anastasia Stulova04307942018-11-16 16:22:56 +00001636 Ty = Ty->getPointeeType();
Anastasia Stulova04307942018-11-16 16:22:56 +00001637 SETy = SETy->getPointeeType();
Anastasia Stulovad1986d12019-01-14 11:44:22 +00001638 }
Anastasia Stulova04307942018-11-16 16:22:56 +00001639 assert(!Ty.isNull() && !SETy.isNull() &&
1640 Ty.getAddressSpace() != SETy.getAddressSpace());
1641 goto CheckNoBasePath;
1642 }
John McCall9320b872011-09-09 05:25:32 +00001643 // These should not have an inheritance path.
1644 case CK_Dynamic:
1645 case CK_ToUnion:
1646 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001647 case CK_NullToMemberPointer:
1648 case CK_NullToPointer:
1649 case CK_ConstructorConversion:
1650 case CK_IntegralToPointer:
1651 case CK_PointerToIntegral:
1652 case CK_ToVoid:
1653 case CK_VectorSplat:
1654 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001655 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001656 case CK_IntegralToFloating:
1657 case CK_FloatingToIntegral:
1658 case CK_FloatingCast:
1659 case CK_ObjCObjectLValueCast:
1660 case CK_FloatingRealToComplex:
1661 case CK_FloatingComplexToReal:
1662 case CK_FloatingComplexCast:
1663 case CK_FloatingComplexToIntegralComplex:
1664 case CK_IntegralRealToComplex:
1665 case CK_IntegralComplexToReal:
1666 case CK_IntegralComplexCast:
1667 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001668 case CK_ARCProduceObject:
1669 case CK_ARCConsumeObject:
1670 case CK_ARCReclaimReturnedObject:
1671 case CK_ARCExtendBlockObject:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001672 case CK_ZeroToOCLOpaqueType:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001673 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00001674 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +00001675 case CK_FixedPointToIntegral:
1676 case CK_IntegralToFixedPoint:
John McCall9320b872011-09-09 05:25:32 +00001677 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1678 goto CheckNoBasePath;
1679
1680 case CK_Dependent:
1681 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001682 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001683 case CK_AtomicToNonAtomic:
1684 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001685 case CK_PointerToBoolean:
1686 case CK_IntegralToBoolean:
1687 case CK_FloatingToBoolean:
1688 case CK_MemberPointerToBoolean:
1689 case CK_FloatingComplexToBoolean:
1690 case CK_IntegralComplexToBoolean:
1691 case CK_LValueBitCast: // -> bool&
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00001692 case CK_LValueToRValueBitCast:
John McCall9320b872011-09-09 05:25:32 +00001693 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001694 case CK_BuiltinFnToFnPtr:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001695 case CK_FixedPointToBoolean:
John McCall9320b872011-09-09 05:25:32 +00001696 CheckNoBasePath:
1697 assert(path_empty() && "Cast kind should not have a base path!");
1698 break;
1699 }
Alp Tokerc1086762013-12-07 13:51:35 +00001700 return true;
John McCall9320b872011-09-09 05:25:32 +00001701}
1702
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001703const char *CastExpr::getCastKindName(CastKind CK) {
1704 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001705#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1706#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001707 }
John McCallc5e62b42010-11-13 09:02:35 +00001708 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001709}
1710
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001711namespace {
Richard Smith1ef75542018-06-27 20:30:34 +00001712 const Expr *skipImplicitTemporary(const Expr *E) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001713 // Skip through reference binding to temporary.
Richard Smith1ef75542018-06-27 20:30:34 +00001714 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01001715 E = Materialize->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001716
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001717 // Skip any temporary bindings; they're implicit.
Richard Smith1ef75542018-06-27 20:30:34 +00001718 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1719 E = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001720
Richard Smith1ef75542018-06-27 20:30:34 +00001721 return E;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001722 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001723}
1724
Douglas Gregord196a582009-12-14 19:27:10 +00001725Expr *CastExpr::getSubExprAsWritten() {
Richard Smith1ef75542018-06-27 20:30:34 +00001726 const Expr *SubExpr = nullptr;
1727 const CastExpr *E = this;
Douglas Gregord196a582009-12-14 19:27:10 +00001728 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001729 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001730
Douglas Gregord196a582009-12-14 19:27:10 +00001731 // Conversions by constructor and conversion functions have a
1732 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001733 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001734 SubExpr =
1735 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001736 else if (E->getCastKind() == CK_UserDefinedConversion) {
1737 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1738 isa<BlockExpr>(SubExpr)) &&
1739 "Unexpected SubExpr for CK_UserDefinedConversion.");
Richard Smith1ef75542018-06-27 20:30:34 +00001740 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1741 SubExpr = MCE->getImplicitObjectArgument();
Manman Ren8abc2e52016-02-02 22:23:03 +00001742 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001743
Douglas Gregord196a582009-12-14 19:27:10 +00001744 // If the subexpression we're left with is an implicit cast, look
1745 // through that, too.
Fangrui Song6907ce22018-07-30 19:24:48 +00001746 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1747
Richard Smith1ef75542018-06-27 20:30:34 +00001748 return const_cast<Expr*>(SubExpr);
1749}
1750
1751NamedDecl *CastExpr::getConversionFunction() const {
1752 const Expr *SubExpr = nullptr;
1753
1754 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1755 SubExpr = skipImplicitTemporary(E->getSubExpr());
1756
1757 if (E->getCastKind() == CK_ConstructorConversion)
1758 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1759
1760 if (E->getCastKind() == CK_UserDefinedConversion) {
1761 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1762 return MCE->getMethodDecl();
1763 }
1764 }
1765
1766 return nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001767}
1768
John McCallcf142162010-08-07 06:22:56 +00001769CXXBaseSpecifier **CastExpr::path_buffer() {
1770 switch (getStmtClass()) {
1771#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001772#define CASTEXPR(Type, Base) \
1773 case Stmt::Type##Class: \
1774 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001775#define STMT(Type, Base)
1776#include "clang/AST/StmtNodes.inc"
1777 default:
1778 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001779 }
1780}
1781
John McCallf1ef7962017-08-15 21:42:47 +00001782const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1783 QualType opType) {
1784 auto RD = unionType->castAs<RecordType>()->getDecl();
1785 return getTargetFieldForToUnionCast(RD, opType);
1786}
1787
1788const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1789 QualType OpType) {
1790 auto &Ctx = RD->getASTContext();
1791 RecordDecl::field_iterator Field, FieldEnd;
1792 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1793 Field != FieldEnd; ++Field) {
1794 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1795 !Field->isUnnamedBitfield()) {
1796 return *Field;
1797 }
1798 }
1799 return nullptr;
1800}
1801
Craig Topper37932912013-08-18 10:09:15 +00001802ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001803 CastKind Kind, Expr *Operand,
1804 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001805 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001806 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001807 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
Richard Smith27252a12019-06-14 17:46:38 +00001808 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
1809 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
1810 assert((Kind != CK_LValueToRValue ||
1811 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
1812 "invalid type for lvalue-to-rvalue conversion");
John McCallcf142162010-08-07 06:22:56 +00001813 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001814 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001815 if (PathSize)
1816 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1817 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001818 return E;
1819}
1820
Craig Topper37932912013-08-18 10:09:15 +00001821ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001822 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001823 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001824 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1825}
1826
1827
Craig Topper37932912013-08-18 10:09:15 +00001828CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001829 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001830 const CXXCastPath *BasePath,
1831 TypeSourceInfo *WrittenTy,
1832 SourceLocation L, SourceLocation R) {
1833 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001834 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001835 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001836 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001837 if (PathSize)
1838 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1839 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001840 return E;
1841}
1842
Craig Topper37932912013-08-18 10:09:15 +00001843CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1844 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001845 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001846 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1847}
1848
Chris Lattner1b926492006-08-23 06:42:10 +00001849/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1850/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001851StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001852 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001853#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1854#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001855 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001856 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001857}
Steve Naroff47500512007-04-19 23:00:49 +00001858
John McCalle3027922010-08-25 11:45:40 +00001859BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001860BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1861 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001862 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001863 case OO_Plus: return BO_Add;
1864 case OO_Minus: return BO_Sub;
1865 case OO_Star: return BO_Mul;
1866 case OO_Slash: return BO_Div;
1867 case OO_Percent: return BO_Rem;
1868 case OO_Caret: return BO_Xor;
1869 case OO_Amp: return BO_And;
1870 case OO_Pipe: return BO_Or;
1871 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00001872 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00001873 case OO_Less: return BO_LT;
1874 case OO_Greater: return BO_GT;
1875 case OO_PlusEqual: return BO_AddAssign;
1876 case OO_MinusEqual: return BO_SubAssign;
1877 case OO_StarEqual: return BO_MulAssign;
1878 case OO_SlashEqual: return BO_DivAssign;
1879 case OO_PercentEqual: return BO_RemAssign;
1880 case OO_CaretEqual: return BO_XorAssign;
1881 case OO_AmpEqual: return BO_AndAssign;
1882 case OO_PipeEqual: return BO_OrAssign;
1883 case OO_LessLess: return BO_Shl;
1884 case OO_GreaterGreater: return BO_Shr;
1885 case OO_LessLessEqual: return BO_ShlAssign;
1886 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1887 case OO_EqualEqual: return BO_EQ;
1888 case OO_ExclaimEqual: return BO_NE;
1889 case OO_LessEqual: return BO_LE;
1890 case OO_GreaterEqual: return BO_GE;
1891 case OO_AmpAmp: return BO_LAnd;
1892 case OO_PipePipe: return BO_LOr;
1893 case OO_Comma: return BO_Comma;
1894 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001895 }
1896}
1897
1898OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1899 static const OverloadedOperatorKind OverOps[] = {
1900 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1901 OO_Star, OO_Slash, OO_Percent,
1902 OO_Plus, OO_Minus,
1903 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00001904 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001905 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1906 OO_EqualEqual, OO_ExclaimEqual,
1907 OO_Amp,
1908 OO_Caret,
1909 OO_Pipe,
1910 OO_AmpAmp,
1911 OO_PipePipe,
1912 OO_Equal, OO_StarEqual,
1913 OO_SlashEqual, OO_PercentEqual,
1914 OO_PlusEqual, OO_MinusEqual,
1915 OO_LessLessEqual, OO_GreaterGreaterEqual,
1916 OO_AmpEqual, OO_CaretEqual,
1917 OO_PipeEqual,
1918 OO_Comma
1919 };
1920 return OverOps[Opc];
1921}
1922
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001923bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
1924 Opcode Opc,
1925 Expr *LHS, Expr *RHS) {
1926 if (Opc != BO_Add)
1927 return false;
1928
1929 // Check that we have one pointer and one integer operand.
1930 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001931 if (LHS->getType()->isPointerType()) {
1932 if (!RHS->getType()->isIntegerType())
1933 return false;
1934 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001935 } else if (RHS->getType()->isPointerType()) {
1936 if (!LHS->getType()->isIntegerType())
1937 return false;
1938 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001939 } else {
1940 return false;
1941 }
1942
1943 // Check that the pointer is a nullptr.
1944 if (!PExp->IgnoreParenCasts()
1945 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
1946 return false;
1947
1948 // Check that the pointee type is char-sized.
1949 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1950 if (!PTy || !PTy->getPointeeType()->isCharType())
1951 return false;
1952
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001953 return true;
1954}
Eric Fiselier708afb52019-05-16 21:04:15 +00001955
1956static QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
1957 SourceLocExpr::IdentKind Kind) {
1958 switch (Kind) {
1959 case SourceLocExpr::File:
1960 case SourceLocExpr::Function: {
1961 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
1962 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
1963 }
1964 case SourceLocExpr::Line:
1965 case SourceLocExpr::Column:
1966 return Ctx.UnsignedIntTy;
1967 }
1968 llvm_unreachable("unhandled case");
1969}
1970
1971SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
1972 SourceLocation BLoc, SourceLocation RParenLoc,
1973 DeclContext *ParentContext)
1974 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
Haojian Wu876bb862020-03-17 08:33:37 +01001975 VK_RValue, OK_Ordinary),
Eric Fiselier708afb52019-05-16 21:04:15 +00001976 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
1977 SourceLocExprBits.Kind = Kind;
Haojian Wu876bb862020-03-17 08:33:37 +01001978 setDependence(ExprDependence::None);
Eric Fiselier708afb52019-05-16 21:04:15 +00001979}
1980
1981StringRef SourceLocExpr::getBuiltinStr() const {
1982 switch (getIdentKind()) {
1983 case File:
1984 return "__builtin_FILE";
1985 case Function:
1986 return "__builtin_FUNCTION";
1987 case Line:
1988 return "__builtin_LINE";
1989 case Column:
1990 return "__builtin_COLUMN";
1991 }
1992 llvm_unreachable("unexpected IdentKind!");
1993}
1994
1995APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
1996 const Expr *DefaultExpr) const {
1997 SourceLocation Loc;
1998 const DeclContext *Context;
1999
2000 std::tie(Loc,
2001 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2002 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2003 return {DIE->getUsedLocation(), DIE->getUsedContext()};
2004 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2005 return {DAE->getUsedLocation(), DAE->getUsedContext()};
2006 return {this->getLocation(), this->getParentContext()};
2007 }();
2008
2009 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2010 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2011
2012 auto MakeStringLiteral = [&](StringRef Tmp) {
2013 using LValuePathEntry = APValue::LValuePathEntry;
2014 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2015 // Decay the string to a pointer to the first character.
2016 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2017 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2018 };
2019
2020 switch (getIdentKind()) {
2021 case SourceLocExpr::File:
2022 return MakeStringLiteral(PLoc.getFilename());
2023 case SourceLocExpr::Function: {
2024 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2025 return MakeStringLiteral(
2026 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2027 : std::string(""));
2028 }
2029 case SourceLocExpr::Line:
2030 case SourceLocExpr::Column: {
2031 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002032 /*isUnsigned=*/true);
Eric Fiselier708afb52019-05-16 21:04:15 +00002033 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2034 : PLoc.getColumn();
2035 return APValue(IntVal);
2036 }
2037 }
2038 llvm_unreachable("unhandled case");
2039}
2040
Craig Topper37932912013-08-18 10:09:15 +00002041InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Haojian Wu876bb862020-03-17 08:33:37 +01002042 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2043 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary),
2044 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2045 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
Sebastian Redlc83ed822012-02-17 08:42:25 +00002046 sawArrayRangeDesignator(false);
Haojian Wu18c97662020-03-16 16:49:38 +01002047 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Haojian Wu876bb862020-03-17 08:33:37 +01002048
2049 setDependence(computeDependence(this));
Anders Carlsson4692db02007-08-31 04:56:16 +00002050}
Chris Lattner1ec5f562007-06-27 05:38:08 +00002051
Craig Topper37932912013-08-18 10:09:15 +00002052void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002053 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00002054 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002055}
2056
Craig Topper37932912013-08-18 10:09:15 +00002057void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00002058 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002059}
2060
Craig Topper37932912013-08-18 10:09:15 +00002061Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002062 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00002063 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00002064 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00002065 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002068 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00002069 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002070 return Result;
2071}
2072
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002073void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00002074 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002075 ArrayFillerOrUnionFieldInit = filler;
2076 // Fill out any "holes" in the array due to designated initializers.
2077 Expr **inits = getInits();
2078 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00002079 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002080 inits[i] = filler;
2081}
2082
Richard Smith9ec1e482012-04-15 02:50:59 +00002083bool InitListExpr::isStringLiteralInit() const {
2084 if (getNumInits() != 1)
2085 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00002086 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2087 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00002088 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00002089 // It is possible for getInit() to return null.
2090 const Expr *Init = getInit(0);
2091 if (!Init)
2092 return false;
2093 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00002094 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2095}
2096
Richard Smith122f88d2016-12-06 23:52:28 +00002097bool InitListExpr::isTransparent() const {
2098 assert(isSemanticForm() && "syntactic form never semantically transparent");
2099
2100 // A glvalue InitListExpr is always just sugar.
2101 if (isGLValue()) {
2102 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2103 return true;
2104 }
2105
2106 // Otherwise, we're sugar if and only if we have exactly one initializer that
2107 // is of the same type.
2108 if (getNumInits() != 1 || !getInit(0))
2109 return false;
2110
Richard Smith382bc512017-02-23 22:41:47 +00002111 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2112 // transparent struct copy.
2113 if (!getInit(0)->isRValue() && getType()->isRecordType())
2114 return false;
2115
Richard Smith122f88d2016-12-06 23:52:28 +00002116 return getType().getCanonicalType() ==
2117 getInit(0)->getType().getCanonicalType();
2118}
2119
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002120bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2121 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2122
Peter Wufa52e002019-07-16 01:13:36 +00002123 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002124 return false;
2125 }
2126
Peter Wufa52e002019-07-16 01:13:36 +00002127 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002128 return Lit && Lit->getValue() == 0;
2129}
2130
Stephen Kelly724e9e52018-08-09 20:05:03 +00002131SourceLocation InitListExpr::getBeginLoc() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00002132 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002133 return SyntacticForm->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002134 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002135 if (Beg.isInvalid()) {
2136 // Find the first non-null initializer.
2137 for (InitExprsTy::const_iterator I = InitExprs.begin(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002138 E = InitExprs.end();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002139 I != E; ++I) {
2140 if (Stmt *S = *I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002141 Beg = S->getBeginLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002142 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002143 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002144 }
2145 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002146 return Beg;
2147}
2148
Stephen Kelly02a67ba2018-08-09 20:05:47 +00002149SourceLocation InitListExpr::getEndLoc() const {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002150 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002151 return SyntacticForm->getEndLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002152 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002153 if (End.isInvalid()) {
2154 // Find the first non-null initializer from the end.
2155 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002156 E = InitExprs.rend();
2157 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002158 if (Stmt *S = *I) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002159 End = S->getEndLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002160 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002161 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002162 }
2163 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002164 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002165}
2166
Steve Naroff991e99d2008-09-04 15:31:07 +00002167/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002168///
John McCallc833dea2012-02-17 03:32:35 +00002169const FunctionProtoType *BlockExpr::getFunctionType() const {
2170 // The block pointer is never sugared, but the function type might be.
2171 return cast<BlockPointerType>(getType())
2172 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002173}
2174
Mike Stump11289f42009-09-09 15:08:12 +00002175SourceLocation BlockExpr::getCaretLocation() const {
2176 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002177}
Mike Stump11289f42009-09-09 15:08:12 +00002178const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002179 return TheBlock->getBody();
2180}
Mike Stump11289f42009-09-09 15:08:12 +00002181Stmt *BlockExpr::getBody() {
2182 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002183}
Steve Naroff415d3d52008-10-08 17:01:13 +00002184
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002185
Chris Lattner1ec5f562007-06-27 05:38:08 +00002186//===----------------------------------------------------------------------===//
2187// Generic Expression Routines
2188//===----------------------------------------------------------------------===//
2189
Chris Lattner237f2752009-02-14 07:37:35 +00002190/// isUnusedResultAWarning - Return true if this immediate expression should
2191/// be warned about if the result is unused. If so, fill in Loc and Ranges
2192/// with location to warn on and the source range[s] to report with the
2193/// warning.
Fangrui Song6907ce22018-07-30 19:24:48 +00002194bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
Eli Friedmanc11535c2012-05-24 00:47:05 +00002195 SourceRange &R1, SourceRange &R2,
2196 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002197 // Don't warn if the expr is type dependent. The type could end up
2198 // instantiating to void.
2199 if (isTypeDependent())
2200 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002201
Chris Lattner1ec5f562007-06-27 05:38:08 +00002202 switch (getStmtClass()) {
2203 default:
John McCallc493a732010-03-12 07:11:26 +00002204 if (getType()->isVoidType())
2205 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002206 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002207 Loc = getExprLoc();
2208 R1 = getSourceRange();
2209 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002210 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002211 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002212 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002213 case GenericSelectionExprClass:
2214 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002215 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002216 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002217 case CoyieldExprClass:
2218 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002219 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002220 case ChooseExprClass:
2221 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2222 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002223 case UnaryOperatorClass: {
2224 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002225
Chris Lattner1ec5f562007-06-27 05:38:08 +00002226 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002227 case UO_Plus:
2228 case UO_Minus:
2229 case UO_AddrOf:
2230 case UO_Not:
2231 case UO_LNot:
2232 case UO_Deref:
2233 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002234 case UO_Coawait:
2235 // This is just the 'operator co_await' call inside the guts of a
2236 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002237 case UO_PostInc:
2238 case UO_PostDec:
2239 case UO_PreInc:
2240 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002241 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002242 case UO_Real:
2243 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002244 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002245 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2246 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002247 return false;
2248 break;
John McCalle3027922010-08-25 11:45:40 +00002249 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002250 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002251 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002252 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002253 Loc = UO->getOperatorLoc();
2254 R1 = UO->getSubExpr()->getSourceRange();
2255 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002256 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002257 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002258 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002259 switch (BO->getOpcode()) {
2260 default:
2261 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002262 // Consider the RHS of comma for side effects. LHS was checked by
2263 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002264 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002265 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2266 // lvalue-ness) of an assignment written in a macro.
2267 if (IntegerLiteral *IE =
2268 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2269 if (IE->getValue() == 0)
2270 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002271 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002272 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002273 case BO_LAnd:
2274 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002275 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2276 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002277 return false;
2278 break;
John McCall1e3715a2010-02-16 04:10:53 +00002279 }
Chris Lattner237f2752009-02-14 07:37:35 +00002280 if (BO->isAssignmentOp())
2281 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002282 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002283 Loc = BO->getOperatorLoc();
2284 R1 = BO->getLHS()->getSourceRange();
2285 R2 = BO->getRHS()->getSourceRange();
2286 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002287 }
Chris Lattner86928112007-08-25 02:00:02 +00002288 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002289 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002290 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002291 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002292
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002293 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002294 // If only one of the LHS or RHS is a warning, the operator might
2295 // be being used for control flow. Only warn if both the LHS and
2296 // RHS are warnings.
Nathan Huckleberry321f9022019-06-19 18:37:01 +00002297 const auto *Exp = cast<ConditionalOperator>(this);
2298 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2299 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2300 }
2301 case BinaryConditionalOperatorClass: {
2302 const auto *Exp = cast<BinaryConditionalOperator>(this);
2303 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002304 }
2305
Chris Lattnera44d1162007-06-27 05:58:59 +00002306 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002307 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002308 Loc = cast<MemberExpr>(this)->getMemberLoc();
2309 R1 = SourceRange(Loc, Loc);
2310 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2311 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002312
Chris Lattner1ec5f562007-06-27 05:38:08 +00002313 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002314 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002315 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2316 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2317 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2318 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002319
Chandler Carruth46339472011-08-17 09:49:44 +00002320 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002321 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002322 // overloads as there is no reasonable way to define these such that they
2323 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002324 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002325 // provides additional value as well. If this list is updated,
2326 // DiagnoseUnusedComparison should be as well.
2327 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002328 switch (Op->getOperator()) {
2329 default:
2330 break;
2331 case OO_EqualEqual:
2332 case OO_ExclaimEqual:
2333 case OO_Less:
2334 case OO_Greater:
2335 case OO_GreaterEqual:
2336 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002337 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2338 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002339 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002340 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002341 Loc = Op->getOperatorLoc();
2342 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002343 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002344 }
Chandler Carruth46339472011-08-17 09:49:44 +00002345
2346 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002347 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002348 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002349 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002350 case CXXMemberCallExprClass:
2351 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002352 // If this is a direct call, get the callee.
2353 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002354 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner237f2752009-02-14 07:37:35 +00002355 // If the callee has attribute pure, const, or warn_unused_result, warn
2356 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002357 //
2358 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2359 // updated to match for QoI.
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00002360 if (CE->hasUnusedResultAttr(Ctx) ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002361 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002362 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002363 Loc = CE->getCallee()->getBeginLoc();
Chris Lattner1a6babf2009-10-13 04:53:48 +00002364 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002365
Chris Lattner1a6babf2009-10-13 04:53:48 +00002366 if (unsigned NumArgs = CE->getNumArgs())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002367 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002368 CE->getArg(NumArgs - 1)->getEndLoc());
Chris Lattner1a6babf2009-10-13 04:53:48 +00002369 return true;
2370 }
Chris Lattner237f2752009-02-14 07:37:35 +00002371 }
2372 return false;
2373 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002374
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002375 // If we don't know precisely what we're looking at, let's not warn.
2376 case UnresolvedLookupExprClass:
2377 case CXXUnresolvedConstructExprClass:
2378 return false;
2379
Anders Carlsson6aa50392009-11-17 17:11:23 +00002380 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002381 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002382 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
Erich Keane46441fd2019-07-25 15:10:56 +00002383 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2384 if (Type->hasAttr<WarnUnusedAttr>() ||
2385 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002386 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002387 Loc = getBeginLoc();
Lubos Lunak1f490f32013-07-21 13:15:58 +00002388 R1 = getSourceRange();
2389 return true;
2390 }
2391 }
Erich Keane46441fd2019-07-25 15:10:56 +00002392
2393 const auto *CE = cast<CXXConstructExpr>(this);
2394 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2395 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2396 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2397 WarnE = this;
2398 Loc = getBeginLoc();
2399 R1 = getSourceRange();
2400
2401 if (unsigned NumArgs = CE->getNumArgs())
2402 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2403 CE->getArg(NumArgs - 1)->getEndLoc());
2404 return true;
2405 }
2406 }
2407
Anders Carlsson6aa50392009-11-17 17:11:23 +00002408 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002409 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002410
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002411 case ObjCMessageExprClass: {
2412 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002413 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002414 ME->isInstanceMessage() &&
2415 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002416 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002417 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002418 Loc = getExprLoc();
2419 R1 = ME->getSourceRange();
2420 return true;
2421 }
2422
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002423 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002424 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002425 WarnE = this;
2426 Loc = getExprLoc();
2427 return true;
2428 }
2429
Chris Lattner237f2752009-02-14 07:37:35 +00002430 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002431 }
Mike Stump11289f42009-09-09 15:08:12 +00002432
John McCallb7bd14f2010-12-02 01:19:52 +00002433 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002434 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002435 Loc = getExprLoc();
2436 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002437 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002438
John McCallfe96e0b2011-11-06 09:01:30 +00002439 case PseudoObjectExprClass: {
2440 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2441
2442 // Only complain about things that have the form of a getter.
2443 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2444 isa<BinaryOperator>(PO->getSyntacticForm()))
2445 return false;
2446
Eli Friedmanc11535c2012-05-24 00:47:05 +00002447 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002448 Loc = getExprLoc();
2449 R1 = getSourceRange();
2450 return true;
2451 }
2452
Chris Lattner944d3062008-07-26 19:51:01 +00002453 case StmtExprClass: {
2454 // Statement exprs don't logically have side effects themselves, but are
2455 // sometimes used in macros in ways that give them a type that is unused.
2456 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2457 // however, if the result of the stmt expr is dead, we don't want to emit a
2458 // warning.
2459 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002460 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002461 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002462 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002463 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2464 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002465 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
John McCallc493a732010-03-12 07:11:26 +00002468 if (getType()->isVoidType())
2469 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002470 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002471 Loc = cast<StmtExpr>(this)->getLParenLoc();
2472 R1 = getSourceRange();
2473 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002474 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002475 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002476 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002477 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002478 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002479 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002480 if (CE->getCastKind() == CK_ToVoid) {
2481 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002482 CE->getSubExpr()->getType().isVolatileQualified()) {
2483 const DeclRefExpr *DRE =
2484 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2485 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002486 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2487 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002488 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2489 R1, R2, Ctx);
2490 }
2491 }
Chris Lattner2706a552009-07-28 18:25:28 +00002492 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002493 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002494
Eli Friedmanc11535c2012-05-24 00:47:05 +00002495 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002496 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002497 if (CE->getCastKind() == CK_ConstructorConversion)
2498 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002499
Eli Friedmanc11535c2012-05-24 00:47:05 +00002500 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002501 if (const CXXFunctionalCastExpr *CXXCE =
2502 dyn_cast<CXXFunctionalCastExpr>(this)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002503 Loc = CXXCE->getBeginLoc();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002504 R1 = CXXCE->getSubExpr()->getSourceRange();
2505 } else {
2506 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2507 Loc = CStyleCE->getLParenLoc();
2508 R1 = CStyleCE->getSubExpr()->getSourceRange();
2509 }
Chris Lattner237f2752009-02-14 07:37:35 +00002510 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002511 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002512 case ImplicitCastExprClass: {
2513 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002514
Eli Friedmanc11535c2012-05-24 00:47:05 +00002515 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2516 if (ICE->getCastKind() == CK_LValueToRValue &&
2517 ICE->getSubExpr()->getType().isVolatileQualified())
2518 return false;
2519
2520 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2521 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002522 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002523 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002524 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002525 case CXXDefaultInitExprClass:
2526 return (cast<CXXDefaultInitExpr>(this)
2527 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002528
2529 case CXXNewExprClass:
2530 // FIXME: In theory, there might be new expressions that don't have side
2531 // effects (e.g. a placement new with an uninitialized POD).
2532 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002533 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002534 case MaterializeTemporaryExprClass:
Tykerb0561b32019-11-17 11:41:55 +01002535 return cast<MaterializeTemporaryExpr>(this)
2536 ->getSubExpr()
2537 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002538 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002539 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2540 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002541 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002542 return cast<ExprWithCleanups>(this)->getSubExpr()
2543 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002544 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002545}
2546
Fariborz Jahanian07735332009-02-22 18:40:18 +00002547/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002548/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002549bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002550 const Expr *E = IgnoreParens();
2551 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002552 default:
2553 return false;
2554 case ObjCIvarRefExprClass:
2555 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002556 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002557 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002558 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002559 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002560 case MaterializeTemporaryExprClass:
Tykerb0561b32019-11-17 11:41:55 +01002561 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2562 Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002563 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002564 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002565 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002566 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002567
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002568 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2569 if (VD->hasGlobalStorage())
2570 return true;
2571 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002572 // dereferencing to a pointer is always a gc'able candidate,
2573 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002574 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002575 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002576 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002577 return false;
2578 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002579 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002580 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002581 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002582 }
2583 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002584 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002585 }
2586}
Sebastian Redlce354af2010-09-10 20:55:33 +00002587
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002588bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2589 if (isTypeDependent())
2590 return false;
John McCall086a4642010-11-24 05:12:34 +00002591 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002592}
2593
John McCall0009fcc2011-04-26 20:42:42 +00002594QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002595 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002596
2597 // Bound member expressions are always one of these possibilities:
2598 // x->m x.m x->*y x.*y
2599 // (possibly parenthesized)
2600
2601 expr = expr->IgnoreParens();
2602 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2603 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2604 return mem->getMemberDecl()->getType();
2605 }
2606
2607 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2608 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2609 ->getPointeeType();
2610 assert(type->isFunctionType());
2611 return type;
2612 }
2613
David Majnemerced8bdf2015-02-25 17:36:15 +00002614 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002615 return QualType();
2616}
2617
Bruno Ricci46148f22019-02-17 18:50:51 +00002618static Expr *IgnoreImpCastsSingleStep(Expr *E) {
2619 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2620 return ICE->getSubExpr();
2621
2622 if (auto *FE = dyn_cast<FullExpr>(E))
2623 return FE->getSubExpr();
2624
Bruno Riccid4038002019-02-17 13:47:29 +00002625 return E;
Ted Kremenek6f375e52014-04-16 07:26:09 +00002626}
2627
Bruno Ricci46148f22019-02-17 18:50:51 +00002628static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
2629 // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2630 // addition to what IgnoreImpCasts() skips to account for the current
2631 // behaviour of IgnoreParenImpCasts().
2632 Expr *SubE = IgnoreImpCastsSingleStep(E);
2633 if (SubE != E)
2634 return SubE;
2635
2636 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01002637 return MTE->getSubExpr();
Bruno Ricci46148f22019-02-17 18:50:51 +00002638
2639 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2640 return NTTP->getReplacement();
2641
2642 return E;
2643}
2644
2645static Expr *IgnoreCastsSingleStep(Expr *E) {
2646 if (auto *CE = dyn_cast<CastExpr>(E))
2647 return CE->getSubExpr();
2648
2649 if (auto *FE = dyn_cast<FullExpr>(E))
2650 return FE->getSubExpr();
2651
2652 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01002653 return MTE->getSubExpr();
Bruno Ricci46148f22019-02-17 18:50:51 +00002654
2655 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2656 return NTTP->getReplacement();
2657
2658 return E;
2659}
2660
2661static Expr *IgnoreLValueCastsSingleStep(Expr *E) {
2662 // Skip what IgnoreCastsSingleStep skips, except that only
2663 // lvalue-to-rvalue casts are skipped.
2664 if (auto *CE = dyn_cast<CastExpr>(E))
2665 if (CE->getCastKind() != CK_LValueToRValue)
2666 return E;
2667
2668 return IgnoreCastsSingleStep(E);
2669}
2670
2671static Expr *IgnoreBaseCastsSingleStep(Expr *E) {
2672 if (auto *CE = dyn_cast<CastExpr>(E))
2673 if (CE->getCastKind() == CK_DerivedToBase ||
2674 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2675 CE->getCastKind() == CK_NoOp)
2676 return CE->getSubExpr();
2677
2678 return E;
2679}
2680
2681static Expr *IgnoreImplicitSingleStep(Expr *E) {
2682 Expr *SubE = IgnoreImpCastsSingleStep(E);
2683 if (SubE != E)
2684 return SubE;
2685
2686 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01002687 return MTE->getSubExpr();
Bruno Ricci46148f22019-02-17 18:50:51 +00002688
2689 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2690 return BTE->getSubExpr();
2691
2692 return E;
2693}
2694
Richard Smith75990952019-12-05 18:04:46 -08002695static Expr *IgnoreImplicitAsWrittenSingleStep(Expr *E) {
2696 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2697 return ICE->getSubExprAsWritten();
2698
2699 return IgnoreImplicitSingleStep(E);
2700}
2701
Stephen Kelly9a3ff472020-01-11 12:09:45 +00002702static Expr *IgnoreParensOnlySingleStep(Expr *E) {
2703 if (auto *PE = dyn_cast<ParenExpr>(E))
2704 return PE->getSubExpr();
2705 return E;
2706}
2707
Bruno Ricci46148f22019-02-17 18:50:51 +00002708static Expr *IgnoreParensSingleStep(Expr *E) {
2709 if (auto *PE = dyn_cast<ParenExpr>(E))
2710 return PE->getSubExpr();
2711
2712 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2713 if (UO->getOpcode() == UO_Extension)
2714 return UO->getSubExpr();
2715 }
2716
2717 else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2718 if (!GSE->isResultDependent())
2719 return GSE->getResultExpr();
2720 }
2721
2722 else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2723 if (!CE->isConditionDependent())
2724 return CE->getChosenSubExpr();
2725 }
2726
Bruno Ricci46148f22019-02-17 18:50:51 +00002727 return E;
2728}
2729
2730static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
2731 if (auto *CE = dyn_cast<CastExpr>(E)) {
2732 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2733 // ptr<->int casts of the same width. We also ignore all identity casts.
2734 Expr *SubExpr = CE->getSubExpr();
2735 bool IsIdentityCast =
2736 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2737 bool IsSameWidthCast =
2738 (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2739 (SubExpr->getType()->isPointerType() ||
2740 SubExpr->getType()->isIntegralType(Ctx)) &&
2741 (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2742
2743 if (IsIdentityCast || IsSameWidthCast)
2744 return SubExpr;
2745 }
2746
2747 else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2748 return NTTP->getReplacement();
2749
2750 return E;
2751}
2752
2753static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2754template <typename FnTy, typename... FnTys>
2755static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2756 return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2757}
2758
2759/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2760/// Recursively apply each of the functions to E until reaching a fixed point.
2761/// Note that a null E is valid; in this case nothing is done.
2762template <typename... FnTys>
2763static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
Bruno Riccid4038002019-02-17 13:47:29 +00002764 Expr *LastE = nullptr;
2765 while (E != LastE) {
2766 LastE = E;
Bruno Ricci46148f22019-02-17 18:50:51 +00002767 E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
Bruno Riccid4038002019-02-17 13:47:29 +00002768 }
2769 return E;
John McCall34376a62010-12-04 03:47:34 +00002770}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002771
Bruno Ricci46148f22019-02-17 18:50:51 +00002772Expr *Expr::IgnoreImpCasts() {
2773 return IgnoreExprNodes(this, IgnoreImpCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002774}
2775
2776Expr *Expr::IgnoreCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002777 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002778}
2779
Bruno Ricci46148f22019-02-17 18:50:51 +00002780Expr *Expr::IgnoreImplicit() {
2781 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002782}
2783
Richard Smith75990952019-12-05 18:04:46 -08002784Expr *Expr::IgnoreImplicitAsWritten() {
2785 return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
2786}
2787
Bruno Ricci46148f22019-02-17 18:50:51 +00002788Expr *Expr::IgnoreParens() {
2789 return IgnoreExprNodes(this, IgnoreParensSingleStep);
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002790}
2791
John McCalleebc8322010-05-05 22:59:52 +00002792Expr *Expr::IgnoreParenImpCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002793 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2794 IgnoreImpCastsExtraSingleStep);
2795}
2796
2797Expr *Expr::IgnoreParenCasts() {
2798 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
John McCalleebc8322010-05-05 22:59:52 +00002799}
2800
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002801Expr *Expr::IgnoreConversionOperator() {
Bruno Riccie64aee82019-02-03 19:50:56 +00002802 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002803 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002804 return MCE->getImplicitObjectArgument();
2805 }
2806 return this;
2807}
2808
Bruno Ricci46148f22019-02-17 18:50:51 +00002809Expr *Expr::IgnoreParenLValueCasts() {
2810 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2811 IgnoreLValueCastsSingleStep);
2812}
2813
2814Expr *Expr::ignoreParenBaseCasts() {
2815 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2816 IgnoreBaseCastsSingleStep);
2817}
2818
Bruno Riccie64aee82019-02-03 19:50:56 +00002819Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
Bruno Ricci46148f22019-02-17 18:50:51 +00002820 return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2821 return IgnoreNoopCastsSingleStep(Ctx, E);
2822 });
Chris Lattneref26c772009-03-13 17:28:01 +00002823}
2824
Stephen Kelly98e8f772019-05-04 16:51:58 +01002825Expr *Expr::IgnoreUnlessSpelledInSource() {
2826 Expr *E = this;
2827
2828 Expr *LastE = nullptr;
2829 while (E != LastE) {
2830 LastE = E;
Stephen Kelly9a3ff472020-01-11 12:09:45 +00002831 E = IgnoreExprNodes(E, IgnoreImplicitSingleStep, IgnoreImpCastsSingleStep,
2832 IgnoreParensOnlySingleStep);
Stephen Kelly98e8f772019-05-04 16:51:58 +01002833
2834 auto SR = E->getSourceRange();
2835
2836 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
2837 if (C->getNumArgs() == 1) {
2838 Expr *A = C->getArg(0);
2839 if (A->getSourceRange() == SR || !isa<CXXTemporaryObjectExpr>(C))
2840 E = A;
2841 }
2842 }
2843
2844 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
2845 Expr *ExprNode = C->getImplicitObjectArgument()->IgnoreParenImpCasts();
2846 if (ExprNode->getSourceRange() == SR)
2847 E = ExprNode;
2848 }
2849 }
2850
2851 return E;
2852}
2853
Douglas Gregord196a582009-12-14 19:27:10 +00002854bool Expr::isDefaultArgument() const {
2855 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002856 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01002857 E = M->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00002858
Douglas Gregord196a582009-12-14 19:27:10 +00002859 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2860 E = ICE->getSubExprAsWritten();
Fangrui Song6907ce22018-07-30 19:24:48 +00002861
Douglas Gregord196a582009-12-14 19:27:10 +00002862 return isa<CXXDefaultArgExpr>(E);
2863}
Chris Lattneref26c772009-03-13 17:28:01 +00002864
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002865/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002866/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002867static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002868 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01002869 E = M->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00002870
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002871 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002872 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002873 E = ICE->getSubExpr();
2874 else
2875 break;
2876 }
2877
2878 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2879 E = BE->getSubExpr();
2880
2881 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002882 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002883 E = ICE->getSubExpr();
2884 else
2885 break;
2886 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002887
2888 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002889}
2890
John McCall7a626f62010-09-15 10:14:12 +00002891/// isTemporaryObject - Determines if this expression produces a
2892/// temporary of the given class type.
2893bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2894 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2895 return false;
2896
Anders Carlsson66bbf502010-11-28 16:40:49 +00002897 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002898
John McCall02dc8c72010-09-15 20:59:13 +00002899 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002900 if (!E->Classify(C).isPRValue()) {
2901 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002902 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002903 return false;
2904 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002905
John McCallf4ee1dd2010-09-16 06:57:56 +00002906 // Black-list a few cases which yield pr-values of class type that don't
2907 // refer to temporaries of that type:
2908
2909 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002910 if (isa<ImplicitCastExpr>(E)) {
2911 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2912 case CK_DerivedToBase:
2913 case CK_UncheckedDerivedToBase:
2914 return false;
2915 default:
2916 break;
2917 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002918 }
2919
John McCallf4ee1dd2010-09-16 06:57:56 +00002920 // - member expressions (all)
2921 if (isa<MemberExpr>(E))
2922 return false;
2923
Eli Friedman13ffdd82012-06-15 23:51:06 +00002924 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2925 if (BO->isPtrMemOp())
2926 return false;
2927
John McCallc07a0c72011-02-17 10:25:35 +00002928 // - opaque values (all)
2929 if (isa<OpaqueValueExpr>(E))
2930 return false;
2931
John McCall7a626f62010-09-15 10:14:12 +00002932 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002933}
2934
Douglas Gregor25b7e052011-03-02 21:06:53 +00002935bool Expr::isImplicitCXXThis() const {
2936 const Expr *E = this;
Fangrui Song6907ce22018-07-30 19:24:48 +00002937
Douglas Gregor25b7e052011-03-02 21:06:53 +00002938 // Strip away parentheses and casts we don't care about.
2939 while (true) {
2940 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2941 E = Paren->getSubExpr();
2942 continue;
2943 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002944
Douglas Gregor25b7e052011-03-02 21:06:53 +00002945 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2946 if (ICE->getCastKind() == CK_NoOp ||
2947 ICE->getCastKind() == CK_LValueToRValue ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002948 ICE->getCastKind() == CK_DerivedToBase ||
Douglas Gregor25b7e052011-03-02 21:06:53 +00002949 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2950 E = ICE->getSubExpr();
2951 continue;
2952 }
2953 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002954
Douglas Gregor25b7e052011-03-02 21:06:53 +00002955 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2956 if (UnOp->getOpcode() == UO_Extension) {
2957 E = UnOp->getSubExpr();
2958 continue;
2959 }
2960 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002961
Douglas Gregorfe314812011-06-21 17:03:29 +00002962 if (const MaterializeTemporaryExpr *M
2963 = dyn_cast<MaterializeTemporaryExpr>(E)) {
Tykerb0561b32019-11-17 11:41:55 +01002964 E = M->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00002965 continue;
2966 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002967
Douglas Gregor25b7e052011-03-02 21:06:53 +00002968 break;
2969 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002970
Douglas Gregor25b7e052011-03-02 21:06:53 +00002971 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2972 return This->isImplicit();
Fangrui Song6907ce22018-07-30 19:24:48 +00002973
Douglas Gregor25b7e052011-03-02 21:06:53 +00002974 return false;
2975}
2976
Douglas Gregor4619e432008-12-05 23:32:09 +00002977/// hasAnyTypeDependentArguments - Determines if any of the expressions
2978/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002979bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002980 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002981 if (Exprs[I]->isTypeDependent())
2982 return true;
2983
2984 return false;
2985}
2986
Abramo Bagnara847c6602014-05-22 19:20:46 +00002987bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2988 const Expr **Culprit) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +00002989 assert(!isValueDependent() &&
2990 "Expression evaluator can't be called on a dependent expression.");
2991
Eli Friedman384da272009-01-25 03:12:18 +00002992 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002993 // which can be evaluated at compile-time. It very closely parallels
2994 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2995 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2996 // to isEvaluatable most of the time.
2997 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002998 // If we ever capture reference-binding directly in the AST, we can
2999 // kill the second parameter.
3000
3001 if (IsForRef) {
3002 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003003 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3004 return true;
3005 if (Culprit)
3006 *Culprit = this;
3007 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00003008 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00003009
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003010 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00003011 default: break;
Akira Hatanakad35a4542019-11-20 18:13:44 -08003012 case Stmt::ExprWithCleanupsClass:
3013 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3014 Ctx, IsForRef, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003015 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00003016 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003017 return true;
John McCall81c9cea2010-08-01 21:51:45 +00003018 case CXXTemporaryObjectExprClass:
3019 case CXXConstructExprClass: {
3020 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00003021
Eli Friedman4c27ac22013-07-16 22:40:53 +00003022 if (CE->getConstructor()->isTrivial() &&
3023 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3024 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00003025 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00003026
Eli Friedman4c27ac22013-07-16 22:40:53 +00003027 // Trivial copy constructor
3028 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00003029 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00003030 }
3031
Richard Smithd62306a2011-11-10 06:34:14 +00003032 break;
John McCall81c9cea2010-08-01 21:51:45 +00003033 }
Fangrui Song407659a2018-11-30 23:41:18 +00003034 case ConstantExprClass: {
3035 // FIXME: We should be able to return "true" here, but it can lead to extra
3036 // error messages. E.g. in Sema/array-init.c.
3037 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3038 return Exp->isConstantInitializer(Ctx, false, Culprit);
3039 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003040 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00003041 // This handles gcc's extension that allows global initializers like
3042 // "struct x {int x;} x = (struct x) {};".
3043 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003044 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00003045 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003046 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00003047 case DesignatedInitUpdateExprClass: {
3048 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3049 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3050 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3051 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003052 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00003053 const InitListExpr *ILE = cast<InitListExpr>(this);
Dmitri Gribenkoc5f25442019-05-10 06:39:20 +00003054 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
Eli Friedman4c27ac22013-07-16 22:40:53 +00003055 if (ILE->getType()->isArrayType()) {
3056 unsigned numInits = ILE->getNumInits();
3057 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00003058 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00003059 return false;
3060 }
3061 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003062 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00003063
3064 if (ILE->getType()->isRecordType()) {
3065 unsigned ElementNo = 0;
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003066 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00003067 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00003068 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00003069 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00003070 continue;
3071
3072 // Don't emit anonymous bitfields, they just affect layout.
3073 if (Field->isUnnamedBitfield())
3074 continue;
3075
3076 if (ElementNo < ILE->getNumInits()) {
3077 const Expr *Elt = ILE->getInit(ElementNo++);
3078 if (Field->isBitField()) {
3079 // Bitfields have to evaluate to an integer.
Fangrui Song407659a2018-11-30 23:41:18 +00003080 EvalResult Result;
3081 if (!Elt->EvaluateAsInt(Result, Ctx)) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00003082 if (Culprit)
3083 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00003084 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003085 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00003086 } else {
3087 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00003088 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00003089 return false;
3090 }
3091 }
3092 }
3093 return true;
3094 }
3095
3096 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003097 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00003098 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003099 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00003100 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00003101 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00003102 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003103 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00003104 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00003105 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003106 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00003107 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00003108 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3109 if (Culprit)
3110 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00003111 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003112 }
Eli Friedman75807f22013-07-20 00:40:58 +00003113 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003114 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003115 case UnaryOperatorClass: {
3116 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00003117 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003118 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003119 break;
3120 }
John McCall8b0f4ff2010-08-02 21:13:48 +00003121 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00003122 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00003123 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00003124 case CStyleCastExprClass:
3125 case ObjCBridgedCastExprClass:
3126 case CXXDynamicCastExprClass:
3127 case CXXReinterpretCastExprClass:
3128 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00003129 const CastExpr *CE = cast<CastExpr>(this);
3130
Eli Friedman13ec75b2011-12-21 00:43:02 +00003131 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00003132 if (CE->getCastKind() == CK_NoOp ||
3133 CE->getCastKind() == CK_LValueToRValue ||
3134 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00003135 CE->getCastKind() == CK_ConstructorConversion ||
3136 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003137 CE->getCastKind() == CK_AtomicToNonAtomic ||
3138 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003139 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00003140
Eli Friedman384da272009-01-25 03:12:18 +00003141 break;
Richard Smith161f09a2011-12-06 22:44:34 +00003142 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003143 case MaterializeTemporaryExprClass:
Tykerb0561b32019-11-17 11:41:55 +01003144 return cast<MaterializeTemporaryExpr>(this)
3145 ->getSubExpr()
3146 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003147
Eli Friedman4c27ac22013-07-16 22:40:53 +00003148 case SubstNonTypeTemplateParmExprClass:
3149 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003150 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003151 case CXXDefaultArgExprClass:
3152 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003153 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003154 case CXXDefaultInitExprClass:
3155 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003156 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003157 }
Richard Smithce8eca52015-12-08 03:21:47 +00003158 // Allow certain forms of UB in constant initializers: signed integer
3159 // overflow and floating-point division by zero. We'll give a warning on
3160 // these, but they're common enough that we have to accept them.
3161 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00003162 return true;
3163 if (Culprit)
3164 *Culprit = this;
3165 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00003166}
3167
Nico Weber758fbac2018-02-13 21:31:47 +00003168bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3169 const FunctionDecl* FD = getDirectCallee();
3170 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3171 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3172 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003173
Nico Weber758fbac2018-02-13 21:31:47 +00003174 const Expr* Arg = getArg(0);
3175 bool ArgVal;
3176 return !Arg->isValueDependent() &&
3177 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3178}
3179
Scott Douglasscc013592015-06-10 15:18:23 +00003180namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003181 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00003182 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003183 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00003184 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003185 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00003186
3187 public:
3188 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003189 : Inherited(Context),
3190 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00003191
3192 bool hasSideEffects() const { return HasSideEffects; }
3193
3194 void VisitExpr(const Expr *E) {
3195 if (!HasSideEffects &&
3196 E->HasSideEffects(Context, IncludePossibleEffects))
3197 HasSideEffects = true;
3198 }
3199 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003200}
Scott Douglasscc013592015-06-10 15:18:23 +00003201
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003202bool Expr::HasSideEffects(const ASTContext &Ctx,
3203 bool IncludePossibleEffects) const {
3204 // In circumstances where we care about definite side effects instead of
3205 // potential side effects, we want to ignore expressions that are part of a
3206 // macro expansion as a potential side effect.
3207 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3208 return false;
3209
Richard Smith0421ce72012-08-07 04:16:51 +00003210 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003211 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00003212
3213 switch (getStmtClass()) {
3214 case NoStmtClass:
3215 #define ABSTRACT_STMT(Type)
3216 #define STMT(Type, Base) case Type##Class:
3217 #define EXPR(Type, Base)
3218 #include "clang/AST/StmtNodes.inc"
3219 llvm_unreachable("unexpected Expr kind");
3220
3221 case DependentScopeDeclRefExprClass:
3222 case CXXUnresolvedConstructExprClass:
3223 case CXXDependentScopeMemberExprClass:
3224 case UnresolvedLookupExprClass:
3225 case UnresolvedMemberExprClass:
3226 case PackExpansionExprClass:
3227 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00003228 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003229 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00003230 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003231 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3232
Richard Smitha33e4fe2012-08-07 05:18:29 +00003233 case DeclRefExprClass:
3234 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003235 case PredefinedExprClass:
3236 case IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003237 case FixedPointLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003238 case FloatingLiteralClass:
3239 case ImaginaryLiteralClass:
3240 case StringLiteralClass:
3241 case CharacterLiteralClass:
3242 case OffsetOfExprClass:
3243 case ImplicitValueInitExprClass:
3244 case UnaryExprOrTypeTraitExprClass:
3245 case AddrLabelExprClass:
3246 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003247 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003248 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003249 case CXXBoolLiteralExprClass:
3250 case CXXNullPtrLiteralExprClass:
3251 case CXXThisExprClass:
3252 case CXXScalarValueInitExprClass:
3253 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003254 case ArrayTypeTraitExprClass:
3255 case ExpressionTraitExprClass:
3256 case CXXNoexceptExprClass:
3257 case SizeOfPackExprClass:
3258 case ObjCStringLiteralClass:
3259 case ObjCEncodeExprClass:
3260 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003261 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003262 case CXXUuidofExprClass:
3263 case OpaqueValueExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +00003264 case SourceLocExprClass:
Saar Raz5d98ba62019-10-15 15:24:26 +00003265 case ConceptSpecializationExprClass:
Saar Raza0f50d72020-01-18 09:11:43 +02003266 case RequiresExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003267 // These never have a side-effect.
3268 return false;
3269
Bill Wendling7c44da22018-10-31 03:48:47 +00003270 case ConstantExprClass:
3271 // FIXME: Move this into the "return false;" block above.
3272 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3273 Ctx, IncludePossibleEffects);
3274
Richard Smith0421ce72012-08-07 04:16:51 +00003275 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003276 case CXXOperatorCallExprClass:
3277 case CXXMemberCallExprClass:
3278 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003279 case UserDefinedLiteralClass: {
3280 // We don't know a call definitely has side effects, except for calls
3281 // to pure/const functions that definitely don't.
3282 // If the call itself is considered side-effect free, check the operands.
3283 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3284 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3285 if (IsPure || !IncludePossibleEffects)
3286 break;
3287 return true;
3288 }
3289
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003290 case BlockExprClass:
3291 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003292 if (!IncludePossibleEffects)
3293 break;
3294 return true;
3295
John McCall5e77d762013-04-16 07:28:30 +00003296 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003297 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003298 case CompoundAssignOperatorClass:
3299 case VAArgExprClass:
3300 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003301 case CXXThrowExprClass:
3302 case CXXNewExprClass:
3303 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003304 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003305 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003306 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003307 // These always have a side-effect.
3308 return true;
3309
Scott Douglasscc013592015-06-10 15:18:23 +00003310 case StmtExprClass: {
3311 // StmtExprs have a side-effect if any substatement does.
3312 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3313 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3314 return Finder.hasSideEffects();
3315 }
3316
Tim Shen4a05bb82016-06-21 20:29:17 +00003317 case ExprWithCleanupsClass:
3318 if (IncludePossibleEffects)
3319 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3320 return true;
3321 break;
3322
Richard Smith0421ce72012-08-07 04:16:51 +00003323 case ParenExprClass:
3324 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003325 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003326 case MemberExprClass:
3327 case ConditionalOperatorClass:
3328 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003329 case CompoundLiteralExprClass:
3330 case ExtVectorElementExprClass:
3331 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003332 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003333 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003334 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003335 case CXXPseudoDestructorExprClass:
Richard Smith778dc0f2019-10-19 00:04:38 +00003336 case CXXRewrittenBinaryOperatorClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003337 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003338 case SubstNonTypeTemplateParmExprClass:
3339 case MaterializeTemporaryExprClass:
3340 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003341 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003342 case AsTypeExprClass:
3343 // These have a side-effect if any subexpression does.
3344 break;
3345
Richard Smitha33e4fe2012-08-07 05:18:29 +00003346 case UnaryOperatorClass:
3347 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003348 return true;
3349 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003350
3351 case BinaryOperatorClass:
3352 if (cast<BinaryOperator>(this)->isAssignmentOp())
3353 return true;
3354 break;
3355
Richard Smith0421ce72012-08-07 04:16:51 +00003356 case InitListExprClass:
3357 // FIXME: The children for an InitListExpr doesn't include the array filler.
3358 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003359 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003360 return true;
3361 break;
3362
3363 case GenericSelectionExprClass:
3364 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003365 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003366
3367 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003368 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3369 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003370
3371 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003372 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3373 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003374
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003375 case CXXDefaultInitExprClass: {
3376 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3377 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003378 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003379 // If we've not yet parsed the initializer, assume it has side-effects.
3380 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003381 }
Richard Smith852c9db2013-04-20 22:23:05 +00003382
Richard Smith0421ce72012-08-07 04:16:51 +00003383 case CXXDynamicCastExprClass: {
3384 // A dynamic_cast expression has side-effects if it can throw.
3385 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3386 if (DCE->getTypeAsWritten()->isReferenceType() &&
3387 DCE->getCastKind() == CK_Dynamic)
3388 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003389 }
3390 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003391 case ImplicitCastExprClass:
3392 case CStyleCastExprClass:
3393 case CXXStaticCastExprClass:
3394 case CXXReinterpretCastExprClass:
3395 case CXXConstCastExprClass:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00003396 case CXXFunctionalCastExprClass:
3397 case BuiltinBitCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003398 // While volatile reads are side-effecting in both C and C++, we treat them
3399 // as having possible (not definite) side-effects. This allows idiomatic
3400 // code to behave without warning, such as sizeof(*v) for a volatile-
3401 // qualified pointer.
3402 if (!IncludePossibleEffects)
3403 break;
3404
Richard Smitha33e4fe2012-08-07 05:18:29 +00003405 const CastExpr *CE = cast<CastExpr>(this);
3406 if (CE->getCastKind() == CK_LValueToRValue &&
3407 CE->getSubExpr()->getType().isVolatileQualified())
3408 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003409 break;
3410 }
3411
Richard Smithef8bf432012-08-13 20:08:14 +00003412 case CXXTypeidExprClass:
3413 // typeid might throw if its subexpression is potentially-evaluated, so has
3414 // side-effects in that case whether or not its subexpression does.
3415 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003416
3417 case CXXConstructExprClass:
3418 case CXXTemporaryObjectExprClass: {
3419 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003420 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003421 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003422 // A trivial constructor does not add any side-effects of its own. Just look
3423 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003424 break;
3425 }
3426
Richard Smith5179eb72016-06-28 19:03:57 +00003427 case CXXInheritedCtorInitExprClass: {
3428 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3429 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3430 return true;
3431 break;
3432 }
3433
Richard Smith0421ce72012-08-07 04:16:51 +00003434 case LambdaExprClass: {
3435 const LambdaExpr *LE = cast<LambdaExpr>(this);
Richard Smithb3d203f2018-10-19 19:01:34 +00003436 for (Expr *E : LE->capture_inits())
3437 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003438 return true;
3439 return false;
3440 }
3441
3442 case PseudoObjectExprClass: {
3443 // Only look for side-effects in the semantic form, and look past
3444 // OpaqueValueExpr bindings in that form.
3445 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3446 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3447 E = PO->semantics_end();
3448 I != E; ++I) {
3449 const Expr *Subexpr = *I;
3450 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3451 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003452 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003453 return true;
3454 }
3455 return false;
3456 }
3457
3458 case ObjCBoxedExprClass:
3459 case ObjCArrayLiteralClass:
3460 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003461 case ObjCSelectorExprClass:
3462 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003463 case ObjCIsaExprClass:
3464 case ObjCIndirectCopyRestoreExprClass:
3465 case ObjCSubscriptRefExprClass:
3466 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003467 case ObjCMessageExprClass:
3468 case ObjCPropertyRefExprClass:
3469 // FIXME: Classify these cases better.
3470 if (IncludePossibleEffects)
3471 return true;
3472 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003473 }
3474
3475 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003476 for (const Stmt *SubStmt : children())
3477 if (SubStmt &&
3478 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3479 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003480
3481 return false;
3482}
3483
Douglas Gregor1be329d2012-02-23 07:33:15 +00003484namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003485 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003486 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3487 {
3488 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003489
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003490 bool NonTrivial;
Fangrui Song6907ce22018-07-30 19:24:48 +00003491
Douglas Gregor1be329d2012-02-23 07:33:15 +00003492 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003493 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003494 : Inherited(Context), NonTrivial(false) { }
Fangrui Song6907ce22018-07-30 19:24:48 +00003495
Douglas Gregor1be329d2012-02-23 07:33:15 +00003496 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003497
3498 void VisitCallExpr(const CallExpr *E) {
3499 if (const CXXMethodDecl *Method
3500 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003501 if (Method->isTrivial()) {
3502 // Recurse to children of the call.
3503 Inherited::VisitStmt(E);
3504 return;
3505 }
3506 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003507
Douglas Gregor1be329d2012-02-23 07:33:15 +00003508 NonTrivial = true;
3509 }
Scott Douglass503fc392015-06-10 13:53:15 +00003510
3511 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003512 if (E->getConstructor()->isTrivial()) {
3513 // Recurse to children of the call.
3514 Inherited::VisitStmt(E);
3515 return;
3516 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003517
Douglas Gregor1be329d2012-02-23 07:33:15 +00003518 NonTrivial = true;
3519 }
Scott Douglass503fc392015-06-10 13:53:15 +00003520
3521 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003522 if (E->getTemporary()->getDestructor()->isTrivial()) {
3523 Inherited::VisitStmt(E);
3524 return;
3525 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003526
Douglas Gregor1be329d2012-02-23 07:33:15 +00003527 NonTrivial = true;
3528 }
3529 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003530}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003531
Scott Douglass503fc392015-06-10 13:53:15 +00003532bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003533 NonTrivialCallFinder Finder(Ctx);
3534 Finder.Visit(this);
Fangrui Song6907ce22018-07-30 19:24:48 +00003535 return Finder.hasNonTrivialCall();
Douglas Gregor1be329d2012-02-23 07:33:15 +00003536}
3537
Fangrui Song6907ce22018-07-30 19:24:48 +00003538/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003539/// pointer constant or not, as well as the specific kind of constant detected.
3540/// Null pointer constants can be integer constant expressions with the
3541/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3542/// (a GNU extension).
3543Expr::NullPointerConstantKind
3544Expr::isNullPointerConstant(ASTContext &Ctx,
3545 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003546 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003547 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003548 switch (NPC) {
3549 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003550 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003551 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003552 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003553 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003554 else
3555 return NPCK_NotNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003556
Douglas Gregor56751b52009-09-25 04:25:58 +00003557 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003558 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003559 }
3560 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003561
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003562 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003563 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003564 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003565 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003566 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003567 QualType Pointee = PT->getPointeeType();
Richard Smithdab73ce2018-11-28 06:25:06 +00003568 Qualifiers Qs = Pointee.getQualifiers();
Yaxun Liub7318e02017-10-13 03:37:48 +00003569 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3570 // has non-default address space it is not treated as nullptr.
3571 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3572 // since it cannot be assigned to a pointer to constant address space.
Richard Smithdab73ce2018-11-28 06:25:06 +00003573 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
Yaxun Liub7318e02017-10-13 03:37:48 +00003574 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3575 (Ctx.getLangOpts().OpenCL &&
3576 Ctx.getLangOpts().OpenCLVersion < 200 &&
Richard Smithdab73ce2018-11-28 06:25:06 +00003577 Pointee.getAddressSpace() == LangAS::opencl_private))
3578 Qs.removeAddressSpace();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003579
Richard Smithdab73ce2018-11-28 06:25:06 +00003580 if (Pointee->isVoidType() && Qs.empty() && // to void*
3581 CE->getSubExpr()->getType()->isIntegerType()) // from int
Douglas Gregor56751b52009-09-25 04:25:58 +00003582 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003583 }
Steve Naroffada7d422007-05-20 17:54:12 +00003584 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003585 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3586 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003587 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003588 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3589 // Accept ((void*)0) as a null pointer constant, as many other
3590 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003591 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003592 } else if (const GenericSelectionExpr *GE =
3593 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003594 if (GE->isResultDependent())
3595 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003596 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003597 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3598 if (CE->isConditionDependent())
3599 return NPCK_NotNull;
3600 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003601 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003602 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003603 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003604 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003605 } else if (const CXXDefaultInitExpr *DefaultInit
3606 = dyn_cast<CXXDefaultInitExpr>(this)) {
3607 // See through default initializer expressions.
3608 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003609 } else if (isa<GNUNullExpr>(this)) {
3610 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003611 return NPCK_GNUNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003612 } else if (const MaterializeTemporaryExpr *M
Douglas Gregorfe314812011-06-21 17:03:29 +00003613 = dyn_cast<MaterializeTemporaryExpr>(this)) {
Tykerb0561b32019-11-17 11:41:55 +01003614 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003615 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3616 if (const Expr *Source = OVE->getSourceExpr())
3617 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003618 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003619
Richard Smith89645bc2013-01-02 12:01:23 +00003620 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003621 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003622 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003623
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003624 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003625 if (!Ctx.getLangOpts().CPlusPlus11 &&
3626 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003627 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3628 const Expr *InitExpr = CLE->getInitializer();
3629 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3630 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3631 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003632 // This expression must be an integer type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003633 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003634 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003635 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003636
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003637 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003638 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3639 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003640 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003641 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003642 if (Lit && !Lit->getValue())
3643 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003644 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003645 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003646 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003647 // If we have an integer constant expression, we need to *evaluate* it and
3648 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003649 if (!isIntegerConstantExpr(Ctx))
3650 return NPCK_NotNull;
3651 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003652
David Blaikie1c7c8f72012-08-08 17:33:31 +00003653 if (EvaluateKnownConstInt(Ctx) != 0)
3654 return NPCK_NotNull;
3655
3656 if (isa<IntegerLiteral>(this))
3657 return NPCK_ZeroLiteral;
3658 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003659}
Steve Narofff7a5da12007-07-28 23:10:27 +00003660
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003661/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003662/// property, find the underlying property reference expression.
3663const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3664 const Expr *E = this;
3665 while (true) {
3666 assert((E->getValueKind() == VK_LValue &&
3667 E->getObjectKind() == OK_ObjCProperty) &&
3668 "expression is not a property reference");
3669 E = E->IgnoreParenCasts();
3670 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3671 if (BO->getOpcode() == BO_Comma) {
3672 E = BO->getRHS();
3673 continue;
3674 }
3675 }
3676
3677 break;
3678 }
3679
3680 return cast<ObjCPropertyRefExpr>(E);
3681}
3682
Anna Zaks97c7ce32012-10-01 20:34:04 +00003683bool Expr::isObjCSelfExpr() const {
3684 const Expr *E = IgnoreParenImpCasts();
3685
3686 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3687 if (!DRE)
3688 return false;
3689
3690 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3691 if (!Param)
3692 return false;
3693
3694 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3695 if (!M)
3696 return false;
3697
3698 return M->getSelfDecl() == Param;
3699}
3700
John McCalld25db7e2013-05-06 21:39:12 +00003701FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003702 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003703
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003704 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003705 if (ICE->getCastKind() == CK_LValueToRValue ||
3706 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003707 E = ICE->getSubExpr()->IgnoreParens();
3708 else
3709 break;
3710 }
3711
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003712 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003713 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003714 if (Field->isBitField())
3715 return Field;
3716
George Burgess IV00f70bd2018-03-01 05:43:23 +00003717 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3718 FieldDecl *Ivar = IvarRef->getDecl();
3719 if (Ivar->isBitField())
3720 return Ivar;
3721 }
John McCalld25db7e2013-05-06 21:39:12 +00003722
Richard Smith7873de02016-08-11 22:25:46 +00003723 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003724 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3725 if (Field->isBitField())
3726 return Field;
3727
Richard Smith7873de02016-08-11 22:25:46 +00003728 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3729 if (Expr *E = BD->getBinding())
3730 return E->getSourceBitField();
3731 }
3732
Eli Friedman609ada22011-07-13 02:05:57 +00003733 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003734 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003735 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003736
Eli Friedman609ada22011-07-13 02:05:57 +00003737 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003738 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003739 }
3740
Richard Smith5b571672014-09-24 23:55:00 +00003741 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3742 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3743 return UnOp->getSubExpr()->getSourceBitField();
3744
Craig Topper36250ad2014-05-12 05:36:57 +00003745 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003746}
3747
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003748bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003749 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003750 const Expr *E = this->IgnoreParens();
Fangrui Song6907ce22018-07-30 19:24:48 +00003751
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003752 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003753 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003754 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003755 E = ICE->getSubExpr()->IgnoreParens();
3756 else
3757 break;
3758 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003759
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003760 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3761 return ASE->getBase()->getType()->isVectorType();
3762
3763 if (isa<ExtVectorElementExpr>(E))
3764 return true;
3765
Richard Smith7873de02016-08-11 22:25:46 +00003766 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3767 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3768 if (auto *E = BD->getBinding())
3769 return E->refersToVectorElement();
3770
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003771 return false;
3772}
3773
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003774bool Expr::refersToGlobalRegisterVar() const {
3775 const Expr *E = this->IgnoreParenImpCasts();
3776
3777 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3778 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3779 if (VD->getStorageClass() == SC_Register &&
3780 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3781 return true;
3782
3783 return false;
3784}
3785
Richard Trieu4c05de82019-09-21 03:02:26 +00003786bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
3787 E1 = E1->IgnoreParens();
3788 E2 = E2->IgnoreParens();
3789
3790 if (E1->getStmtClass() != E2->getStmtClass())
3791 return false;
3792
3793 switch (E1->getStmtClass()) {
3794 default:
3795 return false;
3796 case CXXThisExprClass:
3797 return true;
3798 case DeclRefExprClass: {
3799 // DeclRefExpr without an ImplicitCastExpr can happen for integral
3800 // template parameters.
3801 const auto *DRE1 = cast<DeclRefExpr>(E1);
3802 const auto *DRE2 = cast<DeclRefExpr>(E2);
3803 return DRE1->isRValue() && DRE2->isRValue() &&
3804 DRE1->getDecl() == DRE2->getDecl();
3805 }
3806 case ImplicitCastExprClass: {
3807 // Peel off implicit casts.
3808 while (true) {
3809 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
3810 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
3811 if (!ICE1 || !ICE2)
3812 return false;
3813 if (ICE1->getCastKind() != ICE2->getCastKind())
3814 return false;
3815 E1 = ICE1->getSubExpr()->IgnoreParens();
3816 E2 = ICE2->getSubExpr()->IgnoreParens();
3817 // The final cast must be one of these types.
3818 if (ICE1->getCastKind() == CK_LValueToRValue ||
3819 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
3820 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
3821 break;
3822 }
3823 }
3824
3825 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
3826 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
3827 if (DRE1 && DRE2)
3828 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
3829
3830 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
3831 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
3832 if (Ivar1 && Ivar2) {
3833 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
3834 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
3835 }
3836
3837 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
3838 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
3839 if (Array1 && Array2) {
3840 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
3841 return false;
3842
3843 auto Idx1 = Array1->getIdx();
3844 auto Idx2 = Array2->getIdx();
3845 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
3846 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
3847 if (Integer1 && Integer2) {
Richard Trieu77297f02019-09-21 04:18:54 +00003848 if (!llvm::APInt::isSameValue(Integer1->getValue(),
3849 Integer2->getValue()))
Richard Trieu4c05de82019-09-21 03:02:26 +00003850 return false;
3851 } else {
3852 if (!isSameComparisonOperand(Idx1, Idx2))
3853 return false;
3854 }
3855
3856 return true;
3857 }
3858
3859 // Walk the MemberExpr chain.
3860 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
3861 const auto *ME1 = cast<MemberExpr>(E1);
3862 const auto *ME2 = cast<MemberExpr>(E2);
3863 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
3864 return false;
3865 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
3866 if (D->isStaticDataMember())
3867 return true;
3868 E1 = ME1->getBase()->IgnoreParenImpCasts();
3869 E2 = ME2->getBase()->IgnoreParenImpCasts();
3870 }
3871
3872 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
3873 return true;
3874
3875 // A static member variable can end the MemberExpr chain with either
3876 // a MemberExpr or a DeclRefExpr.
3877 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
3878 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3879 return DRE->getDecl();
3880 if (const auto *ME = dyn_cast<MemberExpr>(E))
3881 return ME->getMemberDecl();
3882 return nullptr;
3883 };
3884
3885 const ValueDecl *VD1 = getAnyDecl(E1);
3886 const ValueDecl *VD2 = getAnyDecl(E2);
3887 return declaresSameEntity(VD1, VD2);
3888 }
3889 }
3890}
3891
Chris Lattnerb8211f62009-02-16 22:14:05 +00003892/// isArrow - Return true if the base expression is a pointer to vector,
3893/// return false if the base expression is a vector.
3894bool ExtVectorElementExpr::isArrow() const {
3895 return getBase()->getType()->isPointerType();
3896}
3897
Nate Begemance4d7fc2008-04-18 23:10:10 +00003898unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003899 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003900 return VT->getNumElements();
3901 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003902}
3903
Nate Begemanf322eab2008-05-09 06:41:27 +00003904/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003905bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003906 // FIXME: Refactor this code to an accessor on the AST node which returns the
3907 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003908 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003909
3910 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003911 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003912 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003913
Nate Begeman7e5185b2009-01-18 02:01:21 +00003914 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003915 if (Comp[0] == 's' || Comp[0] == 'S')
3916 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003917
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003918 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003919 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003920 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003921
Steve Naroff0d595ca2007-07-30 03:29:09 +00003922 return false;
3923}
Chris Lattner885b4952007-08-02 23:36:59 +00003924
Nate Begemanf322eab2008-05-09 06:41:27 +00003925/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003926void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003927 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003928 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003929 bool isNumericAccessor = false;
3930 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003931 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003932 isNumericAccessor = true;
3933 }
Mike Stump11289f42009-09-09 15:08:12 +00003934
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003935 bool isHi = Comp == "hi";
3936 bool isLo = Comp == "lo";
3937 bool isEven = Comp == "even";
3938 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003939
Nate Begemanf322eab2008-05-09 06:41:27 +00003940 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3941 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003942
Nate Begemanf322eab2008-05-09 06:41:27 +00003943 if (isHi)
3944 Index = e + i;
3945 else if (isLo)
3946 Index = i;
3947 else if (isEven)
3948 Index = 2 * i;
3949 else if (isOdd)
3950 Index = 2 * i + 1;
3951 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003952 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003953
Nate Begemand3862152008-05-13 21:03:02 +00003954 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003955 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003956}
3957
Haojian Wu876bb862020-03-17 08:33:37 +01003958ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003959 QualType Type, SourceLocation BLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00003960 SourceLocation RP)
Haojian Wu876bb862020-03-17 08:33:37 +01003961 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary),
3962 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003963 SubExprs = new (C) Stmt*[args.size()];
Haojian Wu876bb862020-03-17 08:33:37 +01003964 for (unsigned i = 0; i != args.size(); i++)
Douglas Gregora6e053e2010-12-15 01:34:56 +00003965 SubExprs[i] = args[i];
Haojian Wu876bb862020-03-17 08:33:37 +01003966
3967 setDependence(computeDependence(this));
Douglas Gregora6e053e2010-12-15 01:34:56 +00003968}
3969
Craig Topper37932912013-08-18 10:09:15 +00003970void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003971 if (SubExprs) C.Deallocate(SubExprs);
3972
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003973 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003974 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003975 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003976}
Nate Begeman48745922009-08-12 02:28:50 +00003977
Bruno Ricci94498c72019-01-26 13:58:15 +00003978GenericSelectionExpr::GenericSelectionExpr(
Bruno Riccidb076832019-01-26 14:15:10 +00003979 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
Bruno Ricci94498c72019-01-26 13:58:15 +00003980 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3981 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3982 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
3983 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
3984 AssocExprs[ResultIndex]->getValueKind(),
Haojian Wu876bb862020-03-17 08:33:37 +01003985 AssocExprs[ResultIndex]->getObjectKind()),
Bruno Ricci94498c72019-01-26 13:58:15 +00003986 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00003987 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00003988 assert(AssocTypes.size() == AssocExprs.size() &&
3989 "Must have the same number of association expressions"
3990 " and TypeSourceInfo!");
3991 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
3992
Bruno Riccidb076832019-01-26 14:15:10 +00003993 GenericSelectionExprBits.GenericLoc = GenericLoc;
3994 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00003995 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00003996 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
3997 std::copy(AssocTypes.begin(), AssocTypes.end(),
3998 getTrailingObjects<TypeSourceInfo *>());
Haojian Wu876bb862020-03-17 08:33:37 +01003999
4000 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
Peter Collingbourne91147592011-04-15 00:35:48 +00004001}
4002
Bruno Ricci94498c72019-01-26 13:58:15 +00004003GenericSelectionExpr::GenericSelectionExpr(
4004 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4005 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4006 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4007 bool ContainsUnexpandedParameterPack)
4008 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
Haojian Wu876bb862020-03-17 08:33:37 +01004009 OK_Ordinary),
Bruno Ricci94498c72019-01-26 13:58:15 +00004010 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00004011 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00004012 assert(AssocTypes.size() == AssocExprs.size() &&
4013 "Must have the same number of association expressions"
4014 " and TypeSourceInfo!");
4015
Bruno Riccidb076832019-01-26 14:15:10 +00004016 GenericSelectionExprBits.GenericLoc = GenericLoc;
4017 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00004018 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00004019 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4020 std::copy(AssocTypes.begin(), AssocTypes.end(),
4021 getTrailingObjects<TypeSourceInfo *>());
Haojian Wu876bb862020-03-17 08:33:37 +01004022
4023 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
Bruno Riccidb076832019-01-26 14:15:10 +00004024}
4025
4026GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4027 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4028
4029GenericSelectionExpr *GenericSelectionExpr::Create(
4030 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4031 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4032 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4033 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4034 unsigned NumAssocs = AssocExprs.size();
4035 void *Mem = Context.Allocate(
4036 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4037 alignof(GenericSelectionExpr));
4038 return new (Mem) GenericSelectionExpr(
4039 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4040 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4041}
4042
4043GenericSelectionExpr *GenericSelectionExpr::Create(
4044 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4045 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4046 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4047 bool ContainsUnexpandedParameterPack) {
4048 unsigned NumAssocs = AssocExprs.size();
4049 void *Mem = Context.Allocate(
4050 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4051 alignof(GenericSelectionExpr));
4052 return new (Mem) GenericSelectionExpr(
4053 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4054 RParenLoc, ContainsUnexpandedParameterPack);
4055}
4056
4057GenericSelectionExpr *
4058GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4059 unsigned NumAssocs) {
4060 void *Mem = Context.Allocate(
4061 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4062 alignof(GenericSelectionExpr));
4063 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
Peter Collingbourne91147592011-04-15 00:35:48 +00004064}
4065
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004066//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004067// DesignatedInitExpr
4068//===----------------------------------------------------------------------===//
4069
Chandler Carruth631abd92011-06-16 06:47:06 +00004070IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004071 assert(Kind == FieldDesignator && "Only valid on a field designator");
4072 if (Field.NameOrField & 0x01)
4073 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
4074 else
4075 return getField()->getIdentifier();
4076}
4077
Craig Topper37932912013-08-18 10:09:15 +00004078DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00004079 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00004080 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00004081 bool GNUSyntax,
Haojian Wu876bb862020-03-17 08:33:37 +01004082 ArrayRef<Expr *> IndexExprs, Expr *Init)
4083 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4084 Init->getObjectKind()),
4085 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4086 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004087 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004088
4089 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004090 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004091 *Child++ = Init;
4092
4093 // Copy the designators and their subexpressions, computing
4094 // value-dependence along the way.
4095 unsigned IndexIdx = 0;
4096 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00004097 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004098 if (this->Designators[I].isArrayDesignator()) {
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004099 // Copy the index expressions into permanent storage.
4100 *Child++ = IndexExprs[IndexIdx++];
4101 } else if (this->Designators[I].isArrayRangeDesignator()) {
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004102 // Copy the start/end expressions into permanent storage.
4103 *Child++ = IndexExprs[IndexIdx++];
4104 *Child++ = IndexExprs[IndexIdx++];
4105 }
4106 }
4107
Benjamin Kramerc215e762012-08-24 11:54:20 +00004108 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Haojian Wu876bb862020-03-17 08:33:37 +01004109 setDependence(computeDependence(this));
Douglas Gregord5846a12009-04-15 06:41:24 +00004110}
4111
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004112DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00004113DesignatedInitExpr::Create(const ASTContext &C,
4114 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004115 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004116 SourceLocation ColonOrEqualLoc,
4117 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004118 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004119 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00004120 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004121 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004122 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004123}
4124
Craig Topper37932912013-08-18 10:09:15 +00004125DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00004126 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004127 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004128 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00004129 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4130}
4131
Craig Topper37932912013-08-18 10:09:15 +00004132void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004133 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00004134 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004135 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00004136 NumDesignators = NumDesigs;
4137 for (unsigned I = 0; I != NumDesigs; ++I)
4138 Designators[I] = Desigs[I];
4139}
4140
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00004141SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4142 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4143 if (size() == 1)
4144 return DIE->getDesignator(0)->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004145 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004146 DIE->getDesignator(size() - 1)->getEndLoc());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00004147}
4148
Stephen Kelly724e9e52018-08-09 20:05:03 +00004149SourceLocation DesignatedInitExpr::getBeginLoc() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004150 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00004151 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4152 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004153 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00004154 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004155 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
4156 else
4157 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
4158 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00004159 StartLoc =
4160 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00004161 return StartLoc;
4162}
4163
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004164SourceLocation DesignatedInitExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004165 return getInit()->getEndLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004166}
4167
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004168Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004169 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004170 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004171}
4172
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004173Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004174 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004175 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004176 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004177}
4178
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004179Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004180 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004181 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004182 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004183}
4184
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004185/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00004186/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00004187void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00004188 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00004189 const Designator *Last) {
4190 unsigned NumNewDesignators = Last - First;
4191 if (NumNewDesignators == 0) {
4192 std::copy_backward(Designators + Idx + 1,
4193 Designators + NumDesignators,
4194 Designators + Idx);
4195 --NumNewDesignators;
4196 return;
4197 } else if (NumNewDesignators == 1) {
4198 Designators[Idx] = *First;
4199 return;
4200 }
4201
Mike Stump11289f42009-09-09 15:08:12 +00004202 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004203 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00004204 std::copy(Designators, Designators + Idx, NewDesignators);
4205 std::copy(First, Last, NewDesignators + Idx);
4206 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4207 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00004208 Designators = NewDesignators;
4209 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4210}
4211
Yunzhong Gaocb779302015-06-10 00:27:52 +00004212DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
Haojian Wu876bb862020-03-17 08:33:37 +01004213 SourceLocation lBraceLoc,
4214 Expr *baseExpr,
4215 SourceLocation rBraceLoc)
4216 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4217 OK_Ordinary) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00004218 BaseAndUpdaterExprs[0] = baseExpr;
4219
4220 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4221 ILE->setType(baseExpr->getType());
4222 BaseAndUpdaterExprs[1] = ILE;
Haojian Wu876bb862020-03-17 08:33:37 +01004223
Haojian Wu4b0f1e12020-03-17 10:36:19 +01004224 // FIXME: this is wrong, set it correctly.
Haojian Wu876bb862020-03-17 08:33:37 +01004225 setDependence(ExprDependence::None);
Yunzhong Gaocb779302015-06-10 00:27:52 +00004226}
4227
Stephen Kelly724e9e52018-08-09 20:05:03 +00004228SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004229 return getBase()->getBeginLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004230}
4231
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004232SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004233 return getBase()->getEndLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004234}
4235
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004236ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4237 SourceLocation RParenLoc)
Haojian Wu876bb862020-03-17 08:33:37 +01004238 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary),
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004239 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4240 ParenListExprBits.NumExprs = Exprs.size();
4241
Haojian Wu876bb862020-03-17 08:33:37 +01004242 for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004243 getTrailingObjects<Stmt *>()[I] = Exprs[I];
Haojian Wu876bb862020-03-17 08:33:37 +01004244 setDependence(computeDependence(this));
Nate Begeman5ec4b312009-08-10 23:49:36 +00004245}
4246
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004247ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4248 : Expr(ParenListExprClass, Empty) {
4249 ParenListExprBits.NumExprs = NumExprs;
4250}
4251
4252ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4253 SourceLocation LParenLoc,
4254 ArrayRef<Expr *> Exprs,
4255 SourceLocation RParenLoc) {
4256 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4257 alignof(ParenListExpr));
4258 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4259}
4260
4261ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4262 unsigned NumExprs) {
4263 void *Mem =
4264 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4265 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4266}
4267
John McCall1bf58462011-02-16 08:02:54 +00004268const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4269 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4270 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00004271 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
Tykerb0561b32019-11-17 11:41:55 +01004272 e = m->getSubExpr();
John McCall1bf58462011-02-16 08:02:54 +00004273 e = cast<CXXConstructExpr>(e)->getArg(0);
4274 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4275 e = ice->getSubExpr();
4276 return cast<OpaqueValueExpr>(e);
4277}
4278
Craig Topper37932912013-08-18 10:09:15 +00004279PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4280 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00004281 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004282 void *buffer =
4283 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004284 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004285 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4286}
4287
4288PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4289 : Expr(PseudoObjectExprClass, shell) {
4290 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4291}
4292
Craig Topper37932912013-08-18 10:09:15 +00004293PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00004294 ArrayRef<Expr*> semantics,
4295 unsigned resultIndex) {
4296 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004297 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00004298
4299 QualType type;
4300 ExprValueKind VK;
4301 if (resultIndex == NoResult) {
4302 type = C.VoidTy;
4303 VK = VK_RValue;
4304 } else {
4305 assert(resultIndex < semantics.size());
4306 type = semantics[resultIndex]->getType();
4307 VK = semantics[resultIndex]->getValueKind();
4308 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4309 }
4310
James Y Knighte00a67e2015-12-31 04:18:25 +00004311 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004312 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004313 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4314 resultIndex);
4315}
4316
4317PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
Haojian Wu876bb862020-03-17 08:33:37 +01004318 Expr *syntax, ArrayRef<Expr *> semantics,
John McCallfe96e0b2011-11-06 09:01:30 +00004319 unsigned resultIndex)
Haojian Wu876bb862020-03-17 08:33:37 +01004320 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
John McCallfe96e0b2011-11-06 09:01:30 +00004321 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4322 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4323
4324 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4325 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4326 getSubExprsBuffer()[i] = E;
4327
John McCallfe96e0b2011-11-06 09:01:30 +00004328 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00004329 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00004330 "opaque-value semantic expressions for pseudo-object "
4331 "operations must have sources");
4332 }
Haojian Wu876bb862020-03-17 08:33:37 +01004333
4334 setDependence(computeDependence(this));
John McCallfe96e0b2011-11-06 09:01:30 +00004335}
4336
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004337//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004338// Child Iterators for iterating over subexpressions/substatements
4339//===----------------------------------------------------------------------===//
4340
Peter Collingbournee190dee2011-03-11 19:24:49 +00004341// UnaryExprOrTypeTraitExpr
4342Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004343 const_child_range CCR =
4344 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4345 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4346}
4347
4348Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00004349 // If this is of a type and the type is a VLA type (and not a typedef), the
4350 // size expression of the VLA needs to be treated as an executable expression.
4351 // Why isn't this weirdness documented better in StmtIterator?
4352 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004353 if (const VariableArrayType *T =
4354 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4355 return const_child_range(const_child_iterator(T), const_child_iterator());
4356 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00004357 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004358 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004359}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004360
Haojian Wu876bb862020-03-17 08:33:37 +01004361AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
4362 AtomicOp op, SourceLocation RP)
4363 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary),
4364 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004365 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
Haojian Wu876bb862020-03-17 08:33:37 +01004366 for (unsigned i = 0; i != args.size(); i++)
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004367 SubExprs[i] = args[i];
Haojian Wu876bb862020-03-17 08:33:37 +01004368 setDependence(computeDependence(this));
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004369}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004370
4371unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4372 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004373 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004374 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004375 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004376 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004377 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004378
Yaxun Liu30d652a2017-08-15 16:02:49 +00004379 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004380 case AO__c11_atomic_store:
4381 case AO__c11_atomic_exchange:
4382 case AO__atomic_load:
4383 case AO__atomic_store:
4384 case AO__atomic_store_n:
4385 case AO__atomic_exchange_n:
4386 case AO__c11_atomic_fetch_add:
4387 case AO__c11_atomic_fetch_sub:
4388 case AO__c11_atomic_fetch_and:
4389 case AO__c11_atomic_fetch_or:
4390 case AO__c11_atomic_fetch_xor:
Tim Northover5cf58762019-11-21 10:31:30 +00004391 case AO__c11_atomic_fetch_max:
4392 case AO__c11_atomic_fetch_min:
Richard Smithfeea8832012-04-12 05:08:17 +00004393 case AO__atomic_fetch_add:
4394 case AO__atomic_fetch_sub:
4395 case AO__atomic_fetch_and:
4396 case AO__atomic_fetch_or:
4397 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004398 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004399 case AO__atomic_add_fetch:
4400 case AO__atomic_sub_fetch:
4401 case AO__atomic_and_fetch:
4402 case AO__atomic_or_fetch:
4403 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004404 case AO__atomic_nand_fetch:
Tim Northover5cf58762019-11-21 10:31:30 +00004405 case AO__atomic_min_fetch:
4406 case AO__atomic_max_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004407 case AO__atomic_fetch_min:
4408 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004409 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004410
Yaxun Liu30d652a2017-08-15 16:02:49 +00004411 case AO__opencl_atomic_store:
4412 case AO__opencl_atomic_exchange:
4413 case AO__opencl_atomic_fetch_add:
4414 case AO__opencl_atomic_fetch_sub:
4415 case AO__opencl_atomic_fetch_and:
4416 case AO__opencl_atomic_fetch_or:
4417 case AO__opencl_atomic_fetch_xor:
4418 case AO__opencl_atomic_fetch_min:
4419 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004420 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004421 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004422
4423 case AO__c11_atomic_compare_exchange_strong:
4424 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004425 return 5;
4426
Yaxun Liu39195062017-08-04 18:16:31 +00004427 case AO__opencl_atomic_compare_exchange_strong:
4428 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004429 case AO__atomic_compare_exchange:
4430 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004431 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004432 }
4433 llvm_unreachable("unknown atomic op");
4434}
Alexey Bataeva1764212015-09-30 09:22:36 +00004435
Yaxun Liu39195062017-08-04 18:16:31 +00004436QualType AtomicExpr::getValueType() const {
4437 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4438 if (auto AT = T->getAs<AtomicType>())
4439 return AT->getValueType();
4440 return T;
4441}
4442
Alexey Bataev31300ed2016-02-04 11:27:03 +00004443QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004444 unsigned ArraySectionCount = 0;
4445 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4446 Base = OASE->getBase();
4447 ++ArraySectionCount;
4448 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004449 while (auto *ASE =
4450 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004451 Base = ASE->getBase();
4452 ++ArraySectionCount;
4453 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004454 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004455 auto OriginalTy = Base->getType();
4456 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4457 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4458 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4459
4460 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4461 if (OriginalTy->isAnyPointerType())
4462 OriginalTy = OriginalTy->getPointeeType();
4463 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004464 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004465 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4466 }
4467 }
4468 return OriginalTy;
4469}