]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/Stmt.cpp
Import DTS files from Linux 4.18
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / AST / Stmt.cpp
1 //===- Stmt.cpp - Statement AST Node Implementation -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Stmt class and statement subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTDiagnostic.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclGroup.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/ExprOpenMP.h"
21 #include "clang/AST/Stmt.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/StmtOpenMP.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Basic/CharInfo.h"
27 #include "clang/Basic/LLVM.h"
28 #include "clang/Basic/SourceLocation.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Token.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <algorithm>
40 #include <cassert>
41 #include <cstring>
42 #include <string>
43 #include <utility>
44
45 using namespace clang;
46
47 static struct StmtClassNameTable {
48   const char *Name;
49   unsigned Counter;
50   unsigned Size;
51 } StmtClassInfo[Stmt::lastStmtConstant+1];
52
53 static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) {
54   static bool Initialized = false;
55   if (Initialized)
56     return StmtClassInfo[E];
57
58   // Intialize the table on the first use.
59   Initialized = true;
60 #define ABSTRACT_STMT(STMT)
61 #define STMT(CLASS, PARENT) \
62   StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS;    \
63   StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS);
64 #include "clang/AST/StmtNodes.inc"
65
66   return StmtClassInfo[E];
67 }
68
69 void *Stmt::operator new(size_t bytes, const ASTContext& C,
70                          unsigned alignment) {
71   return ::operator new(bytes, C, alignment);
72 }
73
74 const char *Stmt::getStmtClassName() const {
75   return getStmtInfoTableEntry((StmtClass) StmtBits.sClass).Name;
76 }
77
78 void Stmt::PrintStats() {
79   // Ensure the table is primed.
80   getStmtInfoTableEntry(Stmt::NullStmtClass);
81
82   unsigned sum = 0;
83   llvm::errs() << "\n*** Stmt/Expr Stats:\n";
84   for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
85     if (StmtClassInfo[i].Name == nullptr) continue;
86     sum += StmtClassInfo[i].Counter;
87   }
88   llvm::errs() << "  " << sum << " stmts/exprs total.\n";
89   sum = 0;
90   for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
91     if (StmtClassInfo[i].Name == nullptr) continue;
92     if (StmtClassInfo[i].Counter == 0) continue;
93     llvm::errs() << "    " << StmtClassInfo[i].Counter << " "
94                  << StmtClassInfo[i].Name << ", " << StmtClassInfo[i].Size
95                  << " each (" << StmtClassInfo[i].Counter*StmtClassInfo[i].Size
96                  << " bytes)\n";
97     sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size;
98   }
99
100   llvm::errs() << "Total bytes = " << sum << "\n";
101 }
102
103 void Stmt::addStmtClass(StmtClass s) {
104   ++getStmtInfoTableEntry(s).Counter;
105 }
106
107 bool Stmt::StatisticsEnabled = false;
108 void Stmt::EnableStatistics() {
109   StatisticsEnabled = true;
110 }
111
112 Stmt *Stmt::IgnoreImplicit() {
113   Stmt *s = this;
114
115   if (auto *ewc = dyn_cast<ExprWithCleanups>(s))
116     s = ewc->getSubExpr();
117
118   if (auto *mte = dyn_cast<MaterializeTemporaryExpr>(s))
119     s = mte->GetTemporaryExpr();
120
121   if (auto *bte = dyn_cast<CXXBindTemporaryExpr>(s))
122     s = bte->getSubExpr();
123
124   while (auto *ice = dyn_cast<ImplicitCastExpr>(s))
125     s = ice->getSubExpr();
126
127   return s;
128 }
129
130 /// \brief Skip no-op (attributed, compound) container stmts and skip captured
131 /// stmt at the top, if \a IgnoreCaptured is true.
132 Stmt *Stmt::IgnoreContainers(bool IgnoreCaptured) {
133   Stmt *S = this;
134   if (IgnoreCaptured)
135     if (auto CapS = dyn_cast_or_null<CapturedStmt>(S))
136       S = CapS->getCapturedStmt();
137   while (true) {
138     if (auto AS = dyn_cast_or_null<AttributedStmt>(S))
139       S = AS->getSubStmt();
140     else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) {
141       if (CS->size() != 1)
142         break;
143       S = CS->body_back();
144     } else
145       break;
146   }
147   return S;
148 }
149
150 /// \brief Strip off all label-like statements.
151 ///
152 /// This will strip off label statements, case statements, attributed
153 /// statements and default statements recursively.
154 const Stmt *Stmt::stripLabelLikeStatements() const {
155   const Stmt *S = this;
156   while (true) {
157     if (const LabelStmt *LS = dyn_cast<LabelStmt>(S))
158       S = LS->getSubStmt();
159     else if (const SwitchCase *SC = dyn_cast<SwitchCase>(S))
160       S = SC->getSubStmt();
161     else if (const AttributedStmt *AS = dyn_cast<AttributedStmt>(S))
162       S = AS->getSubStmt();
163     else
164       return S;
165   }
166 }
167
168 namespace {
169
170   struct good {};
171   struct bad {};
172
173   // These silly little functions have to be static inline to suppress
174   // unused warnings, and they have to be defined to suppress other
175   // warnings.
176   static inline good is_good(good) { return good(); }
177
178   typedef Stmt::child_range children_t();
179   template <class T> good implements_children(children_t T::*) {
180     return good();
181   }
182   LLVM_ATTRIBUTE_UNUSED
183   static inline bad implements_children(children_t Stmt::*) {
184     return bad();
185   }
186
187   typedef SourceLocation getLocStart_t() const;
188   template <class T> good implements_getLocStart(getLocStart_t T::*) {
189     return good();
190   }
191   LLVM_ATTRIBUTE_UNUSED
192   static inline bad implements_getLocStart(getLocStart_t Stmt::*) {
193     return bad();
194   }
195
196   typedef SourceLocation getLocEnd_t() const;
197   template <class T> good implements_getLocEnd(getLocEnd_t T::*) {
198     return good();
199   }
200   LLVM_ATTRIBUTE_UNUSED
201   static inline bad implements_getLocEnd(getLocEnd_t Stmt::*) {
202     return bad();
203   }
204
205 #define ASSERT_IMPLEMENTS_children(type) \
206   (void) is_good(implements_children(&type::children))
207 #define ASSERT_IMPLEMENTS_getLocStart(type) \
208   (void) is_good(implements_getLocStart(&type::getLocStart))
209 #define ASSERT_IMPLEMENTS_getLocEnd(type) \
210   (void) is_good(implements_getLocEnd(&type::getLocEnd))
211
212 } // namespace
213
214 /// Check whether the various Stmt classes implement their member
215 /// functions.
216 LLVM_ATTRIBUTE_UNUSED
217 static inline void check_implementations() {
218 #define ABSTRACT_STMT(type)
219 #define STMT(type, base) \
220   ASSERT_IMPLEMENTS_children(type); \
221   ASSERT_IMPLEMENTS_getLocStart(type); \
222   ASSERT_IMPLEMENTS_getLocEnd(type);
223 #include "clang/AST/StmtNodes.inc"
224 }
225
226 Stmt::child_range Stmt::children() {
227   switch (getStmtClass()) {
228   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
229 #define ABSTRACT_STMT(type)
230 #define STMT(type, base) \
231   case Stmt::type##Class: \
232     return static_cast<type*>(this)->children();
233 #include "clang/AST/StmtNodes.inc"
234   }
235   llvm_unreachable("unknown statement kind!");
236 }
237
238 // Amusing macro metaprogramming hack: check whether a class provides
239 // a more specific implementation of getSourceRange.
240 //
241 // See also Expr.cpp:getExprLoc().
242 namespace {
243
244   /// This implementation is used when a class provides a custom
245   /// implementation of getSourceRange.
246   template <class S, class T>
247   SourceRange getSourceRangeImpl(const Stmt *stmt,
248                                  SourceRange (T::*v)() const) {
249     return static_cast<const S*>(stmt)->getSourceRange();
250   }
251
252   /// This implementation is used when a class doesn't provide a custom
253   /// implementation of getSourceRange.  Overload resolution should pick it over
254   /// the implementation above because it's more specialized according to
255   /// function template partial ordering.
256   template <class S>
257   SourceRange getSourceRangeImpl(const Stmt *stmt,
258                                  SourceRange (Stmt::*v)() const) {
259     return SourceRange(static_cast<const S*>(stmt)->getLocStart(),
260                        static_cast<const S*>(stmt)->getLocEnd());
261   }
262
263 } // namespace
264
265 SourceRange Stmt::getSourceRange() const {
266   switch (getStmtClass()) {
267   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
268 #define ABSTRACT_STMT(type)
269 #define STMT(type, base) \
270   case Stmt::type##Class: \
271     return getSourceRangeImpl<type>(this, &type::getSourceRange);
272 #include "clang/AST/StmtNodes.inc"
273   }
274   llvm_unreachable("unknown statement kind!");
275 }
276
277 SourceLocation Stmt::getLocStart() const {
278 //  llvm::errs() << "getLocStart() for " << getStmtClassName() << "\n";
279   switch (getStmtClass()) {
280   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
281 #define ABSTRACT_STMT(type)
282 #define STMT(type, base) \
283   case Stmt::type##Class: \
284     return static_cast<const type*>(this)->getLocStart();
285 #include "clang/AST/StmtNodes.inc"
286   }
287   llvm_unreachable("unknown statement kind");
288 }
289
290 SourceLocation Stmt::getLocEnd() const {
291   switch (getStmtClass()) {
292   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
293 #define ABSTRACT_STMT(type)
294 #define STMT(type, base) \
295   case Stmt::type##Class: \
296     return static_cast<const type*>(this)->getLocEnd();
297 #include "clang/AST/StmtNodes.inc"
298   }
299   llvm_unreachable("unknown statement kind");
300 }
301
302 CompoundStmt::CompoundStmt(ArrayRef<Stmt *> Stmts, SourceLocation LB,
303                            SourceLocation RB)
304     : Stmt(CompoundStmtClass), LBraceLoc(LB), RBraceLoc(RB) {
305   CompoundStmtBits.NumStmts = Stmts.size();
306   setStmts(Stmts);
307 }
308
309 void CompoundStmt::setStmts(ArrayRef<Stmt *> Stmts) {
310   assert(CompoundStmtBits.NumStmts == Stmts.size() &&
311          "NumStmts doesn't fit in bits of CompoundStmtBits.NumStmts!");
312
313   std::copy(Stmts.begin(), Stmts.end(), body_begin());
314 }
315
316 CompoundStmt *CompoundStmt::Create(const ASTContext &C, ArrayRef<Stmt *> Stmts,
317                                    SourceLocation LB, SourceLocation RB) {
318   void *Mem =
319       C.Allocate(totalSizeToAlloc<Stmt *>(Stmts.size()), alignof(CompoundStmt));
320   return new (Mem) CompoundStmt(Stmts, LB, RB);
321 }
322
323 CompoundStmt *CompoundStmt::CreateEmpty(const ASTContext &C,
324                                         unsigned NumStmts) {
325   void *Mem =
326       C.Allocate(totalSizeToAlloc<Stmt *>(NumStmts), alignof(CompoundStmt));
327   CompoundStmt *New = new (Mem) CompoundStmt(EmptyShell());
328   New->CompoundStmtBits.NumStmts = NumStmts;
329   return New;
330 }
331
332 const char *LabelStmt::getName() const {
333   return getDecl()->getIdentifier()->getNameStart();
334 }
335
336 AttributedStmt *AttributedStmt::Create(const ASTContext &C, SourceLocation Loc,
337                                        ArrayRef<const Attr*> Attrs,
338                                        Stmt *SubStmt) {
339   assert(!Attrs.empty() && "Attrs should not be empty");
340   void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(Attrs.size()),
341                          alignof(AttributedStmt));
342   return new (Mem) AttributedStmt(Loc, Attrs, SubStmt);
343 }
344
345 AttributedStmt *AttributedStmt::CreateEmpty(const ASTContext &C,
346                                             unsigned NumAttrs) {
347   assert(NumAttrs > 0 && "NumAttrs should be greater than zero");
348   void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(NumAttrs),
349                          alignof(AttributedStmt));
350   return new (Mem) AttributedStmt(EmptyShell(), NumAttrs);
351 }
352
353 std::string AsmStmt::generateAsmString(const ASTContext &C) const {
354   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
355     return gccAsmStmt->generateAsmString(C);
356   if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
357     return msAsmStmt->generateAsmString(C);
358   llvm_unreachable("unknown asm statement kind!");
359 }
360
361 StringRef AsmStmt::getOutputConstraint(unsigned i) const {
362   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
363     return gccAsmStmt->getOutputConstraint(i);
364   if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
365     return msAsmStmt->getOutputConstraint(i);
366   llvm_unreachable("unknown asm statement kind!");
367 }
368
369 const Expr *AsmStmt::getOutputExpr(unsigned i) const {
370   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
371     return gccAsmStmt->getOutputExpr(i);
372   if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
373     return msAsmStmt->getOutputExpr(i);
374   llvm_unreachable("unknown asm statement kind!");
375 }
376
377 StringRef AsmStmt::getInputConstraint(unsigned i) const {
378   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
379     return gccAsmStmt->getInputConstraint(i);
380   if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
381     return msAsmStmt->getInputConstraint(i);
382   llvm_unreachable("unknown asm statement kind!");
383 }
384
385 const Expr *AsmStmt::getInputExpr(unsigned i) const {
386   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
387     return gccAsmStmt->getInputExpr(i);
388   if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
389     return msAsmStmt->getInputExpr(i);
390   llvm_unreachable("unknown asm statement kind!");
391 }
392
393 StringRef AsmStmt::getClobber(unsigned i) const {
394   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
395     return gccAsmStmt->getClobber(i);
396   if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
397     return msAsmStmt->getClobber(i);
398   llvm_unreachable("unknown asm statement kind!");
399 }
400
401 /// getNumPlusOperands - Return the number of output operands that have a "+"
402 /// constraint.
403 unsigned AsmStmt::getNumPlusOperands() const {
404   unsigned Res = 0;
405   for (unsigned i = 0, e = getNumOutputs(); i != e; ++i)
406     if (isOutputPlusConstraint(i))
407       ++Res;
408   return Res;
409 }
410
411 char GCCAsmStmt::AsmStringPiece::getModifier() const {
412   assert(isOperand() && "Only Operands can have modifiers.");
413   return isLetter(Str[0]) ? Str[0] : '\0';
414 }
415
416 StringRef GCCAsmStmt::getClobber(unsigned i) const {
417   return getClobberStringLiteral(i)->getString();
418 }
419
420 Expr *GCCAsmStmt::getOutputExpr(unsigned i) {
421   return cast<Expr>(Exprs[i]);
422 }
423
424 /// getOutputConstraint - Return the constraint string for the specified
425 /// output operand.  All output constraints are known to be non-empty (either
426 /// '=' or '+').
427 StringRef GCCAsmStmt::getOutputConstraint(unsigned i) const {
428   return getOutputConstraintLiteral(i)->getString();
429 }
430
431 Expr *GCCAsmStmt::getInputExpr(unsigned i) {
432   return cast<Expr>(Exprs[i + NumOutputs]);
433 }
434
435 void GCCAsmStmt::setInputExpr(unsigned i, Expr *E) {
436   Exprs[i + NumOutputs] = E;
437 }
438
439 /// getInputConstraint - Return the specified input constraint.  Unlike output
440 /// constraints, these can be empty.
441 StringRef GCCAsmStmt::getInputConstraint(unsigned i) const {
442   return getInputConstraintLiteral(i)->getString();
443 }
444
445 void GCCAsmStmt::setOutputsAndInputsAndClobbers(const ASTContext &C,
446                                                 IdentifierInfo **Names,
447                                                 StringLiteral **Constraints,
448                                                 Stmt **Exprs,
449                                                 unsigned NumOutputs,
450                                                 unsigned NumInputs,
451                                                 StringLiteral **Clobbers,
452                                                 unsigned NumClobbers) {
453   this->NumOutputs = NumOutputs;
454   this->NumInputs = NumInputs;
455   this->NumClobbers = NumClobbers;
456
457   unsigned NumExprs = NumOutputs + NumInputs;
458
459   C.Deallocate(this->Names);
460   this->Names = new (C) IdentifierInfo*[NumExprs];
461   std::copy(Names, Names + NumExprs, this->Names);
462
463   C.Deallocate(this->Exprs);
464   this->Exprs = new (C) Stmt*[NumExprs];
465   std::copy(Exprs, Exprs + NumExprs, this->Exprs);
466
467   C.Deallocate(this->Constraints);
468   this->Constraints = new (C) StringLiteral*[NumExprs];
469   std::copy(Constraints, Constraints + NumExprs, this->Constraints);
470
471   C.Deallocate(this->Clobbers);
472   this->Clobbers = new (C) StringLiteral*[NumClobbers];
473   std::copy(Clobbers, Clobbers + NumClobbers, this->Clobbers);
474 }
475
476 /// getNamedOperand - Given a symbolic operand reference like %[foo],
477 /// translate this into a numeric value needed to reference the same operand.
478 /// This returns -1 if the operand name is invalid.
479 int GCCAsmStmt::getNamedOperand(StringRef SymbolicName) const {
480   unsigned NumPlusOperands = 0;
481
482   // Check if this is an output operand.
483   for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) {
484     if (getOutputName(i) == SymbolicName)
485       return i;
486   }
487
488   for (unsigned i = 0, e = getNumInputs(); i != e; ++i)
489     if (getInputName(i) == SymbolicName)
490       return getNumOutputs() + NumPlusOperands + i;
491
492   // Not found.
493   return -1;
494 }
495
496 /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
497 /// it into pieces.  If the asm string is erroneous, emit errors and return
498 /// true, otherwise return false.
499 unsigned GCCAsmStmt::AnalyzeAsmString(SmallVectorImpl<AsmStringPiece>&Pieces,
500                                 const ASTContext &C, unsigned &DiagOffs) const {
501   StringRef Str = getAsmString()->getString();
502   const char *StrStart = Str.begin();
503   const char *StrEnd = Str.end();
504   const char *CurPtr = StrStart;
505
506   // "Simple" inline asms have no constraints or operands, just convert the asm
507   // string to escape $'s.
508   if (isSimple()) {
509     std::string Result;
510     for (; CurPtr != StrEnd; ++CurPtr) {
511       switch (*CurPtr) {
512       case '$':
513         Result += "$$";
514         break;
515       default:
516         Result += *CurPtr;
517         break;
518       }
519     }
520     Pieces.push_back(AsmStringPiece(Result));
521     return 0;
522   }
523
524   // CurStringPiece - The current string that we are building up as we scan the
525   // asm string.
526   std::string CurStringPiece;
527
528   bool HasVariants = !C.getTargetInfo().hasNoAsmVariants();
529
530   unsigned LastAsmStringToken = 0;
531   unsigned LastAsmStringOffset = 0;
532
533   while (true) {
534     // Done with the string?
535     if (CurPtr == StrEnd) {
536       if (!CurStringPiece.empty())
537         Pieces.push_back(AsmStringPiece(CurStringPiece));
538       return 0;
539     }
540
541     char CurChar = *CurPtr++;
542     switch (CurChar) {
543     case '$': CurStringPiece += "$$"; continue;
544     case '{': CurStringPiece += (HasVariants ? "$(" : "{"); continue;
545     case '|': CurStringPiece += (HasVariants ? "$|" : "|"); continue;
546     case '}': CurStringPiece += (HasVariants ? "$)" : "}"); continue;
547     case '%':
548       break;
549     default:
550       CurStringPiece += CurChar;
551       continue;
552     }
553
554     // Escaped "%" character in asm string.
555     if (CurPtr == StrEnd) {
556       // % at end of string is invalid (no escape).
557       DiagOffs = CurPtr-StrStart-1;
558       return diag::err_asm_invalid_escape;
559     }
560     // Handle escaped char and continue looping over the asm string.
561     char EscapedChar = *CurPtr++;
562     switch (EscapedChar) {
563     default:
564       break;
565     case '%': // %% -> %
566     case '{': // %{ -> {
567     case '}': // %} -> }
568       CurStringPiece += EscapedChar;
569       continue;
570     case '=': // %= -> Generate a unique ID.
571       CurStringPiece += "${:uid}";
572       continue;
573     }
574
575     // Otherwise, we have an operand.  If we have accumulated a string so far,
576     // add it to the Pieces list.
577     if (!CurStringPiece.empty()) {
578       Pieces.push_back(AsmStringPiece(CurStringPiece));
579       CurStringPiece.clear();
580     }
581
582     // Handle operands that have asmSymbolicName (e.g., %x[foo]) and those that
583     // don't (e.g., %x4). 'x' following the '%' is the constraint modifier.
584
585     const char *Begin = CurPtr - 1; // Points to the character following '%'.
586     const char *Percent = Begin - 1; // Points to '%'.
587
588     if (isLetter(EscapedChar)) {
589       if (CurPtr == StrEnd) { // Premature end.
590         DiagOffs = CurPtr-StrStart-1;
591         return diag::err_asm_invalid_escape;
592       }
593       EscapedChar = *CurPtr++;
594     }
595
596     const TargetInfo &TI = C.getTargetInfo();
597     const SourceManager &SM = C.getSourceManager();
598     const LangOptions &LO = C.getLangOpts();
599
600     // Handle operands that don't have asmSymbolicName (e.g., %x4).
601     if (isDigit(EscapedChar)) {
602       // %n - Assembler operand n
603       unsigned N = 0;
604
605       --CurPtr;
606       while (CurPtr != StrEnd && isDigit(*CurPtr))
607         N = N*10 + ((*CurPtr++)-'0');
608
609       unsigned NumOperands =
610         getNumOutputs() + getNumPlusOperands() + getNumInputs();
611       if (N >= NumOperands) {
612         DiagOffs = CurPtr-StrStart-1;
613         return diag::err_asm_invalid_operand_number;
614       }
615
616       // Str contains "x4" (Operand without the leading %).
617       std::string Str(Begin, CurPtr - Begin);
618
619       // (BeginLoc, EndLoc) represents the range of the operand we are currently
620       // processing. Unlike Str, the range includes the leading '%'.
621       SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
622           Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
623           &LastAsmStringOffset);
624       SourceLocation EndLoc = getAsmString()->getLocationOfByte(
625           CurPtr - StrStart, SM, LO, TI, &LastAsmStringToken,
626           &LastAsmStringOffset);
627
628       Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
629       continue;
630     }
631
632     // Handle operands that have asmSymbolicName (e.g., %x[foo]).
633     if (EscapedChar == '[') {
634       DiagOffs = CurPtr-StrStart-1;
635
636       // Find the ']'.
637       const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr);
638       if (NameEnd == nullptr)
639         return diag::err_asm_unterminated_symbolic_operand_name;
640       if (NameEnd == CurPtr)
641         return diag::err_asm_empty_symbolic_operand_name;
642
643       StringRef SymbolicName(CurPtr, NameEnd - CurPtr);
644
645       int N = getNamedOperand(SymbolicName);
646       if (N == -1) {
647         // Verify that an operand with that name exists.
648         DiagOffs = CurPtr-StrStart;
649         return diag::err_asm_unknown_symbolic_operand_name;
650       }
651
652       // Str contains "x[foo]" (Operand without the leading %).
653       std::string Str(Begin, NameEnd + 1 - Begin);
654
655       // (BeginLoc, EndLoc) represents the range of the operand we are currently
656       // processing. Unlike Str, the range includes the leading '%'.
657       SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
658           Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
659           &LastAsmStringOffset);
660       SourceLocation EndLoc = getAsmString()->getLocationOfByte(
661           NameEnd + 1 - StrStart, SM, LO, TI, &LastAsmStringToken,
662           &LastAsmStringOffset);
663
664       Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
665
666       CurPtr = NameEnd+1;
667       continue;
668     }
669
670     DiagOffs = CurPtr-StrStart-1;
671     return diag::err_asm_invalid_escape;
672   }
673 }
674
675 /// Assemble final IR asm string (GCC-style).
676 std::string GCCAsmStmt::generateAsmString(const ASTContext &C) const {
677   // Analyze the asm string to decompose it into its pieces.  We know that Sema
678   // has already done this, so it is guaranteed to be successful.
679   SmallVector<GCCAsmStmt::AsmStringPiece, 4> Pieces;
680   unsigned DiagOffs;
681   AnalyzeAsmString(Pieces, C, DiagOffs);
682
683   std::string AsmString;
684   for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
685     if (Pieces[i].isString())
686       AsmString += Pieces[i].getString();
687     else if (Pieces[i].getModifier() == '\0')
688       AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
689     else
690       AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
691                    Pieces[i].getModifier() + '}';
692   }
693   return AsmString;
694 }
695
696 /// Assemble final IR asm string (MS-style).
697 std::string MSAsmStmt::generateAsmString(const ASTContext &C) const {
698   // FIXME: This needs to be translated into the IR string representation.
699   return AsmStr;
700 }
701
702 Expr *MSAsmStmt::getOutputExpr(unsigned i) {
703   return cast<Expr>(Exprs[i]);
704 }
705
706 Expr *MSAsmStmt::getInputExpr(unsigned i) {
707   return cast<Expr>(Exprs[i + NumOutputs]);
708 }
709
710 void MSAsmStmt::setInputExpr(unsigned i, Expr *E) {
711   Exprs[i + NumOutputs] = E;
712 }
713
714 //===----------------------------------------------------------------------===//
715 // Constructors
716 //===----------------------------------------------------------------------===//
717
718 GCCAsmStmt::GCCAsmStmt(const ASTContext &C, SourceLocation asmloc,
719                        bool issimple, bool isvolatile, unsigned numoutputs,
720                        unsigned numinputs, IdentifierInfo **names,
721                        StringLiteral **constraints, Expr **exprs,
722                        StringLiteral *asmstr, unsigned numclobbers,
723                        StringLiteral **clobbers, SourceLocation rparenloc)
724     : AsmStmt(GCCAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
725               numinputs, numclobbers), RParenLoc(rparenloc), AsmStr(asmstr) {
726   unsigned NumExprs = NumOutputs + NumInputs;
727
728   Names = new (C) IdentifierInfo*[NumExprs];
729   std::copy(names, names + NumExprs, Names);
730
731   Exprs = new (C) Stmt*[NumExprs];
732   std::copy(exprs, exprs + NumExprs, Exprs);
733
734   Constraints = new (C) StringLiteral*[NumExprs];
735   std::copy(constraints, constraints + NumExprs, Constraints);
736
737   Clobbers = new (C) StringLiteral*[NumClobbers];
738   std::copy(clobbers, clobbers + NumClobbers, Clobbers);
739 }
740
741 MSAsmStmt::MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
742                      SourceLocation lbraceloc, bool issimple, bool isvolatile,
743                      ArrayRef<Token> asmtoks, unsigned numoutputs,
744                      unsigned numinputs,
745                      ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs,
746                      StringRef asmstr, ArrayRef<StringRef> clobbers,
747                      SourceLocation endloc)
748     : AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
749               numinputs, clobbers.size()), LBraceLoc(lbraceloc),
750               EndLoc(endloc), NumAsmToks(asmtoks.size()) {
751   initialize(C, asmstr, asmtoks, constraints, exprs, clobbers);
752 }
753
754 static StringRef copyIntoContext(const ASTContext &C, StringRef str) {
755   return str.copy(C);
756 }
757
758 void MSAsmStmt::initialize(const ASTContext &C, StringRef asmstr,
759                            ArrayRef<Token> asmtoks,
760                            ArrayRef<StringRef> constraints,
761                            ArrayRef<Expr*> exprs,
762                            ArrayRef<StringRef> clobbers) {
763   assert(NumAsmToks == asmtoks.size());
764   assert(NumClobbers == clobbers.size());
765
766   assert(exprs.size() == NumOutputs + NumInputs);
767   assert(exprs.size() == constraints.size());
768
769   AsmStr = copyIntoContext(C, asmstr);
770
771   Exprs = new (C) Stmt*[exprs.size()];
772   std::copy(exprs.begin(), exprs.end(), Exprs);
773
774   AsmToks = new (C) Token[asmtoks.size()];
775   std::copy(asmtoks.begin(), asmtoks.end(), AsmToks);
776
777   Constraints = new (C) StringRef[exprs.size()];
778   std::transform(constraints.begin(), constraints.end(), Constraints,
779                  [&](StringRef Constraint) {
780                    return copyIntoContext(C, Constraint);
781                  });
782
783   Clobbers = new (C) StringRef[NumClobbers];
784   // FIXME: Avoid the allocation/copy if at all possible.
785   std::transform(clobbers.begin(), clobbers.end(), Clobbers,
786                  [&](StringRef Clobber) {
787                    return copyIntoContext(C, Clobber);
788                  });
789 }
790
791 IfStmt::IfStmt(const ASTContext &C, SourceLocation IL, bool IsConstexpr,
792                Stmt *init, VarDecl *var, Expr *cond, Stmt *then,
793                SourceLocation EL, Stmt *elsev)
794     : Stmt(IfStmtClass), IfLoc(IL), ElseLoc(EL) {
795   setConstexpr(IsConstexpr);
796   setConditionVariable(C, var);
797   SubExprs[INIT] = init;
798   SubExprs[COND] = cond;
799   SubExprs[THEN] = then;
800   SubExprs[ELSE] = elsev;
801 }
802
803 VarDecl *IfStmt::getConditionVariable() const {
804   if (!SubExprs[VAR])
805     return nullptr;
806
807   DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
808   return cast<VarDecl>(DS->getSingleDecl());
809 }
810
811 void IfStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
812   if (!V) {
813     SubExprs[VAR] = nullptr;
814     return;
815   }
816
817   SourceRange VarRange = V->getSourceRange();
818   SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
819                                    VarRange.getEnd());
820 }
821
822 bool IfStmt::isObjCAvailabilityCheck() const {
823   return isa<ObjCAvailabilityCheckExpr>(SubExprs[COND]);
824 }
825
826 ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
827                  Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
828                  SourceLocation RP)
829   : Stmt(ForStmtClass), ForLoc(FL), LParenLoc(LP), RParenLoc(RP)
830 {
831   SubExprs[INIT] = Init;
832   setConditionVariable(C, condVar);
833   SubExprs[COND] = Cond;
834   SubExprs[INC] = Inc;
835   SubExprs[BODY] = Body;
836 }
837
838 VarDecl *ForStmt::getConditionVariable() const {
839   if (!SubExprs[CONDVAR])
840     return nullptr;
841
842   DeclStmt *DS = cast<DeclStmt>(SubExprs[CONDVAR]);
843   return cast<VarDecl>(DS->getSingleDecl());
844 }
845
846 void ForStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
847   if (!V) {
848     SubExprs[CONDVAR] = nullptr;
849     return;
850   }
851
852   SourceRange VarRange = V->getSourceRange();
853   SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
854                                        VarRange.getEnd());
855 }
856
857 SwitchStmt::SwitchStmt(const ASTContext &C, Stmt *init, VarDecl *Var,
858                        Expr *cond)
859     : Stmt(SwitchStmtClass), FirstCase(nullptr, false) {
860   setConditionVariable(C, Var);
861   SubExprs[INIT] = init;
862   SubExprs[COND] = cond;
863   SubExprs[BODY] = nullptr;
864 }
865
866 VarDecl *SwitchStmt::getConditionVariable() const {
867   if (!SubExprs[VAR])
868     return nullptr;
869
870   DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
871   return cast<VarDecl>(DS->getSingleDecl());
872 }
873
874 void SwitchStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
875   if (!V) {
876     SubExprs[VAR] = nullptr;
877     return;
878   }
879
880   SourceRange VarRange = V->getSourceRange();
881   SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
882                                    VarRange.getEnd());
883 }
884
885 Stmt *SwitchCase::getSubStmt() {
886   if (isa<CaseStmt>(this))
887     return cast<CaseStmt>(this)->getSubStmt();
888   return cast<DefaultStmt>(this)->getSubStmt();
889 }
890
891 WhileStmt::WhileStmt(const ASTContext &C, VarDecl *Var, Expr *cond, Stmt *body,
892                      SourceLocation WL)
893   : Stmt(WhileStmtClass) {
894   setConditionVariable(C, Var);
895   SubExprs[COND] = cond;
896   SubExprs[BODY] = body;
897   WhileLoc = WL;
898 }
899
900 VarDecl *WhileStmt::getConditionVariable() const {
901   if (!SubExprs[VAR])
902     return nullptr;
903
904   DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
905   return cast<VarDecl>(DS->getSingleDecl());
906 }
907
908 void WhileStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
909   if (!V) {
910     SubExprs[VAR] = nullptr;
911     return;
912   }
913
914   SourceRange VarRange = V->getSourceRange();
915   SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
916                                    VarRange.getEnd());
917 }
918
919 // IndirectGotoStmt
920 LabelDecl *IndirectGotoStmt::getConstantTarget() {
921   if (AddrLabelExpr *E =
922         dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts()))
923     return E->getLabel();
924   return nullptr;
925 }
926
927 // ReturnStmt
928 const Expr* ReturnStmt::getRetValue() const {
929   return cast_or_null<Expr>(RetExpr);
930 }
931 Expr* ReturnStmt::getRetValue() {
932   return cast_or_null<Expr>(RetExpr);
933 }
934
935 SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock,
936                        Stmt *Handler)
937     : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) {
938   Children[TRY]     = TryBlock;
939   Children[HANDLER] = Handler;
940 }
941
942 SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry,
943                                SourceLocation TryLoc, Stmt *TryBlock,
944                                Stmt *Handler) {
945   return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler);
946 }
947
948 SEHExceptStmt* SEHTryStmt::getExceptHandler() const {
949   return dyn_cast<SEHExceptStmt>(getHandler());
950 }
951
952 SEHFinallyStmt* SEHTryStmt::getFinallyHandler() const {
953   return dyn_cast<SEHFinallyStmt>(getHandler());
954 }
955
956 SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
957     : Stmt(SEHExceptStmtClass), Loc(Loc) {
958   Children[FILTER_EXPR] = FilterExpr;
959   Children[BLOCK]       = Block;
960 }
961
962 SEHExceptStmt* SEHExceptStmt::Create(const ASTContext &C, SourceLocation Loc,
963                                      Expr *FilterExpr, Stmt *Block) {
964   return new(C) SEHExceptStmt(Loc,FilterExpr,Block);
965 }
966
967 SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block)
968     : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {}
969
970 SEHFinallyStmt* SEHFinallyStmt::Create(const ASTContext &C, SourceLocation Loc,
971                                        Stmt *Block) {
972   return new(C)SEHFinallyStmt(Loc,Block);
973 }
974
975 CapturedStmt::Capture::Capture(SourceLocation Loc, VariableCaptureKind Kind,
976                                VarDecl *Var)
977     : VarAndKind(Var, Kind), Loc(Loc) {
978   switch (Kind) {
979   case VCK_This:
980     assert(!Var && "'this' capture cannot have a variable!");
981     break;
982   case VCK_ByRef:
983     assert(Var && "capturing by reference must have a variable!");
984     break;
985   case VCK_ByCopy:
986     assert(Var && "capturing by copy must have a variable!");
987     assert(
988         (Var->getType()->isScalarType() || (Var->getType()->isReferenceType() &&
989                                             Var->getType()
990                                                 ->castAs<ReferenceType>()
991                                                 ->getPointeeType()
992                                                 ->isScalarType())) &&
993         "captures by copy are expected to have a scalar type!");
994     break;
995   case VCK_VLAType:
996     assert(!Var &&
997            "Variable-length array type capture cannot have a variable!");
998     break;
999   }
1000 }
1001
1002 CapturedStmt::VariableCaptureKind
1003 CapturedStmt::Capture::getCaptureKind() const {
1004   return VarAndKind.getInt();
1005 }
1006
1007 VarDecl *CapturedStmt::Capture::getCapturedVar() const {
1008   assert((capturesVariable() || capturesVariableByCopy()) &&
1009          "No variable available for 'this' or VAT capture");
1010   return VarAndKind.getPointer();
1011 }
1012
1013 CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const {
1014   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1015
1016   // Offset of the first Capture object.
1017   unsigned FirstCaptureOffset = llvm::alignTo(Size, alignof(Capture));
1018
1019   return reinterpret_cast<Capture *>(
1020       reinterpret_cast<char *>(const_cast<CapturedStmt *>(this))
1021       + FirstCaptureOffset);
1022 }
1023
1024 CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind,
1025                            ArrayRef<Capture> Captures,
1026                            ArrayRef<Expr *> CaptureInits,
1027                            CapturedDecl *CD,
1028                            RecordDecl *RD)
1029   : Stmt(CapturedStmtClass), NumCaptures(Captures.size()),
1030     CapDeclAndKind(CD, Kind), TheRecordDecl(RD) {
1031   assert( S && "null captured statement");
1032   assert(CD && "null captured declaration for captured statement");
1033   assert(RD && "null record declaration for captured statement");
1034
1035   // Copy initialization expressions.
1036   Stmt **Stored = getStoredStmts();
1037   for (unsigned I = 0, N = NumCaptures; I != N; ++I)
1038     *Stored++ = CaptureInits[I];
1039
1040   // Copy the statement being captured.
1041   *Stored = S;
1042
1043   // Copy all Capture objects.
1044   Capture *Buffer = getStoredCaptures();
1045   std::copy(Captures.begin(), Captures.end(), Buffer);
1046 }
1047
1048 CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures)
1049   : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures),
1050     CapDeclAndKind(nullptr, CR_Default) {
1051   getStoredStmts()[NumCaptures] = nullptr;
1052 }
1053
1054 CapturedStmt *CapturedStmt::Create(const ASTContext &Context, Stmt *S,
1055                                    CapturedRegionKind Kind,
1056                                    ArrayRef<Capture> Captures,
1057                                    ArrayRef<Expr *> CaptureInits,
1058                                    CapturedDecl *CD,
1059                                    RecordDecl *RD) {
1060   // The layout is
1061   //
1062   // -----------------------------------------------------------
1063   // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture |
1064   // ----------------^-------------------^----------------------
1065   //                 getStoredStmts()    getStoredCaptures()
1066   //
1067   // where S is the statement being captured.
1068   //
1069   assert(CaptureInits.size() == Captures.size() && "wrong number of arguments");
1070
1071   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1);
1072   if (!Captures.empty()) {
1073     // Realign for the following Capture array.
1074     Size = llvm::alignTo(Size, alignof(Capture));
1075     Size += sizeof(Capture) * Captures.size();
1076   }
1077
1078   void *Mem = Context.Allocate(Size);
1079   return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD);
1080 }
1081
1082 CapturedStmt *CapturedStmt::CreateDeserialized(const ASTContext &Context,
1083                                                unsigned NumCaptures) {
1084   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1085   if (NumCaptures > 0) {
1086     // Realign for the following Capture array.
1087     Size = llvm::alignTo(Size, alignof(Capture));
1088     Size += sizeof(Capture) * NumCaptures;
1089   }
1090
1091   void *Mem = Context.Allocate(Size);
1092   return new (Mem) CapturedStmt(EmptyShell(), NumCaptures);
1093 }
1094
1095 Stmt::child_range CapturedStmt::children() {
1096   // Children are captured field initializers.
1097   return child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1098 }
1099
1100 CapturedDecl *CapturedStmt::getCapturedDecl() {
1101   return CapDeclAndKind.getPointer();
1102 }
1103
1104 const CapturedDecl *CapturedStmt::getCapturedDecl() const {
1105   return CapDeclAndKind.getPointer();
1106 }
1107
1108 /// \brief Set the outlined function declaration.
1109 void CapturedStmt::setCapturedDecl(CapturedDecl *D) {
1110   assert(D && "null CapturedDecl");
1111   CapDeclAndKind.setPointer(D);
1112 }
1113
1114 /// \brief Retrieve the captured region kind.
1115 CapturedRegionKind CapturedStmt::getCapturedRegionKind() const {
1116   return CapDeclAndKind.getInt();
1117 }
1118
1119 /// \brief Set the captured region kind.
1120 void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) {
1121   CapDeclAndKind.setInt(Kind);
1122 }
1123
1124 bool CapturedStmt::capturesVariable(const VarDecl *Var) const {
1125   for (const auto &I : captures()) {
1126     if (!I.capturesVariable() && !I.capturesVariableByCopy())
1127       continue;
1128     if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl())
1129       return true;
1130   }
1131
1132   return false;
1133 }