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