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