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