1//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr class and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Expr.h"
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/ComputeDependence.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DependenceFlags.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/IgnoreExpr.h"
26#include "clang/AST/Mangle.h"
27#include "clang/AST/RecordLayout.h"
28#include "clang/AST/TypeBase.h"
29#include "clang/Basic/Builtins.h"
30#include "clang/Basic/CharInfo.h"
31#include "clang/Basic/SourceManager.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Lex/Lexer.h"
34#include "clang/Lex/LiteralSupport.h"
35#include "clang/Lex/Preprocessor.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/Format.h"
38#include "llvm/Support/raw_ostream.h"
39#include <algorithm>
40#include <cstring>
41#include <optional>
42using namespace clang;
43
44const Expr *Expr::getBestDynamicClassTypeExpr() const {
45 const Expr *E = this;
46 while (true) {
47 E = E->IgnoreParenBaseCasts();
48
49 // Follow the RHS of a comma operator.
50 if (auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
51 if (BO->getOpcode() == BO_Comma) {
52 E = BO->getRHS();
53 continue;
54 }
55 }
56
57 // Step into initializer for materialized temporaries.
58 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
59 E = MTE->getSubExpr();
60 continue;
61 }
62
63 break;
64 }
65
66 return E;
67}
68
69const CXXRecordDecl *Expr::getBestDynamicClassType() const {
70 const Expr *E = getBestDynamicClassTypeExpr();
71 QualType DerivedType = E->getType();
72 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
73 DerivedType = PTy->getPointeeType();
74
75 while (const ArrayType *ATy = DerivedType->getAsArrayTypeUnsafe())
76 DerivedType = ATy->getElementType();
77
78 if (DerivedType->isDependentType())
79 return nullptr;
80
81 return DerivedType->castAsCXXRecordDecl();
82}
83
84const Expr *Expr::skipRValueSubobjectAdjustments(
85 SmallVectorImpl<const Expr *> &CommaLHSs,
86 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
87 const Expr *E = this;
88 while (true) {
89 E = E->IgnoreParens();
90
91 if (const auto *CE = dyn_cast<CastExpr>(Val: E)) {
92 if ((CE->getCastKind() == CK_DerivedToBase ||
93 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
94 E->getType()->isRecordType()) {
95 E = CE->getSubExpr();
96 const auto *Derived = E->getType()->castAsCXXRecordDecl();
97 Adjustments.push_back(Elt: SubobjectAdjustment(CE, Derived));
98 continue;
99 }
100
101 if (CE->getCastKind() == CK_NoOp) {
102 E = CE->getSubExpr();
103 continue;
104 }
105 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: E)) {
106 if (!ME->isArrow()) {
107 assert(ME->getBase()->getType()->getAsRecordDecl());
108 if (const auto *Field = dyn_cast<FieldDecl>(Val: ME->getMemberDecl())) {
109 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
110 E = ME->getBase();
111 Adjustments.push_back(Elt: SubobjectAdjustment(Field));
112 continue;
113 }
114 }
115 }
116 } else if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
117 if (BO->getOpcode() == BO_PtrMemD) {
118 assert(BO->getRHS()->isPRValue());
119 E = BO->getLHS();
120 const auto *MPT = BO->getRHS()->getType()->getAs<MemberPointerType>();
121 Adjustments.push_back(Elt: SubobjectAdjustment(MPT, BO->getRHS()));
122 continue;
123 }
124 if (BO->getOpcode() == BO_Comma) {
125 CommaLHSs.push_back(Elt: BO->getLHS());
126 E = BO->getRHS();
127 continue;
128 }
129 }
130
131 // Nothing changed.
132 break;
133 }
134 return E;
135}
136
137bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
138 const Expr *E = IgnoreParens();
139
140 // If this value has _Bool type, it is obvious 0/1.
141 if (E->getType()->isBooleanType()) return true;
142 // If this is a non-scalar-integer type, we don't care enough to try.
143 if (!E->getType()->isIntegralOrEnumerationType()) return false;
144
145 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
146 switch (UO->getOpcode()) {
147 case UO_Plus:
148 return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
149 case UO_LNot:
150 return true;
151 default:
152 return false;
153 }
154 }
155
156 // Only look through implicit casts. If the user writes
157 // '(int) (a && b)' treat it as an arbitrary int.
158 // FIXME: Should we look through any cast expression in !Semantic mode?
159 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Val: E))
160 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
161
162 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
163 switch (BO->getOpcode()) {
164 default: return false;
165 case BO_LT: // Relational operators.
166 case BO_GT:
167 case BO_LE:
168 case BO_GE:
169 case BO_EQ: // Equality operators.
170 case BO_NE:
171 case BO_LAnd: // AND operator.
172 case BO_LOr: // Logical OR operator.
173 return true;
174
175 case BO_And: // Bitwise AND operator.
176 case BO_Xor: // Bitwise XOR operator.
177 case BO_Or: // Bitwise OR operator.
178 // Handle things like (x==2)|(y==12).
179 return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
180 BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
181
182 case BO_Comma:
183 case BO_Assign:
184 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
185 }
186 }
187
188 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E))
189 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
190 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
191
192 if (isa<ObjCBoolLiteralExpr>(Val: E))
193 return true;
194
195 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
196 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
197
198 if (const FieldDecl *FD = E->getSourceBitField())
199 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
200 !FD->getBitWidth()->isValueDependent() && FD->getBitWidthValue() == 1)
201 return true;
202
203 return false;
204}
205
206bool Expr::isFlexibleArrayMemberLike(
207 const ASTContext &Ctx,
208 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
209 bool IgnoreTemplateOrMacroSubstitution) const {
210 const Expr *E = IgnoreParens();
211 const Decl *D = nullptr;
212
213 if (const auto *ME = dyn_cast<MemberExpr>(Val: E))
214 D = ME->getMemberDecl();
215 else if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E))
216 D = DRE->getDecl();
217 else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(Val: E))
218 D = IRE->getDecl();
219
220 return Decl::isFlexibleArrayMemberLike(Context: Ctx, D, Ty: E->getType(),
221 StrictFlexArraysLevel,
222 IgnoreTemplateOrMacroSubstitution);
223}
224
225const ValueDecl *
226Expr::getAsBuiltinConstantDeclRef(const ASTContext &Context) const {
227 Expr::EvalResult Eval;
228
229 if (EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) {
230 APValue &Value = Eval.Val;
231
232 if (Value.isMemberPointer())
233 return Value.getMemberPointerDecl();
234
235 if (Value.isLValue() && Value.getLValueOffset().isZero())
236 return Value.getLValueBase().dyn_cast<const ValueDecl *>();
237 }
238
239 return nullptr;
240}
241
242// Amusing macro metaprogramming hack: check whether a class provides
243// a more specific implementation of getExprLoc().
244//
245// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
246namespace {
247 /// This implementation is used when a class provides a custom
248 /// implementation of getExprLoc.
249 template <class E, class T>
250 SourceLocation getExprLocImpl(const Expr *expr,
251 SourceLocation (T::*v)() const) {
252 return static_cast<const E*>(expr)->getExprLoc();
253 }
254
255 /// This implementation is used when a class doesn't provide
256 /// a custom implementation of getExprLoc. Overload resolution
257 /// should pick it over the implementation above because it's
258 /// more specialized according to function template partial ordering.
259 template <class E>
260 SourceLocation getExprLocImpl(const Expr *expr,
261 SourceLocation (Expr::*v)() const) {
262 return static_cast<const E *>(expr)->getBeginLoc();
263 }
264}
265
266QualType Expr::getEnumCoercedType(const ASTContext &Ctx) const {
267 if (isa<EnumType>(Val: getType()))
268 return getType();
269 if (const auto *ECD = getEnumConstantDecl()) {
270 const auto *ED = cast<EnumDecl>(Val: ECD->getDeclContext());
271 if (ED->isCompleteDefinition())
272 return Ctx.getCanonicalTagType(TD: ED);
273 }
274 return getType();
275}
276
277SourceLocation Expr::getExprLoc() const {
278 switch (getStmtClass()) {
279 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
280#define ABSTRACT_STMT(type)
281#define STMT(type, base) \
282 case Stmt::type##Class: break;
283#define EXPR(type, base) \
284 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
285#include "clang/AST/StmtNodes.inc"
286 }
287 llvm_unreachable("unknown expression kind");
288}
289
290//===----------------------------------------------------------------------===//
291// Primary Expressions.
292//===----------------------------------------------------------------------===//
293
294static void AssertResultStorageKind(ConstantResultStorageKind Kind) {
295 assert((Kind == ConstantResultStorageKind::APValue ||
296 Kind == ConstantResultStorageKind::Int64 ||
297 Kind == ConstantResultStorageKind::None) &&
298 "Invalid StorageKind Value");
299 (void)Kind;
300}
301
302ConstantResultStorageKind ConstantExpr::getStorageKind(const APValue &Value) {
303 switch (Value.getKind()) {
304 case APValue::None:
305 case APValue::Indeterminate:
306 return ConstantResultStorageKind::None;
307 case APValue::Int:
308 if (!Value.getInt().needsCleanup())
309 return ConstantResultStorageKind::Int64;
310 [[fallthrough]];
311 default:
312 return ConstantResultStorageKind::APValue;
313 }
314}
315
316ConstantResultStorageKind
317ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
318 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
319 return ConstantResultStorageKind::Int64;
320 return ConstantResultStorageKind::APValue;
321}
322
323ConstantExpr::ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
324 bool IsImmediateInvocation)
325 : FullExpr(ConstantExprClass, SubExpr) {
326 ConstantExprBits.ResultKind = llvm::to_underlying(E: StorageKind);
327 ConstantExprBits.APValueKind = APValue::None;
328 ConstantExprBits.IsUnsigned = false;
329 ConstantExprBits.BitWidth = 0;
330 ConstantExprBits.HasCleanup = false;
331 ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
332
333 if (StorageKind == ConstantResultStorageKind::APValue)
334 ::new (getTrailingObjects<APValue>()) APValue();
335}
336
337ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
338 ConstantResultStorageKind StorageKind,
339 bool IsImmediateInvocation) {
340 assert(!isa<ConstantExpr>(E));
341 AssertResultStorageKind(Kind: StorageKind);
342
343 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
344 Counts: StorageKind == ConstantResultStorageKind::APValue,
345 Counts: StorageKind == ConstantResultStorageKind::Int64);
346 void *Mem = Context.Allocate(Size, Align: alignof(ConstantExpr));
347 return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
348}
349
350ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
351 const APValue &Result) {
352 ConstantResultStorageKind StorageKind = getStorageKind(Value: Result);
353 ConstantExpr *Self = Create(Context, E, StorageKind);
354 Self->SetResult(Value: Result, Context);
355 return Self;
356}
357
358ConstantExpr::ConstantExpr(EmptyShell Empty,
359 ConstantResultStorageKind StorageKind)
360 : FullExpr(ConstantExprClass, Empty) {
361 ConstantExprBits.ResultKind = llvm::to_underlying(E: StorageKind);
362
363 if (StorageKind == ConstantResultStorageKind::APValue)
364 ::new (getTrailingObjects<APValue>()) APValue();
365}
366
367ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
368 ConstantResultStorageKind StorageKind) {
369 AssertResultStorageKind(Kind: StorageKind);
370
371 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
372 Counts: StorageKind == ConstantResultStorageKind::APValue,
373 Counts: StorageKind == ConstantResultStorageKind::Int64);
374 void *Mem = Context.Allocate(Size, Align: alignof(ConstantExpr));
375 return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
376}
377
378void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
379 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
380 "Invalid storage for this value kind");
381 ConstantExprBits.APValueKind = Value.getKind();
382 switch (getResultStorageKind()) {
383 case ConstantResultStorageKind::None:
384 return;
385 case ConstantResultStorageKind::Int64:
386 Int64Result() = *Value.getInt().getRawData();
387 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
388 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
389 return;
390 case ConstantResultStorageKind::APValue:
391 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
392 ConstantExprBits.HasCleanup = true;
393 Context.addDestruction(Ptr: &APValueResult());
394 }
395 APValueResult() = std::move(Value);
396 return;
397 }
398 llvm_unreachable("Invalid ResultKind Bits");
399}
400
401llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
402 switch (getResultStorageKind()) {
403 case ConstantResultStorageKind::APValue:
404 return APValueResult().getInt();
405 case ConstantResultStorageKind::Int64:
406 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
407 ConstantExprBits.IsUnsigned);
408 default:
409 llvm_unreachable("invalid Accessor");
410 }
411}
412
413APValue ConstantExpr::getAPValueResult() const {
414
415 switch (getResultStorageKind()) {
416 case ConstantResultStorageKind::APValue:
417 return APValueResult();
418 case ConstantResultStorageKind::Int64:
419 return APValue(
420 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
421 ConstantExprBits.IsUnsigned));
422 case ConstantResultStorageKind::None:
423 if (ConstantExprBits.APValueKind == APValue::Indeterminate)
424 return APValue::IndeterminateValue();
425 return APValue();
426 }
427 llvm_unreachable("invalid ResultKind");
428}
429
430DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
431 bool RefersToEnclosingVariableOrCapture, QualType T,
432 ExprValueKind VK, SourceLocation L,
433 const DeclarationNameLoc &LocInfo,
434 NonOdrUseReason NOUR)
435 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
436 DeclRefExprBits.HasQualifier = false;
437 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
438 DeclRefExprBits.HasFoundDecl = false;
439 DeclRefExprBits.HadMultipleCandidates = false;
440 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
441 RefersToEnclosingVariableOrCapture;
442 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
443 DeclRefExprBits.NonOdrUseReason = NOUR;
444 DeclRefExprBits.IsImmediateEscalating = false;
445 DeclRefExprBits.Loc = L;
446 setDependence(computeDependence(E: this, Ctx));
447}
448
449DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
450 NestedNameSpecifierLoc QualifierLoc,
451 SourceLocation TemplateKWLoc, ValueDecl *D,
452 bool RefersToEnclosingVariableOrCapture,
453 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
454 const TemplateArgumentListInfo *TemplateArgs,
455 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
456 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
457 DNLoc(NameInfo.getInfo()) {
458 DeclRefExprBits.Loc = NameInfo.getLoc();
459 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
460 if (QualifierLoc)
461 new (getTrailingObjects<NestedNameSpecifierLoc>())
462 NestedNameSpecifierLoc(QualifierLoc);
463 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
464 if (FoundD)
465 *getTrailingObjects<NamedDecl *>() = FoundD;
466 DeclRefExprBits.HasTemplateKWAndArgsInfo
467 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
468 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
469 RefersToEnclosingVariableOrCapture;
470 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
471 DeclRefExprBits.NonOdrUseReason = NOUR;
472 if (TemplateArgs) {
473 auto Deps = TemplateArgumentDependence::None;
474 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
475 TemplateKWLoc, List: *TemplateArgs, OutArgArray: getTrailingObjects<TemplateArgumentLoc>(),
476 Deps);
477 assert(!(Deps & TemplateArgumentDependence::Dependent) &&
478 "built a DeclRefExpr with dependent template args");
479 } else if (TemplateKWLoc.isValid()) {
480 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
481 TemplateKWLoc);
482 }
483 DeclRefExprBits.IsImmediateEscalating = false;
484 DeclRefExprBits.HadMultipleCandidates = 0;
485 setDependence(computeDependence(E: this, Ctx));
486}
487
488DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
489 NestedNameSpecifierLoc QualifierLoc,
490 SourceLocation TemplateKWLoc, ValueDecl *D,
491 bool RefersToEnclosingVariableOrCapture,
492 SourceLocation NameLoc, QualType T,
493 ExprValueKind VK, NamedDecl *FoundD,
494 const TemplateArgumentListInfo *TemplateArgs,
495 NonOdrUseReason NOUR) {
496 return Create(Context, QualifierLoc, TemplateKWLoc, D,
497 RefersToEnclosingVariableOrCapture,
498 NameInfo: DeclarationNameInfo(D->getDeclName(), NameLoc),
499 T, VK, FoundD, TemplateArgs, NOUR);
500}
501
502DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
503 NestedNameSpecifierLoc QualifierLoc,
504 SourceLocation TemplateKWLoc, ValueDecl *D,
505 bool RefersToEnclosingVariableOrCapture,
506 const DeclarationNameInfo &NameInfo,
507 QualType T, ExprValueKind VK,
508 NamedDecl *FoundD,
509 const TemplateArgumentListInfo *TemplateArgs,
510 NonOdrUseReason NOUR) {
511 // Filter out cases where the found Decl is the same as the value refenenced.
512 if (D == FoundD)
513 FoundD = nullptr;
514
515 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
516 std::size_t Size =
517 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
518 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
519 Counts: QualifierLoc ? 1 : 0, Counts: FoundD ? 1 : 0,
520 Counts: HasTemplateKWAndArgsInfo ? 1 : 0,
521 Counts: TemplateArgs ? TemplateArgs->size() : 0);
522
523 void *Mem = Context.Allocate(Size, Align: alignof(DeclRefExpr));
524 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
525 RefersToEnclosingVariableOrCapture, NameInfo,
526 FoundD, TemplateArgs, T, VK, NOUR);
527}
528
529DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
530 bool HasQualifier,
531 bool HasFoundDecl,
532 bool HasTemplateKWAndArgsInfo,
533 unsigned NumTemplateArgs) {
534 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
535 std::size_t Size =
536 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
537 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
538 Counts: HasQualifier ? 1 : 0, Counts: HasFoundDecl ? 1 : 0, Counts: HasTemplateKWAndArgsInfo,
539 Counts: NumTemplateArgs);
540 void *Mem = Context.Allocate(Size, Align: alignof(DeclRefExpr));
541 return new (Mem) DeclRefExpr(EmptyShell());
542}
543
544void DeclRefExpr::setDecl(ValueDecl *NewD) {
545 D = NewD;
546 if (getType()->isUndeducedType())
547 setType(NewD->getType());
548 setDependence(computeDependence(E: this, Ctx: NewD->getASTContext()));
549}
550
551SourceLocation DeclRefExpr::getEndLoc() const {
552 if (hasExplicitTemplateArgs())
553 return getRAngleLoc();
554 return getNameInfo().getEndLoc();
555}
556
557SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
558 SourceLocation LParen,
559 SourceLocation RParen,
560 QualType ResultTy,
561 TypeSourceInfo *TSI)
562 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
563 OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
564 setTypeSourceInfo(TSI);
565 setDependence(computeDependence(E: this));
566}
567
568SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
569 QualType ResultTy)
570 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
571
572SYCLUniqueStableNameExpr *
573SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc,
574 SourceLocation LParen, SourceLocation RParen,
575 TypeSourceInfo *TSI) {
576 QualType ResultTy = Ctx.getPointerType(T: Ctx.CharTy.withConst());
577 return new (Ctx)
578 SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
579}
580
581SYCLUniqueStableNameExpr *
582SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) {
583 QualType ResultTy = Ctx.getPointerType(T: Ctx.CharTy.withConst());
584 return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
585}
586
587std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const {
588 return SYCLUniqueStableNameExpr::ComputeName(Context,
589 Ty: getTypeSourceInfo()->getType());
590}
591
592std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,
593 QualType Ty) {
594 auto MangleCallback = [](ASTContext &Ctx,
595 const NamedDecl *ND) -> UnsignedOrNone {
596 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
597 return RD->getDeviceLambdaManglingNumber();
598 return std::nullopt;
599 };
600
601 std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
602 Context, Diags&: Context.getDiagnostics(), Discriminator: MangleCallback)};
603
604 std::string Buffer;
605 Buffer.reserve(res_arg: 128);
606 llvm::raw_string_ostream Out(Buffer);
607 Ctx->mangleCanonicalTypeName(T: Ty, Out);
608
609 return Buffer;
610}
611
612PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy,
613 PredefinedIdentKind IK, bool IsTransparent,
614 StringLiteral *SL)
615 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
616 PredefinedExprBits.Kind = llvm::to_underlying(E: IK);
617 assert((getIdentKind() == IK) &&
618 "IdentKind do not fit in PredefinedExprBitfields!");
619 bool HasFunctionName = SL != nullptr;
620 PredefinedExprBits.HasFunctionName = HasFunctionName;
621 PredefinedExprBits.IsTransparent = IsTransparent;
622 PredefinedExprBits.Loc = L;
623 if (HasFunctionName)
624 setFunctionName(SL);
625 setDependence(computeDependence(E: this));
626}
627
628PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
629 : Expr(PredefinedExprClass, Empty) {
630 PredefinedExprBits.HasFunctionName = HasFunctionName;
631}
632
633PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
634 QualType FNTy, PredefinedIdentKind IK,
635 bool IsTransparent, StringLiteral *SL) {
636 bool HasFunctionName = SL != nullptr;
637 void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: HasFunctionName),
638 Align: alignof(PredefinedExpr));
639 return new (Mem) PredefinedExpr(L, FNTy, IK, IsTransparent, SL);
640}
641
642PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
643 bool HasFunctionName) {
644 void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: HasFunctionName),
645 Align: alignof(PredefinedExpr));
646 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
647}
648
649StringRef PredefinedExpr::getIdentKindName(PredefinedIdentKind IK) {
650 switch (IK) {
651 case PredefinedIdentKind::Func:
652 return "__func__";
653 case PredefinedIdentKind::Function:
654 return "__FUNCTION__";
655 case PredefinedIdentKind::FuncDName:
656 return "__FUNCDNAME__";
657 case PredefinedIdentKind::LFunction:
658 return "L__FUNCTION__";
659 case PredefinedIdentKind::PrettyFunction:
660 return "__PRETTY_FUNCTION__";
661 case PredefinedIdentKind::FuncSig:
662 return "__FUNCSIG__";
663 case PredefinedIdentKind::LFuncSig:
664 return "L__FUNCSIG__";
665 case PredefinedIdentKind::PrettyFunctionNoVirtual:
666 break;
667 }
668 llvm_unreachable("Unknown ident kind for PredefinedExpr");
669}
670
671// FIXME: Maybe this should use DeclPrinter with a special "print predefined
672// expr" policy instead.
673std::string PredefinedExpr::ComputeName(PredefinedIdentKind IK,
674 const Decl *CurrentDecl,
675 bool ForceElaboratedPrinting) {
676 ASTContext &Context = CurrentDecl->getASTContext();
677
678 if (IK == PredefinedIdentKind::FuncDName) {
679 if (const NamedDecl *ND = dyn_cast<NamedDecl>(Val: CurrentDecl)) {
680 std::unique_ptr<MangleContext> MC;
681 MC.reset(p: Context.createMangleContext());
682
683 if (MC->shouldMangleDeclName(D: ND)) {
684 SmallString<256> Buffer;
685 llvm::raw_svector_ostream Out(Buffer);
686 GlobalDecl GD;
687 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: ND))
688 GD = GlobalDecl(CD, Ctor_Base);
689 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Val: ND))
690 GD = GlobalDecl(DD, Dtor_Base);
691 else if (auto FD = dyn_cast<FunctionDecl>(Val: ND)) {
692 GD = FD->isReferenceableKernel() ? GlobalDecl(FD) : GlobalDecl(ND);
693 } else
694 GD = GlobalDecl(ND);
695 MC->mangleName(GD, Out);
696
697 if (!Buffer.empty() && Buffer.front() == '\01')
698 return std::string(Buffer.substr(Start: 1));
699 return std::string(Buffer);
700 }
701 return std::string(ND->getIdentifier()->getName());
702 }
703 return "";
704 }
705 if (isa<BlockDecl>(Val: CurrentDecl)) {
706 // For blocks we only emit something if it is enclosed in a function
707 // For top-level block we'd like to include the name of variable, but we
708 // don't have it at this point.
709 auto DC = CurrentDecl->getDeclContext();
710 if (DC->isFileContext())
711 return "";
712
713 SmallString<256> Buffer;
714 llvm::raw_svector_ostream Out(Buffer);
715 if (auto *DCBlock = dyn_cast<BlockDecl>(Val: DC))
716 // For nested blocks, propagate up to the parent.
717 Out << ComputeName(IK, CurrentDecl: DCBlock);
718 else if (auto *DCDecl = dyn_cast<Decl>(Val: DC))
719 Out << ComputeName(IK, CurrentDecl: DCDecl) << "_block_invoke";
720 return std::string(Out.str());
721 }
722 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CurrentDecl)) {
723 const auto &LO = Context.getLangOpts();
724 bool IsFuncOrFunctionInNonMSVCCompatEnv =
725 ((IK == PredefinedIdentKind::Func ||
726 IK == PredefinedIdentKind ::Function) &&
727 !LO.MSVCCompat);
728 bool IsLFunctionInMSVCCommpatEnv =
729 IK == PredefinedIdentKind::LFunction && LO.MSVCCompat;
730 bool IsFuncOrFunctionOrLFunctionOrFuncDName =
731 IK != PredefinedIdentKind::PrettyFunction &&
732 IK != PredefinedIdentKind::PrettyFunctionNoVirtual &&
733 IK != PredefinedIdentKind::FuncSig &&
734 IK != PredefinedIdentKind::LFuncSig;
735 if ((ForceElaboratedPrinting &&
736 (IsFuncOrFunctionInNonMSVCCompatEnv || IsLFunctionInMSVCCommpatEnv)) ||
737 (!ForceElaboratedPrinting && IsFuncOrFunctionOrLFunctionOrFuncDName))
738 return FD->getNameAsString();
739
740 SmallString<256> Name;
741 llvm::raw_svector_ostream Out(Name);
742
743 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
744 if (MD->isVirtual() && IK != PredefinedIdentKind::PrettyFunctionNoVirtual)
745 Out << "virtual ";
746 if (MD->isStatic() && !ForceElaboratedPrinting)
747 Out << "static ";
748 }
749
750 class PrettyCallbacks final : public PrintingCallbacks {
751 public:
752 PrettyCallbacks(const LangOptions &LO) : LO(LO) {}
753 std::string remapPath(StringRef Path) const override {
754 SmallString<128> p(Path);
755 LO.remapPathPrefix(Path&: p);
756 return std::string(p);
757 }
758
759 private:
760 const LangOptions &LO;
761 };
762 PrintingPolicy Policy(Context.getLangOpts());
763 PrettyCallbacks PrettyCB(Context.getLangOpts());
764 Policy.Callbacks = &PrettyCB;
765 if (IK == PredefinedIdentKind::Function && ForceElaboratedPrinting)
766 Policy.SuppressTagKeyword = !LO.MSVCCompat;
767 std::string Proto;
768 llvm::raw_string_ostream POut(Proto);
769
770 const FunctionDecl *Decl = FD;
771 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
772 Decl = Pattern;
773
774 // Bail out if the type of the function has not been set yet.
775 // This can notably happen in the trailing return type of a lambda
776 // expression.
777 const Type *Ty = Decl->getType().getTypePtrOrNull();
778 if (!Ty)
779 return "";
780
781 const FunctionType *AFT = Ty->getAs<FunctionType>();
782 const FunctionProtoType *FT = nullptr;
783 if (FD->hasWrittenPrototype())
784 FT = dyn_cast<FunctionProtoType>(Val: AFT);
785
786 if (IK == PredefinedIdentKind::FuncSig ||
787 IK == PredefinedIdentKind::LFuncSig) {
788 switch (AFT->getCallConv()) {
789 case CC_C: POut << "__cdecl "; break;
790 case CC_X86StdCall: POut << "__stdcall "; break;
791 case CC_X86FastCall: POut << "__fastcall "; break;
792 case CC_X86ThisCall: POut << "__thiscall "; break;
793 case CC_X86VectorCall: POut << "__vectorcall "; break;
794 case CC_X86RegCall: POut << "__regcall "; break;
795 // Only bother printing the conventions that MSVC knows about.
796 default: break;
797 }
798 }
799
800 FD->printQualifiedName(OS&: POut, Policy);
801
802 if (IK == PredefinedIdentKind::Function) {
803 Out << Proto;
804 return std::string(Name);
805 }
806
807 POut << "(";
808 if (FT) {
809 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
810 if (i) POut << ", ";
811 POut << Decl->getParamDecl(i)->getType().stream(Policy);
812 }
813
814 if (FT->isVariadic()) {
815 if (FD->getNumParams()) POut << ", ";
816 POut << "...";
817 } else if ((IK == PredefinedIdentKind::FuncSig ||
818 IK == PredefinedIdentKind::LFuncSig ||
819 !Context.getLangOpts().CPlusPlus) &&
820 !Decl->getNumParams()) {
821 POut << "void";
822 }
823 }
824 POut << ")";
825
826 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
827 assert(FT && "We must have a written prototype in this case.");
828 if (FT->isConst())
829 POut << " const";
830 if (FT->isVolatile())
831 POut << " volatile";
832 RefQualifierKind Ref = MD->getRefQualifier();
833 if (Ref == RQ_LValue)
834 POut << " &";
835 else if (Ref == RQ_RValue)
836 POut << " &&";
837 }
838
839 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
840 SpecsTy Specs;
841 const DeclContext *Ctx = FD->getDeclContext();
842 while (isa_and_nonnull<NamedDecl>(Val: Ctx)) {
843 const ClassTemplateSpecializationDecl *Spec
844 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Ctx);
845 if (Spec && !Spec->isExplicitSpecialization())
846 Specs.push_back(Elt: Spec);
847 Ctx = Ctx->getParent();
848 }
849
850 std::string TemplateParams;
851 llvm::raw_string_ostream TOut(TemplateParams);
852 for (const ClassTemplateSpecializationDecl *D : llvm::reverse(C&: Specs)) {
853 const TemplateParameterList *Params =
854 D->getSpecializedTemplate()->getTemplateParameters();
855 const TemplateArgumentList &Args = D->getTemplateArgs();
856 assert(Params->size() == Args.size());
857 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
858 StringRef Param = Params->getParam(Idx: i)->getName();
859 if (Param.empty()) continue;
860 TOut << Param << " = ";
861 Args.get(Idx: i).print(Policy, Out&: TOut,
862 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
863 Policy, TPL: Params, Idx: i));
864 TOut << ", ";
865 }
866 }
867
868 FunctionTemplateSpecializationInfo *FSI
869 = FD->getTemplateSpecializationInfo();
870 if (FSI && !FSI->isExplicitSpecialization()) {
871 const TemplateParameterList* Params
872 = FSI->getTemplate()->getTemplateParameters();
873 const TemplateArgumentList* Args = FSI->TemplateArguments;
874 assert(Params->size() == Args->size());
875 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
876 StringRef Param = Params->getParam(Idx: i)->getName();
877 if (Param.empty()) continue;
878 TOut << Param << " = ";
879 Args->get(Idx: i).print(Policy, Out&: TOut, /*IncludeType*/ true);
880 TOut << ", ";
881 }
882 }
883
884 if (!TemplateParams.empty()) {
885 // remove the trailing comma and space
886 TemplateParams.resize(n: TemplateParams.size() - 2);
887 POut << " [" << TemplateParams << "]";
888 }
889
890 // Print "auto" for all deduced return types. This includes C++1y return
891 // type deduction and lambdas. For trailing return types resolve the
892 // decltype expression. Otherwise print the real type when this is
893 // not a constructor or destructor.
894 if (isLambdaMethod(DC: FD))
895 Proto = "auto " + Proto;
896 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
897 FT->getReturnType()
898 ->getAs<DecltypeType>()
899 ->getUnderlyingType()
900 .getAsStringInternal(Str&: Proto, Policy);
901 else if (!isa<CXXConstructorDecl>(Val: FD) && !isa<CXXDestructorDecl>(Val: FD))
902 AFT->getReturnType().getAsStringInternal(Str&: Proto, Policy);
903
904 Out << Proto;
905
906 return std::string(Name);
907 }
908 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(Val: CurrentDecl)) {
909 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
910 // Skip to its enclosing function or method, but not its enclosing
911 // CapturedDecl.
912 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
913 const Decl *D = Decl::castFromDeclContext(DC);
914 return ComputeName(IK, CurrentDecl: D);
915 }
916 llvm_unreachable("CapturedDecl not inside a function or method");
917 }
918 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: CurrentDecl)) {
919 SmallString<256> Name;
920 llvm::raw_svector_ostream Out(Name);
921 Out << (MD->isInstanceMethod() ? '-' : '+');
922 Out << '[';
923
924 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
925 // a null check to avoid a crash.
926 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
927 Out << *ID;
928
929 if (const ObjCCategoryImplDecl *CID =
930 dyn_cast<ObjCCategoryImplDecl>(Val: MD->getDeclContext()))
931 Out << '(' << *CID << ')';
932
933 Out << ' ';
934 MD->getSelector().print(OS&: Out);
935 Out << ']';
936
937 return std::string(Name);
938 }
939 if (isa<TranslationUnitDecl>(Val: CurrentDecl) &&
940 IK == PredefinedIdentKind::PrettyFunction) {
941 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
942 return "top level";
943 }
944 return "";
945}
946
947void APNumericStorage::setIntValue(const ASTContext &C,
948 const llvm::APInt &Val) {
949 if (hasAllocation())
950 C.Deallocate(Ptr: pVal);
951
952 BitWidth = Val.getBitWidth();
953 unsigned NumWords = Val.getNumWords();
954 const uint64_t* Words = Val.getRawData();
955 if (NumWords > 1) {
956 pVal = new (C) uint64_t[NumWords];
957 std::copy(first: Words, last: Words + NumWords, result: pVal);
958 } else if (NumWords == 1)
959 VAL = Words[0];
960 else
961 VAL = 0;
962}
963
964IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
965 QualType type, SourceLocation l)
966 : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
967 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
968 assert(V.getBitWidth() == C.getIntWidth(type) &&
969 "Integer type is not the correct size for constant.");
970 setValue(C, Val: V);
971 setDependence(ExprDependence::None);
972}
973
974IntegerLiteral *
975IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
976 QualType type, SourceLocation l) {
977 return new (C) IntegerLiteral(C, V, type, l);
978}
979
980IntegerLiteral *
981IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
982 return new (C) IntegerLiteral(Empty);
983}
984
985FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
986 QualType type, SourceLocation l,
987 unsigned Scale)
988 : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
989 Scale(Scale) {
990 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
991 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
992 "Fixed point type is not the correct size for constant.");
993 setValue(C, Val: V);
994 setDependence(ExprDependence::None);
995}
996
997FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
998 const llvm::APInt &V,
999 QualType type,
1000 SourceLocation l,
1001 unsigned Scale) {
1002 return new (C) FixedPointLiteral(C, V, type, l, Scale);
1003}
1004
1005FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,
1006 EmptyShell Empty) {
1007 return new (C) FixedPointLiteral(Empty);
1008}
1009
1010std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
1011 // Currently the longest decimal number that can be printed is the max for an
1012 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
1013 // which is 43 characters.
1014 SmallString<64> S;
1015 FixedPointValueToString(
1016 Str&: S, Val: llvm::APSInt::getUnsigned(X: getValue().getZExtValue()), Scale);
1017 return std::string(S);
1018}
1019
1020void CharacterLiteral::print(unsigned Val, CharacterLiteralKind Kind,
1021 raw_ostream &OS) {
1022 switch (Kind) {
1023 case CharacterLiteralKind::Ascii:
1024 break; // no prefix.
1025 case CharacterLiteralKind::Wide:
1026 OS << 'L';
1027 break;
1028 case CharacterLiteralKind::UTF8:
1029 OS << "u8";
1030 break;
1031 case CharacterLiteralKind::UTF16:
1032 OS << 'u';
1033 break;
1034 case CharacterLiteralKind::UTF32:
1035 OS << 'U';
1036 break;
1037 }
1038
1039 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Val);
1040 if (!Escaped.empty()) {
1041 OS << "'" << Escaped << "'";
1042 } else {
1043 // A character literal might be sign-extended, which
1044 // would result in an invalid \U escape sequence.
1045 // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1046 // are not correctly handled.
1047 if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteralKind::Ascii)
1048 Val &= 0xFFu;
1049 if (Val < 256 && isPrintable(c: (unsigned char)Val))
1050 OS << "'" << (char)Val << "'";
1051 else if (Val < 256)
1052 OS << "'\\x" << llvm::format(Fmt: "%02x", Vals: Val) << "'";
1053 else if (Val <= 0xFFFF)
1054 OS << "'\\u" << llvm::format(Fmt: "%04x", Vals: Val) << "'";
1055 else
1056 OS << "'\\U" << llvm::format(Fmt: "%08x", Vals: Val) << "'";
1057 }
1058}
1059
1060FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1061 bool isexact, QualType Type, SourceLocation L)
1062 : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1063 setSemantics(V.getSemantics());
1064 FloatingLiteralBits.IsExact = isexact;
1065 setValue(C, Val: V);
1066 setDependence(ExprDependence::None);
1067}
1068
1069FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1070 : Expr(FloatingLiteralClass, Empty) {
1071 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1072 FloatingLiteralBits.IsExact = false;
1073}
1074
1075FloatingLiteral *
1076FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1077 bool isexact, QualType Type, SourceLocation L) {
1078 return new (C) FloatingLiteral(C, V, isexact, Type, L);
1079}
1080
1081FloatingLiteral *
1082FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
1083 return new (C) FloatingLiteral(C, Empty);
1084}
1085
1086/// getValueAsApproximateDouble - This returns the value as an inaccurate
1087/// double. Note that this may cause loss of precision, but is useful for
1088/// debugging dumps, etc.
1089double FloatingLiteral::getValueAsApproximateDouble() const {
1090 llvm::APFloat V = getValue();
1091 bool ignored;
1092 V.convert(ToSemantics: llvm::APFloat::IEEEdouble(), RM: llvm::APFloat::rmNearestTiesToEven,
1093 losesInfo: &ignored);
1094 return V.convertToDouble();
1095}
1096
1097unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1098 StringLiteralKind SK) {
1099 unsigned CharByteWidth = 0;
1100 switch (SK) {
1101 case StringLiteralKind::Ordinary:
1102 case StringLiteralKind::UTF8:
1103 case StringLiteralKind::Binary:
1104 CharByteWidth = Target.getCharWidth();
1105 break;
1106 case StringLiteralKind::Wide:
1107 CharByteWidth = Target.getWCharWidth();
1108 break;
1109 case StringLiteralKind::UTF16:
1110 CharByteWidth = Target.getChar16Width();
1111 break;
1112 case StringLiteralKind::UTF32:
1113 CharByteWidth = Target.getChar32Width();
1114 break;
1115 case StringLiteralKind::Unevaluated:
1116 return sizeof(char); // Host;
1117 }
1118 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1119 CharByteWidth /= 8;
1120 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1121 "The only supported character byte widths are 1,2 and 4!");
1122 return CharByteWidth;
1123}
1124
1125StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1126 StringLiteralKind Kind, bool Pascal, QualType Ty,
1127 ArrayRef<SourceLocation> Locs)
1128 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1129
1130 unsigned Length = Str.size();
1131
1132 StringLiteralBits.Kind = llvm::to_underlying(E: Kind);
1133 StringLiteralBits.NumConcatenated = Locs.size();
1134
1135 if (Kind != StringLiteralKind::Unevaluated) {
1136 assert(Ctx.getAsConstantArrayType(Ty) &&
1137 "StringLiteral must be of constant array type!");
1138 unsigned CharByteWidth = mapCharByteWidth(Target: Ctx.getTargetInfo(), SK: Kind);
1139 unsigned ByteLength = Str.size();
1140 assert((ByteLength % CharByteWidth == 0) &&
1141 "The size of the data must be a multiple of CharByteWidth!");
1142
1143 // Avoid the expensive division. The compiler should be able to figure it
1144 // out by itself. However as of clang 7, even with the appropriate
1145 // llvm_unreachable added just here, it is not able to do so.
1146 switch (CharByteWidth) {
1147 case 1:
1148 Length = ByteLength;
1149 break;
1150 case 2:
1151 Length = ByteLength / 2;
1152 break;
1153 case 4:
1154 Length = ByteLength / 4;
1155 break;
1156 default:
1157 llvm_unreachable("Unsupported character width!");
1158 }
1159
1160 StringLiteralBits.CharByteWidth = CharByteWidth;
1161 StringLiteralBits.IsPascal = Pascal;
1162 } else {
1163 assert(!Pascal && "Can't make an unevaluated Pascal string");
1164 StringLiteralBits.CharByteWidth = 1;
1165 StringLiteralBits.IsPascal = false;
1166 }
1167
1168 *getTrailingObjects<unsigned>() = Length;
1169
1170 // Initialize the trailing array of SourceLocation.
1171 // This is safe since SourceLocation is POD-like.
1172 llvm::copy(Range&: Locs, Out: getTrailingObjects<SourceLocation>());
1173
1174 // Initialize the trailing array of char holding the string data.
1175 llvm::copy(Range&: Str, Out: getTrailingObjects<char>());
1176
1177 setDependence(ExprDependence::None);
1178}
1179
1180StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1181 unsigned Length, unsigned CharByteWidth)
1182 : Expr(StringLiteralClass, Empty) {
1183 StringLiteralBits.CharByteWidth = CharByteWidth;
1184 StringLiteralBits.NumConcatenated = NumConcatenated;
1185 *getTrailingObjects<unsigned>() = Length;
1186}
1187
1188StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1189 StringLiteralKind Kind, bool Pascal,
1190 QualType Ty,
1191 ArrayRef<SourceLocation> Locs) {
1192 void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<unsigned, SourceLocation, char>(
1193 Counts: 1, Counts: Locs.size(), Counts: Str.size()),
1194 Align: alignof(StringLiteral));
1195 return new (Mem) StringLiteral(Ctx, Str, Kind, Pascal, Ty, Locs);
1196}
1197
1198StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1199 unsigned NumConcatenated,
1200 unsigned Length,
1201 unsigned CharByteWidth) {
1202 void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<unsigned, SourceLocation, char>(
1203 Counts: 1, Counts: NumConcatenated, Counts: Length * CharByteWidth),
1204 Align: alignof(StringLiteral));
1205 return new (Mem)
1206 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1207}
1208
1209void StringLiteral::outputString(raw_ostream &OS) const {
1210 switch (getKind()) {
1211 case StringLiteralKind::Unevaluated:
1212 case StringLiteralKind::Ordinary:
1213 case StringLiteralKind::Binary:
1214 break; // no prefix.
1215 case StringLiteralKind::Wide:
1216 OS << 'L';
1217 break;
1218 case StringLiteralKind::UTF8:
1219 OS << "u8";
1220 break;
1221 case StringLiteralKind::UTF16:
1222 OS << 'u';
1223 break;
1224 case StringLiteralKind::UTF32:
1225 OS << 'U';
1226 break;
1227 }
1228 OS << '"';
1229 static const char Hex[] = "0123456789ABCDEF";
1230
1231 unsigned LastSlashX = getLength();
1232 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1233 uint32_t Char = getCodeUnit(i: I);
1234 StringRef Escaped = escapeCStyle<EscapeChar::Double>(Ch: Char);
1235 if (Escaped.empty()) {
1236 // FIXME: Convert UTF-8 back to codepoints before rendering.
1237
1238 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1239 // Leave invalid surrogates alone; we'll use \x for those.
1240 if (getKind() == StringLiteralKind::UTF16 && I != N - 1 &&
1241 Char >= 0xd800 && Char <= 0xdbff) {
1242 uint32_t Trail = getCodeUnit(i: I + 1);
1243 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1244 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1245 ++I;
1246 }
1247 }
1248
1249 if (Char > 0xff) {
1250 // If this is a wide string, output characters over 0xff using \x
1251 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1252 // codepoint: use \x escapes for invalid codepoints.
1253 if (getKind() == StringLiteralKind::Wide ||
1254 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1255 // FIXME: Is this the best way to print wchar_t?
1256 OS << "\\x";
1257 int Shift = 28;
1258 while ((Char >> Shift) == 0)
1259 Shift -= 4;
1260 for (/**/; Shift >= 0; Shift -= 4)
1261 OS << Hex[(Char >> Shift) & 15];
1262 LastSlashX = I;
1263 continue;
1264 }
1265
1266 if (Char > 0xffff)
1267 OS << "\\U00"
1268 << Hex[(Char >> 20) & 15]
1269 << Hex[(Char >> 16) & 15];
1270 else
1271 OS << "\\u";
1272 OS << Hex[(Char >> 12) & 15]
1273 << Hex[(Char >> 8) & 15]
1274 << Hex[(Char >> 4) & 15]
1275 << Hex[(Char >> 0) & 15];
1276 continue;
1277 }
1278
1279 // If we used \x... for the previous character, and this character is a
1280 // hexadecimal digit, prevent it being slurped as part of the \x.
1281 if (LastSlashX + 1 == I) {
1282 switch (Char) {
1283 case '0': case '1': case '2': case '3': case '4':
1284 case '5': case '6': case '7': case '8': case '9':
1285 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1286 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1287 OS << "\"\"";
1288 }
1289 }
1290
1291 assert(Char <= 0xff &&
1292 "Characters above 0xff should already have been handled.");
1293
1294 if (isPrintable(c: Char))
1295 OS << (char)Char;
1296 else // Output anything hard as an octal escape.
1297 OS << '\\'
1298 << (char)('0' + ((Char >> 6) & 7))
1299 << (char)('0' + ((Char >> 3) & 7))
1300 << (char)('0' + ((Char >> 0) & 7));
1301 } else {
1302 // Handle some common non-printable cases to make dumps prettier.
1303 OS << Escaped;
1304 }
1305 }
1306 OS << '"';
1307}
1308
1309/// getLocationOfByte - Return a source location that points to the specified
1310/// byte of this string literal.
1311///
1312/// Strings are amazingly complex. They can be formed from multiple tokens and
1313/// can have escape sequences in them in addition to the usual trigraph and
1314/// escaped newline business. This routine handles this complexity.
1315///
1316/// The *StartToken sets the first token to be searched in this function and
1317/// the *StartTokenByteOffset is the byte offset of the first token. Before
1318/// returning, it updates the *StartToken to the TokNo of the token being found
1319/// and sets *StartTokenByteOffset to the byte offset of the token in the
1320/// string.
1321/// Using these two parameters can reduce the time complexity from O(n^2) to
1322/// O(n) if one wants to get the location of byte for all the tokens in a
1323/// string.
1324///
1325SourceLocation
1326StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1327 const LangOptions &Features,
1328 const TargetInfo &Target, unsigned *StartToken,
1329 unsigned *StartTokenByteOffset) const {
1330 // No source location of bytes for binary literals since they don't come from
1331 // source.
1332 if (getKind() == StringLiteralKind::Binary)
1333 return getStrTokenLoc(TokNum: 0);
1334
1335 assert((getKind() == StringLiteralKind::Ordinary ||
1336 getKind() == StringLiteralKind::UTF8 ||
1337 getKind() == StringLiteralKind::Unevaluated) &&
1338 "Only narrow string literals are currently supported");
1339
1340 // Loop over all of the tokens in this string until we find the one that
1341 // contains the byte we're looking for.
1342 unsigned TokNo = 0;
1343 unsigned StringOffset = 0;
1344 if (StartToken)
1345 TokNo = *StartToken;
1346 if (StartTokenByteOffset) {
1347 StringOffset = *StartTokenByteOffset;
1348 ByteNo -= StringOffset;
1349 }
1350 while (true) {
1351 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1352 SourceLocation StrTokLoc = getStrTokenLoc(TokNum: TokNo);
1353
1354 // Get the spelling of the string so that we can get the data that makes up
1355 // the string literal, not the identifier for the macro it is potentially
1356 // expanded through.
1357 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(Loc: StrTokLoc);
1358
1359 // Re-lex the token to get its length and original spelling.
1360 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc: StrTokSpellingLoc);
1361 bool Invalid = false;
1362 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
1363 if (Invalid) {
1364 if (StartTokenByteOffset != nullptr)
1365 *StartTokenByteOffset = StringOffset;
1366 if (StartToken != nullptr)
1367 *StartToken = TokNo;
1368 return StrTokSpellingLoc;
1369 }
1370
1371 const char *StrData = Buffer.data()+LocInfo.second;
1372
1373 // Create a lexer starting at the beginning of this token.
1374 Lexer TheLexer(SM.getLocForStartOfFile(FID: LocInfo.first), Features,
1375 Buffer.begin(), StrData, Buffer.end());
1376 Token TheTok;
1377 TheLexer.LexFromRawLexer(Result&: TheTok);
1378
1379 // Use the StringLiteralParser to compute the length of the string in bytes.
1380 StringLiteralParser SLP(TheTok, SM, Features, Target);
1381 unsigned TokNumBytes = SLP.GetStringLength();
1382
1383 // If the byte is in this token, return the location of the byte.
1384 if (ByteNo < TokNumBytes ||
1385 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1386 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1387
1388 // Now that we know the offset of the token in the spelling, use the
1389 // preprocessor to get the offset in the original source.
1390 if (StartTokenByteOffset != nullptr)
1391 *StartTokenByteOffset = StringOffset;
1392 if (StartToken != nullptr)
1393 *StartToken = TokNo;
1394 return Lexer::AdvanceToTokenCharacter(TokStart: StrTokLoc, Characters: Offset, SM, LangOpts: Features);
1395 }
1396
1397 // Move to the next string token.
1398 StringOffset += TokNumBytes;
1399 ++TokNo;
1400 ByteNo -= TokNumBytes;
1401 }
1402}
1403
1404/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1405/// corresponds to, e.g. "sizeof" or "[pre]++".
1406StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1407 switch (Op) {
1408#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1409#include "clang/AST/OperationKinds.def"
1410 }
1411 llvm_unreachable("Unknown unary operator");
1412}
1413
1414UnaryOperatorKind
1415UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1416 switch (OO) {
1417 default: llvm_unreachable("No unary operator for overloaded function");
1418 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1419 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1420 case OO_Amp: return UO_AddrOf;
1421 case OO_Star: return UO_Deref;
1422 case OO_Plus: return UO_Plus;
1423 case OO_Minus: return UO_Minus;
1424 case OO_Tilde: return UO_Not;
1425 case OO_Exclaim: return UO_LNot;
1426 case OO_Coawait: return UO_Coawait;
1427 }
1428}
1429
1430OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1431 switch (Opc) {
1432 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1433 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1434 case UO_AddrOf: return OO_Amp;
1435 case UO_Deref: return OO_Star;
1436 case UO_Plus: return OO_Plus;
1437 case UO_Minus: return OO_Minus;
1438 case UO_Not: return OO_Tilde;
1439 case UO_LNot: return OO_Exclaim;
1440 case UO_Coawait: return OO_Coawait;
1441 default: return OO_None;
1442 }
1443}
1444
1445
1446//===----------------------------------------------------------------------===//
1447// Postfix Operators.
1448//===----------------------------------------------------------------------===//
1449#ifndef NDEBUG
1450static unsigned SizeOfCallExprInstance(Expr::StmtClass SC) {
1451 switch (SC) {
1452 case Expr::CallExprClass:
1453 return sizeof(CallExpr);
1454 case Expr::CXXOperatorCallExprClass:
1455 return sizeof(CXXOperatorCallExpr);
1456 case Expr::CXXMemberCallExprClass:
1457 return sizeof(CXXMemberCallExpr);
1458 case Expr::UserDefinedLiteralClass:
1459 return sizeof(UserDefinedLiteral);
1460 case Expr::CUDAKernelCallExprClass:
1461 return sizeof(CUDAKernelCallExpr);
1462 default:
1463 llvm_unreachable("unexpected class deriving from CallExpr!");
1464 }
1465}
1466#endif
1467
1468// changing the size of SourceLocation, CallExpr, and
1469// subclasses requires careful considerations
1470static_assert(sizeof(SourceLocation) == 4 && sizeof(CXXOperatorCallExpr) <= 32,
1471 "we assume CXXOperatorCallExpr is at most 32 bytes");
1472
1473CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1474 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1475 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1476 unsigned MinNumArgs, ADLCallKind UsesADL)
1477 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1478 NumArgs = std::max<unsigned>(a: Args.size(), b: MinNumArgs);
1479 unsigned NumPreArgs = PreArgs.size();
1480 CallExprBits.NumPreArgs = NumPreArgs;
1481 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1482 assert(SizeOfCallExprInstance(SC) <= OffsetToTrailingObjects &&
1483 "This CallExpr subclass is too big or unsupported");
1484
1485 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1486
1487 setCallee(Fn);
1488 for (unsigned I = 0; I != NumPreArgs; ++I)
1489 setPreArg(I, PreArg: PreArgs[I]);
1490 for (unsigned I = 0; I != Args.size(); ++I)
1491 setArg(Arg: I, ArgExpr: Args[I]);
1492 for (unsigned I = Args.size(); I != NumArgs; ++I)
1493 setArg(Arg: I, ArgExpr: nullptr);
1494
1495 this->computeDependence();
1496
1497 CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1498 CallExprBits.IsCoroElideSafe = false;
1499 CallExprBits.ExplicitObjectMemFunUsingMemberSyntax = false;
1500 CallExprBits.HasTrailingSourceLoc = false;
1501
1502 if (hasStoredFPFeatures())
1503 setStoredFPFeatures(FPFeatures);
1504}
1505
1506CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1507 bool HasFPFeatures, EmptyShell Empty)
1508 : Expr(SC, Empty), NumArgs(NumArgs) {
1509 CallExprBits.NumPreArgs = NumPreArgs;
1510 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1511 CallExprBits.HasFPFeatures = HasFPFeatures;
1512 CallExprBits.IsCoroElideSafe = false;
1513 CallExprBits.ExplicitObjectMemFunUsingMemberSyntax = false;
1514 CallExprBits.HasTrailingSourceLoc = false;
1515}
1516
1517CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1518 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1519 SourceLocation RParenLoc,
1520 FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1521 ADLCallKind UsesADL) {
1522 unsigned NumArgs = std::max<unsigned>(a: Args.size(), b: MinNumArgs);
1523 unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1524 /*NumPreArgs=*/0, NumArgs, HasFPFeatures: FPFeatures.requiresTrailingStorage());
1525 void *Mem = Ctx.Allocate(
1526 Size: sizeToAllocateForCallExprSubclass<CallExpr>(SizeOfTrailingObjects),
1527 Align: alignof(CallExpr));
1528 CallExpr *E =
1529 new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1530 RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1531 E->updateTrailingSourceLoc();
1532 return E;
1533}
1534
1535CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1536 bool HasFPFeatures, EmptyShell Empty) {
1537 unsigned SizeOfTrailingObjects =
1538 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1539 void *Mem = Ctx.Allocate(
1540 Size: sizeToAllocateForCallExprSubclass<CallExpr>(SizeOfTrailingObjects),
1541 Align: alignof(CallExpr));
1542 return new (Mem)
1543 CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1544}
1545
1546Decl *Expr::getReferencedDeclOfCallee() {
1547
1548 // Optimize for the common case first
1549 // (simple function or member function call)
1550 // then try more exotic possibilities.
1551 Expr *CEE = IgnoreImpCasts();
1552
1553 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CEE))
1554 return DRE->getDecl();
1555
1556 if (auto *ME = dyn_cast<MemberExpr>(Val: CEE))
1557 return ME->getMemberDecl();
1558
1559 CEE = CEE->IgnoreParens();
1560
1561 while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(Val: CEE))
1562 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1563
1564 // If we're calling a dereference, look at the pointer instead.
1565 while (true) {
1566 if (auto *BO = dyn_cast<BinaryOperator>(Val: CEE)) {
1567 if (BO->isPtrMemOp()) {
1568 CEE = BO->getRHS()->IgnoreParenImpCasts();
1569 continue;
1570 }
1571 } else if (auto *UO = dyn_cast<UnaryOperator>(Val: CEE)) {
1572 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1573 UO->getOpcode() == UO_Plus) {
1574 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1575 continue;
1576 }
1577 }
1578 break;
1579 }
1580
1581 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CEE))
1582 return DRE->getDecl();
1583 if (auto *ME = dyn_cast<MemberExpr>(Val: CEE))
1584 return ME->getMemberDecl();
1585 if (auto *BE = dyn_cast<BlockExpr>(Val: CEE))
1586 return BE->getBlockDecl();
1587
1588 return nullptr;
1589}
1590
1591/// If this is a call to a builtin, return the builtin ID. If not, return 0.
1592unsigned CallExpr::getBuiltinCallee() const {
1593 const auto *FDecl = getDirectCallee();
1594 return FDecl ? FDecl->getBuiltinID() : 0;
1595}
1596
1597bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1598 if (unsigned BI = getBuiltinCallee())
1599 return Ctx.BuiltinInfo.isUnevaluated(ID: BI);
1600 return false;
1601}
1602
1603QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1604 const Expr *Callee = getCallee();
1605 QualType CalleeType = Callee->getType();
1606 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1607 CalleeType = FnTypePtr->getPointeeType();
1608 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1609 CalleeType = BPT->getPointeeType();
1610 } else if (CalleeType->isSpecificPlaceholderType(K: BuiltinType::BoundMember)) {
1611 if (isa<CXXPseudoDestructorExpr>(Val: Callee->IgnoreParens()))
1612 return Ctx.VoidTy;
1613
1614 if (isa<UnresolvedMemberExpr>(Val: Callee->IgnoreParens()))
1615 return Ctx.DependentTy;
1616
1617 // This should never be overloaded and so should never return null.
1618 CalleeType = Expr::findBoundMemberType(expr: Callee);
1619 assert(!CalleeType.isNull());
1620 } else if (CalleeType->isRecordType()) {
1621 // If the Callee is a record type, then it is a not-yet-resolved
1622 // dependent call to the call operator of that type.
1623 return Ctx.DependentTy;
1624 } else if (CalleeType->isDependentType() ||
1625 CalleeType->isSpecificPlaceholderType(K: BuiltinType::Overload)) {
1626 return Ctx.DependentTy;
1627 }
1628
1629 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1630 return FnType->getReturnType();
1631}
1632
1633std::pair<const NamedDecl *, const WarnUnusedResultAttr *>
1634Expr::getUnusedResultAttrImpl(const Decl *Callee, QualType ReturnType) {
1635 // If the callee is marked nodiscard, return that attribute
1636 if (Callee != nullptr)
1637 if (const auto *A = Callee->getAttr<WarnUnusedResultAttr>())
1638 return {nullptr, A};
1639
1640 // If the return type is a struct, union, or enum that is marked nodiscard,
1641 // then return the return type attribute.
1642 if (const TagDecl *TD = ReturnType->getAsTagDecl())
1643 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1644 return {TD, A};
1645
1646 for (const auto *TD = ReturnType->getAs<TypedefType>(); TD;
1647 TD = TD->desugar()->getAs<TypedefType>())
1648 if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())
1649 return {TD->getDecl(), A};
1650 return {nullptr, nullptr};
1651}
1652
1653OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1654 SourceLocation OperatorLoc,
1655 TypeSourceInfo *tsi,
1656 ArrayRef<OffsetOfNode> comps,
1657 ArrayRef<Expr*> exprs,
1658 SourceLocation RParenLoc) {
1659 void *Mem = C.Allocate(
1660 Size: totalSizeToAlloc<OffsetOfNode, Expr *>(Counts: comps.size(), Counts: exprs.size()));
1661
1662 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1663 RParenLoc);
1664}
1665
1666OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1667 unsigned numComps, unsigned numExprs) {
1668 void *Mem =
1669 C.Allocate(Size: totalSizeToAlloc<OffsetOfNode, Expr *>(Counts: numComps, Counts: numExprs));
1670 return new (Mem) OffsetOfExpr(numComps, numExprs);
1671}
1672
1673OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1674 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1675 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
1676 SourceLocation RParenLoc)
1677 : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1678 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1679 NumComps(comps.size()), NumExprs(exprs.size()) {
1680 for (unsigned i = 0; i != comps.size(); ++i)
1681 setComponent(Idx: i, ON: comps[i]);
1682 for (unsigned i = 0; i != exprs.size(); ++i)
1683 setIndexExpr(Idx: i, E: exprs[i]);
1684
1685 setDependence(computeDependence(E: this));
1686}
1687
1688IdentifierInfo *OffsetOfNode::getFieldName() const {
1689 assert(getKind() == Field || getKind() == Identifier);
1690 if (getKind() == Field)
1691 return getField()->getIdentifier();
1692
1693 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1694}
1695
1696UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1697 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1698 SourceLocation op, SourceLocation rp)
1699 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1700 OpLoc(op), RParenLoc(rp) {
1701 assert(ExprKind <= UETT_Last && "invalid enum value!");
1702 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1703 assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
1704 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
1705 UnaryExprOrTypeTraitExprBits.IsType = false;
1706 Argument.Ex = E;
1707 setDependence(computeDependence(E: this));
1708}
1709
1710MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1711 NestedNameSpecifierLoc QualifierLoc,
1712 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
1713 DeclAccessPair FoundDecl,
1714 const DeclarationNameInfo &NameInfo,
1715 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1716 ExprValueKind VK, ExprObjectKind OK,
1717 NonOdrUseReason NOUR)
1718 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1719 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1720 assert(!NameInfo.getName() ||
1721 MemberDecl->getDeclName() == NameInfo.getName());
1722 MemberExprBits.IsArrow = IsArrow;
1723 MemberExprBits.HasQualifier = QualifierLoc.hasQualifier();
1724 MemberExprBits.HasFoundDecl =
1725 FoundDecl.getDecl() != MemberDecl ||
1726 FoundDecl.getAccess() != MemberDecl->getAccess();
1727 MemberExprBits.HasTemplateKWAndArgsInfo =
1728 TemplateArgs || TemplateKWLoc.isValid();
1729 MemberExprBits.HadMultipleCandidates = false;
1730 MemberExprBits.NonOdrUseReason = NOUR;
1731 MemberExprBits.OperatorLoc = OperatorLoc;
1732
1733 if (hasQualifier())
1734 new (getTrailingObjects<NestedNameSpecifierLoc>())
1735 NestedNameSpecifierLoc(QualifierLoc);
1736 if (hasFoundDecl())
1737 *getTrailingObjects<DeclAccessPair>() = FoundDecl;
1738 if (TemplateArgs) {
1739 auto Deps = TemplateArgumentDependence::None;
1740 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1741 TemplateKWLoc, List: *TemplateArgs, OutArgArray: getTrailingObjects<TemplateArgumentLoc>(),
1742 Deps);
1743 } else if (TemplateKWLoc.isValid()) {
1744 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1745 TemplateKWLoc);
1746 }
1747 setDependence(computeDependence(E: this));
1748}
1749
1750MemberExpr *MemberExpr::Create(
1751 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1752 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1753 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1754 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1755 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1756 bool HasQualifier = QualifierLoc.hasQualifier();
1757 bool HasFoundDecl = FoundDecl.getDecl() != MemberDecl ||
1758 FoundDecl.getAccess() != MemberDecl->getAccess();
1759 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1760 std::size_t Size =
1761 totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,
1762 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
1763 Counts: HasQualifier, Counts: HasFoundDecl, Counts: HasTemplateKWAndArgsInfo,
1764 Counts: TemplateArgs ? TemplateArgs->size() : 0);
1765
1766 void *Mem = C.Allocate(Size, Align: alignof(MemberExpr));
1767 return new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, QualifierLoc,
1768 TemplateKWLoc, MemberDecl, FoundDecl, NameInfo,
1769 TemplateArgs, T, VK, OK, NOUR);
1770}
1771
1772MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1773 bool HasQualifier, bool HasFoundDecl,
1774 bool HasTemplateKWAndArgsInfo,
1775 unsigned NumTemplateArgs) {
1776 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1777 "template args but no template arg info?");
1778 std::size_t Size =
1779 totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,
1780 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
1781 Counts: HasQualifier, Counts: HasFoundDecl, Counts: HasTemplateKWAndArgsInfo,
1782 Counts: NumTemplateArgs);
1783 void *Mem = Context.Allocate(Size, Align: alignof(MemberExpr));
1784 return new (Mem) MemberExpr(EmptyShell());
1785}
1786
1787void MemberExpr::setMemberDecl(ValueDecl *NewD) {
1788 MemberDecl = NewD;
1789 if (getType()->isUndeducedType())
1790 setType(NewD->getType());
1791 setDependence(computeDependence(E: this));
1792}
1793
1794SourceLocation MemberExpr::getBeginLoc() const {
1795 if (isImplicitAccess()) {
1796 if (hasQualifier())
1797 return getQualifierLoc().getBeginLoc();
1798 return MemberLoc;
1799 }
1800
1801 // FIXME: We don't want this to happen. Rather, we should be able to
1802 // detect all kinds of implicit accesses more cleanly.
1803 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1804 if (BaseStartLoc.isValid())
1805 return BaseStartLoc;
1806 return MemberLoc;
1807}
1808SourceLocation MemberExpr::getEndLoc() const {
1809 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1810 if (hasExplicitTemplateArgs())
1811 EndLoc = getRAngleLoc();
1812 else if (EndLoc.isInvalid())
1813 EndLoc = getBase()->getEndLoc();
1814 return EndLoc;
1815}
1816
1817bool CastExpr::CastConsistency() const {
1818 switch (getCastKind()) {
1819 case CK_DerivedToBase:
1820 case CK_UncheckedDerivedToBase:
1821 case CK_DerivedToBaseMemberPointer:
1822 case CK_BaseToDerived:
1823 case CK_BaseToDerivedMemberPointer:
1824 assert(!path_empty() && "Cast kind should have a base path!");
1825 break;
1826
1827 case CK_CPointerToObjCPointerCast:
1828 assert(getType()->isObjCObjectPointerType());
1829 assert(getSubExpr()->getType()->isPointerType());
1830 goto CheckNoBasePath;
1831
1832 case CK_BlockPointerToObjCPointerCast:
1833 assert(getType()->isObjCObjectPointerType());
1834 assert(getSubExpr()->getType()->isBlockPointerType());
1835 goto CheckNoBasePath;
1836
1837 case CK_ReinterpretMemberPointer:
1838 assert(getType()->isMemberPointerType());
1839 assert(getSubExpr()->getType()->isMemberPointerType());
1840 goto CheckNoBasePath;
1841
1842 case CK_BitCast:
1843 // Arbitrary casts to C pointer types count as bitcasts.
1844 // Otherwise, we should only have block and ObjC pointer casts
1845 // here if they stay within the type kind.
1846 if (!getType()->isPointerType()) {
1847 assert(getType()->isObjCObjectPointerType() ==
1848 getSubExpr()->getType()->isObjCObjectPointerType());
1849 assert(getType()->isBlockPointerType() ==
1850 getSubExpr()->getType()->isBlockPointerType());
1851 }
1852 goto CheckNoBasePath;
1853
1854 case CK_AnyPointerToBlockPointerCast:
1855 assert(getType()->isBlockPointerType());
1856 assert(getSubExpr()->getType()->isAnyPointerType() &&
1857 !getSubExpr()->getType()->isBlockPointerType());
1858 goto CheckNoBasePath;
1859
1860 case CK_CopyAndAutoreleaseBlockObject:
1861 assert(getType()->isBlockPointerType());
1862 assert(getSubExpr()->getType()->isBlockPointerType());
1863 goto CheckNoBasePath;
1864
1865 case CK_FunctionToPointerDecay:
1866 assert(getType()->isPointerType());
1867 assert(getSubExpr()->getType()->isFunctionType());
1868 goto CheckNoBasePath;
1869
1870 case CK_AddressSpaceConversion: {
1871 auto Ty = getType();
1872 auto SETy = getSubExpr()->getType();
1873 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1874 if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1875 Ty = Ty->getPointeeType();
1876 SETy = SETy->getPointeeType();
1877 }
1878 assert((Ty->isDependentType() || SETy->isDependentType()) ||
1879 (!Ty.isNull() && !SETy.isNull() &&
1880 Ty.getAddressSpace() != SETy.getAddressSpace()));
1881 goto CheckNoBasePath;
1882 }
1883 // These should not have an inheritance path.
1884 case CK_Dynamic:
1885 case CK_ToUnion:
1886 case CK_ArrayToPointerDecay:
1887 case CK_NullToMemberPointer:
1888 case CK_NullToPointer:
1889 case CK_ConstructorConversion:
1890 case CK_IntegralToPointer:
1891 case CK_PointerToIntegral:
1892 case CK_ToVoid:
1893 case CK_VectorSplat:
1894 case CK_IntegralCast:
1895 case CK_BooleanToSignedIntegral:
1896 case CK_IntegralToFloating:
1897 case CK_FloatingToIntegral:
1898 case CK_FloatingCast:
1899 case CK_ObjCObjectLValueCast:
1900 case CK_FloatingRealToComplex:
1901 case CK_FloatingComplexToReal:
1902 case CK_FloatingComplexCast:
1903 case CK_FloatingComplexToIntegralComplex:
1904 case CK_IntegralRealToComplex:
1905 case CK_IntegralComplexToReal:
1906 case CK_IntegralComplexCast:
1907 case CK_IntegralComplexToFloatingComplex:
1908 case CK_ARCProduceObject:
1909 case CK_ARCConsumeObject:
1910 case CK_ARCReclaimReturnedObject:
1911 case CK_ARCExtendBlockObject:
1912 case CK_ZeroToOCLOpaqueType:
1913 case CK_IntToOCLSampler:
1914 case CK_FloatingToFixedPoint:
1915 case CK_FixedPointToFloating:
1916 case CK_FixedPointCast:
1917 case CK_FixedPointToIntegral:
1918 case CK_IntegralToFixedPoint:
1919 case CK_MatrixCast:
1920 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1921 goto CheckNoBasePath;
1922
1923 case CK_Dependent:
1924 case CK_LValueToRValue:
1925 case CK_NoOp:
1926 case CK_AtomicToNonAtomic:
1927 case CK_NonAtomicToAtomic:
1928 case CK_PointerToBoolean:
1929 case CK_IntegralToBoolean:
1930 case CK_FloatingToBoolean:
1931 case CK_MemberPointerToBoolean:
1932 case CK_FloatingComplexToBoolean:
1933 case CK_IntegralComplexToBoolean:
1934 case CK_LValueBitCast: // -> bool&
1935 case CK_LValueToRValueBitCast:
1936 case CK_UserDefinedConversion: // operator bool()
1937 case CK_BuiltinFnToFnPtr:
1938 case CK_FixedPointToBoolean:
1939 case CK_HLSLArrayRValue:
1940 case CK_HLSLVectorTruncation:
1941 case CK_HLSLMatrixTruncation:
1942 case CK_HLSLElementwiseCast:
1943 case CK_HLSLAggregateSplatCast:
1944 CheckNoBasePath:
1945 assert(path_empty() && "Cast kind should not have a base path!");
1946 break;
1947 }
1948 return true;
1949}
1950
1951const char *CastExpr::getCastKindName(CastKind CK) {
1952 switch (CK) {
1953#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1954#include "clang/AST/OperationKinds.def"
1955 }
1956 llvm_unreachable("Unhandled cast kind!");
1957}
1958
1959namespace {
1960// Skip over implicit nodes produced as part of semantic analysis.
1961// Designed for use with IgnoreExprNodes.
1962static Expr *ignoreImplicitSemaNodes(Expr *E) {
1963 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(Val: E))
1964 return Materialize->getSubExpr();
1965
1966 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(Val: E))
1967 return Binder->getSubExpr();
1968
1969 if (auto *Full = dyn_cast<FullExpr>(Val: E))
1970 return Full->getSubExpr();
1971
1972 if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(Val: E);
1973 CPLIE && CPLIE->getInitExprs().size() == 1)
1974 return CPLIE->getInitExprs()[0];
1975
1976 return E;
1977}
1978} // namespace
1979
1980Expr *CastExpr::getSubExprAsWritten() {
1981 const Expr *SubExpr = nullptr;
1982
1983 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(Val: SubExpr)) {
1984 SubExpr = IgnoreExprNodes(E: E->getSubExpr(), Fns&: ignoreImplicitSemaNodes);
1985
1986 // Conversions by constructor and conversion functions have a
1987 // subexpression describing the call; strip it off.
1988 if (E->getCastKind() == CK_ConstructorConversion) {
1989 SubExpr = IgnoreExprNodes(E: cast<CXXConstructExpr>(Val: SubExpr)->getArg(Arg: 0),
1990 Fns&: ignoreImplicitSemaNodes);
1991 } else if (E->getCastKind() == CK_UserDefinedConversion) {
1992 assert((isa<CallExpr, BlockExpr>(SubExpr)) &&
1993 "Unexpected SubExpr for CK_UserDefinedConversion.");
1994 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: SubExpr))
1995 SubExpr = MCE->getImplicitObjectArgument();
1996 }
1997 }
1998
1999 return const_cast<Expr *>(SubExpr);
2000}
2001
2002NamedDecl *CastExpr::getConversionFunction() const {
2003 const Expr *SubExpr = nullptr;
2004
2005 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(Val: SubExpr)) {
2006 SubExpr = IgnoreExprNodes(E: E->getSubExpr(), Fns&: ignoreImplicitSemaNodes);
2007
2008 if (E->getCastKind() == CK_ConstructorConversion)
2009 return cast<CXXConstructExpr>(Val: SubExpr)->getConstructor();
2010
2011 if (E->getCastKind() == CK_UserDefinedConversion) {
2012 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: SubExpr))
2013 return MCE->getMethodDecl();
2014 }
2015 }
2016
2017 return nullptr;
2018}
2019
2020CXXBaseSpecifier **CastExpr::path_buffer() {
2021 switch (getStmtClass()) {
2022#define ABSTRACT_STMT(x)
2023#define CASTEXPR(Type, Base) \
2024 case Stmt::Type##Class: \
2025 return static_cast<Type *>(this) \
2026 ->getTrailingObjectsNonStrict<CXXBaseSpecifier *>();
2027#define STMT(Type, Base)
2028#include "clang/AST/StmtNodes.inc"
2029 default:
2030 llvm_unreachable("non-cast expressions not possible here");
2031 }
2032}
2033
2034const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
2035 QualType opType) {
2036 return getTargetFieldForToUnionCast(RD: unionType->castAsRecordDecl(), opType);
2037}
2038
2039const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
2040 QualType OpType) {
2041 auto &Ctx = RD->getASTContext();
2042 RecordDecl::field_iterator Field, FieldEnd;
2043 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2044 Field != FieldEnd; ++Field) {
2045 if (Ctx.hasSameUnqualifiedType(T1: Field->getType(), T2: OpType) &&
2046 !Field->isUnnamedBitField()) {
2047 return *Field;
2048 }
2049 }
2050 return nullptr;
2051}
2052
2053FPOptionsOverride *CastExpr::getTrailingFPFeatures() {
2054 assert(hasStoredFPFeatures());
2055 switch (getStmtClass()) {
2056 case ImplicitCastExprClass:
2057 return static_cast<ImplicitCastExpr *>(this)
2058 ->getTrailingObjects<FPOptionsOverride>();
2059 case CStyleCastExprClass:
2060 return static_cast<CStyleCastExpr *>(this)
2061 ->getTrailingObjects<FPOptionsOverride>();
2062 case CXXFunctionalCastExprClass:
2063 return static_cast<CXXFunctionalCastExpr *>(this)
2064 ->getTrailingObjects<FPOptionsOverride>();
2065 case CXXStaticCastExprClass:
2066 return static_cast<CXXStaticCastExpr *>(this)
2067 ->getTrailingObjects<FPOptionsOverride>();
2068 default:
2069 llvm_unreachable("Cast does not have FPFeatures");
2070 }
2071}
2072
2073ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
2074 CastKind Kind, Expr *Operand,
2075 const CXXCastPath *BasePath,
2076 ExprValueKind VK,
2077 FPOptionsOverride FPO) {
2078 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2079 void *Buffer =
2080 C.Allocate(Size: totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2081 Counts: PathSize, Counts: FPO.requiresTrailingStorage()));
2082 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2083 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2084 assert((Kind != CK_LValueToRValue ||
2085 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
2086 "invalid type for lvalue-to-rvalue conversion");
2087 ImplicitCastExpr *E =
2088 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
2089 if (PathSize)
2090 llvm::uninitialized_copy(Src: *BasePath,
2091 Dst: E->getTrailingObjects<CXXBaseSpecifier *>());
2092 return E;
2093}
2094
2095ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
2096 unsigned PathSize,
2097 bool HasFPFeatures) {
2098 void *Buffer =
2099 C.Allocate(Size: totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2100 Counts: PathSize, Counts: HasFPFeatures));
2101 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2102}
2103
2104CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
2105 ExprValueKind VK, CastKind K, Expr *Op,
2106 const CXXCastPath *BasePath,
2107 FPOptionsOverride FPO,
2108 TypeSourceInfo *WrittenTy,
2109 SourceLocation L, SourceLocation R) {
2110 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2111 void *Buffer =
2112 C.Allocate(Size: totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2113 Counts: PathSize, Counts: FPO.requiresTrailingStorage()));
2114 CStyleCastExpr *E =
2115 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2116 if (PathSize)
2117 llvm::uninitialized_copy(Src: *BasePath,
2118 Dst: E->getTrailingObjects<CXXBaseSpecifier *>());
2119 return E;
2120}
2121
2122CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2123 unsigned PathSize,
2124 bool HasFPFeatures) {
2125 void *Buffer =
2126 C.Allocate(Size: totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2127 Counts: PathSize, Counts: HasFPFeatures));
2128 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2129}
2130
2131/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2132/// corresponds to, e.g. "<<=".
2133StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
2134 switch (Op) {
2135#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2136#include "clang/AST/OperationKinds.def"
2137 }
2138 llvm_unreachable("Invalid OpCode!");
2139}
2140
2141BinaryOperatorKind
2142BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2143 switch (OO) {
2144 default: llvm_unreachable("Not an overloadable binary operator");
2145 case OO_Plus: return BO_Add;
2146 case OO_Minus: return BO_Sub;
2147 case OO_Star: return BO_Mul;
2148 case OO_Slash: return BO_Div;
2149 case OO_Percent: return BO_Rem;
2150 case OO_Caret: return BO_Xor;
2151 case OO_Amp: return BO_And;
2152 case OO_Pipe: return BO_Or;
2153 case OO_Equal: return BO_Assign;
2154 case OO_Spaceship: return BO_Cmp;
2155 case OO_Less: return BO_LT;
2156 case OO_Greater: return BO_GT;
2157 case OO_PlusEqual: return BO_AddAssign;
2158 case OO_MinusEqual: return BO_SubAssign;
2159 case OO_StarEqual: return BO_MulAssign;
2160 case OO_SlashEqual: return BO_DivAssign;
2161 case OO_PercentEqual: return BO_RemAssign;
2162 case OO_CaretEqual: return BO_XorAssign;
2163 case OO_AmpEqual: return BO_AndAssign;
2164 case OO_PipeEqual: return BO_OrAssign;
2165 case OO_LessLess: return BO_Shl;
2166 case OO_GreaterGreater: return BO_Shr;
2167 case OO_LessLessEqual: return BO_ShlAssign;
2168 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2169 case OO_EqualEqual: return BO_EQ;
2170 case OO_ExclaimEqual: return BO_NE;
2171 case OO_LessEqual: return BO_LE;
2172 case OO_GreaterEqual: return BO_GE;
2173 case OO_AmpAmp: return BO_LAnd;
2174 case OO_PipePipe: return BO_LOr;
2175 case OO_Comma: return BO_Comma;
2176 case OO_ArrowStar: return BO_PtrMemI;
2177 }
2178}
2179
2180OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2181 static const OverloadedOperatorKind OverOps[] = {
2182 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2183 OO_Star, OO_Slash, OO_Percent,
2184 OO_Plus, OO_Minus,
2185 OO_LessLess, OO_GreaterGreater,
2186 OO_Spaceship,
2187 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2188 OO_EqualEqual, OO_ExclaimEqual,
2189 OO_Amp,
2190 OO_Caret,
2191 OO_Pipe,
2192 OO_AmpAmp,
2193 OO_PipePipe,
2194 OO_Equal, OO_StarEqual,
2195 OO_SlashEqual, OO_PercentEqual,
2196 OO_PlusEqual, OO_MinusEqual,
2197 OO_LessLessEqual, OO_GreaterGreaterEqual,
2198 OO_AmpEqual, OO_CaretEqual,
2199 OO_PipeEqual,
2200 OO_Comma
2201 };
2202 return OverOps[Opc];
2203}
2204
2205bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2206 Opcode Opc,
2207 const Expr *LHS,
2208 const Expr *RHS) {
2209 if (Opc != BO_Add)
2210 return false;
2211
2212 // Check that we have one pointer and one integer operand.
2213 const Expr *PExp;
2214 if (LHS->getType()->isPointerType()) {
2215 if (!RHS->getType()->isIntegerType())
2216 return false;
2217 PExp = LHS;
2218 } else if (RHS->getType()->isPointerType()) {
2219 if (!LHS->getType()->isIntegerType())
2220 return false;
2221 PExp = RHS;
2222 } else {
2223 return false;
2224 }
2225
2226 // Workaround for old glibc's __PTR_ALIGN macro
2227 if (auto *Select =
2228 dyn_cast<ConditionalOperator>(Val: PExp->IgnoreParenNoopCasts(Ctx))) {
2229 // If the condition can be constant evaluated, we check the selected arm.
2230 bool EvalResult;
2231 if (!Select->getCond()->EvaluateAsBooleanCondition(Result&: EvalResult, Ctx))
2232 return false;
2233 PExp = EvalResult ? Select->getTrueExpr() : Select->getFalseExpr();
2234 }
2235
2236 // Check that the pointer is a nullptr.
2237 if (!PExp->IgnoreParenCasts()
2238 ->isNullPointerConstant(Ctx, NPC: Expr::NPC_ValueDependentIsNotNull))
2239 return false;
2240
2241 // Check that the pointee type is char-sized.
2242 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2243 if (!PTy || !PTy->getPointeeType()->isCharType())
2244 return false;
2245
2246 return true;
2247}
2248
2249SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Kind,
2250 QualType ResultTy, SourceLocation BLoc,
2251 SourceLocation RParenLoc,
2252 DeclContext *ParentContext)
2253 : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),
2254 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2255 SourceLocExprBits.Kind = llvm::to_underlying(E: Kind);
2256 // In dependent contexts, function names may change.
2257 setDependence(MayBeDependent(Kind) && ParentContext->isDependentContext()
2258 ? ExprDependence::ValueInstantiation
2259 : ExprDependence::None);
2260}
2261
2262StringRef SourceLocExpr::getBuiltinStr() const {
2263 switch (getIdentKind()) {
2264 case SourceLocIdentKind::File:
2265 return "__builtin_FILE";
2266 case SourceLocIdentKind::FileName:
2267 return "__builtin_FILE_NAME";
2268 case SourceLocIdentKind::Function:
2269 return "__builtin_FUNCTION";
2270 case SourceLocIdentKind::FuncSig:
2271 return "__builtin_FUNCSIG";
2272 case SourceLocIdentKind::Line:
2273 return "__builtin_LINE";
2274 case SourceLocIdentKind::Column:
2275 return "__builtin_COLUMN";
2276 case SourceLocIdentKind::SourceLocStruct:
2277 return "__builtin_source_location";
2278 }
2279 llvm_unreachable("unexpected IdentKind!");
2280}
2281
2282APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2283 const Expr *DefaultExpr) const {
2284 SourceLocation Loc;
2285 const DeclContext *Context;
2286
2287 if (const auto *DIE = dyn_cast_if_present<CXXDefaultInitExpr>(Val: DefaultExpr)) {
2288 Loc = DIE->getUsedLocation();
2289 Context = DIE->getUsedContext();
2290 } else if (const auto *DAE =
2291 dyn_cast_if_present<CXXDefaultArgExpr>(Val: DefaultExpr)) {
2292 Loc = DAE->getUsedLocation();
2293 Context = DAE->getUsedContext();
2294 } else {
2295 Loc = getLocation();
2296 Context = getParentContext();
2297 }
2298
2299 // If we are currently parsing a lambda declarator, we might not have a fully
2300 // formed call operator declaration yet, and we could not form a function name
2301 // for it. Because we do not have access to Sema/function scopes here, we
2302 // detect this case by relying on the fact such method doesn't yet have a
2303 // type.
2304 if (const auto *D = dyn_cast<CXXMethodDecl>(Val: Context);
2305 D && D->getFunctionTypeLoc().isNull() && isLambdaCallOperator(MD: D))
2306 Context = D->getParent()->getParent();
2307
2308 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2309 Loc: Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2310
2311 auto MakeStringLiteral = [&](StringRef Tmp) {
2312 using LValuePathEntry = APValue::LValuePathEntry;
2313 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Key: Tmp);
2314 // Decay the string to a pointer to the first character.
2315 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(Index: 0)};
2316 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2317 };
2318
2319 switch (getIdentKind()) {
2320 case SourceLocIdentKind::FileName: {
2321 // __builtin_FILE_NAME() is a Clang-specific extension that expands to the
2322 // the last part of __builtin_FILE().
2323 SmallString<256> FileName;
2324 clang::Preprocessor::processPathToFileName(
2325 FileName, PLoc, LangOpts: Ctx.getLangOpts(), TI: Ctx.getTargetInfo());
2326 return MakeStringLiteral(FileName);
2327 }
2328 case SourceLocIdentKind::File: {
2329 SmallString<256> Path(PLoc.getFilename());
2330 clang::Preprocessor::processPathForFileMacro(Path, LangOpts: Ctx.getLangOpts(),
2331 TI: Ctx.getTargetInfo());
2332 return MakeStringLiteral(Path);
2333 }
2334 case SourceLocIdentKind::Function:
2335 case SourceLocIdentKind::FuncSig: {
2336 const auto *CurDecl = dyn_cast<Decl>(Val: Context);
2337 const auto Kind = getIdentKind() == SourceLocIdentKind::Function
2338 ? PredefinedIdentKind::Function
2339 : PredefinedIdentKind::FuncSig;
2340 return MakeStringLiteral(
2341 CurDecl ? PredefinedExpr::ComputeName(IK: Kind, CurrentDecl: CurDecl) : std::string(""));
2342 }
2343 case SourceLocIdentKind::Line:
2344 return APValue(Ctx.MakeIntValue(Value: PLoc.getLine(), Type: Ctx.UnsignedIntTy));
2345 case SourceLocIdentKind::Column:
2346 return APValue(Ctx.MakeIntValue(Value: PLoc.getColumn(), Type: Ctx.UnsignedIntTy));
2347 case SourceLocIdentKind::SourceLocStruct: {
2348 // Fill in a std::source_location::__impl structure, by creating an
2349 // artificial file-scoped CompoundLiteralExpr, and returning a pointer to
2350 // that.
2351 const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();
2352 assert(ImplDecl);
2353
2354 // Construct an APValue for the __impl struct, and get or create a Decl
2355 // corresponding to that. Note that we've already verified that the shape of
2356 // the ImplDecl type is as expected.
2357
2358 APValue Value(APValue::UninitStruct(), 0, 4);
2359 for (const FieldDecl *F : ImplDecl->fields()) {
2360 StringRef Name = F->getName();
2361 if (Name == "_M_file_name") {
2362 SmallString<256> Path(PLoc.getFilename());
2363 clang::Preprocessor::processPathForFileMacro(Path, LangOpts: Ctx.getLangOpts(),
2364 TI: Ctx.getTargetInfo());
2365 Value.getStructField(i: F->getFieldIndex()) = MakeStringLiteral(Path);
2366 } else if (Name == "_M_function_name") {
2367 // Note: this emits the PrettyFunction name -- different than what
2368 // __builtin_FUNCTION() above returns!
2369 const auto *CurDecl = dyn_cast<Decl>(Val: Context);
2370 Value.getStructField(i: F->getFieldIndex()) = MakeStringLiteral(
2371 CurDecl && !isa<TranslationUnitDecl>(Val: CurDecl)
2372 ? StringRef(PredefinedExpr::ComputeName(
2373 IK: PredefinedIdentKind::PrettyFunction, CurrentDecl: CurDecl))
2374 : "");
2375 } else if (Name == "_M_line") {
2376 llvm::APSInt IntVal = Ctx.MakeIntValue(Value: PLoc.getLine(), Type: F->getType());
2377 Value.getStructField(i: F->getFieldIndex()) = APValue(IntVal);
2378 } else if (Name == "_M_column") {
2379 llvm::APSInt IntVal = Ctx.MakeIntValue(Value: PLoc.getColumn(), Type: F->getType());
2380 Value.getStructField(i: F->getFieldIndex()) = APValue(IntVal);
2381 }
2382 }
2383
2384 UnnamedGlobalConstantDecl *GV =
2385 Ctx.getUnnamedGlobalConstantDecl(Ty: getType()->getPointeeType(), Value);
2386
2387 return APValue(GV, CharUnits::Zero(), ArrayRef<APValue::LValuePathEntry>{},
2388 false);
2389 }
2390 }
2391 llvm_unreachable("unhandled case");
2392}
2393
2394EmbedExpr::EmbedExpr(const ASTContext &Ctx, SourceLocation Loc,
2395 EmbedDataStorage *Data, unsigned Begin,
2396 unsigned NumOfElements)
2397 : Expr(EmbedExprClass, Ctx.IntTy, VK_PRValue, OK_Ordinary),
2398 EmbedKeywordLoc(Loc), Ctx(&Ctx), Data(Data), Begin(Begin),
2399 NumOfElements(NumOfElements) {
2400 setDependence(ExprDependence::None);
2401 FakeChildNode = IntegerLiteral::Create(
2402 C: Ctx, V: llvm::APInt::getZero(numBits: Ctx.getTypeSize(T: getType())), type: getType(), l: Loc);
2403 assert(getType()->isSignedIntegerType() && "IntTy should be signed");
2404}
2405
2406InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2407 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2408 : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2409 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2410 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2411 sawArrayRangeDesignator(ARD: false);
2412 InitExprs.insert(C, I: InitExprs.end(), From: initExprs.begin(), To: initExprs.end());
2413
2414 setDependence(computeDependence(E: this));
2415}
2416
2417void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2418 if (NumInits > InitExprs.size())
2419 InitExprs.reserve(C, N: NumInits);
2420}
2421
2422void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2423 InitExprs.resize(C, N: NumInits, NV: nullptr);
2424}
2425
2426Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2427 if (Init >= InitExprs.size()) {
2428 InitExprs.insert(C, I: InitExprs.end(), NumToInsert: Init - InitExprs.size() + 1, Elt: nullptr);
2429 setInit(Init, expr);
2430 return nullptr;
2431 }
2432
2433 Expr *Result = cast_or_null<Expr>(Val: InitExprs[Init]);
2434 setInit(Init, expr);
2435 return Result;
2436}
2437
2438void InitListExpr::setArrayFiller(Expr *filler) {
2439 assert(!hasArrayFiller() && "Filler already set!");
2440 ArrayFillerOrUnionFieldInit = filler;
2441 // Fill out any "holes" in the array due to designated initializers.
2442 Expr **inits = getInits();
2443 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2444 if (inits[i] == nullptr)
2445 inits[i] = filler;
2446}
2447
2448bool InitListExpr::isStringLiteralInit() const {
2449 if (getNumInits() != 1)
2450 return false;
2451 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2452 if (!AT || !AT->getElementType()->isIntegerType())
2453 return false;
2454 // It is possible for getInit() to return null.
2455 const Expr *Init = getInit(Init: 0);
2456 if (!Init)
2457 return false;
2458 Init = Init->IgnoreParenImpCasts();
2459 return isa<StringLiteral>(Val: Init) || isa<ObjCEncodeExpr>(Val: Init);
2460}
2461
2462bool InitListExpr::isTransparent() const {
2463 assert(isSemanticForm() && "syntactic form never semantically transparent");
2464
2465 // A glvalue InitListExpr is always just sugar.
2466 if (isGLValue()) {
2467 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2468 return true;
2469 }
2470
2471 // Otherwise, we're sugar if and only if we have exactly one initializer that
2472 // is of the same type.
2473 if (getNumInits() != 1 || !getInit(Init: 0))
2474 return false;
2475
2476 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2477 // transparent struct copy.
2478 if (!getInit(Init: 0)->isPRValue() && getType()->isRecordType())
2479 return false;
2480
2481 return getType().getCanonicalType() ==
2482 getInit(Init: 0)->getType().getCanonicalType();
2483}
2484
2485bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2486 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2487
2488 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(Init: 0)) {
2489 return false;
2490 }
2491
2492 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(Val: getInit(Init: 0)->IgnoreImplicit());
2493 return Lit && Lit->getValue() == 0;
2494}
2495
2496SourceLocation InitListExpr::getBeginLoc() const {
2497 if (InitListExpr *SyntacticForm = getSyntacticForm())
2498 return SyntacticForm->getBeginLoc();
2499 SourceLocation Beg = LBraceLoc;
2500 if (Beg.isInvalid()) {
2501 // Find the first non-null initializer.
2502 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2503 E = InitExprs.end();
2504 I != E; ++I) {
2505 if (Stmt *S = *I) {
2506 Beg = S->getBeginLoc();
2507 break;
2508 }
2509 }
2510 }
2511 return Beg;
2512}
2513
2514SourceLocation InitListExpr::getEndLoc() const {
2515 if (InitListExpr *SyntacticForm = getSyntacticForm())
2516 return SyntacticForm->getEndLoc();
2517 SourceLocation End = RBraceLoc;
2518 if (End.isInvalid()) {
2519 // Find the first non-null initializer from the end.
2520 for (Stmt *S : llvm::reverse(C: InitExprs)) {
2521 if (S) {
2522 End = S->getEndLoc();
2523 break;
2524 }
2525 }
2526 }
2527 return End;
2528}
2529
2530/// getFunctionType - Return the underlying function type for this block.
2531///
2532const FunctionProtoType *BlockExpr::getFunctionType() const {
2533 // The block pointer is never sugared, but the function type might be.
2534 return cast<BlockPointerType>(Val: getType())
2535 ->getPointeeType()->castAs<FunctionProtoType>();
2536}
2537
2538SourceLocation BlockExpr::getCaretLocation() const {
2539 return TheBlock->getCaretLocation();
2540}
2541const Stmt *BlockExpr::getBody() const {
2542 return TheBlock->getBody();
2543}
2544Stmt *BlockExpr::getBody() {
2545 return TheBlock->getBody();
2546}
2547
2548
2549//===----------------------------------------------------------------------===//
2550// Generic Expression Routines
2551//===----------------------------------------------------------------------===//
2552
2553/// Helper to determine wether \c E is a CXXConstructExpr constructing
2554/// a DecompositionDecl. Used to skip Clang-generated calls to std::get
2555/// for structured bindings.
2556static bool IsDecompositionDeclRefExpr(const Expr *E) {
2557 const auto *Unwrapped = E->IgnoreUnlessSpelledInSource();
2558 const auto *Ref = dyn_cast<DeclRefExpr>(Val: Unwrapped);
2559 if (!Ref)
2560 return false;
2561
2562 return isa_and_nonnull<DecompositionDecl>(Val: Ref->getDecl());
2563}
2564
2565bool Expr::isReadIfDiscardedInCPlusPlus11() const {
2566 // In C++11, discarded-value expressions of a certain form are special,
2567 // according to [expr]p10:
2568 // The lvalue-to-rvalue conversion (4.1) is applied only if the
2569 // expression is a glvalue of volatile-qualified type and it has
2570 // one of the following forms:
2571 if (!isGLValue() || !getType().isVolatileQualified())
2572 return false;
2573
2574 const Expr *E = IgnoreParens();
2575
2576 // - id-expression (5.1.1),
2577 if (isa<DeclRefExpr>(Val: E))
2578 return true;
2579
2580 // - subscripting (5.2.1),
2581 if (isa<ArraySubscriptExpr>(Val: E))
2582 return true;
2583
2584 // - class member access (5.2.5),
2585 if (isa<MemberExpr>(Val: E))
2586 return true;
2587
2588 // - indirection (5.3.1),
2589 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
2590 if (UO->getOpcode() == UO_Deref)
2591 return true;
2592
2593 if (auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
2594 // - pointer-to-member operation (5.5),
2595 if (BO->isPtrMemOp())
2596 return true;
2597
2598 // - comma expression (5.18) where the right operand is one of the above.
2599 if (BO->getOpcode() == BO_Comma)
2600 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2601 }
2602
2603 // - conditional expression (5.16) where both the second and the third
2604 // operands are one of the above, or
2605 if (auto *CO = dyn_cast<ConditionalOperator>(Val: E))
2606 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2607 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2608 // The related edge case of "*x ?: *x".
2609 if (auto *BCO =
2610 dyn_cast<BinaryConditionalOperator>(Val: E)) {
2611 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: BCO->getTrueExpr()))
2612 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2613 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2614 }
2615
2616 // Objective-C++ extensions to the rule.
2617 if (isa<ObjCIvarRefExpr>(Val: E))
2618 return true;
2619 if (const auto *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
2620 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(Val: POE->getSyntacticForm()))
2621 return true;
2622 }
2623
2624 return false;
2625}
2626
2627/// isUnusedResultAWarning - Return true if this immediate expression should
2628/// be warned about if the result is unused. If so, fill in Loc and Ranges
2629/// with location to warn on and the source range[s] to report with the
2630/// warning.
2631bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2632 SourceRange &R1, SourceRange &R2,
2633 ASTContext &Ctx) const {
2634 // Don't warn if the expr is type dependent. The type could end up
2635 // instantiating to void.
2636 if (isTypeDependent())
2637 return false;
2638
2639 switch (getStmtClass()) {
2640 default:
2641 if (getType()->isVoidType())
2642 return false;
2643 WarnE = this;
2644 Loc = getExprLoc();
2645 R1 = getSourceRange();
2646 return true;
2647 case ParenExprClass:
2648 return cast<ParenExpr>(Val: this)->getSubExpr()->
2649 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2650 case GenericSelectionExprClass:
2651 return cast<GenericSelectionExpr>(Val: this)->getResultExpr()->
2652 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2653 case CoawaitExprClass:
2654 case CoyieldExprClass:
2655 return cast<CoroutineSuspendExpr>(Val: this)->getResumeExpr()->
2656 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2657 case ChooseExprClass:
2658 return cast<ChooseExpr>(Val: this)->getChosenSubExpr()->
2659 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2660 case UnaryOperatorClass: {
2661 const UnaryOperator *UO = cast<UnaryOperator>(Val: this);
2662
2663 switch (UO->getOpcode()) {
2664 case UO_Plus:
2665 case UO_Minus:
2666 case UO_AddrOf:
2667 case UO_Not:
2668 case UO_LNot:
2669 case UO_Deref:
2670 break;
2671 case UO_Coawait:
2672 // This is just the 'operator co_await' call inside the guts of a
2673 // dependent co_await call.
2674 case UO_PostInc:
2675 case UO_PostDec:
2676 case UO_PreInc:
2677 case UO_PreDec: // ++/--
2678 return false; // Not a warning.
2679 case UO_Real:
2680 case UO_Imag:
2681 // accessing a piece of a volatile complex is a side-effect.
2682 if (Ctx.getCanonicalType(T: UO->getSubExpr()->getType())
2683 .isVolatileQualified())
2684 return false;
2685 break;
2686 case UO_Extension:
2687 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2688 }
2689 WarnE = this;
2690 Loc = UO->getOperatorLoc();
2691 R1 = UO->getSubExpr()->getSourceRange();
2692 return true;
2693 }
2694 case BinaryOperatorClass: {
2695 const BinaryOperator *BO = cast<BinaryOperator>(Val: this);
2696 switch (BO->getOpcode()) {
2697 default:
2698 break;
2699 // Consider the RHS of comma for side effects. LHS was checked by
2700 // Sema::CheckCommaOperands.
2701 case BO_Comma:
2702 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2703 // lvalue-ness) of an assignment written in a macro.
2704 if (IntegerLiteral *IE =
2705 dyn_cast<IntegerLiteral>(Val: BO->getRHS()->IgnoreParens()))
2706 if (IE->getValue() == 0)
2707 return false;
2708 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2709 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2710 case BO_LAnd:
2711 case BO_LOr:
2712 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2713 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2714 return false;
2715 break;
2716 }
2717 if (BO->isAssignmentOp())
2718 return false;
2719 WarnE = this;
2720 Loc = BO->getOperatorLoc();
2721 R1 = BO->getLHS()->getSourceRange();
2722 R2 = BO->getRHS()->getSourceRange();
2723 return true;
2724 }
2725 case CompoundAssignOperatorClass:
2726 case VAArgExprClass:
2727 case AtomicExprClass:
2728 return false;
2729
2730 case ConditionalOperatorClass: {
2731 // If only one of the LHS or RHS is a warning, the operator might
2732 // be being used for control flow. Only warn if both the LHS and
2733 // RHS are warnings.
2734 const auto *Exp = cast<ConditionalOperator>(Val: this);
2735 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2736 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2737 }
2738 case BinaryConditionalOperatorClass: {
2739 const auto *Exp = cast<BinaryConditionalOperator>(Val: this);
2740 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2741 }
2742
2743 case MemberExprClass:
2744 WarnE = this;
2745 Loc = cast<MemberExpr>(Val: this)->getMemberLoc();
2746 R1 = SourceRange(Loc, Loc);
2747 R2 = cast<MemberExpr>(Val: this)->getBase()->getSourceRange();
2748 return true;
2749
2750 case ArraySubscriptExprClass:
2751 WarnE = this;
2752 Loc = cast<ArraySubscriptExpr>(Val: this)->getRBracketLoc();
2753 R1 = cast<ArraySubscriptExpr>(Val: this)->getLHS()->getSourceRange();
2754 R2 = cast<ArraySubscriptExpr>(Val: this)->getRHS()->getSourceRange();
2755 return true;
2756
2757 case CXXOperatorCallExprClass: {
2758 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2759 // overloads as there is no reasonable way to define these such that they
2760 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2761 // warning: operators == and != are commonly typo'ed, and so warning on them
2762 // provides additional value as well. If this list is updated,
2763 // DiagnoseUnusedComparison should be as well.
2764 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(Val: this);
2765 switch (Op->getOperator()) {
2766 default:
2767 break;
2768 case OO_EqualEqual:
2769 case OO_ExclaimEqual:
2770 case OO_Less:
2771 case OO_Greater:
2772 case OO_GreaterEqual:
2773 case OO_LessEqual:
2774 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2775 Op->getCallReturnType(Ctx)->isVoidType())
2776 break;
2777 WarnE = this;
2778 Loc = Op->getOperatorLoc();
2779 R1 = Op->getSourceRange();
2780 return true;
2781 }
2782
2783 // Fallthrough for generic call handling.
2784 [[fallthrough]];
2785 }
2786 case CallExprClass:
2787 case CXXMemberCallExprClass:
2788 case UserDefinedLiteralClass: {
2789 // If this is a direct call, get the callee.
2790 const CallExpr *CE = cast<CallExpr>(Val: this);
2791 // If the callee has attribute pure, const, or warn_unused_result, warn
2792 // about it. void foo() { strlen("bar"); } should warn.
2793 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2794 // updated to match for QoI.
2795 const Decl *FD = CE->getCalleeDecl();
2796 bool PureOrConst =
2797 FD && (FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>());
2798 if (CE->hasUnusedResultAttr(Ctx) || PureOrConst) {
2799 WarnE = this;
2800 Loc = getBeginLoc();
2801 R1 = getSourceRange();
2802
2803 if (unsigned NumArgs = CE->getNumArgs())
2804 R2 = SourceRange(CE->getArg(Arg: 0)->getBeginLoc(),
2805 CE->getArg(Arg: NumArgs - 1)->getEndLoc());
2806 return true;
2807 }
2808 return false;
2809 }
2810
2811 // If we don't know precisely what we're looking at, let's not warn.
2812 case UnresolvedLookupExprClass:
2813 case CXXUnresolvedConstructExprClass:
2814 case RecoveryExprClass:
2815 return false;
2816
2817 case CXXTemporaryObjectExprClass:
2818 case CXXConstructExprClass: {
2819 const auto *CE = cast<CXXConstructExpr>(Val: this);
2820 const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl();
2821
2822 if ((Type && Type->hasAttr<WarnUnusedAttr>()) ||
2823 CE->hasUnusedResultAttr(Ctx)) {
2824 WarnE = this;
2825 Loc = getBeginLoc();
2826 R1 = getSourceRange();
2827
2828 if (unsigned NumArgs = CE->getNumArgs())
2829 R2 = SourceRange(CE->getArg(Arg: 0)->getBeginLoc(),
2830 CE->getArg(Arg: NumArgs - 1)->getEndLoc());
2831 return true;
2832 }
2833 return false;
2834 }
2835
2836 case ObjCMessageExprClass: {
2837 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(Val: this);
2838 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2839 ME->isInstanceMessage() &&
2840 !ME->getType()->isVoidType() &&
2841 ME->getMethodFamily() == OMF_init) {
2842 WarnE = this;
2843 Loc = getExprLoc();
2844 R1 = ME->getSourceRange();
2845 return true;
2846 }
2847
2848 if (ME->hasUnusedResultAttr(Ctx)) {
2849 WarnE = this;
2850 Loc = getExprLoc();
2851 return true;
2852 }
2853
2854 return false;
2855 }
2856
2857 case ObjCPropertyRefExprClass:
2858 case ObjCSubscriptRefExprClass:
2859 WarnE = this;
2860 Loc = getExprLoc();
2861 R1 = getSourceRange();
2862 return true;
2863
2864 case PseudoObjectExprClass: {
2865 const auto *POE = cast<PseudoObjectExpr>(Val: this);
2866
2867 // For some syntactic forms, we should always warn.
2868 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(
2869 Val: POE->getSyntacticForm())) {
2870 WarnE = this;
2871 Loc = getExprLoc();
2872 R1 = getSourceRange();
2873 return true;
2874 }
2875
2876 // For others, we should never warn.
2877 if (auto *BO = dyn_cast<BinaryOperator>(Val: POE->getSyntacticForm()))
2878 if (BO->isAssignmentOp())
2879 return false;
2880 if (auto *UO = dyn_cast<UnaryOperator>(Val: POE->getSyntacticForm()))
2881 if (UO->isIncrementDecrementOp())
2882 return false;
2883
2884 // Otherwise, warn if the result expression would warn.
2885 const Expr *Result = POE->getResultExpr();
2886 return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2887 }
2888
2889 case StmtExprClass: {
2890 // Statement exprs don't logically have side effects themselves, but are
2891 // sometimes used in macros in ways that give them a type that is unused.
2892 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2893 // however, if the result of the stmt expr is dead, we don't want to emit a
2894 // warning.
2895 const CompoundStmt *CS = cast<StmtExpr>(Val: this)->getSubStmt();
2896 if (!CS->body_empty()) {
2897 if (const Expr *E = dyn_cast<Expr>(Val: CS->body_back()))
2898 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2899 if (const LabelStmt *Label = dyn_cast<LabelStmt>(Val: CS->body_back()))
2900 if (const Expr *E = dyn_cast<Expr>(Val: Label->getSubStmt()))
2901 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2902 }
2903
2904 if (getType()->isVoidType())
2905 return false;
2906 WarnE = this;
2907 Loc = cast<StmtExpr>(Val: this)->getLParenLoc();
2908 R1 = getSourceRange();
2909 return true;
2910 }
2911 case CXXFunctionalCastExprClass:
2912 case CStyleCastExprClass: {
2913 // Ignore an explicit cast to void, except in C++98 if the operand is a
2914 // volatile glvalue for which we would trigger an implicit read in any
2915 // other language mode. (Such an implicit read always happens as part of
2916 // the lvalue conversion in C, and happens in C++ for expressions of all
2917 // forms where it seems likely the user intended to trigger a volatile
2918 // load.)
2919 const CastExpr *CE = cast<CastExpr>(Val: this);
2920 const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2921 if (CE->getCastKind() == CK_ToVoid) {
2922 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2923 SubE->isReadIfDiscardedInCPlusPlus11()) {
2924 // Suppress the "unused value" warning for idiomatic usage of
2925 // '(void)var;' used to suppress "unused variable" warnings.
2926 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: SubE))
2927 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
2928 if (!VD->isExternallyVisible())
2929 return false;
2930
2931 // The lvalue-to-rvalue conversion would have no effect for an array.
2932 // It's implausible that the programmer expected this to result in a
2933 // volatile array load, so don't warn.
2934 if (SubE->getType()->isArrayType())
2935 return false;
2936
2937 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2938 }
2939 return false;
2940 }
2941
2942 // If this is a cast to a constructor conversion, check the operand.
2943 // Otherwise, the result of the cast is unused.
2944 if (CE->getCastKind() == CK_ConstructorConversion)
2945 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2946 if (CE->getCastKind() == CK_Dependent)
2947 return false;
2948
2949 WarnE = this;
2950 if (const CXXFunctionalCastExpr *CXXCE =
2951 dyn_cast<CXXFunctionalCastExpr>(Val: this)) {
2952 Loc = CXXCE->getBeginLoc();
2953 R1 = CXXCE->getSubExpr()->getSourceRange();
2954 } else {
2955 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(Val: this);
2956 Loc = CStyleCE->getLParenLoc();
2957 R1 = CStyleCE->getSubExpr()->getSourceRange();
2958 }
2959 return true;
2960 }
2961 case ImplicitCastExprClass: {
2962 const CastExpr *ICE = cast<ImplicitCastExpr>(Val: this);
2963
2964 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2965 if (ICE->getCastKind() == CK_LValueToRValue &&
2966 ICE->getSubExpr()->getType().isVolatileQualified())
2967 return false;
2968
2969 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2970 }
2971 case CXXDefaultArgExprClass:
2972 return (cast<CXXDefaultArgExpr>(Val: this)
2973 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2974 case CXXDefaultInitExprClass:
2975 return (cast<CXXDefaultInitExpr>(Val: this)
2976 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2977
2978 case CXXNewExprClass:
2979 // FIXME: In theory, there might be new expressions that don't have side
2980 // effects (e.g. a placement new with an uninitialized POD).
2981 case CXXDeleteExprClass:
2982 return false;
2983 case MaterializeTemporaryExprClass:
2984 return cast<MaterializeTemporaryExpr>(Val: this)
2985 ->getSubExpr()
2986 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2987 case CXXBindTemporaryExprClass:
2988 return cast<CXXBindTemporaryExpr>(Val: this)->getSubExpr()
2989 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2990 case ExprWithCleanupsClass:
2991 return cast<ExprWithCleanups>(Val: this)->getSubExpr()
2992 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2993 case OpaqueValueExprClass:
2994 return cast<OpaqueValueExpr>(Val: this)->getSourceExpr()->isUnusedResultAWarning(
2995 WarnE, Loc, R1, R2, Ctx);
2996 }
2997}
2998
2999/// isOBJCGCCandidate - Check if an expression is objc gc'able.
3000/// returns true, if it is; false otherwise.
3001bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
3002 const Expr *E = IgnoreParens();
3003 switch (E->getStmtClass()) {
3004 default:
3005 return false;
3006 case ObjCIvarRefExprClass:
3007 return true;
3008 case Expr::UnaryOperatorClass:
3009 return cast<UnaryOperator>(Val: E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3010 case ImplicitCastExprClass:
3011 return cast<ImplicitCastExpr>(Val: E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3012 case MaterializeTemporaryExprClass:
3013 return cast<MaterializeTemporaryExpr>(Val: E)->getSubExpr()->isOBJCGCCandidate(
3014 Ctx);
3015 case CStyleCastExprClass:
3016 return cast<CStyleCastExpr>(Val: E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3017 case DeclRefExprClass: {
3018 const Decl *D = cast<DeclRefExpr>(Val: E)->getDecl();
3019
3020 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3021 if (VD->hasGlobalStorage())
3022 return true;
3023 QualType T = VD->getType();
3024 // dereferencing to a pointer is always a gc'able candidate,
3025 // unless it is __weak.
3026 return T->isPointerType() &&
3027 (Ctx.getObjCGCAttrKind(Ty: T) != Qualifiers::Weak);
3028 }
3029 return false;
3030 }
3031 case MemberExprClass: {
3032 const MemberExpr *M = cast<MemberExpr>(Val: E);
3033 return M->getBase()->isOBJCGCCandidate(Ctx);
3034 }
3035 case ArraySubscriptExprClass:
3036 return cast<ArraySubscriptExpr>(Val: E)->getBase()->isOBJCGCCandidate(Ctx);
3037 }
3038}
3039
3040bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
3041 if (isTypeDependent())
3042 return false;
3043 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
3044}
3045
3046QualType Expr::findBoundMemberType(const Expr *expr) {
3047 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
3048
3049 // Bound member expressions are always one of these possibilities:
3050 // x->m x.m x->*y x.*y
3051 // (possibly parenthesized)
3052
3053 expr = expr->IgnoreParens();
3054 if (const MemberExpr *mem = dyn_cast<MemberExpr>(Val: expr)) {
3055 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
3056 return mem->getMemberDecl()->getType();
3057 }
3058
3059 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(Val: expr)) {
3060 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
3061 ->getPointeeType();
3062 assert(type->isFunctionType());
3063 return type;
3064 }
3065
3066 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
3067 return QualType();
3068}
3069
3070Expr *Expr::IgnoreImpCasts() {
3071 return IgnoreExprNodes(E: this, Fns&: IgnoreImplicitCastsSingleStep);
3072}
3073
3074Expr *Expr::IgnoreCasts() {
3075 return IgnoreExprNodes(E: this, Fns&: IgnoreCastsSingleStep);
3076}
3077
3078Expr *Expr::IgnoreImplicit() {
3079 return IgnoreExprNodes(E: this, Fns&: IgnoreImplicitSingleStep);
3080}
3081
3082Expr *Expr::IgnoreImplicitAsWritten() {
3083 return IgnoreExprNodes(E: this, Fns&: IgnoreImplicitAsWrittenSingleStep);
3084}
3085
3086Expr *Expr::IgnoreParens() {
3087 return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep);
3088}
3089
3090Expr *Expr::IgnoreParenImpCasts() {
3091 return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep,
3092 Fns&: IgnoreImplicitCastsExtraSingleStep);
3093}
3094
3095Expr *Expr::IgnoreParenCasts() {
3096 return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep, Fns&: IgnoreCastsSingleStep);
3097}
3098
3099Expr *Expr::IgnoreConversionOperatorSingleStep() {
3100 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: this)) {
3101 if (isa_and_nonnull<CXXConversionDecl>(Val: MCE->getMethodDecl()))
3102 return MCE->getImplicitObjectArgument();
3103 }
3104 return this;
3105}
3106
3107Expr *Expr::IgnoreParenLValueCasts() {
3108 return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep,
3109 Fns&: IgnoreLValueCastsSingleStep);
3110}
3111
3112Expr *Expr::IgnoreParenBaseCasts() {
3113 return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep,
3114 Fns&: IgnoreBaseCastsSingleStep);
3115}
3116
3117Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
3118 auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
3119 if (auto *CE = dyn_cast<CastExpr>(Val: E)) {
3120 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
3121 // ptr<->int casts of the same width. We also ignore all identity casts.
3122 Expr *SubExpr = CE->getSubExpr();
3123 bool IsIdentityCast =
3124 Ctx.hasSameUnqualifiedType(T1: E->getType(), T2: SubExpr->getType());
3125 bool IsSameWidthCast = (E->getType()->isPointerType() ||
3126 E->getType()->isIntegralType(Ctx)) &&
3127 (SubExpr->getType()->isPointerType() ||
3128 SubExpr->getType()->isIntegralType(Ctx)) &&
3129 (Ctx.getTypeSize(T: E->getType()) ==
3130 Ctx.getTypeSize(T: SubExpr->getType()));
3131
3132 if (IsIdentityCast || IsSameWidthCast)
3133 return SubExpr;
3134 } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(Val: E))
3135 return NTTP->getReplacement();
3136
3137 return E;
3138 };
3139 return IgnoreExprNodes(E: this, Fns&: IgnoreParensSingleStep,
3140 Fns&: IgnoreNoopCastsSingleStep);
3141}
3142
3143Expr *Expr::IgnoreUnlessSpelledInSource() {
3144 auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {
3145 if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(Val: E)) {
3146 auto *SE = Cast->getSubExpr();
3147 if (SE->getSourceRange() == E->getSourceRange())
3148 return SE;
3149 }
3150
3151 if (auto *C = dyn_cast<CXXConstructExpr>(Val: E)) {
3152 auto NumArgs = C->getNumArgs();
3153 if (NumArgs == 1 ||
3154 (NumArgs > 1 && isa<CXXDefaultArgExpr>(Val: C->getArg(Arg: 1)))) {
3155 Expr *A = C->getArg(Arg: 0);
3156 if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
3157 return A;
3158 }
3159 }
3160 return E;
3161 };
3162 auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3163 if (auto *C = dyn_cast<CXXMemberCallExpr>(Val: E)) {
3164 Expr *ExprNode = C->getImplicitObjectArgument();
3165 if (ExprNode->getSourceRange() == E->getSourceRange()) {
3166 return ExprNode;
3167 }
3168 if (auto *PE = dyn_cast<ParenExpr>(Val: ExprNode)) {
3169 if (PE->getSourceRange() == C->getSourceRange()) {
3170 return cast<Expr>(Val: PE);
3171 }
3172 }
3173 ExprNode = ExprNode->IgnoreParenImpCasts();
3174 if (ExprNode->getSourceRange() == E->getSourceRange())
3175 return ExprNode;
3176 }
3177 return E;
3178 };
3179
3180 // Used when Clang generates calls to std::get for decomposing
3181 // structured bindings.
3182 auto IgnoreImplicitCallSingleStep = [](Expr *E) {
3183 auto *C = dyn_cast<CallExpr>(Val: E);
3184 if (!C)
3185 return E;
3186
3187 // Looking for calls to a std::get, which usually just takes
3188 // 1 argument (i.e., the structure being decomposed). If it has
3189 // more than 1 argument, the others need to be defaulted.
3190 unsigned NumArgs = C->getNumArgs();
3191 if (NumArgs == 0 || (NumArgs > 1 && !isa<CXXDefaultArgExpr>(Val: C->getArg(Arg: 1))))
3192 return E;
3193
3194 Expr *A = C->getArg(Arg: 0);
3195
3196 // This was spelled out in source. Don't ignore.
3197 if (A->getSourceRange() != E->getSourceRange())
3198 return E;
3199
3200 // If the argument refers to a DecompositionDecl construction,
3201 // ignore it.
3202 if (IsDecompositionDeclRefExpr(E: A))
3203 return A;
3204
3205 return E;
3206 };
3207
3208 return IgnoreExprNodes(
3209 E: this, Fns&: IgnoreImplicitSingleStep, Fns&: IgnoreImplicitCastsExtraSingleStep,
3210 Fns&: IgnoreParensOnlySingleStep, Fns&: IgnoreImplicitConstructorSingleStep,
3211 Fns&: IgnoreImplicitMemberCallSingleStep, Fns&: IgnoreImplicitCallSingleStep);
3212}
3213
3214bool Expr::isDefaultArgument() const {
3215 const Expr *E = this;
3216 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(Val: E))
3217 E = M->getSubExpr();
3218
3219 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
3220 E = ICE->getSubExprAsWritten();
3221
3222 return isa<CXXDefaultArgExpr>(Val: E);
3223}
3224
3225/// Skip over any no-op casts and any temporary-binding
3226/// expressions.
3227static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
3228 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(Val: E))
3229 E = M->getSubExpr();
3230
3231 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
3232 if (ICE->getCastKind() == CK_NoOp)
3233 E = ICE->getSubExpr();
3234 else
3235 break;
3236 }
3237
3238 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(Val: E))
3239 E = BE->getSubExpr();
3240
3241 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
3242 if (ICE->getCastKind() == CK_NoOp)
3243 E = ICE->getSubExpr();
3244 else
3245 break;
3246 }
3247
3248 return E->IgnoreParens();
3249}
3250
3251/// isTemporaryObject - Determines if this expression produces a
3252/// temporary of the given class type.
3253bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3254 if (!C.hasSameUnqualifiedType(T1: getType(), T2: C.getCanonicalTagType(TD: TempTy)))
3255 return false;
3256
3257 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(E: this);
3258
3259 // Temporaries are by definition pr-values of class type.
3260 if (!E->Classify(Ctx&: C).isPRValue()) {
3261 // In this context, property reference is a message call and is pr-value.
3262 if (!isa<ObjCPropertyRefExpr>(Val: E))
3263 return false;
3264 }
3265
3266 // Black-list a few cases which yield pr-values of class type that don't
3267 // refer to temporaries of that type:
3268
3269 // - implicit derived-to-base conversions
3270 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
3271 switch (ICE->getCastKind()) {
3272 case CK_DerivedToBase:
3273 case CK_UncheckedDerivedToBase:
3274 return false;
3275 default:
3276 break;
3277 }
3278 }
3279
3280 // - member expressions (all)
3281 if (isa<MemberExpr>(Val: E))
3282 return false;
3283
3284 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
3285 if (BO->isPtrMemOp())
3286 return false;
3287
3288 // - opaque values (all)
3289 if (isa<OpaqueValueExpr>(Val: E))
3290 return false;
3291
3292 return true;
3293}
3294
3295bool Expr::isImplicitCXXThis() const {
3296 const Expr *E = this;
3297
3298 // Strip away parentheses and casts we don't care about.
3299 while (true) {
3300 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(Val: E)) {
3301 E = Paren->getSubExpr();
3302 continue;
3303 }
3304
3305 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
3306 if (ICE->getCastKind() == CK_NoOp ||
3307 ICE->getCastKind() == CK_LValueToRValue ||
3308 ICE->getCastKind() == CK_DerivedToBase ||
3309 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3310 E = ICE->getSubExpr();
3311 continue;
3312 }
3313 }
3314
3315 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(Val: E)) {
3316 if (UnOp->getOpcode() == UO_Extension) {
3317 E = UnOp->getSubExpr();
3318 continue;
3319 }
3320 }
3321
3322 if (const MaterializeTemporaryExpr *M
3323 = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
3324 E = M->getSubExpr();
3325 continue;
3326 }
3327
3328 break;
3329 }
3330
3331 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(Val: E))
3332 return This->isImplicit();
3333
3334 return false;
3335}
3336
3337/// hasAnyTypeDependentArguments - Determines if any of the expressions
3338/// in Exprs is type-dependent.
3339bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3340 for (unsigned I = 0; I < Exprs.size(); ++I)
3341 if (Exprs[I]->isTypeDependent())
3342 return true;
3343
3344 return false;
3345}
3346
3347bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3348 const Expr **Culprit) const {
3349 assert(!isValueDependent() &&
3350 "Expression evaluator can't be called on a dependent expression.");
3351
3352 // This function is attempting whether an expression is an initializer
3353 // which can be evaluated at compile-time. It very closely parallels
3354 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3355 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3356 // to isEvaluatable most of the time.
3357 //
3358 // If we ever capture reference-binding directly in the AST, we can
3359 // kill the second parameter.
3360
3361 if (IsForRef) {
3362 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: this))
3363 return EWC->getSubExpr()->isConstantInitializer(Ctx, IsForRef: true, Culprit);
3364 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: this))
3365 return MTE->getSubExpr()->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3366 EvalResult Result;
3367 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3368 return true;
3369 if (Culprit)
3370 *Culprit = this;
3371 return false;
3372 }
3373
3374 switch (getStmtClass()) {
3375 default: break;
3376 case Stmt::ExprWithCleanupsClass:
3377 return cast<ExprWithCleanups>(Val: this)->getSubExpr()->isConstantInitializer(
3378 Ctx, IsForRef, Culprit);
3379 case StringLiteralClass:
3380 case ObjCEncodeExprClass:
3381 return true;
3382 case CXXTemporaryObjectExprClass:
3383 case CXXConstructExprClass: {
3384 const CXXConstructExpr *CE = cast<CXXConstructExpr>(Val: this);
3385
3386 if (CE->getConstructor()->isTrivial() &&
3387 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3388 // Trivial default constructor
3389 if (!CE->getNumArgs()) return true;
3390
3391 // Trivial copy constructor
3392 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3393 return CE->getArg(Arg: 0)->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3394 }
3395
3396 break;
3397 }
3398 case ConstantExprClass: {
3399 // FIXME: We should be able to return "true" here, but it can lead to extra
3400 // error messages. E.g. in Sema/array-init.c.
3401 const Expr *Exp = cast<ConstantExpr>(Val: this)->getSubExpr();
3402 return Exp->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3403 }
3404 case CompoundLiteralExprClass: {
3405 // This handles gcc's extension that allows global initializers like
3406 // "struct x {int x;} x = (struct x) {};".
3407 // FIXME: This accepts other cases it shouldn't!
3408 const Expr *Exp = cast<CompoundLiteralExpr>(Val: this)->getInitializer();
3409 return Exp->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3410 }
3411 case DesignatedInitUpdateExprClass: {
3412 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(Val: this);
3413 return DIUE->getBase()->isConstantInitializer(Ctx, IsForRef: false, Culprit) &&
3414 DIUE->getUpdater()->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3415 }
3416 case InitListExprClass: {
3417 // C++ [dcl.init.aggr]p2:
3418 // The elements of an aggregate are:
3419 // - for an array, the array elements in increasing subscript order, or
3420 // - for a class, the direct base classes in declaration order, followed
3421 // by the direct non-static data members (11.4) that are not members of
3422 // an anonymous union, in declaration order.
3423 const InitListExpr *ILE = cast<InitListExpr>(Val: this);
3424 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3425
3426 if (ILE->isTransparent())
3427 return ILE->getInit(Init: 0)->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3428
3429 if (ILE->getType()->isArrayType()) {
3430 unsigned numInits = ILE->getNumInits();
3431 for (unsigned i = 0; i < numInits; i++) {
3432 if (!ILE->getInit(Init: i)->isConstantInitializer(Ctx, IsForRef: false, Culprit))
3433 return false;
3434 }
3435 return true;
3436 }
3437
3438 if (ILE->getType()->isRecordType()) {
3439 unsigned ElementNo = 0;
3440 auto *RD = ILE->getType()->castAsRecordDecl();
3441
3442 // In C++17, bases were added to the list of members used by aggregate
3443 // initialization.
3444 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
3445 for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {
3446 if (ElementNo < ILE->getNumInits()) {
3447 const Expr *Elt = ILE->getInit(Init: ElementNo++);
3448 if (!Elt->isConstantInitializer(Ctx, IsForRef: false, Culprit))
3449 return false;
3450 }
3451 }
3452 }
3453
3454 for (const auto *Field : RD->fields()) {
3455 // If this is a union, skip all the fields that aren't being initialized.
3456 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3457 continue;
3458
3459 // Don't emit anonymous bitfields, they just affect layout.
3460 if (Field->isUnnamedBitField())
3461 continue;
3462
3463 if (ElementNo < ILE->getNumInits()) {
3464 const Expr *Elt = ILE->getInit(Init: ElementNo++);
3465 if (Field->isBitField()) {
3466 // Bitfields have to evaluate to an integer.
3467 EvalResult Result;
3468 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3469 if (Culprit)
3470 *Culprit = Elt;
3471 return false;
3472 }
3473 } else {
3474 bool RefType = Field->getType()->isReferenceType();
3475 if (!Elt->isConstantInitializer(Ctx, IsForRef: RefType, Culprit))
3476 return false;
3477 }
3478 }
3479 }
3480 return true;
3481 }
3482
3483 break;
3484 }
3485 case ImplicitValueInitExprClass:
3486 case NoInitExprClass:
3487 return true;
3488 case ParenExprClass:
3489 return cast<ParenExpr>(Val: this)->getSubExpr()
3490 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3491 case GenericSelectionExprClass:
3492 return cast<GenericSelectionExpr>(Val: this)->getResultExpr()
3493 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3494 case ChooseExprClass:
3495 if (cast<ChooseExpr>(Val: this)->isConditionDependent()) {
3496 if (Culprit)
3497 *Culprit = this;
3498 return false;
3499 }
3500 return cast<ChooseExpr>(Val: this)->getChosenSubExpr()
3501 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3502 case UnaryOperatorClass: {
3503 const UnaryOperator* Exp = cast<UnaryOperator>(Val: this);
3504 if (Exp->getOpcode() == UO_Extension)
3505 return Exp->getSubExpr()->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3506 break;
3507 }
3508 case ObjCBoxedExprClass: {
3509 const ObjCBoxedExpr *BE = cast<ObjCBoxedExpr>(Val: this);
3510 if (Culprit)
3511 *Culprit = this;
3512 return BE->isExpressibleAsConstantInitializer();
3513 }
3514 case ObjCArrayLiteralClass: {
3515 const ObjCArrayLiteral *ALE = cast<ObjCArrayLiteral>(Val: this);
3516 if (Culprit)
3517 *Culprit = this;
3518 return ALE->isExpressibleAsConstantInitializer();
3519 }
3520 case ObjCDictionaryLiteralClass: {
3521 const ObjCDictionaryLiteral *DLE = cast<ObjCDictionaryLiteral>(Val: this);
3522 if (Culprit)
3523 *Culprit = this;
3524 return DLE->isExpressibleAsConstantInitializer();
3525 }
3526 case PackIndexingExprClass: {
3527 return cast<PackIndexingExpr>(Val: this)
3528 ->getSelectedExpr()
3529 ->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3530 }
3531 case CXXFunctionalCastExprClass:
3532 case CXXStaticCastExprClass:
3533 case ImplicitCastExprClass:
3534 case CStyleCastExprClass:
3535 case ObjCBridgedCastExprClass:
3536 case CXXDynamicCastExprClass:
3537 case CXXReinterpretCastExprClass:
3538 case CXXAddrspaceCastExprClass:
3539 case CXXConstCastExprClass: {
3540 const CastExpr *CE = cast<CastExpr>(Val: this);
3541
3542 // Handle misc casts we want to ignore.
3543 if (CE->getCastKind() == CK_NoOp ||
3544 CE->getCastKind() == CK_LValueToRValue ||
3545 CE->getCastKind() == CK_ToUnion ||
3546 CE->getCastKind() == CK_ConstructorConversion ||
3547 CE->getCastKind() == CK_NonAtomicToAtomic ||
3548 CE->getCastKind() == CK_AtomicToNonAtomic ||
3549 CE->getCastKind() == CK_NullToPointer ||
3550 CE->getCastKind() == CK_IntToOCLSampler)
3551 return CE->getSubExpr()->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3552
3553 break;
3554 }
3555 case MaterializeTemporaryExprClass:
3556 return cast<MaterializeTemporaryExpr>(Val: this)
3557 ->getSubExpr()
3558 ->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3559
3560 case SubstNonTypeTemplateParmExprClass:
3561 return cast<SubstNonTypeTemplateParmExpr>(Val: this)->getReplacement()
3562 ->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3563 case CXXDefaultArgExprClass:
3564 return cast<CXXDefaultArgExpr>(Val: this)->getExpr()
3565 ->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3566 case CXXDefaultInitExprClass:
3567 return cast<CXXDefaultInitExpr>(Val: this)->getExpr()
3568 ->isConstantInitializer(Ctx, IsForRef: false, Culprit);
3569 }
3570 // Allow certain forms of UB in constant initializers: signed integer
3571 // overflow and floating-point division by zero. We'll give a warning on
3572 // these, but they're common enough that we have to accept them.
3573 if (isEvaluatable(Ctx, AllowSideEffects: SE_AllowUndefinedBehavior))
3574 return true;
3575 if (Culprit)
3576 *Culprit = this;
3577 return false;
3578}
3579
3580bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3581 unsigned BuiltinID = getBuiltinCallee();
3582 if (BuiltinID != Builtin::BI__assume &&
3583 BuiltinID != Builtin::BI__builtin_assume)
3584 return false;
3585
3586 const Expr* Arg = getArg(Arg: 0);
3587 bool ArgVal;
3588 return !Arg->isValueDependent() &&
3589 Arg->EvaluateAsBooleanCondition(Result&: ArgVal, Ctx) && !ArgVal;
3590}
3591
3592const AllocSizeAttr *CallExpr::getCalleeAllocSizeAttr() const {
3593 if (const FunctionDecl *DirectCallee = getDirectCallee())
3594 return DirectCallee->getAttr<AllocSizeAttr>();
3595 if (const Decl *IndirectCallee = getCalleeDecl())
3596 return IndirectCallee->getAttr<AllocSizeAttr>();
3597 return nullptr;
3598}
3599
3600std::optional<llvm::APInt>
3601CallExpr::evaluateBytesReturnedByAllocSizeCall(const ASTContext &Ctx) const {
3602 const AllocSizeAttr *AllocSize = getCalleeAllocSizeAttr();
3603
3604 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
3605 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
3606 unsigned BitsInSizeT = Ctx.getTypeSize(T: Ctx.getSizeType());
3607 if (getNumArgs() <= SizeArgNo)
3608 return std::nullopt;
3609
3610 auto EvaluateAsSizeT = [&](const Expr *E, llvm::APSInt &Into) {
3611 Expr::EvalResult ExprResult;
3612 if (E->isValueDependent() ||
3613 !E->EvaluateAsInt(Result&: ExprResult, Ctx, AllowSideEffects: Expr::SE_AllowSideEffects))
3614 return false;
3615 Into = ExprResult.Val.getInt();
3616 if (Into.isNegative() || !Into.isIntN(N: BitsInSizeT))
3617 return false;
3618 Into = Into.zext(width: BitsInSizeT);
3619 return true;
3620 };
3621
3622 llvm::APSInt SizeOfElem;
3623 if (!EvaluateAsSizeT(getArg(Arg: SizeArgNo), SizeOfElem))
3624 return std::nullopt;
3625
3626 if (!AllocSize->getNumElemsParam().isValid())
3627 return SizeOfElem;
3628
3629 llvm::APSInt NumberOfElems;
3630 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
3631 if (!EvaluateAsSizeT(getArg(Arg: NumArgNo), NumberOfElems))
3632 return std::nullopt;
3633
3634 bool Overflow;
3635 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(RHS: NumberOfElems, Overflow);
3636 if (Overflow)
3637 return std::nullopt;
3638
3639 return BytesAvailable;
3640}
3641
3642bool CallExpr::isCallToStdMove() const {
3643 return getBuiltinCallee() == Builtin::BImove;
3644}
3645
3646namespace {
3647 /// Look for any side effects within a Stmt.
3648 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3649 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3650 const bool IncludePossibleEffects;
3651 bool HasSideEffects;
3652
3653 public:
3654 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3655 : Inherited(Context),
3656 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3657
3658 bool hasSideEffects() const { return HasSideEffects; }
3659
3660 void VisitDecl(const Decl *D) {
3661 if (!D)
3662 return;
3663
3664 // We assume the caller checks subexpressions (eg, the initializer, VLA
3665 // bounds) for side-effects on our behalf.
3666 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
3667 // Registering a destructor is a side-effect.
3668 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3669 VD->needsDestruction(Ctx: Context))
3670 HasSideEffects = true;
3671 }
3672 }
3673
3674 void VisitDeclStmt(const DeclStmt *DS) {
3675 for (auto *D : DS->decls())
3676 VisitDecl(D);
3677 Inherited::VisitDeclStmt(S: DS);
3678 }
3679
3680 void VisitExpr(const Expr *E) {
3681 if (!HasSideEffects &&
3682 E->HasSideEffects(Ctx: Context, IncludePossibleEffects))
3683 HasSideEffects = true;
3684 }
3685 };
3686}
3687
3688bool Expr::HasSideEffects(const ASTContext &Ctx,
3689 bool IncludePossibleEffects) const {
3690 // In circumstances where we care about definite side effects instead of
3691 // potential side effects, we want to ignore expressions that are part of a
3692 // macro expansion as a potential side effect.
3693 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3694 return false;
3695
3696 switch (getStmtClass()) {
3697 case NoStmtClass:
3698#define ABSTRACT_STMT(Type)
3699#define STMT(Type, Base) case Type##Class:
3700#define EXPR(Type, Base)
3701#include "clang/AST/StmtNodes.inc"
3702 llvm_unreachable("unexpected Expr kind");
3703
3704 case DependentScopeDeclRefExprClass:
3705 case CXXUnresolvedConstructExprClass:
3706 case CXXDependentScopeMemberExprClass:
3707 case UnresolvedLookupExprClass:
3708 case UnresolvedMemberExprClass:
3709 case PackExpansionExprClass:
3710 case SubstNonTypeTemplateParmPackExprClass:
3711 case FunctionParmPackExprClass:
3712 case RecoveryExprClass:
3713 case CXXFoldExprClass:
3714 // Make a conservative assumption for dependent nodes.
3715 return IncludePossibleEffects;
3716
3717 case DeclRefExprClass:
3718 case ObjCIvarRefExprClass:
3719 case PredefinedExprClass:
3720 case IntegerLiteralClass:
3721 case FixedPointLiteralClass:
3722 case FloatingLiteralClass:
3723 case ImaginaryLiteralClass:
3724 case StringLiteralClass:
3725 case CharacterLiteralClass:
3726 case OffsetOfExprClass:
3727 case ImplicitValueInitExprClass:
3728 case UnaryExprOrTypeTraitExprClass:
3729 case AddrLabelExprClass:
3730 case GNUNullExprClass:
3731 case ArrayInitIndexExprClass:
3732 case NoInitExprClass:
3733 case CXXBoolLiteralExprClass:
3734 case CXXNullPtrLiteralExprClass:
3735 case CXXThisExprClass:
3736 case CXXScalarValueInitExprClass:
3737 case TypeTraitExprClass:
3738 case ArrayTypeTraitExprClass:
3739 case ExpressionTraitExprClass:
3740 case CXXNoexceptExprClass:
3741 case SizeOfPackExprClass:
3742 case ObjCStringLiteralClass:
3743 case ObjCEncodeExprClass:
3744 case ObjCBoolLiteralExprClass:
3745 case ObjCAvailabilityCheckExprClass:
3746 case CXXUuidofExprClass:
3747 case OpaqueValueExprClass:
3748 case SourceLocExprClass:
3749 case EmbedExprClass:
3750 case ConceptSpecializationExprClass:
3751 case RequiresExprClass:
3752 case SYCLUniqueStableNameExprClass:
3753 case PackIndexingExprClass:
3754 case HLSLOutArgExprClass:
3755 case OpenACCAsteriskSizeExprClass:
3756 case CXXReflectExprClass:
3757 // These never have a side-effect.
3758 return false;
3759
3760 case ConstantExprClass:
3761 // FIXME: Move this into the "return false;" block above.
3762 return cast<ConstantExpr>(Val: this)->getSubExpr()->HasSideEffects(
3763 Ctx, IncludePossibleEffects);
3764
3765 case CallExprClass:
3766 case CXXOperatorCallExprClass:
3767 case CXXMemberCallExprClass:
3768 case CUDAKernelCallExprClass:
3769 case UserDefinedLiteralClass: {
3770 // We don't know a call definitely has side effects, except for calls
3771 // to pure/const functions that definitely don't.
3772 // If the call itself is considered side-effect free, check the operands.
3773 const Decl *FD = cast<CallExpr>(Val: this)->getCalleeDecl();
3774 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3775 if (IsPure || !IncludePossibleEffects)
3776 break;
3777 return true;
3778 }
3779
3780 case BlockExprClass:
3781 case CXXBindTemporaryExprClass:
3782 if (!IncludePossibleEffects)
3783 break;
3784 return true;
3785
3786 case MSPropertyRefExprClass:
3787 case MSPropertySubscriptExprClass:
3788 case CompoundAssignOperatorClass:
3789 case VAArgExprClass:
3790 case AtomicExprClass:
3791 case CXXThrowExprClass:
3792 case CXXNewExprClass:
3793 case CXXDeleteExprClass:
3794 case CoawaitExprClass:
3795 case DependentCoawaitExprClass:
3796 case CoyieldExprClass:
3797 // These always have a side-effect.
3798 return true;
3799
3800 case StmtExprClass: {
3801 // StmtExprs have a side-effect if any substatement does.
3802 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3803 Finder.Visit(S: cast<StmtExpr>(Val: this)->getSubStmt());
3804 return Finder.hasSideEffects();
3805 }
3806
3807 case ExprWithCleanupsClass:
3808 if (IncludePossibleEffects)
3809 if (cast<ExprWithCleanups>(Val: this)->cleanupsHaveSideEffects())
3810 return true;
3811 break;
3812
3813 case ParenExprClass:
3814 case ArraySubscriptExprClass:
3815 case MatrixSingleSubscriptExprClass:
3816 case MatrixSubscriptExprClass:
3817 case ArraySectionExprClass:
3818 case OMPArrayShapingExprClass:
3819 case OMPIteratorExprClass:
3820 case MemberExprClass:
3821 case ConditionalOperatorClass:
3822 case BinaryConditionalOperatorClass:
3823 case CompoundLiteralExprClass:
3824 case ExtVectorElementExprClass:
3825 case MatrixElementExprClass:
3826 case DesignatedInitExprClass:
3827 case DesignatedInitUpdateExprClass:
3828 case ArrayInitLoopExprClass:
3829 case ParenListExprClass:
3830 case CXXPseudoDestructorExprClass:
3831 case CXXRewrittenBinaryOperatorClass:
3832 case CXXStdInitializerListExprClass:
3833 case SubstNonTypeTemplateParmExprClass:
3834 case MaterializeTemporaryExprClass:
3835 case ShuffleVectorExprClass:
3836 case ConvertVectorExprClass:
3837 case AsTypeExprClass:
3838 case CXXParenListInitExprClass:
3839 // These have a side-effect if any subexpression does.
3840 break;
3841
3842 case UnaryOperatorClass:
3843 if (cast<UnaryOperator>(Val: this)->isIncrementDecrementOp())
3844 return true;
3845 break;
3846
3847 case BinaryOperatorClass:
3848 if (cast<BinaryOperator>(Val: this)->isAssignmentOp())
3849 return true;
3850 break;
3851
3852 case InitListExprClass:
3853 // FIXME: The children for an InitListExpr doesn't include the array filler.
3854 if (const Expr *E = cast<InitListExpr>(Val: this)->getArrayFiller())
3855 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3856 return true;
3857 break;
3858
3859 case GenericSelectionExprClass:
3860 return cast<GenericSelectionExpr>(Val: this)->getResultExpr()->HasSideEffects(
3861 Ctx, IncludePossibleEffects);
3862
3863 case ChooseExprClass:
3864 return cast<ChooseExpr>(Val: this)->getChosenSubExpr()->HasSideEffects(
3865 Ctx, IncludePossibleEffects);
3866
3867 case CXXDefaultArgExprClass:
3868 return cast<CXXDefaultArgExpr>(Val: this)->getExpr()->HasSideEffects(
3869 Ctx, IncludePossibleEffects);
3870
3871 case CXXDefaultInitExprClass: {
3872 const FieldDecl *FD = cast<CXXDefaultInitExpr>(Val: this)->getField();
3873 if (const Expr *E = FD->getInClassInitializer())
3874 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3875 // If we've not yet parsed the initializer, assume it has side-effects.
3876 return true;
3877 }
3878
3879 case CXXDynamicCastExprClass: {
3880 // A dynamic_cast expression has side-effects if it can throw.
3881 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(Val: this);
3882 if (DCE->getTypeAsWritten()->isReferenceType() &&
3883 DCE->getCastKind() == CK_Dynamic)
3884 return true;
3885 }
3886 [[fallthrough]];
3887 case ImplicitCastExprClass:
3888 case CStyleCastExprClass:
3889 case CXXStaticCastExprClass:
3890 case CXXReinterpretCastExprClass:
3891 case CXXConstCastExprClass:
3892 case CXXAddrspaceCastExprClass:
3893 case CXXFunctionalCastExprClass:
3894 case BuiltinBitCastExprClass: {
3895 // While volatile reads are side-effecting in both C and C++, we treat them
3896 // as having possible (not definite) side-effects. This allows idiomatic
3897 // code to behave without warning, such as sizeof(*v) for a volatile-
3898 // qualified pointer.
3899 if (!IncludePossibleEffects)
3900 break;
3901
3902 const CastExpr *CE = cast<CastExpr>(Val: this);
3903 if (CE->getCastKind() == CK_LValueToRValue &&
3904 CE->getSubExpr()->getType().isVolatileQualified())
3905 return true;
3906 break;
3907 }
3908
3909 case CXXTypeidExprClass: {
3910 const auto *TE = cast<CXXTypeidExpr>(Val: this);
3911 if (!TE->isPotentiallyEvaluated())
3912 return false;
3913
3914 // If this type id expression can throw because of a null pointer, that is a
3915 // side-effect independent of if the operand has a side-effect
3916 if (IncludePossibleEffects && TE->hasNullCheck())
3917 return true;
3918
3919 break;
3920 }
3921
3922 case CXXConstructExprClass:
3923 case CXXTemporaryObjectExprClass: {
3924 const CXXConstructExpr *CE = cast<CXXConstructExpr>(Val: this);
3925 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3926 return true;
3927 // A trivial constructor does not add any side-effects of its own. Just look
3928 // at its arguments.
3929 break;
3930 }
3931
3932 case CXXInheritedCtorInitExprClass: {
3933 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(Val: this);
3934 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3935 return true;
3936 break;
3937 }
3938
3939 case LambdaExprClass: {
3940 const LambdaExpr *LE = cast<LambdaExpr>(Val: this);
3941 for (Expr *E : LE->capture_inits())
3942 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3943 return true;
3944 return false;
3945 }
3946
3947 case PseudoObjectExprClass: {
3948 // Only look for side-effects in the semantic form, and look past
3949 // OpaqueValueExpr bindings in that form.
3950 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(Val: this);
3951 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3952 E = PO->semantics_end();
3953 I != E; ++I) {
3954 const Expr *Subexpr = *I;
3955 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: Subexpr))
3956 Subexpr = OVE->getSourceExpr();
3957 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3958 return true;
3959 }
3960 return false;
3961 }
3962
3963 case ObjCBoxedExprClass:
3964 case ObjCArrayLiteralClass:
3965 case ObjCDictionaryLiteralClass:
3966 case ObjCSelectorExprClass:
3967 case ObjCProtocolExprClass:
3968 case ObjCIsaExprClass:
3969 case ObjCIndirectCopyRestoreExprClass:
3970 case ObjCSubscriptRefExprClass:
3971 case ObjCBridgedCastExprClass:
3972 case ObjCMessageExprClass:
3973 case ObjCPropertyRefExprClass:
3974 // FIXME: Classify these cases better.
3975 if (IncludePossibleEffects)
3976 return true;
3977 break;
3978 }
3979
3980 // Recurse to children.
3981 for (const Stmt *SubStmt : children())
3982 if (SubStmt &&
3983 cast<Expr>(Val: SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3984 return true;
3985
3986 return false;
3987}
3988
3989FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {
3990 if (auto Call = dyn_cast<CallExpr>(Val: this))
3991 return Call->getFPFeaturesInEffect(LO);
3992 if (auto UO = dyn_cast<UnaryOperator>(Val: this))
3993 return UO->getFPFeaturesInEffect(LO);
3994 if (auto BO = dyn_cast<BinaryOperator>(Val: this))
3995 return BO->getFPFeaturesInEffect(LO);
3996 if (auto Cast = dyn_cast<CastExpr>(Val: this))
3997 return Cast->getFPFeaturesInEffect(LO);
3998 if (auto ConvertVector = dyn_cast<ConvertVectorExpr>(Val: this))
3999 return ConvertVector->getFPFeaturesInEffect(LO);
4000 return FPOptions::defaultWithoutTrailingStorage(LO);
4001}
4002
4003namespace {
4004 /// Look for a call to a non-trivial function within an expression.
4005 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
4006 {
4007 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
4008
4009 bool NonTrivial;
4010
4011 public:
4012 explicit NonTrivialCallFinder(const ASTContext &Context)
4013 : Inherited(Context), NonTrivial(false) { }
4014
4015 bool hasNonTrivialCall() const { return NonTrivial; }
4016
4017 void VisitCallExpr(const CallExpr *E) {
4018 if (const CXXMethodDecl *Method
4019 = dyn_cast_or_null<const CXXMethodDecl>(Val: E->getCalleeDecl())) {
4020 if (Method->isTrivial()) {
4021 // Recurse to children of the call.
4022 Inherited::VisitStmt(S: E);
4023 return;
4024 }
4025 }
4026
4027 NonTrivial = true;
4028 }
4029
4030 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
4031 if (E->getConstructor()->isTrivial()) {
4032 // Recurse to children of the call.
4033 Inherited::VisitStmt(S: E);
4034 return;
4035 }
4036
4037 NonTrivial = true;
4038 }
4039
4040 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
4041 // Destructor of the temporary might be null if destructor declaration
4042 // is not valid.
4043 if (const CXXDestructorDecl *DtorDecl =
4044 E->getTemporary()->getDestructor()) {
4045 if (DtorDecl->isTrivial()) {
4046 Inherited::VisitStmt(S: E);
4047 return;
4048 }
4049 }
4050
4051 NonTrivial = true;
4052 }
4053 };
4054}
4055
4056bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
4057 NonTrivialCallFinder Finder(Ctx);
4058 Finder.Visit(S: this);
4059 return Finder.hasNonTrivialCall();
4060}
4061
4062/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
4063/// pointer constant or not, as well as the specific kind of constant detected.
4064/// Null pointer constants can be integer constant expressions with the
4065/// value zero, casts of zero to void*, nullptr (C++0X), or __null
4066/// (a GNU extension).
4067Expr::NullPointerConstantKind
4068Expr::isNullPointerConstant(ASTContext &Ctx,
4069 NullPointerConstantValueDependence NPC) const {
4070 if (isValueDependent() &&
4071 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
4072 // Error-dependent expr should never be a null pointer.
4073 if (containsErrors())
4074 return NPCK_NotNull;
4075 switch (NPC) {
4076 case NPC_NeverValueDependent:
4077 llvm_unreachable("Unexpected value dependent expression!");
4078 case NPC_ValueDependentIsNull:
4079 if (isTypeDependent() || getType()->isIntegralType(Ctx))
4080 return NPCK_ZeroExpression;
4081 else
4082 return NPCK_NotNull;
4083
4084 case NPC_ValueDependentIsNotNull:
4085 return NPCK_NotNull;
4086 }
4087 }
4088
4089 // Strip off a cast to void*, if it exists. Except in C++.
4090 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(Val: this)) {
4091 if (!Ctx.getLangOpts().CPlusPlus) {
4092 // Check that it is a cast to void*.
4093 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
4094 QualType Pointee = PT->getPointeeType();
4095 Qualifiers Qs = Pointee.getQualifiers();
4096 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
4097 // has non-default address space it is not treated as nullptr.
4098 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
4099 // since it cannot be assigned to a pointer to constant address space.
4100 if (Ctx.getLangOpts().OpenCL &&
4101 Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace())
4102 Qs.removeAddressSpace();
4103
4104 if (Pointee->isVoidType() && Qs.empty() && // to void*
4105 CE->getSubExpr()->getType()->isIntegerType()) // from int
4106 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4107 }
4108 }
4109 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: this)) {
4110 // Ignore the ImplicitCastExpr type entirely.
4111 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4112 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: this)) {
4113 // Accept ((void*)0) as a null pointer constant, as many other
4114 // implementations do.
4115 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4116 } else if (const GenericSelectionExpr *GE =
4117 dyn_cast<GenericSelectionExpr>(Val: this)) {
4118 if (GE->isResultDependent())
4119 return NPCK_NotNull;
4120 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
4121 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(Val: this)) {
4122 if (CE->isConditionDependent())
4123 return NPCK_NotNull;
4124 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
4125 } else if (const CXXDefaultArgExpr *DefaultArg
4126 = dyn_cast<CXXDefaultArgExpr>(Val: this)) {
4127 // See through default argument expressions.
4128 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
4129 } else if (const CXXDefaultInitExpr *DefaultInit
4130 = dyn_cast<CXXDefaultInitExpr>(Val: this)) {
4131 // See through default initializer expressions.
4132 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
4133 } else if (isa<GNUNullExpr>(Val: this)) {
4134 // The GNU __null extension is always a null pointer constant.
4135 return NPCK_GNUNull;
4136 } else if (const MaterializeTemporaryExpr *M
4137 = dyn_cast<MaterializeTemporaryExpr>(Val: this)) {
4138 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4139 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: this)) {
4140 if (const Expr *Source = OVE->getSourceExpr())
4141 return Source->isNullPointerConstant(Ctx, NPC);
4142 }
4143
4144 // If the expression has no type information, it cannot be a null pointer
4145 // constant.
4146 if (getType().isNull())
4147 return NPCK_NotNull;
4148
4149 // C++11/C23 nullptr_t is always a null pointer constant.
4150 if (getType()->isNullPtrType())
4151 return NPCK_CXX11_nullptr;
4152
4153 if (const RecordType *UT = getType()->getAsUnionType())
4154 if (!Ctx.getLangOpts().CPlusPlus11 && UT &&
4155 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>())
4156 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Val: this)){
4157 const Expr *InitExpr = CLE->getInitializer();
4158 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Val: InitExpr))
4159 return ILE->getInit(Init: 0)->isNullPointerConstant(Ctx, NPC);
4160 }
4161 // This expression must be an integer type.
4162 if (!getType()->isIntegerType() ||
4163 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
4164 return NPCK_NotNull;
4165
4166 if (Ctx.getLangOpts().CPlusPlus11) {
4167 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
4168 // value zero or a prvalue of type std::nullptr_t.
4169 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
4170 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(Val: this);
4171 if (Lit && !Lit->getValue())
4172 return NPCK_ZeroLiteral;
4173 if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
4174 return NPCK_NotNull;
4175 } else {
4176 // If we have an integer constant expression, we need to *evaluate* it and
4177 // test for the value 0.
4178 if (!isIntegerConstantExpr(Ctx))
4179 return NPCK_NotNull;
4180 }
4181
4182 if (EvaluateKnownConstInt(Ctx) != 0)
4183 return NPCK_NotNull;
4184
4185 if (isa<IntegerLiteral>(Val: this))
4186 return NPCK_ZeroLiteral;
4187 return NPCK_ZeroExpression;
4188}
4189
4190/// If this expression is an l-value for an Objective C
4191/// property, find the underlying property reference expression.
4192const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
4193 const Expr *E = this;
4194 while (true) {
4195 assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
4196 "expression is not a property reference");
4197 E = E->IgnoreParenCasts();
4198 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
4199 if (BO->getOpcode() == BO_Comma) {
4200 E = BO->getRHS();
4201 continue;
4202 }
4203 }
4204
4205 break;
4206 }
4207
4208 return cast<ObjCPropertyRefExpr>(Val: E);
4209}
4210
4211bool Expr::isObjCSelfExpr() const {
4212 const Expr *E = IgnoreParenImpCasts();
4213
4214 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
4215 if (!DRE)
4216 return false;
4217
4218 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(Val: DRE->getDecl());
4219 if (!Param)
4220 return false;
4221
4222 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Val: Param->getDeclContext());
4223 if (!M)
4224 return false;
4225
4226 return M->getSelfDecl() == Param;
4227}
4228
4229FieldDecl *Expr::getSourceBitField() {
4230 Expr *E = this->IgnoreParens();
4231
4232 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
4233 if (ICE->getCastKind() == CK_LValueToRValue ||
4234 (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
4235 E = ICE->getSubExpr()->IgnoreParens();
4236 else
4237 break;
4238 }
4239
4240 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(Val: E))
4241 if (FieldDecl *Field = dyn_cast<FieldDecl>(Val: MemRef->getMemberDecl()))
4242 if (Field->isBitField())
4243 return Field;
4244
4245 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(Val: E)) {
4246 FieldDecl *Ivar = IvarRef->getDecl();
4247 if (Ivar->isBitField())
4248 return Ivar;
4249 }
4250
4251 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Val: E)) {
4252 if (FieldDecl *Field = dyn_cast<FieldDecl>(Val: DeclRef->getDecl()))
4253 if (Field->isBitField())
4254 return Field;
4255
4256 if (BindingDecl *BD = dyn_cast<BindingDecl>(Val: DeclRef->getDecl()))
4257 if (Expr *E = BD->getBinding())
4258 return E->getSourceBitField();
4259 }
4260
4261 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
4262 if (BinOp->isAssignmentOp() && BinOp->getLHS())
4263 return BinOp->getLHS()->getSourceBitField();
4264
4265 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
4266 return BinOp->getRHS()->getSourceBitField();
4267 }
4268
4269 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E))
4270 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
4271 return UnOp->getSubExpr()->getSourceBitField();
4272
4273 return nullptr;
4274}
4275
4276EnumConstantDecl *Expr::getEnumConstantDecl() {
4277 Expr *E = this->IgnoreParenImpCasts();
4278 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E))
4279 return dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
4280 return nullptr;
4281}
4282
4283bool Expr::refersToVectorElement() const {
4284 // FIXME: Why do we not just look at the ObjectKind here?
4285 const Expr *E = this->IgnoreParens();
4286
4287 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
4288 if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
4289 E = ICE->getSubExpr()->IgnoreParens();
4290 else
4291 break;
4292 }
4293
4294 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Val: E))
4295 return ASE->getBase()->getType()->isVectorType();
4296
4297 if (isa<ExtVectorElementExpr>(Val: E))
4298 return true;
4299
4300 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E))
4301 if (auto *BD = dyn_cast<BindingDecl>(Val: DRE->getDecl()))
4302 if (auto *E = BD->getBinding())
4303 return E->refersToVectorElement();
4304
4305 return false;
4306}
4307
4308bool Expr::refersToGlobalRegisterVar() const {
4309 const Expr *E = this->IgnoreParenImpCasts();
4310
4311 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
4312 if (const auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
4313 if (VD->getStorageClass() == SC_Register &&
4314 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
4315 return true;
4316
4317 return false;
4318}
4319
4320bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
4321 E1 = E1->IgnoreParens();
4322 E2 = E2->IgnoreParens();
4323
4324 if (E1->getStmtClass() != E2->getStmtClass())
4325 return false;
4326
4327 switch (E1->getStmtClass()) {
4328 default:
4329 return false;
4330 case CXXThisExprClass:
4331 return true;
4332 case DeclRefExprClass: {
4333 // DeclRefExpr without an ImplicitCastExpr can happen for integral
4334 // template parameters.
4335 const auto *DRE1 = cast<DeclRefExpr>(Val: E1);
4336 const auto *DRE2 = cast<DeclRefExpr>(Val: E2);
4337
4338 if (DRE1->getDecl() != DRE2->getDecl())
4339 return false;
4340
4341 if ((DRE1->isPRValue() && DRE2->isPRValue()) ||
4342 (DRE1->isLValue() && DRE2->isLValue()))
4343 return true;
4344
4345 return false;
4346 }
4347 case ImplicitCastExprClass: {
4348 // Peel off implicit casts.
4349 while (true) {
4350 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(Val: E1);
4351 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(Val: E2);
4352 if (!ICE1 || !ICE2)
4353 return false;
4354 if (ICE1->getCastKind() != ICE2->getCastKind())
4355 return isSameComparisonOperand(E1: ICE1->IgnoreParenImpCasts(),
4356 E2: ICE2->IgnoreParenImpCasts());
4357 E1 = ICE1->getSubExpr()->IgnoreParens();
4358 E2 = ICE2->getSubExpr()->IgnoreParens();
4359 // The final cast must be one of these types.
4360 if (ICE1->getCastKind() == CK_LValueToRValue ||
4361 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4362 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4363 break;
4364 }
4365 }
4366
4367 const auto *DRE1 = dyn_cast<DeclRefExpr>(Val: E1);
4368 const auto *DRE2 = dyn_cast<DeclRefExpr>(Val: E2);
4369 if (DRE1 && DRE2)
4370 return declaresSameEntity(D1: DRE1->getDecl(), D2: DRE2->getDecl());
4371
4372 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(Val: E1);
4373 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(Val: E2);
4374 if (Ivar1 && Ivar2) {
4375 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4376 declaresSameEntity(D1: Ivar1->getDecl(), D2: Ivar2->getDecl());
4377 }
4378
4379 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(Val: E1);
4380 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(Val: E2);
4381 if (Array1 && Array2) {
4382 if (!isSameComparisonOperand(E1: Array1->getBase(), E2: Array2->getBase()))
4383 return false;
4384
4385 auto Idx1 = Array1->getIdx();
4386 auto Idx2 = Array2->getIdx();
4387 const auto Integer1 = dyn_cast<IntegerLiteral>(Val: Idx1);
4388 const auto Integer2 = dyn_cast<IntegerLiteral>(Val: Idx2);
4389 if (Integer1 && Integer2) {
4390 if (!llvm::APInt::isSameValue(I1: Integer1->getValue(),
4391 I2: Integer2->getValue()))
4392 return false;
4393 } else {
4394 if (!isSameComparisonOperand(E1: Idx1, E2: Idx2))
4395 return false;
4396 }
4397
4398 return true;
4399 }
4400
4401 // Walk the MemberExpr chain.
4402 while (isa<MemberExpr>(Val: E1) && isa<MemberExpr>(Val: E2)) {
4403 const auto *ME1 = cast<MemberExpr>(Val: E1);
4404 const auto *ME2 = cast<MemberExpr>(Val: E2);
4405 if (!declaresSameEntity(D1: ME1->getMemberDecl(), D2: ME2->getMemberDecl()))
4406 return false;
4407 if (const auto *D = dyn_cast<VarDecl>(Val: ME1->getMemberDecl()))
4408 if (D->isStaticDataMember())
4409 return true;
4410 E1 = ME1->getBase()->IgnoreParenImpCasts();
4411 E2 = ME2->getBase()->IgnoreParenImpCasts();
4412 }
4413
4414 if (isa<CXXThisExpr>(Val: E1) && isa<CXXThisExpr>(Val: E2))
4415 return true;
4416
4417 // A static member variable can end the MemberExpr chain with either
4418 // a MemberExpr or a DeclRefExpr.
4419 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4420 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E))
4421 return DRE->getDecl();
4422 if (const auto *ME = dyn_cast<MemberExpr>(Val: E))
4423 return ME->getMemberDecl();
4424 return nullptr;
4425 };
4426
4427 const ValueDecl *VD1 = getAnyDecl(E1);
4428 const ValueDecl *VD2 = getAnyDecl(E2);
4429 return declaresSameEntity(D1: VD1, D2: VD2);
4430 }
4431 }
4432}
4433
4434/// isArrow - Return true if the base expression is a pointer to vector,
4435/// return false if the base expression is a vector.
4436bool ExtVectorElementExpr::isArrow() const {
4437 return getBase()->getType()->isPointerType();
4438}
4439
4440unsigned ExtVectorElementExpr::getNumElements() const {
4441 if (const VectorType *VT = getType()->getAs<VectorType>())
4442 return VT->getNumElements();
4443 return 1;
4444}
4445
4446unsigned MatrixElementExpr::getNumElements() const {
4447 if (const auto *MT = getType()->getAs<ConstantMatrixType>())
4448 return MT->getNumElementsFlattened();
4449 return 1;
4450}
4451
4452/// containsDuplicateElements - Return true if any Vector element access is
4453/// repeated.
4454bool ExtVectorElementExpr::containsDuplicateElements() const {
4455 // FIXME: Refactor this code to an accessor on the AST node which returns the
4456 // "type" of component access, and share with code below and in Sema.
4457 StringRef Comp = Accessor->getName();
4458
4459 // Halving swizzles do not contain duplicate elements.
4460 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4461 return false;
4462
4463 // Advance past s-char prefix on hex swizzles.
4464 if (Comp[0] == 's' || Comp[0] == 'S')
4465 Comp = Comp.substr(Start: 1);
4466
4467 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4468 if (Comp.substr(Start: i + 1).contains(C: Comp[i]))
4469 return true;
4470
4471 return false;
4472}
4473
4474namespace {
4475struct MatrixAccessorFormat {
4476 bool IsZeroIndexed = false;
4477 unsigned ChunkLen = 0;
4478};
4479
4480static MatrixAccessorFormat GetHLSLMatrixAccessorFormat(StringRef Comp) {
4481 assert(!Comp.empty() && Comp[0] == '_' && "invalid matrix accessor");
4482
4483 MatrixAccessorFormat F;
4484 if (Comp.size() >= 2 && Comp[0] == '_' && Comp[1] == 'm') {
4485 F.IsZeroIndexed = true;
4486 F.ChunkLen = 4; // _mRC
4487 } else {
4488 F.IsZeroIndexed = false;
4489 F.ChunkLen = 3; // _RC
4490 }
4491
4492 assert(F.ChunkLen != 0 && "unrecognized matrix swizzle format");
4493 assert(Comp.size() % F.ChunkLen == 0 &&
4494 "matrix swizzle accessor has invalid length");
4495 return F;
4496}
4497
4498template <typename Fn>
4499static bool ForEachMatrixAccessorIndex(StringRef Comp,
4500 const ConstantMatrixType *MT, Fn &&F) {
4501 auto Format = GetHLSLMatrixAccessorFormat(Comp);
4502
4503 for (unsigned I = 0, E = Comp.size(); I < E; I += Format.ChunkLen) {
4504 unsigned Row = 0, Col = 0;
4505 unsigned ZeroIndexOffset = static_cast<unsigned>(Format.IsZeroIndexed);
4506 unsigned OneIndexOffset = static_cast<unsigned>(!Format.IsZeroIndexed);
4507 Row = static_cast<unsigned>(Comp[I + ZeroIndexOffset + 1] - '0') -
4508 OneIndexOffset;
4509 Col = static_cast<unsigned>(Comp[I + ZeroIndexOffset + 2] - '0') -
4510 OneIndexOffset;
4511
4512 assert(Row < MT->getNumRows() && Col < MT->getNumColumns() &&
4513 "matrix swizzle index out of bounds");
4514 // NOTE: AST layer has no access to LangOptions so we will default to row
4515 // major b\c all other AST matrix representations are row major.
4516 // However in codegen we need to convert to column major if the flag
4517 // requires it.
4518 const unsigned Index = MT->getFlattenedIndex(Row, Column: Col, /*IsRowMajor*/ true);
4519 // Callback returns true to continue, false to stop early.
4520 if (!F(Index))
4521 return false;
4522 }
4523 return true;
4524}
4525
4526} // namespace
4527
4528/// containsDuplicateElements - Return true if any Matrix element access is
4529/// repeated.
4530bool MatrixElementExpr::containsDuplicateElements() const {
4531 StringRef Comp = Accessor->getName();
4532 const auto *MT = getBase()->getType()->castAs<ConstantMatrixType>();
4533
4534 llvm::BitVector Seen(MT->getNumElementsFlattened(), /*t=*/false);
4535 bool HasDup = false;
4536 ForEachMatrixAccessorIndex(Comp, MT, F: [&](unsigned Index) -> bool {
4537 if (Seen[Index]) {
4538 HasDup = true;
4539 return false; // exit early
4540 }
4541 Seen.set(Index);
4542 return true;
4543 });
4544
4545 return HasDup;
4546}
4547
4548/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4549void ExtVectorElementExpr::getEncodedElementAccess(
4550 SmallVectorImpl<uint32_t> &Elts) const {
4551 StringRef Comp = Accessor->getName();
4552 bool isNumericAccessor = false;
4553 if (Comp[0] == 's' || Comp[0] == 'S') {
4554 Comp = Comp.substr(Start: 1);
4555 isNumericAccessor = true;
4556 }
4557
4558 bool isHi = Comp == "hi";
4559 bool isLo = Comp == "lo";
4560 bool isEven = Comp == "even";
4561 bool isOdd = Comp == "odd";
4562
4563 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4564 uint64_t Index;
4565
4566 if (isHi)
4567 Index = e + i;
4568 else if (isLo)
4569 Index = i;
4570 else if (isEven)
4571 Index = 2 * i;
4572 else if (isOdd)
4573 Index = 2 * i + 1;
4574 else
4575 Index = ExtVectorType::getAccessorIdx(c: Comp[i], isNumericAccessor);
4576
4577 Elts.push_back(Elt: Index);
4578 }
4579}
4580
4581void MatrixElementExpr::getEncodedElementAccess(
4582 SmallVectorImpl<uint32_t> &Elts) const {
4583 StringRef Comp = Accessor->getName();
4584 const auto *MT = getBase()->getType()->castAs<ConstantMatrixType>();
4585 ForEachMatrixAccessorIndex(Comp, MT, F: [&](unsigned Index) -> bool {
4586 Elts.push_back(Elt: Index);
4587 return true;
4588 });
4589}
4590
4591ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
4592 QualType Type, SourceLocation BLoc,
4593 SourceLocation RP)
4594 : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4595 BuiltinLoc(BLoc), RParenLoc(RP) {
4596 ShuffleVectorExprBits.NumExprs = args.size();
4597 SubExprs = new (C) Stmt*[args.size()];
4598 for (unsigned i = 0; i != args.size(); i++)
4599 SubExprs[i] = args[i];
4600
4601 setDependence(computeDependence(E: this));
4602}
4603
4604void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
4605 if (SubExprs) C.Deallocate(Ptr: SubExprs);
4606
4607 this->ShuffleVectorExprBits.NumExprs = Exprs.size();
4608 SubExprs = new (C) Stmt *[ShuffleVectorExprBits.NumExprs];
4609 llvm::copy(Range&: Exprs, Out: SubExprs);
4610}
4611
4612GenericSelectionExpr::GenericSelectionExpr(
4613 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4614 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4615 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4616 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4617 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4618 AssocExprs[ResultIndex]->getValueKind(),
4619 AssocExprs[ResultIndex]->getObjectKind()),
4620 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4621 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4622 assert(AssocTypes.size() == AssocExprs.size() &&
4623 "Must have the same number of association expressions"
4624 " and TypeSourceInfo!");
4625 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4626
4627 GenericSelectionExprBits.GenericLoc = GenericLoc;
4628 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4629 ControllingExpr;
4630 llvm::copy(Range&: AssocExprs,
4631 Out: getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4632 llvm::copy(Range&: AssocTypes, Out: getTrailingObjects<TypeSourceInfo *>() +
4633 getIndexOfStartOfAssociatedTypes());
4634
4635 setDependence(computeDependence(E: this, ContainsUnexpandedPack: ContainsUnexpandedParameterPack));
4636}
4637
4638GenericSelectionExpr::GenericSelectionExpr(
4639 const ASTContext &, SourceLocation GenericLoc,
4640 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4641 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4642 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4643 unsigned ResultIndex)
4644 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4645 AssocExprs[ResultIndex]->getValueKind(),
4646 AssocExprs[ResultIndex]->getObjectKind()),
4647 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4648 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4649 assert(AssocTypes.size() == AssocExprs.size() &&
4650 "Must have the same number of association expressions"
4651 " and TypeSourceInfo!");
4652 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4653
4654 GenericSelectionExprBits.GenericLoc = GenericLoc;
4655 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4656 ControllingType;
4657 llvm::copy(Range&: AssocExprs,
4658 Out: getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4659 llvm::copy(Range&: AssocTypes, Out: getTrailingObjects<TypeSourceInfo *>() +
4660 getIndexOfStartOfAssociatedTypes());
4661
4662 setDependence(computeDependence(E: this, ContainsUnexpandedPack: ContainsUnexpandedParameterPack));
4663}
4664
4665GenericSelectionExpr::GenericSelectionExpr(
4666 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4667 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4668 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4669 bool ContainsUnexpandedParameterPack)
4670 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4671 OK_Ordinary),
4672 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4673 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4674 assert(AssocTypes.size() == AssocExprs.size() &&
4675 "Must have the same number of association expressions"
4676 " and TypeSourceInfo!");
4677
4678 GenericSelectionExprBits.GenericLoc = GenericLoc;
4679 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4680 ControllingExpr;
4681 llvm::copy(Range&: AssocExprs,
4682 Out: getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4683 llvm::copy(Range&: AssocTypes, Out: getTrailingObjects<TypeSourceInfo *>() +
4684 getIndexOfStartOfAssociatedTypes());
4685
4686 setDependence(computeDependence(E: this, ContainsUnexpandedPack: ContainsUnexpandedParameterPack));
4687}
4688
4689GenericSelectionExpr::GenericSelectionExpr(
4690 const ASTContext &Context, SourceLocation GenericLoc,
4691 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4692 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4693 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack)
4694 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4695 OK_Ordinary),
4696 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4697 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4698 assert(AssocTypes.size() == AssocExprs.size() &&
4699 "Must have the same number of association expressions"
4700 " and TypeSourceInfo!");
4701
4702 GenericSelectionExprBits.GenericLoc = GenericLoc;
4703 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4704 ControllingType;
4705 llvm::copy(Range&: AssocExprs,
4706 Out: getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4707 llvm::copy(Range&: AssocTypes, Out: getTrailingObjects<TypeSourceInfo *>() +
4708 getIndexOfStartOfAssociatedTypes());
4709
4710 setDependence(computeDependence(E: this, ContainsUnexpandedPack: ContainsUnexpandedParameterPack));
4711}
4712
4713GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4714 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4715
4716GenericSelectionExpr *GenericSelectionExpr::Create(
4717 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4718 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4719 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4720 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4721 unsigned NumAssocs = AssocExprs.size();
4722 void *Mem = Context.Allocate(
4723 Size: totalSizeToAlloc<Stmt *, TypeSourceInfo *>(Counts: 1 + NumAssocs, Counts: NumAssocs),
4724 Align: alignof(GenericSelectionExpr));
4725 return new (Mem) GenericSelectionExpr(
4726 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4727 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4728}
4729
4730GenericSelectionExpr *GenericSelectionExpr::Create(
4731 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4732 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4733 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4734 bool ContainsUnexpandedParameterPack) {
4735 unsigned NumAssocs = AssocExprs.size();
4736 void *Mem = Context.Allocate(
4737 Size: totalSizeToAlloc<Stmt *, TypeSourceInfo *>(Counts: 1 + NumAssocs, Counts: NumAssocs),
4738 Align: alignof(GenericSelectionExpr));
4739 return new (Mem) GenericSelectionExpr(
4740 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4741 RParenLoc, ContainsUnexpandedParameterPack);
4742}
4743
4744GenericSelectionExpr *GenericSelectionExpr::Create(
4745 const ASTContext &Context, SourceLocation GenericLoc,
4746 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4747 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4748 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4749 unsigned ResultIndex) {
4750 unsigned NumAssocs = AssocExprs.size();
4751 void *Mem = Context.Allocate(
4752 Size: totalSizeToAlloc<Stmt *, TypeSourceInfo *>(Counts: 1 + NumAssocs, Counts: NumAssocs),
4753 Align: alignof(GenericSelectionExpr));
4754 return new (Mem) GenericSelectionExpr(
4755 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4756 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4757}
4758
4759GenericSelectionExpr *GenericSelectionExpr::Create(
4760 const ASTContext &Context, SourceLocation GenericLoc,
4761 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4762 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4763 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) {
4764 unsigned NumAssocs = AssocExprs.size();
4765 void *Mem = Context.Allocate(
4766 Size: totalSizeToAlloc<Stmt *, TypeSourceInfo *>(Counts: 1 + NumAssocs, Counts: NumAssocs),
4767 Align: alignof(GenericSelectionExpr));
4768 return new (Mem) GenericSelectionExpr(
4769 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4770 RParenLoc, ContainsUnexpandedParameterPack);
4771}
4772
4773GenericSelectionExpr *
4774GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4775 unsigned NumAssocs) {
4776 void *Mem = Context.Allocate(
4777 Size: totalSizeToAlloc<Stmt *, TypeSourceInfo *>(Counts: 1 + NumAssocs, Counts: NumAssocs),
4778 Align: alignof(GenericSelectionExpr));
4779 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4780}
4781
4782//===----------------------------------------------------------------------===//
4783// DesignatedInitExpr
4784//===----------------------------------------------------------------------===//
4785
4786const IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4787 assert(isFieldDesignator() && "Only valid on a field designator");
4788 if (FieldInfo.NameOrField & 0x01)
4789 return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01);
4790 return getFieldDecl()->getIdentifier();
4791}
4792
4793DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4794 ArrayRef<Designator> Designators,
4795 SourceLocation EqualOrColonLoc,
4796 bool GNUSyntax,
4797 ArrayRef<Expr *> IndexExprs, Expr *Init)
4798 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4799 Init->getObjectKind()),
4800 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4801 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4802 this->Designators = new (C) Designator[NumDesignators];
4803
4804 // Record the initializer itself.
4805 child_iterator Child = child_begin();
4806 *Child++ = Init;
4807
4808 // Copy the designators and their subexpressions, computing
4809 // value-dependence along the way.
4810 unsigned IndexIdx = 0;
4811 for (unsigned I = 0; I != NumDesignators; ++I) {
4812 this->Designators[I] = Designators[I];
4813 if (this->Designators[I].isArrayDesignator()) {
4814 // Copy the index expressions into permanent storage.
4815 *Child++ = IndexExprs[IndexIdx++];
4816 } else if (this->Designators[I].isArrayRangeDesignator()) {
4817 // Copy the start/end expressions into permanent storage.
4818 *Child++ = IndexExprs[IndexIdx++];
4819 *Child++ = IndexExprs[IndexIdx++];
4820 }
4821 }
4822
4823 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4824 setDependence(computeDependence(E: this));
4825}
4826
4827DesignatedInitExpr *DesignatedInitExpr::Create(const ASTContext &C,
4828 ArrayRef<Designator> Designators,
4829 ArrayRef<Expr *> IndexExprs,
4830 SourceLocation ColonOrEqualLoc,
4831 bool UsesColonSyntax,
4832 Expr *Init) {
4833 void *Mem = C.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: IndexExprs.size() + 1),
4834 Align: alignof(DesignatedInitExpr));
4835 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4836 ColonOrEqualLoc, UsesColonSyntax,
4837 IndexExprs, Init);
4838}
4839
4840DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4841 unsigned NumIndexExprs) {
4842 void *Mem = C.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: NumIndexExprs + 1),
4843 Align: alignof(DesignatedInitExpr));
4844 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4845}
4846
4847void DesignatedInitExpr::setDesignators(const ASTContext &C,
4848 const Designator *Desigs,
4849 unsigned NumDesigs) {
4850 Designators = new (C) Designator[NumDesigs];
4851 NumDesignators = NumDesigs;
4852 for (unsigned I = 0; I != NumDesigs; ++I)
4853 Designators[I] = Desigs[I];
4854}
4855
4856SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4857 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4858 if (size() == 1)
4859 return DIE->getDesignator(Idx: 0)->getSourceRange();
4860 return SourceRange(DIE->getDesignator(Idx: 0)->getBeginLoc(),
4861 DIE->getDesignator(Idx: size() - 1)->getEndLoc());
4862}
4863
4864SourceLocation DesignatedInitExpr::getBeginLoc() const {
4865 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4866 Designator &First = *DIE->getDesignator(Idx: 0);
4867 if (First.isFieldDesignator()) {
4868 // Skip past implicit designators for anonymous structs/unions, since
4869 // these do not have valid source locations.
4870 for (unsigned int i = 0; i < DIE->size(); i++) {
4871 Designator &Des = *DIE->getDesignator(Idx: i);
4872 SourceLocation retval = GNUSyntax ? Des.getFieldLoc() : Des.getDotLoc();
4873 if (!retval.isValid())
4874 continue;
4875 return retval;
4876 }
4877 }
4878 return First.getLBracketLoc();
4879}
4880
4881SourceLocation DesignatedInitExpr::getEndLoc() const {
4882 return getInit()->getEndLoc();
4883}
4884
4885Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4886 assert(D.isArrayDesignator() && "Requires array designator");
4887 return getSubExpr(Idx: D.getArrayIndex() + 1);
4888}
4889
4890Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4891 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4892 return getSubExpr(Idx: D.getArrayIndex() + 1);
4893}
4894
4895Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4896 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4897 return getSubExpr(Idx: D.getArrayIndex() + 2);
4898}
4899
4900/// Replaces the designator at index @p Idx with the series
4901/// of designators in [First, Last).
4902void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4903 const Designator *First,
4904 const Designator *Last) {
4905 unsigned NumNewDesignators = Last - First;
4906 if (NumNewDesignators == 0) {
4907 std::copy_backward(first: Designators + Idx + 1,
4908 last: Designators + NumDesignators,
4909 result: Designators + Idx);
4910 --NumNewDesignators;
4911 return;
4912 }
4913 if (NumNewDesignators == 1) {
4914 Designators[Idx] = *First;
4915 return;
4916 }
4917
4918 Designator *NewDesignators
4919 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4920 std::copy(first: Designators, last: Designators + Idx, result: NewDesignators);
4921 std::copy(first: First, last: Last, result: NewDesignators + Idx);
4922 std::copy(first: Designators + Idx + 1, last: Designators + NumDesignators,
4923 result: NewDesignators + Idx + NumNewDesignators);
4924 Designators = NewDesignators;
4925 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4926}
4927
4928DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4929 SourceLocation lBraceLoc,
4930 Expr *baseExpr,
4931 SourceLocation rBraceLoc)
4932 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4933 OK_Ordinary) {
4934 BaseAndUpdaterExprs[0] = baseExpr;
4935
4936 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, {}, rBraceLoc);
4937 ILE->setType(baseExpr->getType());
4938 BaseAndUpdaterExprs[1] = ILE;
4939
4940 // FIXME: this is wrong, set it correctly.
4941 setDependence(ExprDependence::None);
4942}
4943
4944SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4945 return getBase()->getBeginLoc();
4946}
4947
4948SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4949 return getBase()->getEndLoc();
4950}
4951
4952ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4953 SourceLocation RParenLoc)
4954 : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4955 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4956 ParenListExprBits.NumExprs = Exprs.size();
4957 llvm::copy(Range&: Exprs, Out: getTrailingObjects());
4958 setDependence(computeDependence(E: this));
4959}
4960
4961ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4962 : Expr(ParenListExprClass, Empty) {
4963 ParenListExprBits.NumExprs = NumExprs;
4964}
4965
4966ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4967 SourceLocation LParenLoc,
4968 ArrayRef<Expr *> Exprs,
4969 SourceLocation RParenLoc) {
4970 void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: Exprs.size()),
4971 Align: alignof(ParenListExpr));
4972 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4973}
4974
4975ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4976 unsigned NumExprs) {
4977 void *Mem =
4978 Ctx.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: NumExprs), Align: alignof(ParenListExpr));
4979 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4980}
4981
4982/// Certain overflow-dependent code patterns can have their integer overflow
4983/// sanitization disabled. Check for the common pattern `if (a + b < a)` and
4984/// return the resulting BinaryOperator responsible for the addition so we can
4985/// elide overflow checks during codegen.
4986static std::optional<BinaryOperator *>
4987getOverflowPatternBinOp(const BinaryOperator *E) {
4988 Expr *Addition, *ComparedTo;
4989 if (E->getOpcode() == BO_LT) {
4990 Addition = E->getLHS();
4991 ComparedTo = E->getRHS();
4992 } else if (E->getOpcode() == BO_GT) {
4993 Addition = E->getRHS();
4994 ComparedTo = E->getLHS();
4995 } else {
4996 return {};
4997 }
4998
4999 const Expr *AddLHS = nullptr, *AddRHS = nullptr;
5000 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: Addition);
5001
5002 if (BO && BO->getOpcode() == clang::BO_Add) {
5003 // now store addends for lookup on other side of '>'
5004 AddLHS = BO->getLHS();
5005 AddRHS = BO->getRHS();
5006 }
5007
5008 if (!AddLHS || !AddRHS)
5009 return {};
5010
5011 const Decl *LHSDecl, *RHSDecl, *OtherDecl;
5012
5013 LHSDecl = AddLHS->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
5014 RHSDecl = AddRHS->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
5015 OtherDecl = ComparedTo->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
5016
5017 if (!OtherDecl)
5018 return {};
5019
5020 if (!LHSDecl && !RHSDecl)
5021 return {};
5022
5023 if ((LHSDecl && LHSDecl == OtherDecl && LHSDecl != RHSDecl) ||
5024 (RHSDecl && RHSDecl == OtherDecl && RHSDecl != LHSDecl))
5025 return BO;
5026 return {};
5027}
5028
5029/// Compute and set the OverflowPatternExclusion bit based on whether the
5030/// BinaryOperator expression matches an overflow pattern being ignored by
5031/// -fsanitize-undefined-ignore-overflow-pattern=add-signed-overflow-test or
5032/// -fsanitize-undefined-ignore-overflow-pattern=add-unsigned-overflow-test
5033static void computeOverflowPatternExclusion(const ASTContext &Ctx,
5034 const BinaryOperator *E) {
5035 std::optional<BinaryOperator *> Result = getOverflowPatternBinOp(E);
5036 if (!Result.has_value())
5037 return;
5038 QualType AdditionResultType = Result.value()->getType();
5039
5040 if ((AdditionResultType->isSignedIntegerType() &&
5041 Ctx.getLangOpts().isOverflowPatternExcluded(
5042 Kind: LangOptions::OverflowPatternExclusionKind::AddSignedOverflowTest)) ||
5043 (AdditionResultType->isUnsignedIntegerType() &&
5044 Ctx.getLangOpts().isOverflowPatternExcluded(
5045 Kind: LangOptions::OverflowPatternExclusionKind::AddUnsignedOverflowTest)))
5046 Result.value()->setExcludedOverflowPattern(true);
5047}
5048
5049BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
5050 Opcode opc, QualType ResTy, ExprValueKind VK,
5051 ExprObjectKind OK, SourceLocation opLoc,
5052 FPOptionsOverride FPFeatures)
5053 : Expr(BinaryOperatorClass, ResTy, VK, OK) {
5054 BinaryOperatorBits.Opc = opc;
5055 assert(!isCompoundAssignmentOp() &&
5056 "Use CompoundAssignOperator for compound assignments");
5057 BinaryOperatorBits.OpLoc = opLoc;
5058 BinaryOperatorBits.ExcludedOverflowPattern = false;
5059 SubExprs[LHS] = lhs;
5060 SubExprs[RHS] = rhs;
5061 computeOverflowPatternExclusion(Ctx, E: this);
5062 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
5063 if (hasStoredFPFeatures())
5064 setStoredFPFeatures(FPFeatures);
5065 setDependence(computeDependence(E: this));
5066}
5067
5068BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
5069 Opcode opc, QualType ResTy, ExprValueKind VK,
5070 ExprObjectKind OK, SourceLocation opLoc,
5071 FPOptionsOverride FPFeatures, bool dead2)
5072 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
5073 BinaryOperatorBits.Opc = opc;
5074 BinaryOperatorBits.ExcludedOverflowPattern = false;
5075 assert(isCompoundAssignmentOp() &&
5076 "Use CompoundAssignOperator for compound assignments");
5077 BinaryOperatorBits.OpLoc = opLoc;
5078 SubExprs[LHS] = lhs;
5079 SubExprs[RHS] = rhs;
5080 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
5081 if (hasStoredFPFeatures())
5082 setStoredFPFeatures(FPFeatures);
5083 setDependence(computeDependence(E: this));
5084}
5085
5086BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,
5087 bool HasFPFeatures) {
5088 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
5089 void *Mem =
5090 C.Allocate(Size: sizeof(BinaryOperator) + Extra, Align: alignof(BinaryOperator));
5091 return new (Mem) BinaryOperator(EmptyShell());
5092}
5093
5094BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,
5095 Expr *rhs, Opcode opc, QualType ResTy,
5096 ExprValueKind VK, ExprObjectKind OK,
5097 SourceLocation opLoc,
5098 FPOptionsOverride FPFeatures) {
5099 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
5100 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
5101 void *Mem =
5102 C.Allocate(Size: sizeof(BinaryOperator) + Extra, Align: alignof(BinaryOperator));
5103 return new (Mem)
5104 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
5105}
5106
5107CompoundAssignOperator *
5108CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
5109 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
5110 void *Mem = C.Allocate(Size: sizeof(CompoundAssignOperator) + Extra,
5111 Align: alignof(CompoundAssignOperator));
5112 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
5113}
5114
5115CompoundAssignOperator *
5116CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,
5117 Opcode opc, QualType ResTy, ExprValueKind VK,
5118 ExprObjectKind OK, SourceLocation opLoc,
5119 FPOptionsOverride FPFeatures,
5120 QualType CompLHSType, QualType CompResultType) {
5121 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
5122 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
5123 void *Mem = C.Allocate(Size: sizeof(CompoundAssignOperator) + Extra,
5124 Align: alignof(CompoundAssignOperator));
5125 return new (Mem)
5126 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
5127 CompLHSType, CompResultType);
5128}
5129
5130UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,
5131 bool hasFPFeatures) {
5132 void *Mem = C.Allocate(Size: totalSizeToAlloc<FPOptionsOverride>(Counts: hasFPFeatures),
5133 Align: alignof(UnaryOperator));
5134 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
5135}
5136
5137UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,
5138 QualType type, ExprValueKind VK, ExprObjectKind OK,
5139 SourceLocation l, bool CanOverflow,
5140 FPOptionsOverride FPFeatures)
5141 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
5142 UnaryOperatorBits.Opc = opc;
5143 UnaryOperatorBits.CanOverflow = CanOverflow;
5144 UnaryOperatorBits.Loc = l;
5145 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
5146 if (hasStoredFPFeatures())
5147 setStoredFPFeatures(FPFeatures);
5148 setDependence(computeDependence(E: this, Ctx));
5149}
5150
5151UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,
5152 Opcode opc, QualType type,
5153 ExprValueKind VK, ExprObjectKind OK,
5154 SourceLocation l, bool CanOverflow,
5155 FPOptionsOverride FPFeatures) {
5156 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
5157 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(Counts: HasFPFeatures);
5158 void *Mem = C.Allocate(Size, Align: alignof(UnaryOperator));
5159 return new (Mem)
5160 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
5161}
5162
5163const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
5164 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(Val: e))
5165 e = ewc->getSubExpr();
5166 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(Val: e))
5167 e = m->getSubExpr();
5168 e = cast<CXXConstructExpr>(Val: e)->getArg(Arg: 0);
5169 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(Val: e))
5170 e = ice->getSubExpr();
5171 return cast<OpaqueValueExpr>(Val: e);
5172}
5173
5174PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
5175 EmptyShell sh,
5176 unsigned numSemanticExprs) {
5177 void *buffer =
5178 Context.Allocate(Size: totalSizeToAlloc<Expr *>(Counts: 1 + numSemanticExprs),
5179 Align: alignof(PseudoObjectExpr));
5180 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
5181}
5182
5183PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
5184 : Expr(PseudoObjectExprClass, shell) {
5185 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
5186}
5187
5188PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
5189 ArrayRef<Expr*> semantics,
5190 unsigned resultIndex) {
5191 assert(syntax && "no syntactic expression!");
5192 assert(semantics.size() && "no semantic expressions!");
5193
5194 QualType type;
5195 ExprValueKind VK;
5196 if (resultIndex == NoResult) {
5197 type = C.VoidTy;
5198 VK = VK_PRValue;
5199 } else {
5200 assert(resultIndex < semantics.size());
5201 type = semantics[resultIndex]->getType();
5202 VK = semantics[resultIndex]->getValueKind();
5203 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
5204 }
5205
5206 void *buffer = C.Allocate(Size: totalSizeToAlloc<Expr *>(Counts: semantics.size() + 1),
5207 Align: alignof(PseudoObjectExpr));
5208 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
5209 resultIndex);
5210}
5211
5212PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
5213 Expr *syntax, ArrayRef<Expr *> semantics,
5214 unsigned resultIndex)
5215 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
5216 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
5217 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
5218 MutableArrayRef<Expr *> Trail = getTrailingObjects(N: semantics.size() + 1);
5219 Trail[0] = syntax;
5220
5221 assert(llvm::all_of(semantics,
5222 [](const Expr *E) {
5223 return !isa<OpaqueValueExpr>(E) ||
5224 cast<OpaqueValueExpr>(E)->getSourceExpr() !=
5225 nullptr;
5226 }) &&
5227 "opaque-value semantic expressions for pseudo-object "
5228 "operations must have sources");
5229
5230 llvm::copy(Range&: semantics, Out: Trail.drop_front().begin());
5231 setDependence(computeDependence(E: this));
5232}
5233
5234//===----------------------------------------------------------------------===//
5235// Child Iterators for iterating over subexpressions/substatements
5236//===----------------------------------------------------------------------===//
5237
5238// UnaryExprOrTypeTraitExpr
5239Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
5240 const_child_range CCR =
5241 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
5242 return child_range(cast_away_const(RHS: CCR.begin()), cast_away_const(RHS: CCR.end()));
5243}
5244
5245Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
5246 // If this is of a type and the type is a VLA type (and not a typedef), the
5247 // size expression of the VLA needs to be treated as an executable expression.
5248 // Why isn't this weirdness documented better in StmtIterator?
5249 if (isArgumentType()) {
5250 if (const VariableArrayType *T =
5251 dyn_cast<VariableArrayType>(Val: getArgumentType().getTypePtr()))
5252 return const_child_range(const_child_iterator(T), const_child_iterator());
5253 return const_child_range(const_child_iterator(), const_child_iterator());
5254 }
5255 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
5256}
5257
5258AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
5259 AtomicOp op, SourceLocation RP)
5260 : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
5261 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
5262 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
5263 for (unsigned i = 0; i != args.size(); i++)
5264 SubExprs[i] = args[i];
5265 setDependence(computeDependence(E: this));
5266}
5267
5268unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
5269 switch (Op) {
5270 case AO__c11_atomic_init:
5271 case AO__opencl_atomic_init:
5272 case AO__c11_atomic_load:
5273 case AO__atomic_load_n:
5274 case AO__atomic_test_and_set:
5275 case AO__atomic_clear:
5276 return 2;
5277
5278 case AO__scoped_atomic_load_n:
5279 case AO__opencl_atomic_load:
5280 case AO__hip_atomic_load:
5281 case AO__c11_atomic_store:
5282 case AO__c11_atomic_exchange:
5283 case AO__atomic_load:
5284 case AO__atomic_store:
5285 case AO__atomic_store_n:
5286 case AO__atomic_exchange_n:
5287 case AO__c11_atomic_fetch_add:
5288 case AO__c11_atomic_fetch_sub:
5289 case AO__c11_atomic_fetch_and:
5290 case AO__c11_atomic_fetch_or:
5291 case AO__c11_atomic_fetch_xor:
5292 case AO__c11_atomic_fetch_nand:
5293 case AO__c11_atomic_fetch_max:
5294 case AO__c11_atomic_fetch_min:
5295 case AO__atomic_fetch_add:
5296 case AO__atomic_fetch_sub:
5297 case AO__atomic_fetch_and:
5298 case AO__atomic_fetch_or:
5299 case AO__atomic_fetch_xor:
5300 case AO__atomic_fetch_nand:
5301 case AO__atomic_add_fetch:
5302 case AO__atomic_sub_fetch:
5303 case AO__atomic_and_fetch:
5304 case AO__atomic_or_fetch:
5305 case AO__atomic_xor_fetch:
5306 case AO__atomic_nand_fetch:
5307 case AO__atomic_min_fetch:
5308 case AO__atomic_max_fetch:
5309 case AO__atomic_fetch_min:
5310 case AO__atomic_fetch_max:
5311 case AO__atomic_fetch_uinc:
5312 case AO__atomic_fetch_udec:
5313 return 3;
5314
5315 case AO__scoped_atomic_load:
5316 case AO__scoped_atomic_store:
5317 case AO__scoped_atomic_store_n:
5318 case AO__scoped_atomic_fetch_add:
5319 case AO__scoped_atomic_fetch_sub:
5320 case AO__scoped_atomic_fetch_and:
5321 case AO__scoped_atomic_fetch_or:
5322 case AO__scoped_atomic_fetch_xor:
5323 case AO__scoped_atomic_fetch_nand:
5324 case AO__scoped_atomic_add_fetch:
5325 case AO__scoped_atomic_sub_fetch:
5326 case AO__scoped_atomic_and_fetch:
5327 case AO__scoped_atomic_or_fetch:
5328 case AO__scoped_atomic_xor_fetch:
5329 case AO__scoped_atomic_nand_fetch:
5330 case AO__scoped_atomic_min_fetch:
5331 case AO__scoped_atomic_max_fetch:
5332 case AO__scoped_atomic_fetch_min:
5333 case AO__scoped_atomic_fetch_max:
5334 case AO__scoped_atomic_exchange_n:
5335 case AO__scoped_atomic_fetch_uinc:
5336 case AO__scoped_atomic_fetch_udec:
5337 case AO__hip_atomic_exchange:
5338 case AO__hip_atomic_fetch_add:
5339 case AO__hip_atomic_fetch_sub:
5340 case AO__hip_atomic_fetch_and:
5341 case AO__hip_atomic_fetch_or:
5342 case AO__hip_atomic_fetch_xor:
5343 case AO__hip_atomic_fetch_min:
5344 case AO__hip_atomic_fetch_max:
5345 case AO__opencl_atomic_store:
5346 case AO__hip_atomic_store:
5347 case AO__opencl_atomic_exchange:
5348 case AO__opencl_atomic_fetch_add:
5349 case AO__opencl_atomic_fetch_sub:
5350 case AO__opencl_atomic_fetch_and:
5351 case AO__opencl_atomic_fetch_or:
5352 case AO__opencl_atomic_fetch_xor:
5353 case AO__opencl_atomic_fetch_min:
5354 case AO__opencl_atomic_fetch_max:
5355 case AO__atomic_exchange:
5356 return 4;
5357
5358 case AO__scoped_atomic_exchange:
5359 case AO__c11_atomic_compare_exchange_strong:
5360 case AO__c11_atomic_compare_exchange_weak:
5361 return 5;
5362 case AO__hip_atomic_compare_exchange_strong:
5363 case AO__opencl_atomic_compare_exchange_strong:
5364 case AO__opencl_atomic_compare_exchange_weak:
5365 case AO__hip_atomic_compare_exchange_weak:
5366 case AO__atomic_compare_exchange:
5367 case AO__atomic_compare_exchange_n:
5368 return 6;
5369
5370 case AO__scoped_atomic_compare_exchange:
5371 case AO__scoped_atomic_compare_exchange_n:
5372 return 7;
5373 }
5374 llvm_unreachable("unknown atomic op");
5375}
5376
5377QualType AtomicExpr::getValueType() const {
5378 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
5379 if (auto AT = T->getAs<AtomicType>())
5380 return AT->getValueType();
5381 return T;
5382}
5383
5384QualType ArraySectionExpr::getBaseOriginalType(const Expr *Base) {
5385 unsigned ArraySectionCount = 0;
5386 while (auto *OASE = dyn_cast<ArraySectionExpr>(Val: Base->IgnoreParens())) {
5387 Base = OASE->getBase();
5388 ++ArraySectionCount;
5389 }
5390 while (auto *ASE =
5391 dyn_cast<ArraySubscriptExpr>(Val: Base->IgnoreParenImpCasts())) {
5392 Base = ASE->getBase();
5393 ++ArraySectionCount;
5394 }
5395 Base = Base->IgnoreParenImpCasts();
5396 auto OriginalTy = Base->getType();
5397 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Base))
5398 if (auto *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl()))
5399 OriginalTy = PVD->getOriginalType().getNonReferenceType();
5400
5401 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
5402 if (OriginalTy->isAnyPointerType())
5403 OriginalTy = OriginalTy->getPointeeType();
5404 else if (OriginalTy->isArrayType())
5405 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
5406 else
5407 return {};
5408 }
5409 return OriginalTy;
5410}
5411
5412QualType ArraySectionExpr::getElementType() const {
5413 QualType BaseTy = getBase()->IgnoreParenImpCasts()->getType();
5414 // We only have to look into the array section exprs, else we will get the
5415 // type of the base, which should already be valid.
5416 if (auto *ASE = dyn_cast<ArraySectionExpr>(Val: getBase()->IgnoreParenImpCasts()))
5417 BaseTy = ASE->getElementType();
5418
5419 if (BaseTy->isAnyPointerType())
5420 return BaseTy->getPointeeType();
5421 if (BaseTy->isArrayType())
5422 return BaseTy->castAsArrayTypeUnsafe()->getElementType();
5423
5424 // If this isn't a pointer or array, the base is a dependent expression, so
5425 // just return the BaseTy anyway.
5426 assert(BaseTy->isInstantiationDependentType());
5427 return BaseTy;
5428}
5429
5430QualType ArraySectionExpr::getBaseType() const {
5431 // We only have to look into the array section exprs, else we will get the
5432 // type of the base, which should already be valid.
5433 if (auto *ASE = dyn_cast<ArraySectionExpr>(Val: getBase()->IgnoreParenImpCasts()))
5434 return ASE->getElementType();
5435
5436 return getBase()->IgnoreParenImpCasts()->getType();
5437}
5438
5439RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
5440 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
5441 : Expr(RecoveryExprClass, T.getNonReferenceType(),
5442 T->isDependentType() ? VK_LValue : getValueKindForType(T),
5443 OK_Ordinary),
5444 BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
5445 assert(!T.isNull());
5446 assert(!llvm::is_contained(SubExprs, nullptr));
5447
5448 llvm::copy(Range&: SubExprs, Out: getTrailingObjects());
5449 setDependence(computeDependence(E: this));
5450}
5451
5452RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,
5453 SourceLocation BeginLoc,
5454 SourceLocation EndLoc,
5455 ArrayRef<Expr *> SubExprs) {
5456 void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<Expr *>(Counts: SubExprs.size()),
5457 Align: alignof(RecoveryExpr));
5458 return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
5459}
5460
5461RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
5462 void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<Expr *>(Counts: NumSubExprs),
5463 Align: alignof(RecoveryExpr));
5464 return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
5465}
5466
5467void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
5468 assert(
5469 NumDims == Dims.size() &&
5470 "Preallocated number of dimensions is different from the provided one.");
5471 llvm::copy(Range&: Dims, Out: getTrailingObjects<Expr *>());
5472}
5473
5474void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
5475 assert(
5476 NumDims == BR.size() &&
5477 "Preallocated number of dimensions is different from the provided one.");
5478 llvm::copy(Range&: BR, Out: getTrailingObjects<SourceRange>());
5479}
5480
5481OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
5482 SourceLocation L, SourceLocation R,
5483 ArrayRef<Expr *> Dims)
5484 : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
5485 RPLoc(R), NumDims(Dims.size()) {
5486 setBase(Op);
5487 setDimensions(Dims);
5488 setDependence(computeDependence(E: this));
5489}
5490
5491OMPArrayShapingExpr *
5492OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,
5493 SourceLocation L, SourceLocation R,
5494 ArrayRef<Expr *> Dims,
5495 ArrayRef<SourceRange> BracketRanges) {
5496 assert(Dims.size() == BracketRanges.size() &&
5497 "Different number of dimensions and brackets ranges.");
5498 void *Mem = Context.Allocate(
5499 Size: totalSizeToAlloc<Expr *, SourceRange>(Counts: Dims.size() + 1, Counts: Dims.size()),
5500 Align: alignof(OMPArrayShapingExpr));
5501 auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
5502 E->setBracketsRanges(BracketRanges);
5503 return E;
5504}
5505
5506OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
5507 unsigned NumDims) {
5508 void *Mem = Context.Allocate(
5509 Size: totalSizeToAlloc<Expr *, SourceRange>(Counts: NumDims + 1, Counts: NumDims),
5510 Align: alignof(OMPArrayShapingExpr));
5511 return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
5512}
5513
5514void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
5515 getTrailingObjects<Decl *>(N: NumIterators)[I] = D;
5516}
5517
5518void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
5519 assert(I < NumIterators &&
5520 "Idx is greater or equal the number of iterators definitions.");
5521 getTrailingObjects<
5522 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5523 static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
5524}
5525
5526void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
5527 SourceLocation ColonLoc, Expr *End,
5528 SourceLocation SecondColonLoc,
5529 Expr *Step) {
5530 assert(I < NumIterators &&
5531 "Idx is greater or equal the number of iterators definitions.");
5532 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5533 static_cast<int>(RangeExprOffset::Begin)] =
5534 Begin;
5535 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5536 static_cast<int>(RangeExprOffset::End)] = End;
5537 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5538 static_cast<int>(RangeExprOffset::Step)] = Step;
5539 getTrailingObjects<
5540 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5541 static_cast<int>(RangeLocOffset::FirstColonLoc)] =
5542 ColonLoc;
5543 getTrailingObjects<
5544 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5545 static_cast<int>(RangeLocOffset::SecondColonLoc)] =
5546 SecondColonLoc;
5547}
5548
5549Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {
5550 return getTrailingObjects<Decl *>()[I];
5551}
5552
5553OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {
5554 IteratorRange Res;
5555 Res.Begin =
5556 getTrailingObjects<Expr *>()[I * static_cast<int>(
5557 RangeExprOffset::Total) +
5558 static_cast<int>(RangeExprOffset::Begin)];
5559 Res.End =
5560 getTrailingObjects<Expr *>()[I * static_cast<int>(
5561 RangeExprOffset::Total) +
5562 static_cast<int>(RangeExprOffset::End)];
5563 Res.Step =
5564 getTrailingObjects<Expr *>()[I * static_cast<int>(
5565 RangeExprOffset::Total) +
5566 static_cast<int>(RangeExprOffset::Step)];
5567 return Res;
5568}
5569
5570SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {
5571 return getTrailingObjects<
5572 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5573 static_cast<int>(RangeLocOffset::AssignLoc)];
5574}
5575
5576SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {
5577 return getTrailingObjects<
5578 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5579 static_cast<int>(RangeLocOffset::FirstColonLoc)];
5580}
5581
5582SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {
5583 return getTrailingObjects<
5584 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5585 static_cast<int>(RangeLocOffset::SecondColonLoc)];
5586}
5587
5588void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
5589 getTrailingObjects<OMPIteratorHelperData>()[I] = D;
5590}
5591
5592OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {
5593 return getTrailingObjects<OMPIteratorHelperData>()[I];
5594}
5595
5596const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {
5597 return getTrailingObjects<OMPIteratorHelperData>()[I];
5598}
5599
5600OMPIteratorExpr::OMPIteratorExpr(
5601 QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
5602 SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
5603 ArrayRef<OMPIteratorHelperData> Helpers)
5604 : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
5605 IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
5606 NumIterators(Data.size()) {
5607 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
5608 const IteratorDefinition &D = Data[I];
5609 setIteratorDeclaration(I, D: D.IteratorDecl);
5610 setAssignmentLoc(I, Loc: D.AssignmentLoc);
5611 setIteratorRange(I, Begin: D.Range.Begin, ColonLoc: D.ColonLoc, End: D.Range.End,
5612 SecondColonLoc: D.SecondColonLoc, Step: D.Range.Step);
5613 setHelper(I, D: Helpers[I]);
5614 }
5615 setDependence(computeDependence(E: this));
5616}
5617
5618OMPIteratorExpr *
5619OMPIteratorExpr::Create(const ASTContext &Context, QualType T,
5620 SourceLocation IteratorKwLoc, SourceLocation L,
5621 SourceLocation R,
5622 ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
5623 ArrayRef<OMPIteratorHelperData> Helpers) {
5624 assert(Data.size() == Helpers.size() &&
5625 "Data and helpers must have the same size.");
5626 void *Mem = Context.Allocate(
5627 Size: totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5628 Counts: Data.size(), Counts: Data.size() * static_cast<int>(RangeExprOffset::Total),
5629 Counts: Data.size() * static_cast<int>(RangeLocOffset::Total),
5630 Counts: Helpers.size()),
5631 Align: alignof(OMPIteratorExpr));
5632 return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
5633}
5634
5635OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
5636 unsigned NumIterators) {
5637 void *Mem = Context.Allocate(
5638 Size: totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5639 Counts: NumIterators, Counts: NumIterators * static_cast<int>(RangeExprOffset::Total),
5640 Counts: NumIterators * static_cast<int>(RangeLocOffset::Total), Counts: NumIterators),
5641 Align: alignof(OMPIteratorExpr));
5642 return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);
5643}
5644
5645HLSLOutArgExpr *HLSLOutArgExpr::Create(const ASTContext &C, QualType Ty,
5646 OpaqueValueExpr *Base,
5647 OpaqueValueExpr *OpV, Expr *WB,
5648 bool IsInOut) {
5649 return new (C) HLSLOutArgExpr(Ty, Base, OpV, WB, IsInOut);
5650}
5651
5652HLSLOutArgExpr *HLSLOutArgExpr::CreateEmpty(const ASTContext &C) {
5653 return new (C) HLSLOutArgExpr(EmptyShell());
5654}
5655
5656OpenACCAsteriskSizeExpr *OpenACCAsteriskSizeExpr::Create(const ASTContext &C,
5657 SourceLocation Loc) {
5658 return new (C) OpenACCAsteriskSizeExpr(Loc, C.IntTy);
5659}
5660
5661OpenACCAsteriskSizeExpr *
5662OpenACCAsteriskSizeExpr::CreateEmpty(const ASTContext &C) {
5663 return new (C) OpenACCAsteriskSizeExpr({}, C.IntTy);
5664}
5665
5666ConvertVectorExpr *ConvertVectorExpr::CreateEmpty(const ASTContext &C,
5667 bool hasFPFeatures) {
5668 void *Mem = C.Allocate(Size: totalSizeToAlloc<FPOptionsOverride>(Counts: hasFPFeatures),
5669 Align: alignof(ConvertVectorExpr));
5670 return new (Mem) ConvertVectorExpr(hasFPFeatures, EmptyShell());
5671}
5672
5673ConvertVectorExpr *ConvertVectorExpr::Create(
5674 const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
5675 ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc,
5676 SourceLocation RParenLoc, FPOptionsOverride FPFeatures) {
5677 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
5678 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(Counts: HasFPFeatures);
5679 void *Mem = C.Allocate(Size, Align: alignof(ConvertVectorExpr));
5680 return new (Mem) ConvertVectorExpr(SrcExpr, TI, DstType, VK, OK, BuiltinLoc,
5681 RParenLoc, FPFeatures);
5682}
5683
5684APValue &CompoundLiteralExpr::getOrCreateStaticValue(ASTContext &Ctx) const {
5685 assert(hasStaticStorage());
5686 if (!StaticValue) {
5687 StaticValue = new (Ctx) APValue;
5688 Ctx.addDestruction(Ptr: StaticValue);
5689 }
5690 return *StaticValue;
5691}
5692
5693APValue &CompoundLiteralExpr::getStaticValue() const {
5694 assert(StaticValue);
5695 return *StaticValue;
5696}
5697