1//===- Stmt.h - Classes for representing statements -------------*- C++ -*-===//
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 defines the Stmt interface and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_STMT_H
14#define LLVM_CLANG_AST_STMT_H
15
16#include "clang/AST/DeclGroup.h"
17#include "clang/AST/DependenceFlags.h"
18#include "clang/AST/StmtIterator.h"
19#include "clang/Basic/CapturedStmt.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/LLVM.h"
22#include "clang/Basic/SourceLocation.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/BitmaskEnum.h"
25#include "llvm/ADT/PointerIntPair.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/iterator.h"
28#include "llvm/ADT/iterator_range.h"
29#include "llvm/Support/Casting.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/ErrorHandling.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37
38namespace llvm {
39
40class FoldingSetNodeID;
41
42} // namespace llvm
43
44namespace clang {
45
46class ASTContext;
47class Attr;
48class CapturedDecl;
49class Decl;
50class Expr;
51class AddrLabelExpr;
52class LabelDecl;
53class ODRHash;
54class PrinterHelper;
55struct PrintingPolicy;
56class RecordDecl;
57class SourceManager;
58class StringLiteral;
59class Token;
60class VarDecl;
61
62//===----------------------------------------------------------------------===//
63// AST classes for statements.
64//===----------------------------------------------------------------------===//
65
66/// Stmt - This represents one statement.
67///
68class alignas(void *) Stmt {
69public:
70 enum StmtClass {
71 NoStmtClass = 0,
72#define STMT(CLASS, PARENT) CLASS##Class,
73#define STMT_RANGE(BASE, FIRST, LAST) \
74 first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class,
75#define LAST_STMT_RANGE(BASE, FIRST, LAST) \
76 first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class
77#define ABSTRACT_STMT(STMT)
78#include "clang/AST/StmtNodes.inc"
79 };
80
81 // Make vanilla 'new' and 'delete' illegal for Stmts.
82protected:
83 friend class ASTStmtReader;
84 friend class ASTStmtWriter;
85
86 void *operator new(size_t bytes) noexcept {
87 llvm_unreachable("Stmts cannot be allocated with regular 'new'.");
88 }
89
90 void operator delete(void *data) noexcept {
91 llvm_unreachable("Stmts cannot be released with regular 'delete'.");
92 }
93
94 //===--- Statement bitfields classes ---===//
95
96 class StmtBitfields {
97 friend class ASTStmtReader;
98 friend class ASTStmtWriter;
99 friend class Stmt;
100
101 /// The statement class.
102 unsigned sClass : 8;
103 };
104 enum { NumStmtBits = 8 };
105
106 class NullStmtBitfields {
107 friend class ASTStmtReader;
108 friend class ASTStmtWriter;
109 friend class NullStmt;
110
111 unsigned : NumStmtBits;
112
113 /// True if the null statement was preceded by an empty macro, e.g:
114 /// @code
115 /// #define CALL(x)
116 /// CALL(0);
117 /// @endcode
118 unsigned HasLeadingEmptyMacro : 1;
119
120 /// The location of the semi-colon.
121 SourceLocation SemiLoc;
122 };
123
124 class CompoundStmtBitfields {
125 friend class ASTStmtReader;
126 friend class CompoundStmt;
127
128 unsigned : NumStmtBits;
129
130 unsigned NumStmts : 32 - NumStmtBits;
131
132 /// The location of the opening "{".
133 SourceLocation LBraceLoc;
134 };
135
136 class LabelStmtBitfields {
137 friend class LabelStmt;
138
139 unsigned : NumStmtBits;
140
141 SourceLocation IdentLoc;
142 };
143
144 class AttributedStmtBitfields {
145 friend class ASTStmtReader;
146 friend class AttributedStmt;
147
148 unsigned : NumStmtBits;
149
150 /// Number of attributes.
151 unsigned NumAttrs : 32 - NumStmtBits;
152
153 /// The location of the attribute.
154 SourceLocation AttrLoc;
155 };
156
157 class IfStmtBitfields {
158 friend class ASTStmtReader;
159 friend class IfStmt;
160
161 unsigned : NumStmtBits;
162
163 /// True if this if statement is a constexpr if.
164 unsigned IsConstexpr : 1;
165
166 /// True if this if statement has storage for an else statement.
167 unsigned HasElse : 1;
168
169 /// True if this if statement has storage for a variable declaration.
170 unsigned HasVar : 1;
171
172 /// True if this if statement has storage for an init statement.
173 unsigned HasInit : 1;
174
175 /// The location of the "if".
176 SourceLocation IfLoc;
177 };
178
179 class SwitchStmtBitfields {
180 friend class SwitchStmt;
181
182 unsigned : NumStmtBits;
183
184 /// True if the SwitchStmt has storage for an init statement.
185 unsigned HasInit : 1;
186
187 /// True if the SwitchStmt has storage for a condition variable.
188 unsigned HasVar : 1;
189
190 /// If the SwitchStmt is a switch on an enum value, records whether all
191 /// the enum values were covered by CaseStmts. The coverage information
192 /// value is meant to be a hint for possible clients.
193 unsigned AllEnumCasesCovered : 1;
194
195 /// The location of the "switch".
196 SourceLocation SwitchLoc;
197 };
198
199 class WhileStmtBitfields {
200 friend class ASTStmtReader;
201 friend class WhileStmt;
202
203 unsigned : NumStmtBits;
204
205 /// True if the WhileStmt has storage for a condition variable.
206 unsigned HasVar : 1;
207
208 /// The location of the "while".
209 SourceLocation WhileLoc;
210 };
211
212 class DoStmtBitfields {
213 friend class DoStmt;
214
215 unsigned : NumStmtBits;
216
217 /// The location of the "do".
218 SourceLocation DoLoc;
219 };
220
221 class ForStmtBitfields {
222 friend class ForStmt;
223
224 unsigned : NumStmtBits;
225
226 /// The location of the "for".
227 SourceLocation ForLoc;
228 };
229
230 class GotoStmtBitfields {
231 friend class GotoStmt;
232 friend class IndirectGotoStmt;
233
234 unsigned : NumStmtBits;
235
236 /// The location of the "goto".
237 SourceLocation GotoLoc;
238 };
239
240 class ContinueStmtBitfields {
241 friend class ContinueStmt;
242
243 unsigned : NumStmtBits;
244
245 /// The location of the "continue".
246 SourceLocation ContinueLoc;
247 };
248
249 class BreakStmtBitfields {
250 friend class BreakStmt;
251
252 unsigned : NumStmtBits;
253
254 /// The location of the "break".
255 SourceLocation BreakLoc;
256 };
257
258 class ReturnStmtBitfields {
259 friend class ReturnStmt;
260
261 unsigned : NumStmtBits;
262
263 /// True if this ReturnStmt has storage for an NRVO candidate.
264 unsigned HasNRVOCandidate : 1;
265
266 /// The location of the "return".
267 SourceLocation RetLoc;
268 };
269
270 class SwitchCaseBitfields {
271 friend class SwitchCase;
272 friend class CaseStmt;
273
274 unsigned : NumStmtBits;
275
276 /// Used by CaseStmt to store whether it is a case statement
277 /// of the form case LHS ... RHS (a GNU extension).
278 unsigned CaseStmtIsGNURange : 1;
279
280 /// The location of the "case" or "default" keyword.
281 SourceLocation KeywordLoc;
282 };
283
284 //===--- Expression bitfields classes ---===//
285
286 class ExprBitfields {
287 friend class ASTStmtReader; // deserialization
288 friend class AtomicExpr; // ctor
289 friend class BlockDeclRefExpr; // ctor
290 friend class CallExpr; // ctor
291 friend class CXXConstructExpr; // ctor
292 friend class CXXDependentScopeMemberExpr; // ctor
293 friend class CXXNewExpr; // ctor
294 friend class CXXUnresolvedConstructExpr; // ctor
295 friend class DeclRefExpr; // computeDependence
296 friend class DependentScopeDeclRefExpr; // ctor
297 friend class DesignatedInitExpr; // ctor
298 friend class Expr;
299 friend class InitListExpr; // ctor
300 friend class ObjCArrayLiteral; // ctor
301 friend class ObjCDictionaryLiteral; // ctor
302 friend class ObjCMessageExpr; // ctor
303 friend class OffsetOfExpr; // ctor
304 friend class OpaqueValueExpr; // ctor
305 friend class OverloadExpr; // ctor
306 friend class ParenListExpr; // ctor
307 friend class PseudoObjectExpr; // ctor
308 friend class ShuffleVectorExpr; // ctor
309
310 unsigned : NumStmtBits;
311
312 unsigned ValueKind : 2;
313 unsigned ObjectKind : 3;
314 unsigned /*ExprDependence*/ Dependent : llvm::BitWidth<ExprDependence>;
315 };
316 enum { NumExprBits = NumStmtBits + 5 + llvm::BitWidth<ExprDependence> };
317
318 class ConstantExprBitfields {
319 friend class ASTStmtReader;
320 friend class ASTStmtWriter;
321 friend class ConstantExpr;
322
323 unsigned : NumExprBits;
324
325 /// The kind of result that is trail-allocated.
326 unsigned ResultKind : 2;
327
328 /// Kind of Result as defined by APValue::Kind
329 unsigned APValueKind : 4;
330
331 /// When ResultKind == RSK_Int64. whether the trail-allocated integer is
332 /// signed.
333 unsigned IsUnsigned : 1;
334
335 /// When ResultKind == RSK_Int64. the BitWidth of the trail-allocated
336 /// integer. 7 bits because it is the minimal number of bit to represent a
337 /// value from 0 to 64 (the size of the trail-allocated number).
338 unsigned BitWidth : 7;
339
340 /// When ResultKind == RSK_APValue. Wether the ASTContext will cleanup the
341 /// destructor on the trail-allocated APValue.
342 unsigned HasCleanup : 1;
343
344 /// Whether this ConstantExpr was created for immediate invocation.
345 unsigned IsImmediateInvocation : 1;
346 };
347
348 class PredefinedExprBitfields {
349 friend class ASTStmtReader;
350 friend class PredefinedExpr;
351
352 unsigned : NumExprBits;
353
354 /// The kind of this PredefinedExpr. One of the enumeration values
355 /// in PredefinedExpr::IdentKind.
356 unsigned Kind : 4;
357
358 /// True if this PredefinedExpr has a trailing "StringLiteral *"
359 /// for the predefined identifier.
360 unsigned HasFunctionName : 1;
361
362 /// The location of this PredefinedExpr.
363 SourceLocation Loc;
364 };
365
366 class DeclRefExprBitfields {
367 friend class ASTStmtReader; // deserialization
368 friend class DeclRefExpr;
369
370 unsigned : NumExprBits;
371
372 unsigned HasQualifier : 1;
373 unsigned HasTemplateKWAndArgsInfo : 1;
374 unsigned HasFoundDecl : 1;
375 unsigned HadMultipleCandidates : 1;
376 unsigned RefersToEnclosingVariableOrCapture : 1;
377 unsigned NonOdrUseReason : 2;
378
379 /// The location of the declaration name itself.
380 SourceLocation Loc;
381 };
382
383
384 class FloatingLiteralBitfields {
385 friend class FloatingLiteral;
386
387 unsigned : NumExprBits;
388
389 unsigned Semantics : 3; // Provides semantics for APFloat construction
390 unsigned IsExact : 1;
391 };
392
393 class StringLiteralBitfields {
394 friend class ASTStmtReader;
395 friend class StringLiteral;
396
397 unsigned : NumExprBits;
398
399 /// The kind of this string literal.
400 /// One of the enumeration values of StringLiteral::StringKind.
401 unsigned Kind : 3;
402
403 /// The width of a single character in bytes. Only values of 1, 2,
404 /// and 4 bytes are supported. StringLiteral::mapCharByteWidth maps
405 /// the target + string kind to the appropriate CharByteWidth.
406 unsigned CharByteWidth : 3;
407
408 unsigned IsPascal : 1;
409
410 /// The number of concatenated token this string is made of.
411 /// This is the number of trailing SourceLocation.
412 unsigned NumConcatenated;
413 };
414
415 class CharacterLiteralBitfields {
416 friend class CharacterLiteral;
417
418 unsigned : NumExprBits;
419
420 unsigned Kind : 3;
421 };
422
423 class UnaryOperatorBitfields {
424 friend class UnaryOperator;
425
426 unsigned : NumExprBits;
427
428 unsigned Opc : 5;
429 unsigned CanOverflow : 1;
430
431 SourceLocation Loc;
432 };
433
434 class UnaryExprOrTypeTraitExprBitfields {
435 friend class UnaryExprOrTypeTraitExpr;
436
437 unsigned : NumExprBits;
438
439 unsigned Kind : 3;
440 unsigned IsType : 1; // true if operand is a type, false if an expression.
441 };
442
443 class ArraySubscriptExprBitfields {
444 friend class ArraySubscriptExpr;
445
446 unsigned : NumExprBits;
447
448 SourceLocation RBracketLoc;
449 };
450
451 class CallExprBitfields {
452 friend class CallExpr;
453
454 unsigned : NumExprBits;
455
456 unsigned NumPreArgs : 1;
457
458 /// True if the callee of the call expression was found using ADL.
459 unsigned UsesADL : 1;
460
461 /// Padding used to align OffsetToTrailingObjects to a byte multiple.
462 unsigned : 24 - 2 - NumExprBits;
463
464 /// The offset in bytes from the this pointer to the start of the
465 /// trailing objects belonging to CallExpr. Intentionally byte sized
466 /// for faster access.
467 unsigned OffsetToTrailingObjects : 8;
468 };
469 enum { NumCallExprBits = 32 };
470
471 class MemberExprBitfields {
472 friend class ASTStmtReader;
473 friend class MemberExpr;
474
475 unsigned : NumExprBits;
476
477 /// IsArrow - True if this is "X->F", false if this is "X.F".
478 unsigned IsArrow : 1;
479
480 /// True if this member expression used a nested-name-specifier to
481 /// refer to the member, e.g., "x->Base::f", or found its member via
482 /// a using declaration. When true, a MemberExprNameQualifier
483 /// structure is allocated immediately after the MemberExpr.
484 unsigned HasQualifierOrFoundDecl : 1;
485
486 /// True if this member expression specified a template keyword
487 /// and/or a template argument list explicitly, e.g., x->f<int>,
488 /// x->template f, x->template f<int>.
489 /// When true, an ASTTemplateKWAndArgsInfo structure and its
490 /// TemplateArguments (if any) are present.
491 unsigned HasTemplateKWAndArgsInfo : 1;
492
493 /// True if this member expression refers to a method that
494 /// was resolved from an overloaded set having size greater than 1.
495 unsigned HadMultipleCandidates : 1;
496
497 /// Value of type NonOdrUseReason indicating why this MemberExpr does
498 /// not constitute an odr-use of the named declaration. Meaningful only
499 /// when naming a static member.
500 unsigned NonOdrUseReason : 2;
501
502 /// This is the location of the -> or . in the expression.
503 SourceLocation OperatorLoc;
504 };
505
506 class CastExprBitfields {
507 friend class CastExpr;
508 friend class ImplicitCastExpr;
509
510 unsigned : NumExprBits;
511
512 unsigned Kind : 6;
513 unsigned PartOfExplicitCast : 1; // Only set for ImplicitCastExpr.
514
515 /// The number of CXXBaseSpecifiers in the cast. 14 bits would be enough
516 /// here. ([implimits] Direct and indirect base classes [16384]).
517 unsigned BasePathSize;
518 };
519
520 class BinaryOperatorBitfields {
521 friend class BinaryOperator;
522
523 unsigned : NumExprBits;
524
525 unsigned Opc : 6;
526
527 /// This is only meaningful for operations on floating point
528 /// types when additional values need to be in trailing storage.
529 /// It is 0 otherwise.
530 unsigned HasFPFeatures : 1;
531
532 SourceLocation OpLoc;
533 };
534
535 class InitListExprBitfields {
536 friend class InitListExpr;
537
538 unsigned : NumExprBits;
539
540 /// Whether this initializer list originally had a GNU array-range
541 /// designator in it. This is a temporary marker used by CodeGen.
542 unsigned HadArrayRangeDesignator : 1;
543 };
544
545 class ParenListExprBitfields {
546 friend class ASTStmtReader;
547 friend class ParenListExpr;
548
549 unsigned : NumExprBits;
550
551 /// The number of expressions in the paren list.
552 unsigned NumExprs;
553 };
554
555 class GenericSelectionExprBitfields {
556 friend class ASTStmtReader;
557 friend class GenericSelectionExpr;
558
559 unsigned : NumExprBits;
560
561 /// The location of the "_Generic".
562 SourceLocation GenericLoc;
563 };
564
565 class PseudoObjectExprBitfields {
566 friend class ASTStmtReader; // deserialization
567 friend class PseudoObjectExpr;
568
569 unsigned : NumExprBits;
570
571 // These don't need to be particularly wide, because they're
572 // strictly limited by the forms of expressions we permit.
573 unsigned NumSubExprs : 8;
574 unsigned ResultIndex : 32 - 8 - NumExprBits;
575 };
576
577 class SourceLocExprBitfields {
578 friend class ASTStmtReader;
579 friend class SourceLocExpr;
580
581 unsigned : NumExprBits;
582
583 /// The kind of source location builtin represented by the SourceLocExpr.
584 /// Ex. __builtin_LINE, __builtin_FUNCTION, ect.
585 unsigned Kind : 2;
586 };
587
588 class StmtExprBitfields {
589 friend class ASTStmtReader;
590 friend class StmtExpr;
591
592 unsigned : NumExprBits;
593
594 /// The number of levels of template parameters enclosing this statement
595 /// expression. Used to determine if a statement expression remains
596 /// dependent after instantiation.
597 unsigned TemplateDepth;
598 };
599
600 //===--- C++ Expression bitfields classes ---===//
601
602 class CXXOperatorCallExprBitfields {
603 friend class ASTStmtReader;
604 friend class CXXOperatorCallExpr;
605
606 unsigned : NumCallExprBits;
607
608 /// The kind of this overloaded operator. One of the enumerator
609 /// value of OverloadedOperatorKind.
610 unsigned OperatorKind : 6;
611
612 // Only meaningful for floating point types.
613 unsigned FPFeatures : 8;
614 };
615
616 class CXXRewrittenBinaryOperatorBitfields {
617 friend class ASTStmtReader;
618 friend class CXXRewrittenBinaryOperator;
619
620 unsigned : NumCallExprBits;
621
622 unsigned IsReversed : 1;
623 };
624
625 class CXXBoolLiteralExprBitfields {
626 friend class CXXBoolLiteralExpr;
627
628 unsigned : NumExprBits;
629
630 /// The value of the boolean literal.
631 unsigned Value : 1;
632
633 /// The location of the boolean literal.
634 SourceLocation Loc;
635 };
636
637 class CXXNullPtrLiteralExprBitfields {
638 friend class CXXNullPtrLiteralExpr;
639
640 unsigned : NumExprBits;
641
642 /// The location of the null pointer literal.
643 SourceLocation Loc;
644 };
645
646 class CXXThisExprBitfields {
647 friend class CXXThisExpr;
648
649 unsigned : NumExprBits;
650
651 /// Whether this is an implicit "this".
652 unsigned IsImplicit : 1;
653
654 /// The location of the "this".
655 SourceLocation Loc;
656 };
657
658 class CXXThrowExprBitfields {
659 friend class ASTStmtReader;
660 friend class CXXThrowExpr;
661
662 unsigned : NumExprBits;
663
664 /// Whether the thrown variable (if any) is in scope.
665 unsigned IsThrownVariableInScope : 1;
666
667 /// The location of the "throw".
668 SourceLocation ThrowLoc;
669 };
670
671 class CXXDefaultArgExprBitfields {
672 friend class ASTStmtReader;
673 friend class CXXDefaultArgExpr;
674
675 unsigned : NumExprBits;
676
677 /// The location where the default argument expression was used.
678 SourceLocation Loc;
679 };
680
681 class CXXDefaultInitExprBitfields {
682 friend class ASTStmtReader;
683 friend class CXXDefaultInitExpr;
684
685 unsigned : NumExprBits;
686
687 /// The location where the default initializer expression was used.
688 SourceLocation Loc;
689 };
690
691 class CXXScalarValueInitExprBitfields {
692 friend class ASTStmtReader;
693 friend class CXXScalarValueInitExpr;
694
695 unsigned : NumExprBits;
696
697 SourceLocation RParenLoc;
698 };
699
700 class CXXNewExprBitfields {
701 friend class ASTStmtReader;
702 friend class ASTStmtWriter;
703 friend class CXXNewExpr;
704
705 unsigned : NumExprBits;
706
707 /// Was the usage ::new, i.e. is the global new to be used?
708 unsigned IsGlobalNew : 1;
709
710 /// Do we allocate an array? If so, the first trailing "Stmt *" is the
711 /// size expression.
712 unsigned IsArray : 1;
713
714 /// Should the alignment be passed to the allocation function?
715 unsigned ShouldPassAlignment : 1;
716
717 /// If this is an array allocation, does the usual deallocation
718 /// function for the allocated type want to know the allocated size?
719 unsigned UsualArrayDeleteWantsSize : 1;
720
721 /// What kind of initializer do we have? Could be none, parens, or braces.
722 /// In storage, we distinguish between "none, and no initializer expr", and
723 /// "none, but an implicit initializer expr".
724 unsigned StoredInitializationStyle : 2;
725
726 /// True if the allocated type was expressed as a parenthesized type-id.
727 unsigned IsParenTypeId : 1;
728
729 /// The number of placement new arguments.
730 unsigned NumPlacementArgs;
731 };
732
733 class CXXDeleteExprBitfields {
734 friend class ASTStmtReader;
735 friend class CXXDeleteExpr;
736
737 unsigned : NumExprBits;
738
739 /// Is this a forced global delete, i.e. "::delete"?
740 unsigned GlobalDelete : 1;
741
742 /// Is this the array form of delete, i.e. "delete[]"?
743 unsigned ArrayForm : 1;
744
745 /// ArrayFormAsWritten can be different from ArrayForm if 'delete' is
746 /// applied to pointer-to-array type (ArrayFormAsWritten will be false
747 /// while ArrayForm will be true).
748 unsigned ArrayFormAsWritten : 1;
749
750 /// Does the usual deallocation function for the element type require
751 /// a size_t argument?
752 unsigned UsualArrayDeleteWantsSize : 1;
753
754 /// Location of the expression.
755 SourceLocation Loc;
756 };
757
758 class TypeTraitExprBitfields {
759 friend class ASTStmtReader;
760 friend class ASTStmtWriter;
761 friend class TypeTraitExpr;
762
763 unsigned : NumExprBits;
764
765 /// The kind of type trait, which is a value of a TypeTrait enumerator.
766 unsigned Kind : 8;
767
768 /// If this expression is not value-dependent, this indicates whether
769 /// the trait evaluated true or false.
770 unsigned Value : 1;
771
772 /// The number of arguments to this type trait.
773 unsigned NumArgs : 32 - 8 - 1 - NumExprBits;
774 };
775
776 class DependentScopeDeclRefExprBitfields {
777 friend class ASTStmtReader;
778 friend class ASTStmtWriter;
779 friend class DependentScopeDeclRefExpr;
780
781 unsigned : NumExprBits;
782
783 /// Whether the name includes info for explicit template
784 /// keyword and arguments.
785 unsigned HasTemplateKWAndArgsInfo : 1;
786 };
787
788 class CXXConstructExprBitfields {
789 friend class ASTStmtReader;
790 friend class CXXConstructExpr;
791
792 unsigned : NumExprBits;
793
794 unsigned Elidable : 1;
795 unsigned HadMultipleCandidates : 1;
796 unsigned ListInitialization : 1;
797 unsigned StdInitListInitialization : 1;
798 unsigned ZeroInitialization : 1;
799 unsigned ConstructionKind : 3;
800
801 SourceLocation Loc;
802 };
803
804 class ExprWithCleanupsBitfields {
805 friend class ASTStmtReader; // deserialization
806 friend class ExprWithCleanups;
807
808 unsigned : NumExprBits;
809
810 // When false, it must not have side effects.
811 unsigned CleanupsHaveSideEffects : 1;
812
813 unsigned NumObjects : 32 - 1 - NumExprBits;
814 };
815
816 class CXXUnresolvedConstructExprBitfields {
817 friend class ASTStmtReader;
818 friend class CXXUnresolvedConstructExpr;
819
820 unsigned : NumExprBits;
821
822 /// The number of arguments used to construct the type.
823 unsigned NumArgs;
824 };
825
826 class CXXDependentScopeMemberExprBitfields {
827 friend class ASTStmtReader;
828 friend class CXXDependentScopeMemberExpr;
829
830 unsigned : NumExprBits;
831
832 /// Whether this member expression used the '->' operator or
833 /// the '.' operator.
834 unsigned IsArrow : 1;
835
836 /// Whether this member expression has info for explicit template
837 /// keyword and arguments.
838 unsigned HasTemplateKWAndArgsInfo : 1;
839
840 /// See getFirstQualifierFoundInScope() and the comment listing
841 /// the trailing objects.
842 unsigned HasFirstQualifierFoundInScope : 1;
843
844 /// The location of the '->' or '.' operator.
845 SourceLocation OperatorLoc;
846 };
847
848 class OverloadExprBitfields {
849 friend class ASTStmtReader;
850 friend class OverloadExpr;
851
852 unsigned : NumExprBits;
853
854 /// Whether the name includes info for explicit template
855 /// keyword and arguments.
856 unsigned HasTemplateKWAndArgsInfo : 1;
857
858 /// Padding used by the derived classes to store various bits. If you
859 /// need to add some data here, shrink this padding and add your data
860 /// above. NumOverloadExprBits also needs to be updated.
861 unsigned : 32 - NumExprBits - 1;
862
863 /// The number of results.
864 unsigned NumResults;
865 };
866 enum { NumOverloadExprBits = NumExprBits + 1 };
867
868 class UnresolvedLookupExprBitfields {
869 friend class ASTStmtReader;
870 friend class UnresolvedLookupExpr;
871
872 unsigned : NumOverloadExprBits;
873
874 /// True if these lookup results should be extended by
875 /// argument-dependent lookup if this is the operand of a function call.
876 unsigned RequiresADL : 1;
877
878 /// True if these lookup results are overloaded. This is pretty trivially
879 /// rederivable if we urgently need to kill this field.
880 unsigned Overloaded : 1;
881 };
882 static_assert(sizeof(UnresolvedLookupExprBitfields) <= 4,
883 "UnresolvedLookupExprBitfields must be <= than 4 bytes to"
884 "avoid trashing OverloadExprBitfields::NumResults!");
885
886 class UnresolvedMemberExprBitfields {
887 friend class ASTStmtReader;
888 friend class UnresolvedMemberExpr;
889
890 unsigned : NumOverloadExprBits;
891
892 /// Whether this member expression used the '->' operator or
893 /// the '.' operator.
894 unsigned IsArrow : 1;
895
896 /// Whether the lookup results contain an unresolved using declaration.
897 unsigned HasUnresolvedUsing : 1;
898 };
899 static_assert(sizeof(UnresolvedMemberExprBitfields) <= 4,
900 "UnresolvedMemberExprBitfields must be <= than 4 bytes to"
901 "avoid trashing OverloadExprBitfields::NumResults!");
902
903 class CXXNoexceptExprBitfields {
904 friend class ASTStmtReader;
905 friend class CXXNoexceptExpr;
906
907 unsigned : NumExprBits;
908
909 unsigned Value : 1;
910 };
911
912 class SubstNonTypeTemplateParmExprBitfields {
913 friend class ASTStmtReader;
914 friend class SubstNonTypeTemplateParmExpr;
915
916 unsigned : NumExprBits;
917
918 /// The location of the non-type template parameter reference.
919 SourceLocation NameLoc;
920 };
921
922 class RequiresExprBitfields {
923 friend class ASTStmtReader;
924 friend class ASTStmtWriter;
925 friend class RequiresExpr;
926
927 unsigned : NumExprBits;
928
929 unsigned IsSatisfied : 1;
930 SourceLocation RequiresKWLoc;
931 };
932
933 //===--- C++ Coroutines TS bitfields classes ---===//
934
935 class CoawaitExprBitfields {
936 friend class CoawaitExpr;
937
938 unsigned : NumExprBits;
939
940 unsigned IsImplicit : 1;
941 };
942
943 //===--- Obj-C Expression bitfields classes ---===//
944
945 class ObjCIndirectCopyRestoreExprBitfields {
946 friend class ObjCIndirectCopyRestoreExpr;
947
948 unsigned : NumExprBits;
949
950 unsigned ShouldCopy : 1;
951 };
952
953 //===--- Clang Extensions bitfields classes ---===//
954
955 class OpaqueValueExprBitfields {
956 friend class ASTStmtReader;
957 friend class OpaqueValueExpr;
958
959 unsigned : NumExprBits;
960
961 /// The OVE is a unique semantic reference to its source expression if this
962 /// bit is set to true.
963 unsigned IsUnique : 1;
964
965 SourceLocation Loc;
966 };
967
968 union {
969 // Same order as in StmtNodes.td.
970 // Statements
971 StmtBitfields StmtBits;
972 NullStmtBitfields NullStmtBits;
973 CompoundStmtBitfields CompoundStmtBits;
974 LabelStmtBitfields LabelStmtBits;
975 AttributedStmtBitfields AttributedStmtBits;
976 IfStmtBitfields IfStmtBits;
977 SwitchStmtBitfields SwitchStmtBits;
978 WhileStmtBitfields WhileStmtBits;
979 DoStmtBitfields DoStmtBits;
980 ForStmtBitfields ForStmtBits;
981 GotoStmtBitfields GotoStmtBits;
982 ContinueStmtBitfields ContinueStmtBits;
983 BreakStmtBitfields BreakStmtBits;
984 ReturnStmtBitfields ReturnStmtBits;
985 SwitchCaseBitfields SwitchCaseBits;
986
987 // Expressions
988 ExprBitfields ExprBits;
989 ConstantExprBitfields ConstantExprBits;
990 PredefinedExprBitfields PredefinedExprBits;
991 DeclRefExprBitfields DeclRefExprBits;
992 FloatingLiteralBitfields FloatingLiteralBits;
993 StringLiteralBitfields StringLiteralBits;
994 CharacterLiteralBitfields CharacterLiteralBits;
995 UnaryOperatorBitfields UnaryOperatorBits;
996 UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits;
997 ArraySubscriptExprBitfields ArraySubscriptExprBits;
998 CallExprBitfields CallExprBits;
999 MemberExprBitfields MemberExprBits;
1000 CastExprBitfields CastExprBits;
1001 BinaryOperatorBitfields BinaryOperatorBits;
1002 InitListExprBitfields InitListExprBits;
1003 ParenListExprBitfields ParenListExprBits;
1004 GenericSelectionExprBitfields GenericSelectionExprBits;
1005 PseudoObjectExprBitfields PseudoObjectExprBits;
1006 SourceLocExprBitfields SourceLocExprBits;
1007
1008 // GNU Extensions.
1009 StmtExprBitfields StmtExprBits;
1010
1011 // C++ Expressions
1012 CXXOperatorCallExprBitfields CXXOperatorCallExprBits;
1013 CXXRewrittenBinaryOperatorBitfields CXXRewrittenBinaryOperatorBits;
1014 CXXBoolLiteralExprBitfields CXXBoolLiteralExprBits;
1015 CXXNullPtrLiteralExprBitfields CXXNullPtrLiteralExprBits;
1016 CXXThisExprBitfields CXXThisExprBits;
1017 CXXThrowExprBitfields CXXThrowExprBits;
1018 CXXDefaultArgExprBitfields CXXDefaultArgExprBits;
1019 CXXDefaultInitExprBitfields CXXDefaultInitExprBits;
1020 CXXScalarValueInitExprBitfields CXXScalarValueInitExprBits;
1021 CXXNewExprBitfields CXXNewExprBits;
1022 CXXDeleteExprBitfields CXXDeleteExprBits;
1023 TypeTraitExprBitfields TypeTraitExprBits;
1024 DependentScopeDeclRefExprBitfields DependentScopeDeclRefExprBits;
1025 CXXConstructExprBitfields CXXConstructExprBits;
1026 ExprWithCleanupsBitfields ExprWithCleanupsBits;
1027 CXXUnresolvedConstructExprBitfields CXXUnresolvedConstructExprBits;
1028 CXXDependentScopeMemberExprBitfields CXXDependentScopeMemberExprBits;
1029 OverloadExprBitfields OverloadExprBits;
1030 UnresolvedLookupExprBitfields UnresolvedLookupExprBits;
1031 UnresolvedMemberExprBitfields UnresolvedMemberExprBits;
1032 CXXNoexceptExprBitfields CXXNoexceptExprBits;
1033 SubstNonTypeTemplateParmExprBitfields SubstNonTypeTemplateParmExprBits;
1034 RequiresExprBitfields RequiresExprBits;
1035
1036 // C++ Coroutines TS expressions
1037 CoawaitExprBitfields CoawaitBits;
1038
1039 // Obj-C Expressions
1040 ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits;
1041
1042 // Clang Extensions
1043 OpaqueValueExprBitfields OpaqueValueExprBits;
1044 };
1045
1046public:
1047 // Only allow allocation of Stmts using the allocator in ASTContext
1048 // or by doing a placement new.
1049 void* operator new(size_t bytes, const ASTContext& C,
1050 unsigned alignment = 8);
1051
1052 void* operator new(size_t bytes, const ASTContext* C,
1053 unsigned alignment = 8) {
1054 return operator new(bytes, *C, alignment);
1055 }
1056
1057 void *operator new(size_t bytes, void *mem) noexcept { return mem; }
1058
1059 void operator delete(void *, const ASTContext &, unsigned) noexcept {}
1060 void operator delete(void *, const ASTContext *, unsigned) noexcept {}
1061 void operator delete(void *, size_t) noexcept {}
1062 void operator delete(void *, void *) noexcept {}
1063
1064public:
1065 /// A placeholder type used to construct an empty shell of a
1066 /// type, that will be filled in later (e.g., by some
1067 /// de-serialization).
1068 struct EmptyShell {};
1069
1070protected:
1071 /// Iterator for iterating over Stmt * arrays that contain only T *.
1072 ///
1073 /// This is needed because AST nodes use Stmt* arrays to store
1074 /// references to children (to be compatible with StmtIterator).
1075 template<typename T, typename TPtr = T *, typename StmtPtr = Stmt *>
1076 struct CastIterator
1077 : llvm::iterator_adaptor_base<CastIterator<T, TPtr, StmtPtr>, StmtPtr *,
1078 std::random_access_iterator_tag, TPtr> {
1079 using Base = typename CastIterator::iterator_adaptor_base;
1080
1081 CastIterator() : Base(nullptr) {}
1082 CastIterator(StmtPtr *I) : Base(I) {}
1083
1084 typename Base::value_type operator*() const {
1085 return cast_or_null<T>(*this->I);
1086 }
1087 };
1088
1089 /// Const iterator for iterating over Stmt * arrays that contain only T *.
1090 template <typename T>
1091 using ConstCastIterator = CastIterator<T, const T *const, const Stmt *const>;
1092
1093 using ExprIterator = CastIterator<Expr>;
1094 using ConstExprIterator = ConstCastIterator<Expr>;
1095
1096private:
1097 /// Whether statistic collection is enabled.
1098 static bool StatisticsEnabled;
1099
1100protected:
1101 /// Construct an empty statement.
1102 explicit Stmt(StmtClass SC, EmptyShell) : Stmt(SC) {}
1103
1104public:
1105 Stmt() = delete;
1106 Stmt(const Stmt &) = delete;
1107 Stmt(Stmt &&) = delete;
1108 Stmt &operator=(const Stmt &) = delete;
1109 Stmt &operator=(Stmt &&) = delete;
1110
1111 Stmt(StmtClass SC) {
1112 static_assert(sizeof(*this) <= 8,
1113 "changing bitfields changed sizeof(Stmt)");
1114 static_assert(sizeof(*this) % alignof(void *) == 0,
1115 "Insufficient alignment!");
1116 StmtBits.sClass = SC;
1117 if (StatisticsEnabled) Stmt::addStmtClass(SC);
1118 }
1119
1120 StmtClass getStmtClass() const {
1121 return static_cast<StmtClass>(StmtBits.sClass);
1122 }
1123
1124 const char *getStmtClassName() const;
1125
1126 /// SourceLocation tokens are not useful in isolation - they are low level
1127 /// value objects created/interpreted by SourceManager. We assume AST
1128 /// clients will have a pointer to the respective SourceManager.
1129 SourceRange getSourceRange() const LLVM_READONLY;
1130 SourceLocation getBeginLoc() const LLVM_READONLY;
1131 SourceLocation getEndLoc() const LLVM_READONLY;
1132
1133 // global temp stats (until we have a per-module visitor)
1134 static void addStmtClass(const StmtClass s);
1135 static void EnableStatistics();
1136 static void PrintStats();
1137
1138 /// Dumps the specified AST fragment and all subtrees to
1139 /// \c llvm::errs().
1140 void dump() const;
1141 void dump(SourceManager &SM) const;
1142 void dump(raw_ostream &OS, SourceManager &SM) const;
1143 void dump(raw_ostream &OS) const;
1144
1145 /// \return Unique reproducible object identifier
1146 int64_t getID(const ASTContext &Context) const;
1147
1148 /// dumpColor - same as dump(), but forces color highlighting.
1149 void dumpColor() const;
1150
1151 /// dumpPretty/printPretty - These two methods do a "pretty print" of the AST
1152 /// back to its original source language syntax.
1153 void dumpPretty(const ASTContext &Context) const;
1154 void printPretty(raw_ostream &OS, PrinterHelper *Helper,
1155 const PrintingPolicy &Policy, unsigned Indentation = 0,
1156 StringRef NewlineSymbol = "\n",
1157 const ASTContext *Context = nullptr) const;
1158
1159 /// Pretty-prints in JSON format.
1160 void printJson(raw_ostream &Out, PrinterHelper *Helper,
1161 const PrintingPolicy &Policy, bool AddQuotes) const;
1162
1163 /// viewAST - Visualize an AST rooted at this Stmt* using GraphViz. Only
1164 /// works on systems with GraphViz (Mac OS X) or dot+gv installed.
1165 void viewAST() const;
1166
1167 /// Skip no-op (attributed, compound) container stmts and skip captured
1168 /// stmt at the top, if \a IgnoreCaptured is true.
1169 Stmt *IgnoreContainers(bool IgnoreCaptured = false);
1170 const Stmt *IgnoreContainers(bool IgnoreCaptured = false) const {
1171 return const_cast<Stmt *>(this)->IgnoreContainers(IgnoreCaptured);
1172 }
1173
1174 const Stmt *stripLabelLikeStatements() const;
1175 Stmt *stripLabelLikeStatements() {
1176 return const_cast<Stmt*>(
1177 const_cast<const Stmt*>(this)->stripLabelLikeStatements());
1178 }
1179
1180 /// Child Iterators: All subclasses must implement 'children'
1181 /// to permit easy iteration over the substatements/subexpessions of an
1182 /// AST node. This permits easy iteration over all nodes in the AST.
1183 using child_iterator = StmtIterator;
1184 using const_child_iterator = ConstStmtIterator;
1185
1186 using child_range = llvm::iterator_range<child_iterator>;
1187 using const_child_range = llvm::iterator_range<const_child_iterator>;
1188
1189 child_range children();
1190
1191 const_child_range children() const {
1192 auto Children = const_cast<Stmt *>(this)->children();
1193 return const_child_range(Children.begin(), Children.end());
1194 }
1195
1196 child_iterator child_begin() { return children().begin(); }
1197 child_iterator child_end() { return children().end(); }
1198
1199 const_child_iterator child_begin() const { return children().begin(); }
1200 const_child_iterator child_end() const { return children().end(); }
1201
1202 /// Produce a unique representation of the given statement.
1203 ///
1204 /// \param ID once the profiling operation is complete, will contain
1205 /// the unique representation of the given statement.
1206 ///
1207 /// \param Context the AST context in which the statement resides
1208 ///
1209 /// \param Canonical whether the profile should be based on the canonical
1210 /// representation of this statement (e.g., where non-type template
1211 /// parameters are identified by index/level rather than their
1212 /// declaration pointers) or the exact representation of the statement as
1213 /// written in the source.
1214 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
1215 bool Canonical) const;
1216
1217 /// Calculate a unique representation for a statement that is
1218 /// stable across compiler invocations.
1219 ///
1220 /// \param ID profile information will be stored in ID.
1221 ///
1222 /// \param Hash an ODRHash object which will be called where pointers would
1223 /// have been used in the Profile function.
1224 void ProcessODRHash(llvm::FoldingSetNodeID &ID, ODRHash& Hash) const;
1225};
1226
1227/// DeclStmt - Adaptor class for mixing declarations with statements and
1228/// expressions. For example, CompoundStmt mixes statements, expressions
1229/// and declarations (variables, types). Another example is ForStmt, where
1230/// the first statement can be an expression or a declaration.
1231class DeclStmt : public Stmt {
1232 DeclGroupRef DG;
1233 SourceLocation StartLoc, EndLoc;
1234
1235public:
1236 DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc)
1237 : Stmt(DeclStmtClass), DG(dg), StartLoc(startLoc), EndLoc(endLoc) {}
1238
1239 /// Build an empty declaration statement.
1240 explicit DeclStmt(EmptyShell Empty) : Stmt(DeclStmtClass, Empty) {}
1241
1242 /// isSingleDecl - This method returns true if this DeclStmt refers
1243 /// to a single Decl.
1244 bool isSingleDecl() const { return DG.isSingleDecl(); }
1245
1246 const Decl *getSingleDecl() const { return DG.getSingleDecl(); }
1247 Decl *getSingleDecl() { return DG.getSingleDecl(); }
1248
1249 const DeclGroupRef getDeclGroup() const { return DG; }
1250 DeclGroupRef getDeclGroup() { return DG; }
1251 void setDeclGroup(DeclGroupRef DGR) { DG = DGR; }
1252
1253 void setStartLoc(SourceLocation L) { StartLoc = L; }
1254 SourceLocation getEndLoc() const { return EndLoc; }
1255 void setEndLoc(SourceLocation L) { EndLoc = L; }
1256
1257 SourceLocation getBeginLoc() const LLVM_READONLY { return StartLoc; }
1258
1259 static bool classof(const Stmt *T) {
1260 return T->getStmtClass() == DeclStmtClass;
1261 }
1262
1263 // Iterators over subexpressions.
1264 child_range children() {
1265 return child_range(child_iterator(DG.begin(), DG.end()),
1266 child_iterator(DG.end(), DG.end()));
1267 }
1268
1269 const_child_range children() const {
1270 auto Children = const_cast<DeclStmt *>(this)->children();
1271 return const_child_range(Children);
1272 }
1273
1274 using decl_iterator = DeclGroupRef::iterator;
1275 using const_decl_iterator = DeclGroupRef::const_iterator;
1276 using decl_range = llvm::iterator_range<decl_iterator>;
1277 using decl_const_range = llvm::iterator_range<const_decl_iterator>;
1278
1279 decl_range decls() { return decl_range(decl_begin(), decl_end()); }
1280
1281 decl_const_range decls() const {
1282 return decl_const_range(decl_begin(), decl_end());
1283 }
1284
1285 decl_iterator decl_begin() { return DG.begin(); }
1286 decl_iterator decl_end() { return DG.end(); }
1287 const_decl_iterator decl_begin() const { return DG.begin(); }
1288 const_decl_iterator decl_end() const { return DG.end(); }
1289
1290 using reverse_decl_iterator = std::reverse_iterator<decl_iterator>;
1291
1292 reverse_decl_iterator decl_rbegin() {
1293 return reverse_decl_iterator(decl_end());
1294 }
1295
1296 reverse_decl_iterator decl_rend() {
1297 return reverse_decl_iterator(decl_begin());
1298 }
1299};
1300
1301/// NullStmt - This is the null statement ";": C99 6.8.3p3.
1302///
1303class NullStmt : public Stmt {
1304public:
1305 NullStmt(SourceLocation L, bool hasLeadingEmptyMacro = false)
1306 : Stmt(NullStmtClass) {
1307 NullStmtBits.HasLeadingEmptyMacro = hasLeadingEmptyMacro;
1308 setSemiLoc(L);
1309 }
1310
1311 /// Build an empty null statement.
1312 explicit NullStmt(EmptyShell Empty) : Stmt(NullStmtClass, Empty) {}
1313
1314 SourceLocation getSemiLoc() const { return NullStmtBits.SemiLoc; }
1315 void setSemiLoc(SourceLocation L) { NullStmtBits.SemiLoc = L; }
1316
1317 bool hasLeadingEmptyMacro() const {
1318 return NullStmtBits.HasLeadingEmptyMacro;
1319 }
1320
1321 SourceLocation getBeginLoc() const { return getSemiLoc(); }
1322 SourceLocation getEndLoc() const { return getSemiLoc(); }
1323
1324 static bool classof(const Stmt *T) {
1325 return T->getStmtClass() == NullStmtClass;
1326 }
1327
1328 child_range children() {
1329 return child_range(child_iterator(), child_iterator());
1330 }
1331
1332 const_child_range children() const {
1333 return const_child_range(const_child_iterator(), const_child_iterator());
1334 }
1335};
1336
1337/// CompoundStmt - This represents a group of statements like { stmt stmt }.
1338class CompoundStmt final : public Stmt,
1339 private llvm::TrailingObjects<CompoundStmt, Stmt *> {
1340 friend class ASTStmtReader;
1341 friend TrailingObjects;
1342
1343 /// The location of the closing "}". LBraceLoc is stored in CompoundStmtBits.
1344 SourceLocation RBraceLoc;
1345
1346 CompoundStmt(ArrayRef<Stmt *> Stmts, SourceLocation LB, SourceLocation RB);
1347 explicit CompoundStmt(EmptyShell Empty) : Stmt(CompoundStmtClass, Empty) {}
1348
1349 void setStmts(ArrayRef<Stmt *> Stmts);
1350
1351public:
1352 static CompoundStmt *Create(const ASTContext &C, ArrayRef<Stmt *> Stmts,
1353 SourceLocation LB, SourceLocation RB);
1354
1355 // Build an empty compound statement with a location.
1356 explicit CompoundStmt(SourceLocation Loc)
1357 : Stmt(CompoundStmtClass), RBraceLoc(Loc) {
1358 CompoundStmtBits.NumStmts = 0;
1359 CompoundStmtBits.LBraceLoc = Loc;
1360 }
1361
1362 // Build an empty compound statement.
1363 static CompoundStmt *CreateEmpty(const ASTContext &C, unsigned NumStmts);
1364
1365 bool body_empty() const { return CompoundStmtBits.NumStmts == 0; }
1366 unsigned size() const { return CompoundStmtBits.NumStmts; }
1367
1368 using body_iterator = Stmt **;
1369 using body_range = llvm::iterator_range<body_iterator>;
1370
1371 body_range body() { return body_range(body_begin(), body_end()); }
1372 body_iterator body_begin() { return getTrailingObjects<Stmt *>(); }
1373 body_iterator body_end() { return body_begin() + size(); }
1374 Stmt *body_front() { return !body_empty() ? body_begin()[0] : nullptr; }
1375
1376 Stmt *body_back() {
1377 return !body_empty() ? body_begin()[size() - 1] : nullptr;
1378 }
1379
1380 using const_body_iterator = Stmt *const *;
1381 using body_const_range = llvm::iterator_range<const_body_iterator>;
1382
1383 body_const_range body() const {
1384 return body_const_range(body_begin(), body_end());
1385 }
1386
1387 const_body_iterator body_begin() const {
1388 return getTrailingObjects<Stmt *>();
1389 }
1390
1391 const_body_iterator body_end() const { return body_begin() + size(); }
1392
1393 const Stmt *body_front() const {
1394 return !body_empty() ? body_begin()[0] : nullptr;
1395 }
1396
1397 const Stmt *body_back() const {
1398 return !body_empty() ? body_begin()[size() - 1] : nullptr;
1399 }
1400
1401 using reverse_body_iterator = std::reverse_iterator<body_iterator>;
1402
1403 reverse_body_iterator body_rbegin() {
1404 return reverse_body_iterator(body_end());
1405 }
1406
1407 reverse_body_iterator body_rend() {
1408 return reverse_body_iterator(body_begin());
1409 }
1410
1411 using const_reverse_body_iterator =
1412 std::reverse_iterator<const_body_iterator>;
1413
1414 const_reverse_body_iterator body_rbegin() const {
1415 return const_reverse_body_iterator(body_end());
1416 }
1417
1418 const_reverse_body_iterator body_rend() const {
1419 return const_reverse_body_iterator(body_begin());
1420 }
1421
1422 // Get the Stmt that StmtExpr would consider to be the result of this
1423 // compound statement. This is used by StmtExpr to properly emulate the GCC
1424 // compound expression extension, which ignores trailing NullStmts when
1425 // getting the result of the expression.
1426 // i.e. ({ 5;;; })
1427 // ^^ ignored
1428 // If we don't find something that isn't a NullStmt, just return the last
1429 // Stmt.
1430 Stmt *getStmtExprResult() {
1431 for (auto *B : llvm::reverse(body())) {
1432 if (!isa<NullStmt>(B))
1433 return B;
1434 }
1435 return body_back();
1436 }
1437
1438 const Stmt *getStmtExprResult() const {
1439 return const_cast<CompoundStmt *>(this)->getStmtExprResult();
1440 }
1441
1442 SourceLocation getBeginLoc() const { return CompoundStmtBits.LBraceLoc; }
1443 SourceLocation getEndLoc() const { return RBraceLoc; }
1444
1445 SourceLocation getLBracLoc() const { return CompoundStmtBits.LBraceLoc; }
1446 SourceLocation getRBracLoc() const { return RBraceLoc; }
1447
1448 static bool classof(const Stmt *T) {
1449 return T->getStmtClass() == CompoundStmtClass;
1450 }
1451
1452 // Iterators
1453 child_range children() { return child_range(body_begin(), body_end()); }
1454
1455 const_child_range children() const {
1456 return const_child_range(body_begin(), body_end());
1457 }
1458};
1459
1460// SwitchCase is the base class for CaseStmt and DefaultStmt,
1461class SwitchCase : public Stmt {
1462protected:
1463 /// The location of the ":".
1464 SourceLocation ColonLoc;
1465
1466 // The location of the "case" or "default" keyword. Stored in SwitchCaseBits.
1467 // SourceLocation KeywordLoc;
1468
1469 /// A pointer to the following CaseStmt or DefaultStmt class,
1470 /// used by SwitchStmt.
1471 SwitchCase *NextSwitchCase = nullptr;
1472
1473 SwitchCase(StmtClass SC, SourceLocation KWLoc, SourceLocation ColonLoc)
1474 : Stmt(SC), ColonLoc(ColonLoc) {
1475 setKeywordLoc(KWLoc);
1476 }
1477
1478 SwitchCase(StmtClass SC, EmptyShell) : Stmt(SC) {}
1479
1480public:
1481 const SwitchCase *getNextSwitchCase() const { return NextSwitchCase; }
1482 SwitchCase *getNextSwitchCase() { return NextSwitchCase; }
1483 void setNextSwitchCase(SwitchCase *SC) { NextSwitchCase = SC; }
1484
1485 SourceLocation getKeywordLoc() const { return SwitchCaseBits.KeywordLoc; }
1486 void setKeywordLoc(SourceLocation L) { SwitchCaseBits.KeywordLoc = L; }
1487 SourceLocation getColonLoc() const { return ColonLoc; }
1488 void setColonLoc(SourceLocation L) { ColonLoc = L; }
1489
1490 inline Stmt *getSubStmt();
1491 const Stmt *getSubStmt() const {
1492 return const_cast<SwitchCase *>(this)->getSubStmt();
1493 }
1494
1495 SourceLocation getBeginLoc() const { return getKeywordLoc(); }
1496 inline SourceLocation getEndLoc() const LLVM_READONLY;
1497
1498 static bool classof(const Stmt *T) {
1499 return T->getStmtClass() == CaseStmtClass ||
1500 T->getStmtClass() == DefaultStmtClass;
1501 }
1502};
1503
1504/// CaseStmt - Represent a case statement. It can optionally be a GNU case
1505/// statement of the form LHS ... RHS representing a range of cases.
1506class CaseStmt final
1507 : public SwitchCase,
1508 private llvm::TrailingObjects<CaseStmt, Stmt *, SourceLocation> {
1509 friend TrailingObjects;
1510
1511 // CaseStmt is followed by several trailing objects, some of which optional.
1512 // Note that it would be more convenient to put the optional trailing objects
1513 // at the end but this would impact children().
1514 // The trailing objects are in order:
1515 //
1516 // * A "Stmt *" for the LHS of the case statement. Always present.
1517 //
1518 // * A "Stmt *" for the RHS of the case statement. This is a GNU extension
1519 // which allow ranges in cases statement of the form LHS ... RHS.
1520 // Present if and only if caseStmtIsGNURange() is true.
1521 //
1522 // * A "Stmt *" for the substatement of the case statement. Always present.
1523 //
1524 // * A SourceLocation for the location of the ... if this is a case statement
1525 // with a range. Present if and only if caseStmtIsGNURange() is true.
1526 enum { LhsOffset = 0, SubStmtOffsetFromRhs = 1 };
1527 enum { NumMandatoryStmtPtr = 2 };
1528
1529 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
1530 return NumMandatoryStmtPtr + caseStmtIsGNURange();
1531 }
1532
1533 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1534 return caseStmtIsGNURange();
1535 }
1536
1537 unsigned lhsOffset() const { return LhsOffset; }
1538 unsigned rhsOffset() const { return LhsOffset + caseStmtIsGNURange(); }
1539 unsigned subStmtOffset() const { return rhsOffset() + SubStmtOffsetFromRhs; }
1540
1541 /// Build a case statement assuming that the storage for the
1542 /// trailing objects has been properly allocated.
1543 CaseStmt(Expr *lhs, Expr *rhs, SourceLocation caseLoc,
1544 SourceLocation ellipsisLoc, SourceLocation colonLoc)
1545 : SwitchCase(CaseStmtClass, caseLoc, colonLoc) {
1546 // Handle GNU case statements of the form LHS ... RHS.
1547 bool IsGNURange = rhs != nullptr;
1548 SwitchCaseBits.CaseStmtIsGNURange = IsGNURange;
1549 setLHS(lhs);
1550 setSubStmt(nullptr);
1551 if (IsGNURange) {
1552 setRHS(rhs);
1553 setEllipsisLoc(ellipsisLoc);
1554 }
1555 }
1556
1557 /// Build an empty switch case statement.
1558 explicit CaseStmt(EmptyShell Empty, bool CaseStmtIsGNURange)
1559 : SwitchCase(CaseStmtClass, Empty) {
1560 SwitchCaseBits.CaseStmtIsGNURange = CaseStmtIsGNURange;
1561 }
1562
1563public:
1564 /// Build a case statement.
1565 static CaseStmt *Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
1566 SourceLocation caseLoc, SourceLocation ellipsisLoc,
1567 SourceLocation colonLoc);
1568
1569 /// Build an empty case statement.
1570 static CaseStmt *CreateEmpty(const ASTContext &Ctx, bool CaseStmtIsGNURange);
1571
1572 /// True if this case statement is of the form case LHS ... RHS, which
1573 /// is a GNU extension. In this case the RHS can be obtained with getRHS()
1574 /// and the location of the ellipsis can be obtained with getEllipsisLoc().
1575 bool caseStmtIsGNURange() const { return SwitchCaseBits.CaseStmtIsGNURange; }
1576
1577 SourceLocation getCaseLoc() const { return getKeywordLoc(); }
1578 void setCaseLoc(SourceLocation L) { setKeywordLoc(L); }
1579
1580 /// Get the location of the ... in a case statement of the form LHS ... RHS.
1581 SourceLocation getEllipsisLoc() const {
1582 return caseStmtIsGNURange() ? *getTrailingObjects<SourceLocation>()
1583 : SourceLocation();
1584 }
1585
1586 /// Set the location of the ... in a case statement of the form LHS ... RHS.
1587 /// Assert that this case statement is of this form.
1588 void setEllipsisLoc(SourceLocation L) {
1589 assert(
1590 caseStmtIsGNURange() &&
1591 "setEllipsisLoc but this is not a case stmt of the form LHS ... RHS!");
1592 *getTrailingObjects<SourceLocation>() = L;
1593 }
1594
1595 Expr *getLHS() {
1596 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[lhsOffset()]);
1597 }
1598
1599 const Expr *getLHS() const {
1600 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[lhsOffset()]);
1601 }
1602
1603 void setLHS(Expr *Val) {
1604 getTrailingObjects<Stmt *>()[lhsOffset()] = reinterpret_cast<Stmt *>(Val);
1605 }
1606
1607 Expr *getRHS() {
1608 return caseStmtIsGNURange() ? reinterpret_cast<Expr *>(
1609 getTrailingObjects<Stmt *>()[rhsOffset()])
1610 : nullptr;
1611 }
1612
1613 const Expr *getRHS() const {
1614 return caseStmtIsGNURange() ? reinterpret_cast<Expr *>(
1615 getTrailingObjects<Stmt *>()[rhsOffset()])
1616 : nullptr;
1617 }
1618
1619 void setRHS(Expr *Val) {
1620 assert(caseStmtIsGNURange() &&
1621 "setRHS but this is not a case stmt of the form LHS ... RHS!");
1622 getTrailingObjects<Stmt *>()[rhsOffset()] = reinterpret_cast<Stmt *>(Val);
1623 }
1624
1625 Stmt *getSubStmt() { return getTrailingObjects<Stmt *>()[subStmtOffset()]; }
1626 const Stmt *getSubStmt() const {
1627 return getTrailingObjects<Stmt *>()[subStmtOffset()];
1628 }
1629
1630 void setSubStmt(Stmt *S) {
1631 getTrailingObjects<Stmt *>()[subStmtOffset()] = S;
1632 }
1633
1634 SourceLocation getBeginLoc() const { return getKeywordLoc(); }
1635 SourceLocation getEndLoc() const LLVM_READONLY {
1636 // Handle deeply nested case statements with iteration instead of recursion.
1637 const CaseStmt *CS = this;
1638 while (const auto *CS2 = dyn_cast<CaseStmt>(CS->getSubStmt()))
1639 CS = CS2;
1640
1641 return CS->getSubStmt()->getEndLoc();
1642 }
1643
1644 static bool classof(const Stmt *T) {
1645 return T->getStmtClass() == CaseStmtClass;
1646 }
1647
1648 // Iterators
1649 child_range children() {
1650 return child_range(getTrailingObjects<Stmt *>(),
1651 getTrailingObjects<Stmt *>() +
1652 numTrailingObjects(OverloadToken<Stmt *>()));
1653 }
1654
1655 const_child_range children() const {
1656 return const_child_range(getTrailingObjects<Stmt *>(),
1657 getTrailingObjects<Stmt *>() +
1658 numTrailingObjects(OverloadToken<Stmt *>()));
1659 }
1660};
1661
1662class DefaultStmt : public SwitchCase {
1663 Stmt *SubStmt;
1664
1665public:
1666 DefaultStmt(SourceLocation DL, SourceLocation CL, Stmt *substmt)
1667 : SwitchCase(DefaultStmtClass, DL, CL), SubStmt(substmt) {}
1668
1669 /// Build an empty default statement.
1670 explicit DefaultStmt(EmptyShell Empty)
1671 : SwitchCase(DefaultStmtClass, Empty) {}
1672
1673 Stmt *getSubStmt() { return SubStmt; }
1674 const Stmt *getSubStmt() const { return SubStmt; }
1675 void setSubStmt(Stmt *S) { SubStmt = S; }
1676
1677 SourceLocation getDefaultLoc() const { return getKeywordLoc(); }
1678 void setDefaultLoc(SourceLocation L) { setKeywordLoc(L); }
1679
1680 SourceLocation getBeginLoc() const { return getKeywordLoc(); }
1681 SourceLocation getEndLoc() const LLVM_READONLY {
1682 return SubStmt->getEndLoc();
1683 }
1684
1685 static bool classof(const Stmt *T) {
1686 return T->getStmtClass() == DefaultStmtClass;
1687 }
1688
1689 // Iterators
1690 child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
1691
1692 const_child_range children() const {
1693 return const_child_range(&SubStmt, &SubStmt + 1);
1694 }
1695};
1696
1697SourceLocation SwitchCase::getEndLoc() const {
1698 if (const auto *CS = dyn_cast<CaseStmt>(this))
1699 return CS->getEndLoc();
1700 else if (const auto *DS = dyn_cast<DefaultStmt>(this))
1701 return DS->getEndLoc();
1702 llvm_unreachable("SwitchCase is neither a CaseStmt nor a DefaultStmt!");
1703}
1704
1705Stmt *SwitchCase::getSubStmt() {
1706 if (auto *CS = dyn_cast<CaseStmt>(this))
1707 return CS->getSubStmt();
1708 else if (auto *DS = dyn_cast<DefaultStmt>(this))
1709 return DS->getSubStmt();
1710 llvm_unreachable("SwitchCase is neither a CaseStmt nor a DefaultStmt!");
1711}
1712
1713/// Represents a statement that could possibly have a value and type. This
1714/// covers expression-statements, as well as labels and attributed statements.
1715///
1716/// Value statements have a special meaning when they are the last non-null
1717/// statement in a GNU statement expression, where they determine the value
1718/// of the statement expression.
1719class ValueStmt : public Stmt {
1720protected:
1721 using Stmt::Stmt;
1722
1723public:
1724 const Expr *getExprStmt() const;
1725 Expr *getExprStmt() {
1726 const ValueStmt *ConstThis = this;
1727 return const_cast<Expr*>(ConstThis->getExprStmt());
1728 }
1729
1730 static bool classof(const Stmt *T) {
1731 return T->getStmtClass() >= firstValueStmtConstant &&
1732 T->getStmtClass() <= lastValueStmtConstant;
1733 }
1734};
1735
1736/// LabelStmt - Represents a label, which has a substatement. For example:
1737/// foo: return;
1738class LabelStmt : public ValueStmt {
1739 LabelDecl *TheDecl;
1740 Stmt *SubStmt;
1741
1742public:
1743 /// Build a label statement.
1744 LabelStmt(SourceLocation IL, LabelDecl *D, Stmt *substmt)
1745 : ValueStmt(LabelStmtClass), TheDecl(D), SubStmt(substmt) {
1746 setIdentLoc(IL);
1747 }
1748
1749 /// Build an empty label statement.
1750 explicit LabelStmt(EmptyShell Empty) : ValueStmt(LabelStmtClass, Empty) {}
1751
1752 SourceLocation getIdentLoc() const { return LabelStmtBits.IdentLoc; }
1753 void setIdentLoc(SourceLocation L) { LabelStmtBits.IdentLoc = L; }
1754
1755 LabelDecl *getDecl() const { return TheDecl; }
1756 void setDecl(LabelDecl *D) { TheDecl = D; }
1757
1758 const char *getName() const;
1759 Stmt *getSubStmt() { return SubStmt; }
1760
1761 const Stmt *getSubStmt() const { return SubStmt; }
1762 void setSubStmt(Stmt *SS) { SubStmt = SS; }
1763
1764 SourceLocation getBeginLoc() const { return getIdentLoc(); }
1765 SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc();}
1766
1767 child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
1768
1769 const_child_range children() const {
1770 return const_child_range(&SubStmt, &SubStmt + 1);
1771 }
1772
1773 static bool classof(const Stmt *T) {
1774 return T->getStmtClass() == LabelStmtClass;
1775 }
1776};
1777
1778/// Represents an attribute applied to a statement.
1779///
1780/// Represents an attribute applied to a statement. For example:
1781/// [[omp::for(...)]] for (...) { ... }
1782class AttributedStmt final
1783 : public ValueStmt,
1784 private llvm::TrailingObjects<AttributedStmt, const Attr *> {
1785 friend class ASTStmtReader;
1786 friend TrailingObjects;
1787
1788 Stmt *SubStmt;
1789
1790 AttributedStmt(SourceLocation Loc, ArrayRef<const Attr *> Attrs,
1791 Stmt *SubStmt)
1792 : ValueStmt(AttributedStmtClass), SubStmt(SubStmt) {
1793 AttributedStmtBits.NumAttrs = Attrs.size();
1794 AttributedStmtBits.AttrLoc = Loc;
1795 std::copy(Attrs.begin(), Attrs.end(), getAttrArrayPtr());
1796 }
1797
1798 explicit AttributedStmt(EmptyShell Empty, unsigned NumAttrs)
1799 : ValueStmt(AttributedStmtClass, Empty) {
1800 AttributedStmtBits.NumAttrs = NumAttrs;
1801 AttributedStmtBits.AttrLoc = SourceLocation{};
1802 std::fill_n(getAttrArrayPtr(), NumAttrs, nullptr);
1803 }
1804
1805 const Attr *const *getAttrArrayPtr() const {
1806 return getTrailingObjects<const Attr *>();
1807 }
1808 const Attr **getAttrArrayPtr() { return getTrailingObjects<const Attr *>(); }
1809
1810public:
1811 static AttributedStmt *Create(const ASTContext &C, SourceLocation Loc,
1812 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
1813
1814 // Build an empty attributed statement.
1815 static AttributedStmt *CreateEmpty(const ASTContext &C, unsigned NumAttrs);
1816
1817 SourceLocation getAttrLoc() const { return AttributedStmtBits.AttrLoc; }
1818 ArrayRef<const Attr *> getAttrs() const {
1819 return llvm::makeArrayRef(getAttrArrayPtr(), AttributedStmtBits.NumAttrs);
1820 }
1821
1822 Stmt *getSubStmt() { return SubStmt; }
1823 const Stmt *getSubStmt() const { return SubStmt; }
1824
1825 SourceLocation getBeginLoc() const { return getAttrLoc(); }
1826 SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc();}
1827
1828 child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
1829
1830 const_child_range children() const {
1831 return const_child_range(&SubStmt, &SubStmt + 1);
1832 }
1833
1834 static bool classof(const Stmt *T) {
1835 return T->getStmtClass() == AttributedStmtClass;
1836 }
1837};
1838
1839/// IfStmt - This represents an if/then/else.
1840class IfStmt final
1841 : public Stmt,
1842 private llvm::TrailingObjects<IfStmt, Stmt *, SourceLocation> {
1843 friend TrailingObjects;
1844
1845 // IfStmt is followed by several trailing objects, some of which optional.
1846 // Note that it would be more convenient to put the optional trailing
1847 // objects at then end but this would change the order of the children.
1848 // The trailing objects are in order:
1849 //
1850 // * A "Stmt *" for the init statement.
1851 // Present if and only if hasInitStorage().
1852 //
1853 // * A "Stmt *" for the condition variable.
1854 // Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
1855 //
1856 // * A "Stmt *" for the condition.
1857 // Always present. This is in fact a "Expr *".
1858 //
1859 // * A "Stmt *" for the then statement.
1860 // Always present.
1861 //
1862 // * A "Stmt *" for the else statement.
1863 // Present if and only if hasElseStorage().
1864 //
1865 // * A "SourceLocation" for the location of the "else".
1866 // Present if and only if hasElseStorage().
1867 enum { InitOffset = 0, ThenOffsetFromCond = 1, ElseOffsetFromCond = 2 };
1868 enum { NumMandatoryStmtPtr = 2 };
1869
1870 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
1871 return NumMandatoryStmtPtr + hasElseStorage() + hasVarStorage() +
1872 hasInitStorage();
1873 }
1874
1875 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1876 return hasElseStorage();
1877 }
1878
1879 unsigned initOffset() const { return InitOffset; }
1880 unsigned varOffset() const { return InitOffset + hasInitStorage(); }
1881 unsigned condOffset() const {
1882 return InitOffset + hasInitStorage() + hasVarStorage();
1883 }
1884 unsigned thenOffset() const { return condOffset() + ThenOffsetFromCond; }
1885 unsigned elseOffset() const { return condOffset() + ElseOffsetFromCond; }
1886
1887 /// Build an if/then/else statement.
1888 IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, Stmt *Init,
1889 VarDecl *Var, Expr *Cond, Stmt *Then, SourceLocation EL, Stmt *Else);
1890
1891 /// Build an empty if/then/else statement.
1892 explicit IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit);
1893
1894public:
1895 /// Create an IfStmt.
1896 static IfStmt *Create(const ASTContext &Ctx, SourceLocation IL,
1897 bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond,
1898 Stmt *Then, SourceLocation EL = SourceLocation(),
1899 Stmt *Else = nullptr);
1900
1901 /// Create an empty IfStmt optionally with storage for an else statement,
1902 /// condition variable and init expression.
1903 static IfStmt *CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar,
1904 bool HasInit);
1905
1906 /// True if this IfStmt has the storage for an init statement.
1907 bool hasInitStorage() const { return IfStmtBits.HasInit; }
1908
1909 /// True if this IfStmt has storage for a variable declaration.
1910 bool hasVarStorage() const { return IfStmtBits.HasVar; }
1911
1912 /// True if this IfStmt has storage for an else statement.
1913 bool hasElseStorage() const { return IfStmtBits.HasElse; }
1914
1915 Expr *getCond() {
1916 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
1917 }
1918
1919 const Expr *getCond() const {
1920 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
1921 }
1922
1923 void setCond(Expr *Cond) {
1924 getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
1925 }
1926
1927 Stmt *getThen() { return getTrailingObjects<Stmt *>()[thenOffset()]; }
1928 const Stmt *getThen() const {
1929 return getTrailingObjects<Stmt *>()[thenOffset()];
1930 }
1931
1932 void setThen(Stmt *Then) {
1933 getTrailingObjects<Stmt *>()[thenOffset()] = Then;
1934 }
1935
1936 Stmt *getElse() {
1937 return hasElseStorage() ? getTrailingObjects<Stmt *>()[elseOffset()]
1938 : nullptr;
1939 }
1940
1941 const Stmt *getElse() const {
1942 return hasElseStorage() ? getTrailingObjects<Stmt *>()[elseOffset()]
1943 : nullptr;
1944 }
1945
1946 void setElse(Stmt *Else) {
1947 assert(hasElseStorage() &&
1948 "This if statement has no storage for an else statement!");
1949 getTrailingObjects<Stmt *>()[elseOffset()] = Else;
1950 }
1951
1952 /// Retrieve the variable declared in this "if" statement, if any.
1953 ///
1954 /// In the following example, "x" is the condition variable.
1955 /// \code
1956 /// if (int x = foo()) {
1957 /// printf("x is %d", x);
1958 /// }
1959 /// \endcode
1960 VarDecl *getConditionVariable();
1961 const VarDecl *getConditionVariable() const {
1962 return const_cast<IfStmt *>(this)->getConditionVariable();
1963 }
1964
1965 /// Set the condition variable for this if statement.
1966 /// The if statement must have storage for the condition variable.
1967 void setConditionVariable(const ASTContext &Ctx, VarDecl *V);
1968
1969 /// If this IfStmt has a condition variable, return the faux DeclStmt
1970 /// associated with the creation of that condition variable.
1971 DeclStmt *getConditionVariableDeclStmt() {
1972 return hasVarStorage() ? static_cast<DeclStmt *>(
1973 getTrailingObjects<Stmt *>()[varOffset()])
1974 : nullptr;
1975 }
1976
1977 const DeclStmt *getConditionVariableDeclStmt() const {
1978 return hasVarStorage() ? static_cast<DeclStmt *>(
1979 getTrailingObjects<Stmt *>()[varOffset()])
1980 : nullptr;
1981 }
1982
1983 Stmt *getInit() {
1984 return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
1985 : nullptr;
1986 }
1987
1988 const Stmt *getInit() const {
1989 return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
1990 : nullptr;
1991 }
1992
1993 void setInit(Stmt *Init) {
1994 assert(hasInitStorage() &&
1995 "This if statement has no storage for an init statement!");
1996 getTrailingObjects<Stmt *>()[initOffset()] = Init;
1997 }
1998
1999 SourceLocation getIfLoc() const { return IfStmtBits.IfLoc; }
2000 void setIfLoc(SourceLocation IfLoc) { IfStmtBits.IfLoc = IfLoc; }
2001
2002 SourceLocation getElseLoc() const {
2003 return hasElseStorage() ? *getTrailingObjects<SourceLocation>()
2004 : SourceLocation();
2005 }
2006
2007 void setElseLoc(SourceLocation ElseLoc) {
2008 assert(hasElseStorage() &&
2009 "This if statement has no storage for an else statement!");
2010 *getTrailingObjects<SourceLocation>() = ElseLoc;
2011 }
2012
2013 bool isConstexpr() const { return IfStmtBits.IsConstexpr; }
2014 void setConstexpr(bool C) { IfStmtBits.IsConstexpr = C; }
2015
2016 /// If this is an 'if constexpr', determine which substatement will be taken.
2017 /// Otherwise, or if the condition is value-dependent, returns None.
2018 Optional<const Stmt*> getNondiscardedCase(const ASTContext &Ctx) const;
2019
2020 bool isObjCAvailabilityCheck() const;
2021
2022 SourceLocation getBeginLoc() const { return getIfLoc(); }
2023 SourceLocation getEndLoc() const LLVM_READONLY {
2024 if (getElse())
2025 return getElse()->getEndLoc();
2026 return getThen()->getEndLoc();
2027 }
2028
2029 // Iterators over subexpressions. The iterators will include iterating
2030 // over the initialization expression referenced by the condition variable.
2031 child_range children() {
2032 return child_range(getTrailingObjects<Stmt *>(),
2033 getTrailingObjects<Stmt *>() +
2034 numTrailingObjects(OverloadToken<Stmt *>()));
2035 }
2036
2037 const_child_range children() const {
2038 return const_child_range(getTrailingObjects<Stmt *>(),
2039 getTrailingObjects<Stmt *>() +
2040 numTrailingObjects(OverloadToken<Stmt *>()));
2041 }
2042
2043 static bool classof(const Stmt *T) {
2044 return T->getStmtClass() == IfStmtClass;
2045 }
2046};
2047
2048/// SwitchStmt - This represents a 'switch' stmt.
2049class SwitchStmt final : public Stmt,
2050 private llvm::TrailingObjects<SwitchStmt, Stmt *> {
2051 friend TrailingObjects;
2052
2053 /// Points to a linked list of case and default statements.
2054 SwitchCase *FirstCase;
2055
2056 // SwitchStmt is followed by several trailing objects,
2057 // some of which optional. Note that it would be more convenient to
2058 // put the optional trailing objects at the end but this would change
2059 // the order in children().
2060 // The trailing objects are in order:
2061 //
2062 // * A "Stmt *" for the init statement.
2063 // Present if and only if hasInitStorage().
2064 //
2065 // * A "Stmt *" for the condition variable.
2066 // Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
2067 //
2068 // * A "Stmt *" for the condition.
2069 // Always present. This is in fact an "Expr *".
2070 //
2071 // * A "Stmt *" for the body.
2072 // Always present.
2073 enum { InitOffset = 0, BodyOffsetFromCond = 1 };
2074 enum { NumMandatoryStmtPtr = 2 };
2075
2076 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
2077 return NumMandatoryStmtPtr + hasInitStorage() + hasVarStorage();
2078 }
2079
2080 unsigned initOffset() const { return InitOffset; }
2081 unsigned varOffset() const { return InitOffset + hasInitStorage(); }
2082 unsigned condOffset() const {
2083 return InitOffset + hasInitStorage() + hasVarStorage();
2084 }
2085 unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
2086
2087 /// Build a switch statement.
2088 SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond);
2089
2090 /// Build a empty switch statement.
2091 explicit SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar);
2092
2093public:
2094 /// Create a switch statement.
2095 static SwitchStmt *Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
2096 Expr *Cond);
2097
2098 /// Create an empty switch statement optionally with storage for
2099 /// an init expression and a condition variable.
2100 static SwitchStmt *CreateEmpty(const ASTContext &Ctx, bool HasInit,
2101 bool HasVar);
2102
2103 /// True if this SwitchStmt has storage for an init statement.
2104 bool hasInitStorage() const { return SwitchStmtBits.HasInit; }
2105
2106 /// True if this SwitchStmt has storage for a condition variable.
2107 bool hasVarStorage() const { return SwitchStmtBits.HasVar; }
2108
2109 Expr *getCond() {
2110 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2111 }
2112
2113 const Expr *getCond() const {
2114 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2115 }
2116
2117 void setCond(Expr *Cond) {
2118 getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
2119 }
2120
2121 Stmt *getBody() { return getTrailingObjects<Stmt *>()[bodyOffset()]; }
2122 const Stmt *getBody() const {
2123 return getTrailingObjects<Stmt *>()[bodyOffset()];
2124 }
2125
2126 void setBody(Stmt *Body) {
2127 getTrailingObjects<Stmt *>()[bodyOffset()] = Body;
2128 }
2129
2130 Stmt *getInit() {
2131 return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
2132 : nullptr;
2133 }
2134
2135 const Stmt *getInit() const {
2136 return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
2137 : nullptr;
2138 }
2139
2140 void setInit(Stmt *Init) {
2141 assert(hasInitStorage() &&
2142 "This switch statement has no storage for an init statement!");
2143 getTrailingObjects<Stmt *>()[initOffset()] = Init;
2144 }
2145
2146 /// Retrieve the variable declared in this "switch" statement, if any.
2147 ///
2148 /// In the following example, "x" is the condition variable.
2149 /// \code
2150 /// switch (int x = foo()) {
2151 /// case 0: break;
2152 /// // ...
2153 /// }
2154 /// \endcode
2155 VarDecl *getConditionVariable();
2156 const VarDecl *getConditionVariable() const {
2157 return const_cast<SwitchStmt *>(this)->getConditionVariable();
2158 }
2159
2160 /// Set the condition variable in this switch statement.
2161 /// The switch statement must have storage for it.
2162 void setConditionVariable(const ASTContext &Ctx, VarDecl *VD);
2163
2164 /// If this SwitchStmt has a condition variable, return the faux DeclStmt
2165 /// associated with the creation of that condition variable.
2166 DeclStmt *getConditionVariableDeclStmt() {
2167 return hasVarStorage() ? static_cast<DeclStmt *>(
2168 getTrailingObjects<Stmt *>()[varOffset()])
2169 : nullptr;
2170 }
2171
2172 const DeclStmt *getConditionVariableDeclStmt() const {
2173 return hasVarStorage() ? static_cast<DeclStmt *>(
2174 getTrailingObjects<Stmt *>()[varOffset()])
2175 : nullptr;
2176 }
2177
2178 SwitchCase *getSwitchCaseList() { return FirstCase; }
2179 const SwitchCase *getSwitchCaseList() const { return FirstCase; }
2180 void setSwitchCaseList(SwitchCase *SC) { FirstCase = SC; }
2181
2182 SourceLocation getSwitchLoc() const { return SwitchStmtBits.SwitchLoc; }
2183 void setSwitchLoc(SourceLocation L) { SwitchStmtBits.SwitchLoc = L; }
2184
2185 void setBody(Stmt *S, SourceLocation SL) {
2186 setBody(S);
2187 setSwitchLoc(SL);
2188 }
2189
2190 void addSwitchCase(SwitchCase *SC) {
2191 assert(!SC->getNextSwitchCase() &&
2192 "case/default already added to a switch");
2193 SC->setNextSwitchCase(FirstCase);
2194 FirstCase = SC;
2195 }
2196
2197 /// Set a flag in the SwitchStmt indicating that if the 'switch (X)' is a
2198 /// switch over an enum value then all cases have been explicitly covered.
2199 void setAllEnumCasesCovered() { SwitchStmtBits.AllEnumCasesCovered = true; }
2200
2201 /// Returns true if the SwitchStmt is a switch of an enum value and all cases
2202 /// have been explicitly covered.
2203 bool isAllEnumCasesCovered() const {
2204 return SwitchStmtBits.AllEnumCasesCovered;
2205 }
2206
2207 SourceLocation getBeginLoc() const { return getSwitchLoc(); }
2208 SourceLocation getEndLoc() const LLVM_READONLY {
2209 return getBody() ? getBody()->getEndLoc()
2210 : reinterpret_cast<const Stmt *>(getCond())->getEndLoc();
2211 }
2212
2213 // Iterators
2214 child_range children() {
2215 return child_range(getTrailingObjects<Stmt *>(),
2216 getTrailingObjects<Stmt *>() +
2217 numTrailingObjects(OverloadToken<Stmt *>()));
2218 }
2219
2220 const_child_range children() const {
2221 return const_child_range(getTrailingObjects<Stmt *>(),
2222 getTrailingObjects<Stmt *>() +
2223 numTrailingObjects(OverloadToken<Stmt *>()));
2224 }
2225
2226 static bool classof(const Stmt *T) {
2227 return T->getStmtClass() == SwitchStmtClass;
2228 }
2229};
2230
2231/// WhileStmt - This represents a 'while' stmt.
2232class WhileStmt final : public Stmt,
2233 private llvm::TrailingObjects<WhileStmt, Stmt *> {
2234 friend TrailingObjects;
2235
2236 // WhileStmt is followed by several trailing objects,
2237 // some of which optional. Note that it would be more
2238 // convenient to put the optional trailing object at the end
2239 // but this would affect children().
2240 // The trailing objects are in order:
2241 //
2242 // * A "Stmt *" for the condition variable.
2243 // Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
2244 //
2245 // * A "Stmt *" for the condition.
2246 // Always present. This is in fact an "Expr *".
2247 //
2248 // * A "Stmt *" for the body.
2249 // Always present.
2250 //
2251 enum { VarOffset = 0, BodyOffsetFromCond = 1 };
2252 enum { NumMandatoryStmtPtr = 2 };
2253
2254 unsigned varOffset() const { return VarOffset; }
2255 unsigned condOffset() const { return VarOffset + hasVarStorage(); }
2256 unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
2257
2258 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
2259 return NumMandatoryStmtPtr + hasVarStorage();
2260 }
2261
2262 /// Build a while statement.
2263 WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, Stmt *Body,
2264 SourceLocation WL);
2265
2266 /// Build an empty while statement.
2267 explicit WhileStmt(EmptyShell Empty, bool HasVar);
2268
2269public:
2270 /// Create a while statement.
2271 static WhileStmt *Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
2272 Stmt *Body, SourceLocation WL);
2273
2274 /// Create an empty while statement optionally with storage for
2275 /// a condition variable.
2276 static WhileStmt *CreateEmpty(const ASTContext &Ctx, bool HasVar);
2277
2278 /// True if this WhileStmt has storage for a condition variable.
2279 bool hasVarStorage() const { return WhileStmtBits.HasVar; }
2280
2281 Expr *getCond() {
2282 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2283 }
2284
2285 const Expr *getCond() const {
2286 return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
2287 }
2288
2289 void setCond(Expr *Cond) {
2290 getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
2291 }
2292
2293 Stmt *getBody() { return getTrailingObjects<Stmt *>()[bodyOffset()]; }
2294 const Stmt *getBody() const {
2295 return getTrailingObjects<Stmt *>()[bodyOffset()];
2296 }
2297
2298 void setBody(Stmt *Body) {
2299 getTrailingObjects<Stmt *>()[bodyOffset()] = Body;
2300 }
2301
2302 /// Retrieve the variable declared in this "while" statement, if any.
2303 ///
2304 /// In the following example, "x" is the condition variable.
2305 /// \code
2306 /// while (int x = random()) {
2307 /// // ...
2308 /// }
2309 /// \endcode
2310 VarDecl *getConditionVariable();
2311 const VarDecl *getConditionVariable() const {
2312 return const_cast<WhileStmt *>(this)->getConditionVariable();
2313 }
2314
2315 /// Set the condition variable of this while statement.
2316 /// The while statement must have storage for it.
2317 void setConditionVariable(const ASTContext &Ctx, VarDecl *V);
2318
2319 /// If this WhileStmt has a condition variable, return the faux DeclStmt
2320 /// associated with the creation of that condition variable.
2321 DeclStmt *getConditionVariableDeclStmt() {
2322 return hasVarStorage() ? static_cast<DeclStmt *>(
2323 getTrailingObjects<Stmt *>()[varOffset()])
2324 : nullptr;
2325 }
2326
2327 const DeclStmt *getConditionVariableDeclStmt() const {
2328 return hasVarStorage() ? static_cast<DeclStmt *>(
2329 getTrailingObjects<Stmt *>()[varOffset()])
2330 : nullptr;
2331 }
2332
2333 SourceLocation getWhileLoc() const { return WhileStmtBits.WhileLoc; }
2334 void setWhileLoc(SourceLocation L) { WhileStmtBits.WhileLoc = L; }
2335
2336 SourceLocation getBeginLoc() const { return getWhileLoc(); }
2337 SourceLocation getEndLoc() const LLVM_READONLY {
2338 return getBody()->getEndLoc();
2339 }
2340
2341 static bool classof(const Stmt *T) {
2342 return T->getStmtClass() == WhileStmtClass;
2343 }
2344
2345 // Iterators
2346 child_range children() {
2347 return child_range(getTrailingObjects<Stmt *>(),
2348 getTrailingObjects<Stmt *>() +
2349 numTrailingObjects(OverloadToken<Stmt *>()));
2350 }
2351
2352 const_child_range children() const {
2353 return const_child_range(getTrailingObjects<Stmt *>(),
2354 getTrailingObjects<Stmt *>() +
2355 numTrailingObjects(OverloadToken<Stmt *>()));
2356 }
2357};
2358
2359/// DoStmt - This represents a 'do/while' stmt.
2360class DoStmt : public Stmt {
2361 enum { BODY, COND, END_EXPR };
2362 Stmt *SubExprs[END_EXPR];
2363 SourceLocation WhileLoc;
2364 SourceLocation RParenLoc; // Location of final ')' in do stmt condition.
2365
2366public:
2367 DoStmt(Stmt *Body, Expr *Cond, SourceLocation DL, SourceLocation WL,
2368 SourceLocation RP)
2369 : Stmt(DoStmtClass), WhileLoc(WL), RParenLoc(RP) {
2370 setCond(Cond);
2371 setBody(Body);
2372 setDoLoc(DL);
2373 }
2374
2375 /// Build an empty do-while statement.
2376 explicit DoStmt(EmptyShell Empty) : Stmt(DoStmtClass, Empty) {}
2377
2378 Expr *getCond() { return reinterpret_cast<Expr *>(SubExprs[COND]); }
2379 const Expr *getCond() const {
2380 return reinterpret_cast<Expr *>(SubExprs[COND]);
2381 }
2382
2383 void setCond(Expr *Cond) { SubExprs[COND] = reinterpret_cast<Stmt *>(Cond); }
2384
2385 Stmt *getBody() { return SubExprs[BODY]; }
2386 const Stmt *getBody() const { return SubExprs[BODY]; }
2387 void setBody(Stmt *Body) { SubExprs[BODY] = Body; }
2388
2389 SourceLocation getDoLoc() const { return DoStmtBits.DoLoc; }
2390 void setDoLoc(SourceLocation L) { DoStmtBits.DoLoc = L; }
2391 SourceLocation getWhileLoc() const { return WhileLoc; }
2392 void setWhileLoc(SourceLocation L) { WhileLoc = L; }
2393 SourceLocation getRParenLoc() const { return RParenLoc; }
2394 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2395
2396 SourceLocation getBeginLoc() const { return getDoLoc(); }
2397 SourceLocation getEndLoc() const { return getRParenLoc(); }
2398
2399 static bool classof(const Stmt *T) {
2400 return T->getStmtClass() == DoStmtClass;
2401 }
2402
2403 // Iterators
2404 child_range children() {
2405 return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2406 }
2407
2408 const_child_range children() const {
2409 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2410 }
2411};
2412
2413/// ForStmt - This represents a 'for (init;cond;inc)' stmt. Note that any of
2414/// the init/cond/inc parts of the ForStmt will be null if they were not
2415/// specified in the source.
2416class ForStmt : public Stmt {
2417 enum { INIT, CONDVAR, COND, INC, BODY, END_EXPR };
2418 Stmt* SubExprs[END_EXPR]; // SubExprs[INIT] is an expression or declstmt.
2419 SourceLocation LParenLoc, RParenLoc;
2420
2421public:
2422 ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
2423 Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
2424 SourceLocation RP);
2425
2426 /// Build an empty for statement.
2427 explicit ForStmt(EmptyShell Empty) : Stmt(ForStmtClass, Empty) {}
2428
2429 Stmt *getInit() { return SubExprs[INIT]; }
2430
2431 /// Retrieve the variable declared in this "for" statement, if any.
2432 ///
2433 /// In the following example, "y" is the condition variable.
2434 /// \code
2435 /// for (int x = random(); int y = mangle(x); ++x) {
2436 /// // ...
2437 /// }
2438 /// \endcode
2439 VarDecl *getConditionVariable() const;
2440 void setConditionVariable(const ASTContext &C, VarDecl *V);
2441
2442 /// If this ForStmt has a condition variable, return the faux DeclStmt
2443 /// associated with the creation of that condition variable.
2444 const DeclStmt *getConditionVariableDeclStmt() const {
2445 return reinterpret_cast<DeclStmt*>(SubExprs[CONDVAR]);
2446 }
2447
2448 Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); }
2449 Expr *getInc() { return reinterpret_cast<Expr*>(SubExprs[INC]); }
2450 Stmt *getBody() { return SubExprs[BODY]; }
2451
2452 const Stmt *getInit() const { return SubExprs[INIT]; }
2453 const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);}
2454 const Expr *getInc() const { return reinterpret_cast<Expr*>(SubExprs[INC]); }
2455 const Stmt *getBody() const { return SubExprs[BODY]; }
2456
2457 void setInit(Stmt *S) { SubExprs[INIT] = S; }
2458 void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); }
2459 void setInc(Expr *E) { SubExprs[INC] = reinterpret_cast<Stmt*>(E); }
2460 void setBody(Stmt *S) { SubExprs[BODY] = S; }
2461
2462 SourceLocation getForLoc() const { return ForStmtBits.ForLoc; }
2463 void setForLoc(SourceLocation L) { ForStmtBits.ForLoc = L; }
2464 SourceLocation getLParenLoc() const { return LParenLoc; }
2465 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2466 SourceLocation getRParenLoc() const { return RParenLoc; }
2467 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2468
2469 SourceLocation getBeginLoc() const { return getForLoc(); }
2470 SourceLocation getEndLoc() const { return getBody()->getEndLoc(); }
2471
2472 static bool classof(const Stmt *T) {
2473 return T->getStmtClass() == ForStmtClass;
2474 }
2475
2476 // Iterators
2477 child_range children() {
2478 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2479 }
2480
2481 const_child_range children() const {
2482 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2483 }
2484};
2485
2486/// GotoStmt - This represents a direct goto.
2487class GotoStmt : public Stmt {
2488 LabelDecl *Label;
2489 SourceLocation LabelLoc;
2490
2491public:
2492 GotoStmt(LabelDecl *label, SourceLocation GL, SourceLocation LL)
2493 : Stmt(GotoStmtClass), Label(label), LabelLoc(LL) {
2494 setGotoLoc(GL);
2495 }
2496
2497 /// Build an empty goto statement.
2498 explicit GotoStmt(EmptyShell Empty) : Stmt(GotoStmtClass, Empty) {}
2499
2500 LabelDecl *getLabel() const { return Label; }
2501 void setLabel(LabelDecl *D) { Label = D; }
2502
2503 SourceLocation getGotoLoc() const { return GotoStmtBits.GotoLoc; }
2504 void setGotoLoc(SourceLocation L) { GotoStmtBits.GotoLoc = L; }
2505 SourceLocation getLabelLoc() const { return LabelLoc; }
2506 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2507
2508 SourceLocation getBeginLoc() const { return getGotoLoc(); }
2509 SourceLocation getEndLoc() const { return getLabelLoc(); }
2510
2511 static bool classof(const Stmt *T) {
2512 return T->getStmtClass() == GotoStmtClass;
2513 }
2514
2515 // Iterators
2516 child_range children() {
2517 return child_range(child_iterator(), child_iterator());
2518 }
2519
2520 const_child_range children() const {
2521 return const_child_range(const_child_iterator(), const_child_iterator());
2522 }
2523};
2524
2525/// IndirectGotoStmt - This represents an indirect goto.
2526class IndirectGotoStmt : public Stmt {
2527 SourceLocation StarLoc;
2528 Stmt *Target;
2529
2530public:
2531 IndirectGotoStmt(SourceLocation gotoLoc, SourceLocation starLoc, Expr *target)
2532 : Stmt(IndirectGotoStmtClass), StarLoc(starLoc) {
2533 setTarget(target);
2534 setGotoLoc(gotoLoc);
2535 }
2536
2537 /// Build an empty indirect goto statement.
2538 explicit IndirectGotoStmt(EmptyShell Empty)
2539 : Stmt(IndirectGotoStmtClass, Empty) {}
2540
2541 void setGotoLoc(SourceLocation L) { GotoStmtBits.GotoLoc = L; }
2542 SourceLocation getGotoLoc() const { return GotoStmtBits.GotoLoc; }
2543 void setStarLoc(SourceLocation L) { StarLoc = L; }
2544 SourceLocation getStarLoc() const { return StarLoc; }
2545
2546 Expr *getTarget() { return reinterpret_cast<Expr *>(Target); }
2547 const Expr *getTarget() const {
2548 return reinterpret_cast<const Expr *>(Target);
2549 }
2550 void setTarget(Expr *E) { Target = reinterpret_cast<Stmt *>(E); }
2551
2552 /// getConstantTarget - Returns the fixed target of this indirect
2553 /// goto, if one exists.
2554 LabelDecl *getConstantTarget();
2555 const LabelDecl *getConstantTarget() const {
2556 return const_cast<IndirectGotoStmt *>(this)->getConstantTarget();
2557 }
2558
2559 SourceLocation getBeginLoc() const { return getGotoLoc(); }
2560 SourceLocation getEndLoc() const LLVM_READONLY { return Target->getEndLoc(); }
2561
2562 static bool classof(const Stmt *T) {
2563 return T->getStmtClass() == IndirectGotoStmtClass;
2564 }
2565
2566 // Iterators
2567 child_range children() { return child_range(&Target, &Target + 1); }
2568
2569 const_child_range children() const {
2570 return const_child_range(&Target, &Target + 1);
2571 }
2572};
2573
2574/// ContinueStmt - This represents a continue.
2575class ContinueStmt : public Stmt {
2576public:
2577 ContinueStmt(SourceLocation CL) : Stmt(ContinueStmtClass) {
2578 setContinueLoc(CL);
2579 }
2580
2581 /// Build an empty continue statement.
2582 explicit ContinueStmt(EmptyShell Empty) : Stmt(ContinueStmtClass, Empty) {}
2583
2584 SourceLocation getContinueLoc() const { return ContinueStmtBits.ContinueLoc; }
2585 void setContinueLoc(SourceLocation L) { ContinueStmtBits.ContinueLoc = L; }
2586
2587 SourceLocation getBeginLoc() const { return getContinueLoc(); }
2588 SourceLocation getEndLoc() const { return getContinueLoc(); }
2589
2590 static bool classof(const Stmt *T) {
2591 return T->getStmtClass() == ContinueStmtClass;
2592 }
2593
2594 // Iterators
2595 child_range children() {
2596 return child_range(child_iterator(), child_iterator());
2597 }
2598
2599 const_child_range children() const {
2600 return const_child_range(const_child_iterator(), const_child_iterator());
2601 }
2602};
2603
2604/// BreakStmt - This represents a break.
2605class BreakStmt : public Stmt {
2606public:
2607 BreakStmt(SourceLocation BL) : Stmt(BreakStmtClass) {
2608 setBreakLoc(BL);
2609 }
2610
2611 /// Build an empty break statement.
2612 explicit BreakStmt(EmptyShell Empty) : Stmt(BreakStmtClass, Empty) {}
2613
2614 SourceLocation getBreakLoc() const { return BreakStmtBits.BreakLoc; }
2615 void setBreakLoc(SourceLocation L) { BreakStmtBits.BreakLoc = L; }
2616
2617 SourceLocation getBeginLoc() const { return getBreakLoc(); }
2618 SourceLocation getEndLoc() const { return getBreakLoc(); }
2619
2620 static bool classof(const Stmt *T) {
2621 return T->getStmtClass() == BreakStmtClass;
2622 }
2623
2624 // Iterators
2625 child_range children() {
2626 return child_range(child_iterator(), child_iterator());
2627 }
2628
2629 const_child_range children() const {
2630 return const_child_range(const_child_iterator(), const_child_iterator());
2631 }
2632};
2633
2634/// ReturnStmt - This represents a return, optionally of an expression:
2635/// return;
2636/// return 4;
2637///
2638/// Note that GCC allows return with no argument in a function declared to
2639/// return a value, and it allows returning a value in functions declared to
2640/// return void. We explicitly model this in the AST, which means you can't
2641/// depend on the return type of the function and the presence of an argument.
2642class ReturnStmt final
2643 : public Stmt,
2644 private llvm::TrailingObjects<ReturnStmt, const VarDecl *> {
2645 friend TrailingObjects;
2646
2647 /// The return expression.
2648 Stmt *RetExpr;
2649
2650 // ReturnStmt is followed optionally by a trailing "const VarDecl *"
2651 // for the NRVO candidate. Present if and only if hasNRVOCandidate().
2652
2653 /// True if this ReturnStmt has storage for an NRVO candidate.
2654 bool hasNRVOCandidate() const { return ReturnStmtBits.HasNRVOCandidate; }
2655
2656 unsigned numTrailingObjects(OverloadToken<const VarDecl *>) const {
2657 return hasNRVOCandidate();
2658 }
2659
2660 /// Build a return statement.
2661 ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate);
2662
2663 /// Build an empty return statement.
2664 explicit ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate);
2665
2666public:
2667 /// Create a return statement.
2668 static ReturnStmt *Create(const ASTContext &Ctx, SourceLocation RL, Expr *E,
2669 const VarDecl *NRVOCandidate);
2670
2671 /// Create an empty return statement, optionally with
2672 /// storage for an NRVO candidate.
2673 static ReturnStmt *CreateEmpty(const ASTContext &Ctx, bool HasNRVOCandidate);
2674
2675 Expr *getRetValue() { return reinterpret_cast<Expr *>(RetExpr); }
2676 const Expr *getRetValue() const { return reinterpret_cast<Expr *>(RetExpr); }
2677 void setRetValue(Expr *E) { RetExpr = reinterpret_cast<Stmt *>(E); }
2678
2679 /// Retrieve the variable that might be used for the named return
2680 /// value optimization.
2681 ///
2682 /// The optimization itself can only be performed if the variable is
2683 /// also marked as an NRVO object.
2684 const VarDecl *getNRVOCandidate() const {
2685 return hasNRVOCandidate() ? *getTrailingObjects<const VarDecl *>()
2686 : nullptr;
2687 }
2688
2689 /// Set the variable that might be used for the named return value
2690 /// optimization. The return statement must have storage for it,
2691 /// which is the case if and only if hasNRVOCandidate() is true.
2692 void setNRVOCandidate(const VarDecl *Var) {
2693 assert(hasNRVOCandidate() &&
2694 "This return statement has no storage for an NRVO candidate!");
2695 *getTrailingObjects<const VarDecl *>() = Var;
2696 }
2697
2698 SourceLocation getReturnLoc() const { return ReturnStmtBits.RetLoc; }
2699 void setReturnLoc(SourceLocation L) { ReturnStmtBits.RetLoc = L; }
2700
2701 SourceLocation getBeginLoc() const { return getReturnLoc(); }
2702 SourceLocation getEndLoc() const LLVM_READONLY {
2703 return RetExpr ? RetExpr->getEndLoc() : getReturnLoc();
2704 }
2705
2706 static bool classof(const Stmt *T) {
2707 return T->getStmtClass() == ReturnStmtClass;
2708 }
2709
2710 // Iterators
2711 child_range children() {
2712 if (RetExpr)
2713 return child_range(&RetExpr, &RetExpr + 1);
2714 return child_range(child_iterator(), child_iterator());
2715 }
2716
2717 const_child_range children() const {
2718 if (RetExpr)
2719 return const_child_range(&RetExpr, &RetExpr + 1);
2720 return const_child_range(const_child_iterator(), const_child_iterator());
2721 }
2722};
2723
2724/// AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
2725class AsmStmt : public Stmt {
2726protected:
2727 friend class ASTStmtReader;
2728
2729 SourceLocation AsmLoc;
2730
2731 /// True if the assembly statement does not have any input or output
2732 /// operands.
2733 bool IsSimple;
2734
2735 /// If true, treat this inline assembly as having side effects.
2736 /// This assembly statement should not be optimized, deleted or moved.
2737 bool IsVolatile;
2738
2739 unsigned NumOutputs;
2740 unsigned NumInputs;
2741 unsigned NumClobbers;
2742
2743 Stmt **Exprs = nullptr;
2744
2745 AsmStmt(StmtClass SC, SourceLocation asmloc, bool issimple, bool isvolatile,
2746 unsigned numoutputs, unsigned numinputs, unsigned numclobbers)
2747 : Stmt (SC), AsmLoc(asmloc), IsSimple(issimple), IsVolatile(isvolatile),
2748 NumOutputs(numoutputs), NumInputs(numinputs),
2749 NumClobbers(numclobbers) {}
2750
2751public:
2752 /// Build an empty inline-assembly statement.
2753 explicit AsmStmt(StmtClass SC, EmptyShell Empty) : Stmt(SC, Empty) {}
2754
2755 SourceLocation getAsmLoc() const { return AsmLoc; }
2756 void setAsmLoc(SourceLocation L) { AsmLoc = L; }
2757
2758 bool isSimple() const { return IsSimple; }
2759 void setSimple(bool V) { IsSimple = V; }
2760
2761 bool isVolatile() const { return IsVolatile; }
2762 void setVolatile(bool V) { IsVolatile = V; }
2763
2764 SourceLocation getBeginLoc() const LLVM_READONLY { return {}; }
2765 SourceLocation getEndLoc() const LLVM_READONLY { return {}; }
2766
2767 //===--- Asm String Analysis ---===//
2768
2769 /// Assemble final IR asm string.
2770 std::string generateAsmString(const ASTContext &C) const;
2771
2772 //===--- Output operands ---===//
2773
2774 unsigned getNumOutputs() const { return NumOutputs; }
2775
2776 /// getOutputConstraint - Return the constraint string for the specified
2777 /// output operand. All output constraints are known to be non-empty (either
2778 /// '=' or '+').
2779 StringRef getOutputConstraint(unsigned i) const;
2780
2781 /// isOutputPlusConstraint - Return true if the specified output constraint
2782 /// is a "+" constraint (which is both an input and an output) or false if it
2783 /// is an "=" constraint (just an output).
2784 bool isOutputPlusConstraint(unsigned i) const {
2785 return getOutputConstraint(i)[0] == '+';
2786 }
2787
2788 const Expr *getOutputExpr(unsigned i) const;
2789
2790 /// getNumPlusOperands - Return the number of output operands that have a "+"
2791 /// constraint.
2792 unsigned getNumPlusOperands() const;
2793
2794 //===--- Input operands ---===//
2795
2796 unsigned getNumInputs() const { return NumInputs; }
2797
2798 /// getInputConstraint - Return the specified input constraint. Unlike output
2799 /// constraints, these can be empty.
2800 StringRef getInputConstraint(unsigned i) const;
2801
2802 const Expr *getInputExpr(unsigned i) const;
2803
2804 //===--- Other ---===//
2805
2806 unsigned getNumClobbers() const { return NumClobbers; }
2807 StringRef getClobber(unsigned i) const;
2808
2809 static bool classof(const Stmt *T) {
2810 return T->getStmtClass() == GCCAsmStmtClass ||
2811 T->getStmtClass() == MSAsmStmtClass;
2812 }
2813
2814 // Input expr iterators.
2815
2816 using inputs_iterator = ExprIterator;
2817 using const_inputs_iterator = ConstExprIterator;
2818 using inputs_range = llvm::iterator_range<inputs_iterator>;
2819 using inputs_const_range = llvm::iterator_range<const_inputs_iterator>;
2820
2821 inputs_iterator begin_inputs() {
2822 return &Exprs[0] + NumOutputs;
2823 }
2824
2825 inputs_iterator end_inputs() {
2826 return &Exprs[0] + NumOutputs + NumInputs;
2827 }
2828
2829 inputs_range inputs() { return inputs_range(begin_inputs(), end_inputs()); }
2830
2831 const_inputs_iterator begin_inputs() const {
2832 return &Exprs[0] + NumOutputs;
2833 }
2834
2835 const_inputs_iterator end_inputs() const {
2836 return &Exprs[0] + NumOutputs + NumInputs;
2837 }
2838
2839 inputs_const_range inputs() const {
2840 return inputs_const_range(begin_inputs(), end_inputs());
2841 }
2842
2843 // Output expr iterators.
2844
2845 using outputs_iterator = ExprIterator;
2846 using const_outputs_iterator = ConstExprIterator;
2847 using outputs_range = llvm::iterator_range<outputs_iterator>;
2848 using outputs_const_range = llvm::iterator_range<const_outputs_iterator>;
2849
2850 outputs_iterator begin_outputs() {
2851 return &Exprs[0];
2852 }
2853
2854 outputs_iterator end_outputs() {
2855 return &Exprs[0] + NumOutputs;
2856 }
2857
2858 outputs_range outputs() {
2859 return outputs_range(begin_outputs(), end_outputs());
2860 }
2861
2862 const_outputs_iterator begin_outputs() const {
2863 return &Exprs[0];
2864 }
2865
2866 const_outputs_iterator end_outputs() const {
2867 return &Exprs[0] + NumOutputs;
2868 }
2869
2870 outputs_const_range outputs() const {
2871 return outputs_const_range(begin_outputs(), end_outputs());
2872 }
2873
2874 child_range children() {
2875 return child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs);
2876 }
2877
2878 const_child_range children() const {
2879 return const_child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs);
2880 }
2881};
2882
2883/// This represents a GCC inline-assembly statement extension.
2884class GCCAsmStmt : public AsmStmt {
2885 friend class ASTStmtReader;
2886
2887 SourceLocation RParenLoc;
2888 StringLiteral *AsmStr;
2889
2890 // FIXME: If we wanted to, we could allocate all of these in one big array.
2891 StringLiteral **Constraints = nullptr;
2892 StringLiteral **Clobbers = nullptr;
2893 IdentifierInfo **Names = nullptr;
2894 unsigned NumLabels = 0;
2895
2896public:
2897 GCCAsmStmt(const ASTContext &C, SourceLocation asmloc, bool issimple,
2898 bool isvolatile, unsigned numoutputs, unsigned numinputs,
2899 IdentifierInfo **names, StringLiteral **constraints, Expr **exprs,
2900 StringLiteral *asmstr, unsigned numclobbers,
2901 StringLiteral **clobbers, unsigned numlabels,
2902 SourceLocation rparenloc);
2903
2904 /// Build an empty inline-assembly statement.
2905 explicit GCCAsmStmt(EmptyShell Empty) : AsmStmt(GCCAsmStmtClass, Empty) {}
2906
2907 SourceLocation getRParenLoc() const { return RParenLoc; }
2908 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2909
2910 //===--- Asm String Analysis ---===//
2911
2912 const StringLiteral *getAsmString() const { return AsmStr; }
2913 StringLiteral *getAsmString() { return AsmStr; }
2914 void setAsmString(StringLiteral *E) { AsmStr = E; }
2915
2916 /// AsmStringPiece - this is part of a decomposed asm string specification
2917 /// (for use with the AnalyzeAsmString function below). An asm string is
2918 /// considered to be a concatenation of these parts.
2919 class AsmStringPiece {
2920 public:
2921 enum Kind {
2922 String, // String in .ll asm string form, "$" -> "$$" and "%%" -> "%".
2923 Operand // Operand reference, with optional modifier %c4.
2924 };
2925
2926 private:
2927 Kind MyKind;
2928 std::string Str;
2929 unsigned OperandNo;
2930
2931 // Source range for operand references.
2932 CharSourceRange Range;
2933
2934 public:
2935 AsmStringPiece(const std::string &S) : MyKind(String), Str(S) {}
2936 AsmStringPiece(unsigned OpNo, const std::string &S, SourceLocation Begin,
2937 SourceLocation End)
2938 : MyKind(Operand), Str(S), OperandNo(OpNo),
2939 Range(CharSourceRange::getCharRange(Begin, End)) {}
2940
2941 bool isString() const { return MyKind == String; }
2942 bool isOperand() const { return MyKind == Operand; }
2943
2944 const std::string &getString() const { return Str; }
2945
2946 unsigned getOperandNo() const {
2947 assert(isOperand());
2948 return OperandNo;
2949 }
2950
2951 CharSourceRange getRange() const {
2952 assert(isOperand() && "Range is currently used only for Operands.");
2953 return Range;
2954 }
2955
2956 /// getModifier - Get the modifier for this operand, if present. This
2957 /// returns '\0' if there was no modifier.
2958 char getModifier() const;
2959 };
2960
2961 /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
2962 /// it into pieces. If the asm string is erroneous, emit errors and return
2963 /// true, otherwise return false. This handles canonicalization and
2964 /// translation of strings from GCC syntax to LLVM IR syntax, and handles
2965 //// flattening of named references like %[foo] to Operand AsmStringPiece's.
2966 unsigned AnalyzeAsmString(SmallVectorImpl<AsmStringPiece> &Pieces,
2967 const ASTContext &C, unsigned &DiagOffs) const;
2968
2969 /// Assemble final IR asm string.
2970 std::string generateAsmString(const ASTContext &C) const;
2971
2972 //===--- Output operands ---===//
2973
2974 IdentifierInfo *getOutputIdentifier(unsigned i) const { return Names[i]; }
2975
2976 StringRef getOutputName(unsigned i) const {
2977 if (IdentifierInfo *II = getOutputIdentifier(i))
2978 return II->getName();
2979
2980 return {};
2981 }
2982
2983 StringRef getOutputConstraint(unsigned i) const;
2984
2985 const StringLiteral *getOutputConstraintLiteral(unsigned i) const {
2986 return Constraints[i];
2987 }
2988 StringLiteral *getOutputConstraintLiteral(unsigned i) {
2989 return Constraints[i];
2990 }
2991
2992 Expr *getOutputExpr(unsigned i);
2993
2994 const Expr *getOutputExpr(unsigned i) const {
2995 return const_cast<GCCAsmStmt*>(this)->getOutputExpr(i);
2996 }
2997
2998 //===--- Input operands ---===//
2999
3000 IdentifierInfo *getInputIdentifier(unsigned i) const {
3001 return Names[i + NumOutputs];
3002 }
3003
3004 StringRef getInputName(unsigned i) const {
3005 if (IdentifierInfo *II = getInputIdentifier(i))
3006 return II->getName();
3007
3008 return {};
3009 }
3010
3011 StringRef getInputConstraint(unsigned i) const;
3012
3013 const StringLiteral *getInputConstraintLiteral(unsigned i) const {
3014 return Constraints[i + NumOutputs];
3015 }
3016 StringLiteral *getInputConstraintLiteral(unsigned i) {
3017 return Constraints[i + NumOutputs];
3018 }
3019
3020 Expr *getInputExpr(unsigned i);
3021 void setInputExpr(unsigned i, Expr *E);
3022
3023 const Expr *getInputExpr(unsigned i) const {
3024 return const_cast<GCCAsmStmt*>(this)->getInputExpr(i);
3025 }
3026
3027 //===--- Labels ---===//
3028
3029 bool isAsmGoto() const {
3030 return NumLabels > 0;
3031 }
3032
3033 unsigned getNumLabels() const {
3034 return NumLabels;
3035 }
3036
3037 IdentifierInfo *getLabelIdentifier(unsigned i) const {
3038 return Names[i + NumOutputs + NumInputs];
3039 }
3040
3041 AddrLabelExpr *getLabelExpr(unsigned i) const;
3042 StringRef getLabelName(unsigned i) const;
3043 using labels_iterator = CastIterator<AddrLabelExpr>;
3044 using const_labels_iterator = ConstCastIterator<AddrLabelExpr>;
3045 using labels_range = llvm::iterator_range<labels_iterator>;
3046 using labels_const_range = llvm::iterator_range<const_labels_iterator>;
3047
3048 labels_iterator begin_labels() {
3049 return &Exprs[0] + NumOutputs + NumInputs;
3050 }
3051
3052 labels_iterator end_labels() {
3053 return &Exprs[0] + NumOutputs + NumInputs + NumLabels;
3054 }
3055
3056 labels_range labels() {
3057 return labels_range(begin_labels(), end_labels());
3058 }
3059
3060 const_labels_iterator begin_labels() const {
3061 return &Exprs[0] + NumOutputs + NumInputs;
3062 }
3063
3064 const_labels_iterator end_labels() const {
3065 return &Exprs[0] + NumOutputs + NumInputs + NumLabels;
3066 }
3067
3068 labels_const_range labels() const {
3069 return labels_const_range(begin_labels(), end_labels());
3070 }
3071
3072private:
3073 void setOutputsAndInputsAndClobbers(const ASTContext &C,
3074 IdentifierInfo **Names,
3075 StringLiteral **Constraints,
3076 Stmt **Exprs,
3077 unsigned NumOutputs,
3078 unsigned NumInputs,
3079 unsigned NumLabels,
3080 StringLiteral **Clobbers,
3081 unsigned NumClobbers);
3082
3083public:
3084 //===--- Other ---===//
3085
3086 /// getNamedOperand - Given a symbolic operand reference like %[foo],
3087 /// translate this into a numeric value needed to reference the same operand.
3088 /// This returns -1 if the operand name is invalid.
3089 int getNamedOperand(StringRef SymbolicName) const;
3090
3091 StringRef getClobber(unsigned i) const;
3092
3093 StringLiteral *getClobberStringLiteral(unsigned i) { return Clobbers[i]; }
3094 const StringLiteral *getClobberStringLiteral(unsigned i) const {
3095 return Clobbers[i];
3096 }
3097
3098 SourceLocation getBeginLoc() const LLVM_READONLY { return AsmLoc; }
3099 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3100
3101 static bool classof(const Stmt *T) {
3102 return T->getStmtClass() == GCCAsmStmtClass;
3103 }
3104};
3105
3106/// This represents a Microsoft inline-assembly statement extension.
3107class MSAsmStmt : public AsmStmt {
3108 friend class ASTStmtReader;
3109
3110 SourceLocation LBraceLoc, EndLoc;
3111 StringRef AsmStr;
3112
3113 unsigned NumAsmToks = 0;
3114
3115 Token *AsmToks = nullptr;
3116 StringRef *Constraints = nullptr;
3117 StringRef *Clobbers = nullptr;
3118
3119public:
3120 MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
3121 SourceLocation lbraceloc, bool issimple, bool isvolatile,
3122 ArrayRef<Token> asmtoks, unsigned numoutputs, unsigned numinputs,
3123 ArrayRef<StringRef> constraints,
3124 ArrayRef<Expr*> exprs, StringRef asmstr,
3125 ArrayRef<StringRef> clobbers, SourceLocation endloc);
3126
3127 /// Build an empty MS-style inline-assembly statement.
3128 explicit MSAsmStmt(EmptyShell Empty) : AsmStmt(MSAsmStmtClass, Empty) {}
3129
3130 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3131 void setLBraceLoc(SourceLocation L) { LBraceLoc = L; }
3132 SourceLocation getEndLoc() const { return EndLoc; }
3133 void setEndLoc(SourceLocation L) { EndLoc = L; }
3134
3135 bool hasBraces() const { return LBraceLoc.isValid(); }
3136
3137 unsigned getNumAsmToks() { return NumAsmToks; }
3138 Token *getAsmToks() { return AsmToks; }
3139
3140 //===--- Asm String Analysis ---===//
3141 StringRef getAsmString() const { return AsmStr; }
3142
3143 /// Assemble final IR asm string.
3144 std::string generateAsmString(const ASTContext &C) const;
3145
3146 //===--- Output operands ---===//
3147
3148 StringRef getOutputConstraint(unsigned i) const {
3149 assert(i < NumOutputs);
3150 return Constraints[i];
3151 }
3152
3153 Expr *getOutputExpr(unsigned i);
3154
3155 const Expr *getOutputExpr(unsigned i) const {
3156 return const_cast<MSAsmStmt*>(this)->getOutputExpr(i);
3157 }
3158
3159 //===--- Input operands ---===//
3160
3161 StringRef getInputConstraint(unsigned i) const {
3162 assert(i < NumInputs);
3163 return Constraints[i + NumOutputs];
3164 }
3165
3166 Expr *getInputExpr(unsigned i);
3167 void setInputExpr(unsigned i, Expr *E);
3168
3169 const