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