Home | History | Annotate | Line # | Download | only in AST
      1 //===- Stmt.cpp - Statement AST Node Implementation -----------------------===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 // This file implements the Stmt class and statement subclasses.
     10 //
     11 //===----------------------------------------------------------------------===//
     12 
     13 #include "clang/AST/Stmt.h"
     14 #include "clang/AST/ASTContext.h"
     15 #include "clang/AST/ASTDiagnostic.h"
     16 #include "clang/AST/Attr.h"
     17 #include "clang/AST/Decl.h"
     18 #include "clang/AST/DeclGroup.h"
     19 #include "clang/AST/Expr.h"
     20 #include "clang/AST/ExprCXX.h"
     21 #include "clang/AST/ExprConcepts.h"
     22 #include "clang/AST/ExprObjC.h"
     23 #include "clang/AST/ExprOpenMP.h"
     24 #include "clang/AST/StmtCXX.h"
     25 #include "clang/AST/StmtObjC.h"
     26 #include "clang/AST/StmtOpenMP.h"
     27 #include "clang/AST/Type.h"
     28 #include "clang/Basic/CharInfo.h"
     29 #include "clang/Basic/LLVM.h"
     30 #include "clang/Basic/SourceLocation.h"
     31 #include "clang/Basic/TargetInfo.h"
     32 #include "clang/Lex/Token.h"
     33 #include "llvm/ADT/SmallVector.h"
     34 #include "llvm/ADT/StringExtras.h"
     35 #include "llvm/ADT/StringRef.h"
     36 #include "llvm/Support/Casting.h"
     37 #include "llvm/Support/Compiler.h"
     38 #include "llvm/Support/ErrorHandling.h"
     39 #include "llvm/Support/MathExtras.h"
     40 #include "llvm/Support/raw_ostream.h"
     41 #include <algorithm>
     42 #include <cassert>
     43 #include <cstring>
     44 #include <string>
     45 #include <type_traits>
     46 #include <utility>
     47 
     48 using namespace clang;
     49 
     50 static struct StmtClassNameTable {
     51   const char *Name;
     52   unsigned Counter;
     53   unsigned Size;
     54 } StmtClassInfo[Stmt::lastStmtConstant+1];
     55 
     56 static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) {
     57   static bool Initialized = false;
     58   if (Initialized)
     59     return StmtClassInfo[E];
     60 
     61   // Initialize the table on the first use.
     62   Initialized = true;
     63 #define ABSTRACT_STMT(STMT)
     64 #define STMT(CLASS, PARENT) \
     65   StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS;    \
     66   StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS);
     67 #include "clang/AST/StmtNodes.inc"
     68 
     69   return StmtClassInfo[E];
     70 }
     71 
     72 void *Stmt::operator new(size_t bytes, const ASTContext& C,
     73                          unsigned alignment) {
     74   return ::operator new(bytes, C, alignment);
     75 }
     76 
     77 const char *Stmt::getStmtClassName() const {
     78   return getStmtInfoTableEntry((StmtClass) StmtBits.sClass).Name;
     79 }
     80 
     81 // Check that no statement / expression class is polymorphic. LLVM style RTTI
     82 // should be used instead. If absolutely needed an exception can still be added
     83 // here by defining the appropriate macro (but please don't do this).
     84 #define STMT(CLASS, PARENT) \
     85   static_assert(!std::is_polymorphic<CLASS>::value, \
     86                 #CLASS " should not be polymorphic!");
     87 #include "clang/AST/StmtNodes.inc"
     88 
     89 // Check that no statement / expression class has a non-trival destructor.
     90 // Statements and expressions are allocated with the BumpPtrAllocator from
     91 // ASTContext and therefore their destructor is not executed.
     92 #define STMT(CLASS, PARENT)                                                    \
     93   static_assert(std::is_trivially_destructible<CLASS>::value,                  \
     94                 #CLASS " should be trivially destructible!");
     95 // FIXME: InitListExpr is not trivially destructible due to its ASTVector.
     96 #define INITLISTEXPR(CLASS, PARENT)
     97 #include "clang/AST/StmtNodes.inc"
     98 
     99 void Stmt::PrintStats() {
    100   // Ensure the table is primed.
    101   getStmtInfoTableEntry(Stmt::NullStmtClass);
    102 
    103   unsigned sum = 0;
    104   llvm::errs() << "\n*** Stmt/Expr Stats:\n";
    105   for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
    106     if (StmtClassInfo[i].Name == nullptr) continue;
    107     sum += StmtClassInfo[i].Counter;
    108   }
    109   llvm::errs() << "  " << sum << " stmts/exprs total.\n";
    110   sum = 0;
    111   for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
    112     if (StmtClassInfo[i].Name == nullptr) continue;
    113     if (StmtClassInfo[i].Counter == 0) continue;
    114     llvm::errs() << "    " << StmtClassInfo[i].Counter << " "
    115                  << StmtClassInfo[i].Name << ", " << StmtClassInfo[i].Size
    116                  << " each (" << StmtClassInfo[i].Counter*StmtClassInfo[i].Size
    117                  << " bytes)\n";
    118     sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size;
    119   }
    120 
    121   llvm::errs() << "Total bytes = " << sum << "\n";
    122 }
    123 
    124 void Stmt::addStmtClass(StmtClass s) {
    125   ++getStmtInfoTableEntry(s).Counter;
    126 }
    127 
    128 bool Stmt::StatisticsEnabled = false;
    129 void Stmt::EnableStatistics() {
    130   StatisticsEnabled = true;
    131 }
    132 
    133 static std::pair<Stmt::Likelihood, const Attr *>
    134 getLikelihood(ArrayRef<const Attr *> Attrs) {
    135   for (const auto *A : Attrs) {
    136     if (isa<LikelyAttr>(A))
    137       return std::make_pair(Stmt::LH_Likely, A);
    138 
    139     if (isa<UnlikelyAttr>(A))
    140       return std::make_pair(Stmt::LH_Unlikely, A);
    141   }
    142 
    143   return std::make_pair(Stmt::LH_None, nullptr);
    144 }
    145 
    146 static std::pair<Stmt::Likelihood, const Attr *> getLikelihood(const Stmt *S) {
    147   if (const auto *AS = dyn_cast_or_null<AttributedStmt>(S))
    148     return getLikelihood(AS->getAttrs());
    149 
    150   return std::make_pair(Stmt::LH_None, nullptr);
    151 }
    152 
    153 Stmt::Likelihood Stmt::getLikelihood(ArrayRef<const Attr *> Attrs) {
    154   return ::getLikelihood(Attrs).first;
    155 }
    156 
    157 Stmt::Likelihood Stmt::getLikelihood(const Stmt *S) {
    158   return ::getLikelihood(S).first;
    159 }
    160 
    161 const Attr *Stmt::getLikelihoodAttr(const Stmt *S) {
    162   return ::getLikelihood(S).second;
    163 }
    164 
    165 Stmt::Likelihood Stmt::getLikelihood(const Stmt *Then, const Stmt *Else) {
    166   Likelihood LHT = ::getLikelihood(Then).first;
    167   Likelihood LHE = ::getLikelihood(Else).first;
    168   if (LHE == LH_None)
    169     return LHT;
    170 
    171   // If the same attribute is used on both branches there's a conflict.
    172   if (LHT == LHE)
    173     return LH_None;
    174 
    175   if (LHT != LH_None)
    176     return LHT;
    177 
    178   // Invert the value of Else to get the value for Then.
    179   return LHE == LH_Likely ? LH_Unlikely : LH_Likely;
    180 }
    181 
    182 std::tuple<bool, const Attr *, const Attr *>
    183 Stmt::determineLikelihoodConflict(const Stmt *Then, const Stmt *Else) {
    184   std::pair<Likelihood, const Attr *> LHT = ::getLikelihood(Then);
    185   std::pair<Likelihood, const Attr *> LHE = ::getLikelihood(Else);
    186   // If the same attribute is used on both branches there's a conflict.
    187   if (LHT.first != LH_None && LHT.first == LHE.first)
    188     return std::make_tuple(true, LHT.second, LHE.second);
    189 
    190   return std::make_tuple(false, nullptr, nullptr);
    191 }
    192 
    193 /// Skip no-op (attributed, compound) container stmts and skip captured
    194 /// stmt at the top, if \a IgnoreCaptured is true.
    195 Stmt *Stmt::IgnoreContainers(bool IgnoreCaptured) {
    196   Stmt *S = this;
    197   if (IgnoreCaptured)
    198     if (auto CapS = dyn_cast_or_null<CapturedStmt>(S))
    199       S = CapS->getCapturedStmt();
    200   while (true) {
    201     if (auto AS = dyn_cast_or_null<AttributedStmt>(S))
    202       S = AS->getSubStmt();
    203     else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) {
    204       if (CS->size() != 1)
    205         break;
    206       S = CS->body_back();
    207     } else
    208       break;
    209   }
    210   return S;
    211 }
    212 
    213 /// Strip off all label-like statements.
    214 ///
    215 /// This will strip off label statements, case statements, attributed
    216 /// statements and default statements recursively.
    217 const Stmt *Stmt::stripLabelLikeStatements() const {
    218   const Stmt *S = this;
    219   while (true) {
    220     if (const auto *LS = dyn_cast<LabelStmt>(S))
    221       S = LS->getSubStmt();
    222     else if (const auto *SC = dyn_cast<SwitchCase>(S))
    223       S = SC->getSubStmt();
    224     else if (const auto *AS = dyn_cast<AttributedStmt>(S))
    225       S = AS->getSubStmt();
    226     else
    227       return S;
    228   }
    229 }
    230 
    231 namespace {
    232 
    233   struct good {};
    234   struct bad {};
    235 
    236   // These silly little functions have to be static inline to suppress
    237   // unused warnings, and they have to be defined to suppress other
    238   // warnings.
    239   static good is_good(good) { return good(); }
    240 
    241   typedef Stmt::child_range children_t();
    242   template <class T> good implements_children(children_t T::*) {
    243     return good();
    244   }
    245   LLVM_ATTRIBUTE_UNUSED
    246   static bad implements_children(children_t Stmt::*) {
    247     return bad();
    248   }
    249 
    250   typedef SourceLocation getBeginLoc_t() const;
    251   template <class T> good implements_getBeginLoc(getBeginLoc_t T::*) {
    252     return good();
    253   }
    254   LLVM_ATTRIBUTE_UNUSED
    255   static bad implements_getBeginLoc(getBeginLoc_t Stmt::*) { return bad(); }
    256 
    257   typedef SourceLocation getLocEnd_t() const;
    258   template <class T> good implements_getEndLoc(getLocEnd_t T::*) {
    259     return good();
    260   }
    261   LLVM_ATTRIBUTE_UNUSED
    262   static bad implements_getEndLoc(getLocEnd_t Stmt::*) { return bad(); }
    263 
    264 #define ASSERT_IMPLEMENTS_children(type) \
    265   (void) is_good(implements_children(&type::children))
    266 #define ASSERT_IMPLEMENTS_getBeginLoc(type)                                    \
    267   (void)is_good(implements_getBeginLoc(&type::getBeginLoc))
    268 #define ASSERT_IMPLEMENTS_getEndLoc(type)                                      \
    269   (void)is_good(implements_getEndLoc(&type::getEndLoc))
    270 
    271 } // namespace
    272 
    273 /// Check whether the various Stmt classes implement their member
    274 /// functions.
    275 LLVM_ATTRIBUTE_UNUSED
    276 static inline void check_implementations() {
    277 #define ABSTRACT_STMT(type)
    278 #define STMT(type, base)                                                       \
    279   ASSERT_IMPLEMENTS_children(type);                                            \
    280   ASSERT_IMPLEMENTS_getBeginLoc(type);                                         \
    281   ASSERT_IMPLEMENTS_getEndLoc(type);
    282 #include "clang/AST/StmtNodes.inc"
    283 }
    284 
    285 Stmt::child_range Stmt::children() {
    286   switch (getStmtClass()) {
    287   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
    288 #define ABSTRACT_STMT(type)
    289 #define STMT(type, base) \
    290   case Stmt::type##Class: \
    291     return static_cast<type*>(this)->children();
    292 #include "clang/AST/StmtNodes.inc"
    293   }
    294   llvm_unreachable("unknown statement kind!");
    295 }
    296 
    297 // Amusing macro metaprogramming hack: check whether a class provides
    298 // a more specific implementation of getSourceRange.
    299 //
    300 // See also Expr.cpp:getExprLoc().
    301 namespace {
    302 
    303   /// This implementation is used when a class provides a custom
    304   /// implementation of getSourceRange.
    305   template <class S, class T>
    306   SourceRange getSourceRangeImpl(const Stmt *stmt,
    307                                  SourceRange (T::*v)() const) {
    308     return static_cast<const S*>(stmt)->getSourceRange();
    309   }
    310 
    311   /// This implementation is used when a class doesn't provide a custom
    312   /// implementation of getSourceRange.  Overload resolution should pick it over
    313   /// the implementation above because it's more specialized according to
    314   /// function template partial ordering.
    315   template <class S>
    316   SourceRange getSourceRangeImpl(const Stmt *stmt,
    317                                  SourceRange (Stmt::*v)() const) {
    318     return SourceRange(static_cast<const S *>(stmt)->getBeginLoc(),
    319                        static_cast<const S *>(stmt)->getEndLoc());
    320   }
    321 
    322 } // namespace
    323 
    324 SourceRange Stmt::getSourceRange() const {
    325   switch (getStmtClass()) {
    326   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
    327 #define ABSTRACT_STMT(type)
    328 #define STMT(type, base) \
    329   case Stmt::type##Class: \
    330     return getSourceRangeImpl<type>(this, &type::getSourceRange);
    331 #include "clang/AST/StmtNodes.inc"
    332   }
    333   llvm_unreachable("unknown statement kind!");
    334 }
    335 
    336 SourceLocation Stmt::getBeginLoc() const {
    337   switch (getStmtClass()) {
    338   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
    339 #define ABSTRACT_STMT(type)
    340 #define STMT(type, base)                                                       \
    341   case Stmt::type##Class:                                                      \
    342     return static_cast<const type *>(this)->getBeginLoc();
    343 #include "clang/AST/StmtNodes.inc"
    344   }
    345   llvm_unreachable("unknown statement kind");
    346 }
    347 
    348 SourceLocation Stmt::getEndLoc() const {
    349   switch (getStmtClass()) {
    350   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
    351 #define ABSTRACT_STMT(type)
    352 #define STMT(type, base)                                                       \
    353   case Stmt::type##Class:                                                      \
    354     return static_cast<const type *>(this)->getEndLoc();
    355 #include "clang/AST/StmtNodes.inc"
    356   }
    357   llvm_unreachable("unknown statement kind");
    358 }
    359 
    360 int64_t Stmt::getID(const ASTContext &Context) const {
    361   return Context.getAllocator().identifyKnownAlignedObject<Stmt>(this);
    362 }
    363 
    364 CompoundStmt::CompoundStmt(ArrayRef<Stmt *> Stmts, SourceLocation LB,
    365                            SourceLocation RB)
    366     : Stmt(CompoundStmtClass), RBraceLoc(RB) {
    367   CompoundStmtBits.NumStmts = Stmts.size();
    368   setStmts(Stmts);
    369   CompoundStmtBits.LBraceLoc = LB;
    370 }
    371 
    372 void CompoundStmt::setStmts(ArrayRef<Stmt *> Stmts) {
    373   assert(CompoundStmtBits.NumStmts == Stmts.size() &&
    374          "NumStmts doesn't fit in bits of CompoundStmtBits.NumStmts!");
    375 
    376   std::copy(Stmts.begin(), Stmts.end(), body_begin());
    377 }
    378 
    379 CompoundStmt *CompoundStmt::Create(const ASTContext &C, ArrayRef<Stmt *> Stmts,
    380                                    SourceLocation LB, SourceLocation RB) {
    381   void *Mem =
    382       C.Allocate(totalSizeToAlloc<Stmt *>(Stmts.size()), alignof(CompoundStmt));
    383   return new (Mem) CompoundStmt(Stmts, LB, RB);
    384 }
    385 
    386 CompoundStmt *CompoundStmt::CreateEmpty(const ASTContext &C,
    387                                         unsigned NumStmts) {
    388   void *Mem =
    389       C.Allocate(totalSizeToAlloc<Stmt *>(NumStmts), alignof(CompoundStmt));
    390   CompoundStmt *New = new (Mem) CompoundStmt(EmptyShell());
    391   New->CompoundStmtBits.NumStmts = NumStmts;
    392   return New;
    393 }
    394 
    395 const Expr *ValueStmt::getExprStmt() const {
    396   const Stmt *S = this;
    397   do {
    398     if (const auto *E = dyn_cast<Expr>(S))
    399       return E;
    400 
    401     if (const auto *LS = dyn_cast<LabelStmt>(S))
    402       S = LS->getSubStmt();
    403     else if (const auto *AS = dyn_cast<AttributedStmt>(S))
    404       S = AS->getSubStmt();
    405     else
    406       llvm_unreachable("unknown kind of ValueStmt");
    407   } while (isa<ValueStmt>(S));
    408 
    409   return nullptr;
    410 }
    411 
    412 const char *LabelStmt::getName() const {
    413   return getDecl()->getIdentifier()->getNameStart();
    414 }
    415 
    416 AttributedStmt *AttributedStmt::Create(const ASTContext &C, SourceLocation Loc,
    417                                        ArrayRef<const Attr*> Attrs,
    418                                        Stmt *SubStmt) {
    419   assert(!Attrs.empty() && "Attrs should not be empty");
    420   void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(Attrs.size()),
    421                          alignof(AttributedStmt));
    422   return new (Mem) AttributedStmt(Loc, Attrs, SubStmt);
    423 }
    424 
    425 AttributedStmt *AttributedStmt::CreateEmpty(const ASTContext &C,
    426                                             unsigned NumAttrs) {
    427   assert(NumAttrs > 0 && "NumAttrs should be greater than zero");
    428   void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(NumAttrs),
    429                          alignof(AttributedStmt));
    430   return new (Mem) AttributedStmt(EmptyShell(), NumAttrs);
    431 }
    432 
    433 std::string AsmStmt::generateAsmString(const ASTContext &C) const {
    434   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
    435     return gccAsmStmt->generateAsmString(C);
    436   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
    437     return msAsmStmt->generateAsmString(C);
    438   llvm_unreachable("unknown asm statement kind!");
    439 }
    440 
    441 StringRef AsmStmt::getOutputConstraint(unsigned i) const {
    442   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
    443     return gccAsmStmt->getOutputConstraint(i);
    444   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
    445     return msAsmStmt->getOutputConstraint(i);
    446   llvm_unreachable("unknown asm statement kind!");
    447 }
    448 
    449 const Expr *AsmStmt::getOutputExpr(unsigned i) const {
    450   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
    451     return gccAsmStmt->getOutputExpr(i);
    452   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
    453     return msAsmStmt->getOutputExpr(i);
    454   llvm_unreachable("unknown asm statement kind!");
    455 }
    456 
    457 StringRef AsmStmt::getInputConstraint(unsigned i) const {
    458   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
    459     return gccAsmStmt->getInputConstraint(i);
    460   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
    461     return msAsmStmt->getInputConstraint(i);
    462   llvm_unreachable("unknown asm statement kind!");
    463 }
    464 
    465 const Expr *AsmStmt::getInputExpr(unsigned i) const {
    466   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
    467     return gccAsmStmt->getInputExpr(i);
    468   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
    469     return msAsmStmt->getInputExpr(i);
    470   llvm_unreachable("unknown asm statement kind!");
    471 }
    472 
    473 StringRef AsmStmt::getClobber(unsigned i) const {
    474   if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
    475     return gccAsmStmt->getClobber(i);
    476   if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
    477     return msAsmStmt->getClobber(i);
    478   llvm_unreachable("unknown asm statement kind!");
    479 }
    480 
    481 /// getNumPlusOperands - Return the number of output operands that have a "+"
    482 /// constraint.
    483 unsigned AsmStmt::getNumPlusOperands() const {
    484   unsigned Res = 0;
    485   for (unsigned i = 0, e = getNumOutputs(); i != e; ++i)
    486     if (isOutputPlusConstraint(i))
    487       ++Res;
    488   return Res;
    489 }
    490 
    491 char GCCAsmStmt::AsmStringPiece::getModifier() const {
    492   assert(isOperand() && "Only Operands can have modifiers.");
    493   return isLetter(Str[0]) ? Str[0] : '\0';
    494 }
    495 
    496 StringRef GCCAsmStmt::getClobber(unsigned i) const {
    497   return getClobberStringLiteral(i)->getString();
    498 }
    499 
    500 Expr *GCCAsmStmt::getOutputExpr(unsigned i) {
    501   return cast<Expr>(Exprs[i]);
    502 }
    503 
    504 /// getOutputConstraint - Return the constraint string for the specified
    505 /// output operand.  All output constraints are known to be non-empty (either
    506 /// '=' or '+').
    507 StringRef GCCAsmStmt::getOutputConstraint(unsigned i) const {
    508   return getOutputConstraintLiteral(i)->getString();
    509 }
    510 
    511 Expr *GCCAsmStmt::getInputExpr(unsigned i) {
    512   return cast<Expr>(Exprs[i + NumOutputs]);
    513 }
    514 
    515 void GCCAsmStmt::setInputExpr(unsigned i, Expr *E) {
    516   Exprs[i + NumOutputs] = E;
    517 }
    518 
    519 AddrLabelExpr *GCCAsmStmt::getLabelExpr(unsigned i) const {
    520   return cast<AddrLabelExpr>(Exprs[i + NumOutputs + NumInputs]);
    521 }
    522 
    523 StringRef GCCAsmStmt::getLabelName(unsigned i) const {
    524   return getLabelExpr(i)->getLabel()->getName();
    525 }
    526 
    527 /// getInputConstraint - Return the specified input constraint.  Unlike output
    528 /// constraints, these can be empty.
    529 StringRef GCCAsmStmt::getInputConstraint(unsigned i) const {
    530   return getInputConstraintLiteral(i)->getString();
    531 }
    532 
    533 void GCCAsmStmt::setOutputsAndInputsAndClobbers(const ASTContext &C,
    534                                                 IdentifierInfo **Names,
    535                                                 StringLiteral **Constraints,
    536                                                 Stmt **Exprs,
    537                                                 unsigned NumOutputs,
    538                                                 unsigned NumInputs,
    539                                                 unsigned NumLabels,
    540                                                 StringLiteral **Clobbers,
    541                                                 unsigned NumClobbers) {
    542   this->NumOutputs = NumOutputs;
    543   this->NumInputs = NumInputs;
    544   this->NumClobbers = NumClobbers;
    545   this->NumLabels = NumLabels;
    546 
    547   unsigned NumExprs = NumOutputs + NumInputs + NumLabels;
    548 
    549   C.Deallocate(this->Names);
    550   this->Names = new (C) IdentifierInfo*[NumExprs];
    551   std::copy(Names, Names + NumExprs, this->Names);
    552 
    553   C.Deallocate(this->Exprs);
    554   this->Exprs = new (C) Stmt*[NumExprs];
    555   std::copy(Exprs, Exprs + NumExprs, this->Exprs);
    556 
    557   unsigned NumConstraints = NumOutputs + NumInputs;
    558   C.Deallocate(this->Constraints);
    559   this->Constraints = new (C) StringLiteral*[NumConstraints];
    560   std::copy(Constraints, Constraints + NumConstraints, this->Constraints);
    561 
    562   C.Deallocate(this->Clobbers);
    563   this->Clobbers = new (C) StringLiteral*[NumClobbers];
    564   std::copy(Clobbers, Clobbers + NumClobbers, this->Clobbers);
    565 }
    566 
    567 /// getNamedOperand - Given a symbolic operand reference like %[foo],
    568 /// translate this into a numeric value needed to reference the same operand.
    569 /// This returns -1 if the operand name is invalid.
    570 int GCCAsmStmt::getNamedOperand(StringRef SymbolicName) const {
    571   unsigned NumPlusOperands = 0;
    572 
    573   // Check if this is an output operand.
    574   for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) {
    575     if (getOutputName(i) == SymbolicName)
    576       return i;
    577   }
    578 
    579   for (unsigned i = 0, e = getNumInputs(); i != e; ++i)
    580     if (getInputName(i) == SymbolicName)
    581       return getNumOutputs() + NumPlusOperands + i;
    582 
    583   for (unsigned i = 0, e = getNumLabels(); i != e; ++i)
    584     if (getLabelName(i) == SymbolicName)
    585       return i + getNumOutputs() + getNumInputs();
    586 
    587   // Not found.
    588   return -1;
    589 }
    590 
    591 /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
    592 /// it into pieces.  If the asm string is erroneous, emit errors and return
    593 /// true, otherwise return false.
    594 unsigned GCCAsmStmt::AnalyzeAsmString(SmallVectorImpl<AsmStringPiece>&Pieces,
    595                                 const ASTContext &C, unsigned &DiagOffs) const {
    596   StringRef Str = getAsmString()->getString();
    597   const char *StrStart = Str.begin();
    598   const char *StrEnd = Str.end();
    599   const char *CurPtr = StrStart;
    600 
    601   // "Simple" inline asms have no constraints or operands, just convert the asm
    602   // string to escape $'s.
    603   if (isSimple()) {
    604     std::string Result;
    605     for (; CurPtr != StrEnd; ++CurPtr) {
    606       switch (*CurPtr) {
    607       case '$':
    608         Result += "$$";
    609         break;
    610       default:
    611         Result += *CurPtr;
    612         break;
    613       }
    614     }
    615     Pieces.push_back(AsmStringPiece(Result));
    616     return 0;
    617   }
    618 
    619   // CurStringPiece - The current string that we are building up as we scan the
    620   // asm string.
    621   std::string CurStringPiece;
    622 
    623   bool HasVariants = !C.getTargetInfo().hasNoAsmVariants();
    624 
    625   unsigned LastAsmStringToken = 0;
    626   unsigned LastAsmStringOffset = 0;
    627 
    628   while (true) {
    629     // Done with the string?
    630     if (CurPtr == StrEnd) {
    631       if (!CurStringPiece.empty())
    632         Pieces.push_back(AsmStringPiece(CurStringPiece));
    633       return 0;
    634     }
    635 
    636     char CurChar = *CurPtr++;
    637     switch (CurChar) {
    638     case '$': CurStringPiece += "$$"; continue;
    639     case '{': CurStringPiece += (HasVariants ? "$(" : "{"); continue;
    640     case '|': CurStringPiece += (HasVariants ? "$|" : "|"); continue;
    641     case '}': CurStringPiece += (HasVariants ? "$)" : "}"); continue;
    642     case '%':
    643       break;
    644     default:
    645       CurStringPiece += CurChar;
    646       continue;
    647     }
    648 
    649     // Escaped "%" character in asm string.
    650     if (CurPtr == StrEnd) {
    651       // % at end of string is invalid (no escape).
    652       DiagOffs = CurPtr-StrStart-1;
    653       return diag::err_asm_invalid_escape;
    654     }
    655     // Handle escaped char and continue looping over the asm string.
    656     char EscapedChar = *CurPtr++;
    657     switch (EscapedChar) {
    658     default:
    659       break;
    660     case '%': // %% -> %
    661     case '{': // %{ -> {
    662     case '}': // %} -> }
    663       CurStringPiece += EscapedChar;
    664       continue;
    665     case '=': // %= -> Generate a unique ID.
    666       CurStringPiece += "${:uid}";
    667       continue;
    668     }
    669 
    670     // Otherwise, we have an operand.  If we have accumulated a string so far,
    671     // add it to the Pieces list.
    672     if (!CurStringPiece.empty()) {
    673       Pieces.push_back(AsmStringPiece(CurStringPiece));
    674       CurStringPiece.clear();
    675     }
    676 
    677     // Handle operands that have asmSymbolicName (e.g., %x[foo]) and those that
    678     // don't (e.g., %x4). 'x' following the '%' is the constraint modifier.
    679 
    680     const char *Begin = CurPtr - 1; // Points to the character following '%'.
    681     const char *Percent = Begin - 1; // Points to '%'.
    682 
    683     if (isLetter(EscapedChar)) {
    684       if (CurPtr == StrEnd) { // Premature end.
    685         DiagOffs = CurPtr-StrStart-1;
    686         return diag::err_asm_invalid_escape;
    687       }
    688       EscapedChar = *CurPtr++;
    689     }
    690 
    691     const TargetInfo &TI = C.getTargetInfo();
    692     const SourceManager &SM = C.getSourceManager();
    693     const LangOptions &LO = C.getLangOpts();
    694 
    695     // Handle operands that don't have asmSymbolicName (e.g., %x4).
    696     if (isDigit(EscapedChar)) {
    697       // %n - Assembler operand n
    698       unsigned N = 0;
    699 
    700       --CurPtr;
    701       while (CurPtr != StrEnd && isDigit(*CurPtr))
    702         N = N*10 + ((*CurPtr++)-'0');
    703 
    704       unsigned NumOperands = getNumOutputs() + getNumPlusOperands() +
    705                              getNumInputs() + getNumLabels();
    706       if (N >= NumOperands) {
    707         DiagOffs = CurPtr-StrStart-1;
    708         return diag::err_asm_invalid_operand_number;
    709       }
    710 
    711       // Str contains "x4" (Operand without the leading %).
    712       std::string Str(Begin, CurPtr - Begin);
    713 
    714       // (BeginLoc, EndLoc) represents the range of the operand we are currently
    715       // processing. Unlike Str, the range includes the leading '%'.
    716       SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
    717           Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
    718           &LastAsmStringOffset);
    719       SourceLocation EndLoc = getAsmString()->getLocationOfByte(
    720           CurPtr - StrStart, SM, LO, TI, &LastAsmStringToken,
    721           &LastAsmStringOffset);
    722 
    723       Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
    724       continue;
    725     }
    726 
    727     // Handle operands that have asmSymbolicName (e.g., %x[foo]).
    728     if (EscapedChar == '[') {
    729       DiagOffs = CurPtr-StrStart-1;
    730 
    731       // Find the ']'.
    732       const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr);
    733       if (NameEnd == nullptr)
    734         return diag::err_asm_unterminated_symbolic_operand_name;
    735       if (NameEnd == CurPtr)
    736         return diag::err_asm_empty_symbolic_operand_name;
    737 
    738       StringRef SymbolicName(CurPtr, NameEnd - CurPtr);
    739 
    740       int N = getNamedOperand(SymbolicName);
    741       if (N == -1) {
    742         // Verify that an operand with that name exists.
    743         DiagOffs = CurPtr-StrStart;
    744         return diag::err_asm_unknown_symbolic_operand_name;
    745       }
    746 
    747       // Str contains "x[foo]" (Operand without the leading %).
    748       std::string Str(Begin, NameEnd + 1 - Begin);
    749 
    750       // (BeginLoc, EndLoc) represents the range of the operand we are currently
    751       // processing. Unlike Str, the range includes the leading '%'.
    752       SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
    753           Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
    754           &LastAsmStringOffset);
    755       SourceLocation EndLoc = getAsmString()->getLocationOfByte(
    756           NameEnd + 1 - StrStart, SM, LO, TI, &LastAsmStringToken,
    757           &LastAsmStringOffset);
    758 
    759       Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
    760 
    761       CurPtr = NameEnd+1;
    762       continue;
    763     }
    764 
    765     DiagOffs = CurPtr-StrStart-1;
    766     return diag::err_asm_invalid_escape;
    767   }
    768 }
    769 
    770 /// Assemble final IR asm string (GCC-style).
    771 std::string GCCAsmStmt::generateAsmString(const ASTContext &C) const {
    772   // Analyze the asm string to decompose it into its pieces.  We know that Sema
    773   // has already done this, so it is guaranteed to be successful.
    774   SmallVector<GCCAsmStmt::AsmStringPiece, 4> Pieces;
    775   unsigned DiagOffs;
    776   AnalyzeAsmString(Pieces, C, DiagOffs);
    777 
    778   std::string AsmString;
    779   for (const auto &Piece : Pieces) {
    780     if (Piece.isString())
    781       AsmString += Piece.getString();
    782     else if (Piece.getModifier() == '\0')
    783       AsmString += '$' + llvm::utostr(Piece.getOperandNo());
    784     else
    785       AsmString += "${" + llvm::utostr(Piece.getOperandNo()) + ':' +
    786                    Piece.getModifier() + '}';
    787   }
    788   return AsmString;
    789 }
    790 
    791 /// Assemble final IR asm string (MS-style).
    792 std::string MSAsmStmt::generateAsmString(const ASTContext &C) const {
    793   // FIXME: This needs to be translated into the IR string representation.
    794   SmallVector<StringRef, 8> Pieces;
    795   AsmStr.split(Pieces, "\n\t");
    796   std::string MSAsmString;
    797   for (size_t I = 0, E = Pieces.size(); I < E; ++I) {
    798     StringRef Instruction = Pieces[I];
    799     // For vex/vex2/vex3/evex masm style prefix, convert it to att style
    800     // since we don't support masm style prefix in backend.
    801     if (Instruction.startswith("vex "))
    802       MSAsmString += '{' + Instruction.substr(0, 3).str() + '}' +
    803                      Instruction.substr(3).str();
    804     else if (Instruction.startswith("vex2 ") ||
    805              Instruction.startswith("vex3 ") || Instruction.startswith("evex "))
    806       MSAsmString += '{' + Instruction.substr(0, 4).str() + '}' +
    807                      Instruction.substr(4).str();
    808     else
    809       MSAsmString += Instruction.str();
    810     // If this is not the last instruction, adding back the '\n\t'.
    811     if (I < E - 1)
    812       MSAsmString += "\n\t";
    813   }
    814   return MSAsmString;
    815 }
    816 
    817 Expr *MSAsmStmt::getOutputExpr(unsigned i) {
    818   return cast<Expr>(Exprs[i]);
    819 }
    820 
    821 Expr *MSAsmStmt::getInputExpr(unsigned i) {
    822   return cast<Expr>(Exprs[i + NumOutputs]);
    823 }
    824 
    825 void MSAsmStmt::setInputExpr(unsigned i, Expr *E) {
    826   Exprs[i + NumOutputs] = E;
    827 }
    828 
    829 //===----------------------------------------------------------------------===//
    830 // Constructors
    831 //===----------------------------------------------------------------------===//
    832 
    833 GCCAsmStmt::GCCAsmStmt(const ASTContext &C, SourceLocation asmloc,
    834                        bool issimple, bool isvolatile, unsigned numoutputs,
    835                        unsigned numinputs, IdentifierInfo **names,
    836                        StringLiteral **constraints, Expr **exprs,
    837                        StringLiteral *asmstr, unsigned numclobbers,
    838                        StringLiteral **clobbers, unsigned numlabels,
    839                        SourceLocation rparenloc)
    840     : AsmStmt(GCCAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
    841               numinputs, numclobbers),
    842               RParenLoc(rparenloc), AsmStr(asmstr), NumLabels(numlabels) {
    843   unsigned NumExprs = NumOutputs + NumInputs + NumLabels;
    844 
    845   Names = new (C) IdentifierInfo*[NumExprs];
    846   std::copy(names, names + NumExprs, Names);
    847 
    848   Exprs = new (C) Stmt*[NumExprs];
    849   std::copy(exprs, exprs + NumExprs, Exprs);
    850 
    851   unsigned NumConstraints = NumOutputs + NumInputs;
    852   Constraints = new (C) StringLiteral*[NumConstraints];
    853   std::copy(constraints, constraints + NumConstraints, Constraints);
    854 
    855   Clobbers = new (C) StringLiteral*[NumClobbers];
    856   std::copy(clobbers, clobbers + NumClobbers, Clobbers);
    857 }
    858 
    859 MSAsmStmt::MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
    860                      SourceLocation lbraceloc, bool issimple, bool isvolatile,
    861                      ArrayRef<Token> asmtoks, unsigned numoutputs,
    862                      unsigned numinputs,
    863                      ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs,
    864                      StringRef asmstr, ArrayRef<StringRef> clobbers,
    865                      SourceLocation endloc)
    866     : AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
    867               numinputs, clobbers.size()), LBraceLoc(lbraceloc),
    868               EndLoc(endloc), NumAsmToks(asmtoks.size()) {
    869   initialize(C, asmstr, asmtoks, constraints, exprs, clobbers);
    870 }
    871 
    872 static StringRef copyIntoContext(const ASTContext &C, StringRef str) {
    873   return str.copy(C);
    874 }
    875 
    876 void MSAsmStmt::initialize(const ASTContext &C, StringRef asmstr,
    877                            ArrayRef<Token> asmtoks,
    878                            ArrayRef<StringRef> constraints,
    879                            ArrayRef<Expr*> exprs,
    880                            ArrayRef<StringRef> clobbers) {
    881   assert(NumAsmToks == asmtoks.size());
    882   assert(NumClobbers == clobbers.size());
    883 
    884   assert(exprs.size() == NumOutputs + NumInputs);
    885   assert(exprs.size() == constraints.size());
    886 
    887   AsmStr = copyIntoContext(C, asmstr);
    888 
    889   Exprs = new (C) Stmt*[exprs.size()];
    890   std::copy(exprs.begin(), exprs.end(), Exprs);
    891 
    892   AsmToks = new (C) Token[asmtoks.size()];
    893   std::copy(asmtoks.begin(), asmtoks.end(), AsmToks);
    894 
    895   Constraints = new (C) StringRef[exprs.size()];
    896   std::transform(constraints.begin(), constraints.end(), Constraints,
    897                  [&](StringRef Constraint) {
    898                    return copyIntoContext(C, Constraint);
    899                  });
    900 
    901   Clobbers = new (C) StringRef[NumClobbers];
    902   // FIXME: Avoid the allocation/copy if at all possible.
    903   std::transform(clobbers.begin(), clobbers.end(), Clobbers,
    904                  [&](StringRef Clobber) {
    905                    return copyIntoContext(C, Clobber);
    906                  });
    907 }
    908 
    909 IfStmt::IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr,
    910                Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LPL,
    911                SourceLocation RPL, Stmt *Then, SourceLocation EL, Stmt *Else)
    912     : Stmt(IfStmtClass), LParenLoc(LPL), RParenLoc(RPL) {
    913   bool HasElse = Else != nullptr;
    914   bool HasVar = Var != nullptr;
    915   bool HasInit = Init != nullptr;
    916   IfStmtBits.HasElse = HasElse;
    917   IfStmtBits.HasVar = HasVar;
    918   IfStmtBits.HasInit = HasInit;
    919 
    920   setConstexpr(IsConstexpr);
    921 
    922   setCond(Cond);
    923   setThen(Then);
    924   if (HasElse)
    925     setElse(Else);
    926   if (HasVar)
    927     setConditionVariable(Ctx, Var);
    928   if (HasInit)
    929     setInit(Init);
    930 
    931   setIfLoc(IL);
    932   if (HasElse)
    933     setElseLoc(EL);
    934 }
    935 
    936 IfStmt::IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit)
    937     : Stmt(IfStmtClass, Empty) {
    938   IfStmtBits.HasElse = HasElse;
    939   IfStmtBits.HasVar = HasVar;
    940   IfStmtBits.HasInit = HasInit;
    941 }
    942 
    943 IfStmt *IfStmt::Create(const ASTContext &Ctx, SourceLocation IL,
    944                        bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond,
    945                        SourceLocation LPL, SourceLocation RPL, Stmt *Then,
    946                        SourceLocation EL, Stmt *Else) {
    947   bool HasElse = Else != nullptr;
    948   bool HasVar = Var != nullptr;
    949   bool HasInit = Init != nullptr;
    950   void *Mem = Ctx.Allocate(
    951       totalSizeToAlloc<Stmt *, SourceLocation>(
    952           NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse),
    953       alignof(IfStmt));
    954   return new (Mem)
    955       IfStmt(Ctx, IL, IsConstexpr, Init, Var, Cond, LPL, RPL, Then, EL, Else);
    956 }
    957 
    958 IfStmt *IfStmt::CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar,
    959                             bool HasInit) {
    960   void *Mem = Ctx.Allocate(
    961       totalSizeToAlloc<Stmt *, SourceLocation>(
    962           NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse),
    963       alignof(IfStmt));
    964   return new (Mem) IfStmt(EmptyShell(), HasElse, HasVar, HasInit);
    965 }
    966 
    967 VarDecl *IfStmt::getConditionVariable() {
    968   auto *DS = getConditionVariableDeclStmt();
    969   if (!DS)
    970     return nullptr;
    971   return cast<VarDecl>(DS->getSingleDecl());
    972 }
    973 
    974 void IfStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
    975   assert(hasVarStorage() &&
    976          "This if statement has no storage for a condition variable!");
    977 
    978   if (!V) {
    979     getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
    980     return;
    981   }
    982 
    983   SourceRange VarRange = V->getSourceRange();
    984   getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
    985       DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
    986 }
    987 
    988 bool IfStmt::isObjCAvailabilityCheck() const {
    989   return isa<ObjCAvailabilityCheckExpr>(getCond());
    990 }
    991 
    992 Optional<Stmt *> IfStmt::getNondiscardedCase(const ASTContext &Ctx) {
    993   if (!isConstexpr() || getCond()->isValueDependent())
    994     return None;
    995   return !getCond()->EvaluateKnownConstInt(Ctx) ? getElse() : getThen();
    996 }
    997 
    998 Optional<const Stmt *>
    999 IfStmt::getNondiscardedCase(const ASTContext &Ctx) const {
   1000   if (Optional<Stmt *> Result =
   1001           const_cast<IfStmt *>(this)->getNondiscardedCase(Ctx))
   1002     return *Result;
   1003   return None;
   1004 }
   1005 
   1006 ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
   1007                  Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
   1008                  SourceLocation RP)
   1009   : Stmt(ForStmtClass), LParenLoc(LP), RParenLoc(RP)
   1010 {
   1011   SubExprs[INIT] = Init;
   1012   setConditionVariable(C, condVar);
   1013   SubExprs[COND] = Cond;
   1014   SubExprs[INC] = Inc;
   1015   SubExprs[BODY] = Body;
   1016   ForStmtBits.ForLoc = FL;
   1017 }
   1018 
   1019 VarDecl *ForStmt::getConditionVariable() const {
   1020   if (!SubExprs[CONDVAR])
   1021     return nullptr;
   1022 
   1023   auto *DS = cast<DeclStmt>(SubExprs[CONDVAR]);
   1024   return cast<VarDecl>(DS->getSingleDecl());
   1025 }
   1026 
   1027 void ForStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
   1028   if (!V) {
   1029     SubExprs[CONDVAR] = nullptr;
   1030     return;
   1031   }
   1032 
   1033   SourceRange VarRange = V->getSourceRange();
   1034   SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
   1035                                        VarRange.getEnd());
   1036 }
   1037 
   1038 SwitchStmt::SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
   1039                        Expr *Cond, SourceLocation LParenLoc,
   1040                        SourceLocation RParenLoc)
   1041     : Stmt(SwitchStmtClass), FirstCase(nullptr), LParenLoc(LParenLoc),
   1042       RParenLoc(RParenLoc) {
   1043   bool HasInit = Init != nullptr;
   1044   bool HasVar = Var != nullptr;
   1045   SwitchStmtBits.HasInit = HasInit;
   1046   SwitchStmtBits.HasVar = HasVar;
   1047   SwitchStmtBits.AllEnumCasesCovered = false;
   1048 
   1049   setCond(Cond);
   1050   setBody(nullptr);
   1051   if (HasInit)
   1052     setInit(Init);
   1053   if (HasVar)
   1054     setConditionVariable(Ctx, Var);
   1055 
   1056   setSwitchLoc(SourceLocation{});
   1057 }
   1058 
   1059 SwitchStmt::SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar)
   1060     : Stmt(SwitchStmtClass, Empty) {
   1061   SwitchStmtBits.HasInit = HasInit;
   1062   SwitchStmtBits.HasVar = HasVar;
   1063   SwitchStmtBits.AllEnumCasesCovered = false;
   1064 }
   1065 
   1066 SwitchStmt *SwitchStmt::Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
   1067                                Expr *Cond, SourceLocation LParenLoc,
   1068                                SourceLocation RParenLoc) {
   1069   bool HasInit = Init != nullptr;
   1070   bool HasVar = Var != nullptr;
   1071   void *Mem = Ctx.Allocate(
   1072       totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar),
   1073       alignof(SwitchStmt));
   1074   return new (Mem) SwitchStmt(Ctx, Init, Var, Cond, LParenLoc, RParenLoc);
   1075 }
   1076 
   1077 SwitchStmt *SwitchStmt::CreateEmpty(const ASTContext &Ctx, bool HasInit,
   1078                                     bool HasVar) {
   1079   void *Mem = Ctx.Allocate(
   1080       totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar),
   1081       alignof(SwitchStmt));
   1082   return new (Mem) SwitchStmt(EmptyShell(), HasInit, HasVar);
   1083 }
   1084 
   1085 VarDecl *SwitchStmt::getConditionVariable() {
   1086   auto *DS = getConditionVariableDeclStmt();
   1087   if (!DS)
   1088     return nullptr;
   1089   return cast<VarDecl>(DS->getSingleDecl());
   1090 }
   1091 
   1092 void SwitchStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
   1093   assert(hasVarStorage() &&
   1094          "This switch statement has no storage for a condition variable!");
   1095 
   1096   if (!V) {
   1097     getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
   1098     return;
   1099   }
   1100 
   1101   SourceRange VarRange = V->getSourceRange();
   1102   getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
   1103       DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
   1104 }
   1105 
   1106 WhileStmt::WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
   1107                      Stmt *Body, SourceLocation WL, SourceLocation LParenLoc,
   1108                      SourceLocation RParenLoc)
   1109     : Stmt(WhileStmtClass) {
   1110   bool HasVar = Var != nullptr;
   1111   WhileStmtBits.HasVar = HasVar;
   1112 
   1113   setCond(Cond);
   1114   setBody(Body);
   1115   if (HasVar)
   1116     setConditionVariable(Ctx, Var);
   1117 
   1118   setWhileLoc(WL);
   1119   setLParenLoc(LParenLoc);
   1120   setRParenLoc(RParenLoc);
   1121 }
   1122 
   1123 WhileStmt::WhileStmt(EmptyShell Empty, bool HasVar)
   1124     : Stmt(WhileStmtClass, Empty) {
   1125   WhileStmtBits.HasVar = HasVar;
   1126 }
   1127 
   1128 WhileStmt *WhileStmt::Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
   1129                              Stmt *Body, SourceLocation WL,
   1130                              SourceLocation LParenLoc,
   1131                              SourceLocation RParenLoc) {
   1132   bool HasVar = Var != nullptr;
   1133   void *Mem =
   1134       Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar),
   1135                    alignof(WhileStmt));
   1136   return new (Mem) WhileStmt(Ctx, Var, Cond, Body, WL, LParenLoc, RParenLoc);
   1137 }
   1138 
   1139 WhileStmt *WhileStmt::CreateEmpty(const ASTContext &Ctx, bool HasVar) {
   1140   void *Mem =
   1141       Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar),
   1142                    alignof(WhileStmt));
   1143   return new (Mem) WhileStmt(EmptyShell(), HasVar);
   1144 }
   1145 
   1146 VarDecl *WhileStmt::getConditionVariable() {
   1147   auto *DS = getConditionVariableDeclStmt();
   1148   if (!DS)
   1149     return nullptr;
   1150   return cast<VarDecl>(DS->getSingleDecl());
   1151 }
   1152 
   1153 void WhileStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
   1154   assert(hasVarStorage() &&
   1155          "This while statement has no storage for a condition variable!");
   1156 
   1157   if (!V) {
   1158     getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
   1159     return;
   1160   }
   1161 
   1162   SourceRange VarRange = V->getSourceRange();
   1163   getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
   1164       DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
   1165 }
   1166 
   1167 // IndirectGotoStmt
   1168 LabelDecl *IndirectGotoStmt::getConstantTarget() {
   1169   if (auto *E = dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts()))
   1170     return E->getLabel();
   1171   return nullptr;
   1172 }
   1173 
   1174 // ReturnStmt
   1175 ReturnStmt::ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
   1176     : Stmt(ReturnStmtClass), RetExpr(E) {
   1177   bool HasNRVOCandidate = NRVOCandidate != nullptr;
   1178   ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
   1179   if (HasNRVOCandidate)
   1180     setNRVOCandidate(NRVOCandidate);
   1181   setReturnLoc(RL);
   1182 }
   1183 
   1184 ReturnStmt::ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate)
   1185     : Stmt(ReturnStmtClass, Empty) {
   1186   ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
   1187 }
   1188 
   1189 ReturnStmt *ReturnStmt::Create(const ASTContext &Ctx, SourceLocation RL,
   1190                                Expr *E, const VarDecl *NRVOCandidate) {
   1191   bool HasNRVOCandidate = NRVOCandidate != nullptr;
   1192   void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate),
   1193                            alignof(ReturnStmt));
   1194   return new (Mem) ReturnStmt(RL, E, NRVOCandidate);
   1195 }
   1196 
   1197 ReturnStmt *ReturnStmt::CreateEmpty(const ASTContext &Ctx,
   1198                                     bool HasNRVOCandidate) {
   1199   void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate),
   1200                            alignof(ReturnStmt));
   1201   return new (Mem) ReturnStmt(EmptyShell(), HasNRVOCandidate);
   1202 }
   1203 
   1204 // CaseStmt
   1205 CaseStmt *CaseStmt::Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
   1206                            SourceLocation caseLoc, SourceLocation ellipsisLoc,
   1207                            SourceLocation colonLoc) {
   1208   bool CaseStmtIsGNURange = rhs != nullptr;
   1209   void *Mem = Ctx.Allocate(
   1210       totalSizeToAlloc<Stmt *, SourceLocation>(
   1211           NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange),
   1212       alignof(CaseStmt));
   1213   return new (Mem) CaseStmt(lhs, rhs, caseLoc, ellipsisLoc, colonLoc);
   1214 }
   1215 
   1216 CaseStmt *CaseStmt::CreateEmpty(const ASTContext &Ctx,
   1217                                 bool CaseStmtIsGNURange) {
   1218   void *Mem = Ctx.Allocate(
   1219       totalSizeToAlloc<Stmt *, SourceLocation>(
   1220           NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange),
   1221       alignof(CaseStmt));
   1222   return new (Mem) CaseStmt(EmptyShell(), CaseStmtIsGNURange);
   1223 }
   1224 
   1225 SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock,
   1226                        Stmt *Handler)
   1227     : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) {
   1228   Children[TRY]     = TryBlock;
   1229   Children[HANDLER] = Handler;
   1230 }
   1231 
   1232 SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry,
   1233                                SourceLocation TryLoc, Stmt *TryBlock,
   1234                                Stmt *Handler) {
   1235   return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler);
   1236 }
   1237 
   1238 SEHExceptStmt* SEHTryStmt::getExceptHandler() const {
   1239   return dyn_cast<SEHExceptStmt>(getHandler());
   1240 }
   1241 
   1242 SEHFinallyStmt* SEHTryStmt::getFinallyHandler() const {
   1243   return dyn_cast<SEHFinallyStmt>(getHandler());
   1244 }
   1245 
   1246 SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
   1247     : Stmt(SEHExceptStmtClass), Loc(Loc) {
   1248   Children[FILTER_EXPR] = FilterExpr;
   1249   Children[BLOCK]       = Block;
   1250 }
   1251 
   1252 SEHExceptStmt* SEHExceptStmt::Create(const ASTContext &C, SourceLocation Loc,
   1253                                      Expr *FilterExpr, Stmt *Block) {
   1254   return new(C) SEHExceptStmt(Loc,FilterExpr,Block);
   1255 }
   1256 
   1257 SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block)
   1258     : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {}
   1259 
   1260 SEHFinallyStmt* SEHFinallyStmt::Create(const ASTContext &C, SourceLocation Loc,
   1261                                        Stmt *Block) {
   1262   return new(C)SEHFinallyStmt(Loc,Block);
   1263 }
   1264 
   1265 CapturedStmt::Capture::Capture(SourceLocation Loc, VariableCaptureKind Kind,
   1266                                VarDecl *Var)
   1267     : VarAndKind(Var, Kind), Loc(Loc) {
   1268   switch (Kind) {
   1269   case VCK_This:
   1270     assert(!Var && "'this' capture cannot have a variable!");
   1271     break;
   1272   case VCK_ByRef:
   1273     assert(Var && "capturing by reference must have a variable!");
   1274     break;
   1275   case VCK_ByCopy:
   1276     assert(Var && "capturing by copy must have a variable!");
   1277     break;
   1278   case VCK_VLAType:
   1279     assert(!Var &&
   1280            "Variable-length array type capture cannot have a variable!");
   1281     break;
   1282   }
   1283 }
   1284 
   1285 CapturedStmt::VariableCaptureKind
   1286 CapturedStmt::Capture::getCaptureKind() const {
   1287   return VarAndKind.getInt();
   1288 }
   1289 
   1290 VarDecl *CapturedStmt::Capture::getCapturedVar() const {
   1291   assert((capturesVariable() || capturesVariableByCopy()) &&
   1292          "No variable available for 'this' or VAT capture");
   1293   return VarAndKind.getPointer();
   1294 }
   1295 
   1296 CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const {
   1297   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
   1298 
   1299   // Offset of the first Capture object.
   1300   unsigned FirstCaptureOffset = llvm::alignTo(Size, alignof(Capture));
   1301 
   1302   return reinterpret_cast<Capture *>(
   1303       reinterpret_cast<char *>(const_cast<CapturedStmt *>(this))
   1304       + FirstCaptureOffset);
   1305 }
   1306 
   1307 CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind,
   1308                            ArrayRef<Capture> Captures,
   1309                            ArrayRef<Expr *> CaptureInits,
   1310                            CapturedDecl *CD,
   1311                            RecordDecl *RD)
   1312   : Stmt(CapturedStmtClass), NumCaptures(Captures.size()),
   1313     CapDeclAndKind(CD, Kind), TheRecordDecl(RD) {
   1314   assert( S && "null captured statement");
   1315   assert(CD && "null captured declaration for captured statement");
   1316   assert(RD && "null record declaration for captured statement");
   1317 
   1318   // Copy initialization expressions.
   1319   Stmt **Stored = getStoredStmts();
   1320   for (unsigned I = 0, N = NumCaptures; I != N; ++I)
   1321     *Stored++ = CaptureInits[I];
   1322 
   1323   // Copy the statement being captured.
   1324   *Stored = S;
   1325 
   1326   // Copy all Capture objects.
   1327   Capture *Buffer = getStoredCaptures();
   1328   std::copy(Captures.begin(), Captures.end(), Buffer);
   1329 }
   1330 
   1331 CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures)
   1332   : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures),
   1333     CapDeclAndKind(nullptr, CR_Default) {
   1334   getStoredStmts()[NumCaptures] = nullptr;
   1335 }
   1336 
   1337 CapturedStmt *CapturedStmt::Create(const ASTContext &Context, Stmt *S,
   1338                                    CapturedRegionKind Kind,
   1339                                    ArrayRef<Capture> Captures,
   1340                                    ArrayRef<Expr *> CaptureInits,
   1341                                    CapturedDecl *CD,
   1342                                    RecordDecl *RD) {
   1343   // The layout is
   1344   //
   1345   // -----------------------------------------------------------
   1346   // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture |
   1347   // ----------------^-------------------^----------------------
   1348   //                 getStoredStmts()    getStoredCaptures()
   1349   //
   1350   // where S is the statement being captured.
   1351   //
   1352   assert(CaptureInits.size() == Captures.size() && "wrong number of arguments");
   1353 
   1354   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1);
   1355   if (!Captures.empty()) {
   1356     // Realign for the following Capture array.
   1357     Size = llvm::alignTo(Size, alignof(Capture));
   1358     Size += sizeof(Capture) * Captures.size();
   1359   }
   1360 
   1361   void *Mem = Context.Allocate(Size);
   1362   return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD);
   1363 }
   1364 
   1365 CapturedStmt *CapturedStmt::CreateDeserialized(const ASTContext &Context,
   1366                                                unsigned NumCaptures) {
   1367   unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
   1368   if (NumCaptures > 0) {
   1369     // Realign for the following Capture array.
   1370     Size = llvm::alignTo(Size, alignof(Capture));
   1371     Size += sizeof(Capture) * NumCaptures;
   1372   }
   1373 
   1374   void *Mem = Context.Allocate(Size);
   1375   return new (Mem) CapturedStmt(EmptyShell(), NumCaptures);
   1376 }
   1377 
   1378 Stmt::child_range CapturedStmt::children() {
   1379   // Children are captured field initializers.
   1380   return child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
   1381 }
   1382 
   1383 Stmt::const_child_range CapturedStmt::children() const {
   1384   return const_child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
   1385 }
   1386 
   1387 CapturedDecl *CapturedStmt::getCapturedDecl() {
   1388   return CapDeclAndKind.getPointer();
   1389 }
   1390 
   1391 const CapturedDecl *CapturedStmt::getCapturedDecl() const {
   1392   return CapDeclAndKind.getPointer();
   1393 }
   1394 
   1395 /// Set the outlined function declaration.
   1396 void CapturedStmt::setCapturedDecl(CapturedDecl *D) {
   1397   assert(D && "null CapturedDecl");
   1398   CapDeclAndKind.setPointer(D);
   1399 }
   1400 
   1401 /// Retrieve the captured region kind.
   1402 CapturedRegionKind CapturedStmt::getCapturedRegionKind() const {
   1403   return CapDeclAndKind.getInt();
   1404 }
   1405 
   1406 /// Set the captured region kind.
   1407 void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) {
   1408   CapDeclAndKind.setInt(Kind);
   1409 }
   1410 
   1411 bool CapturedStmt::capturesVariable(const VarDecl *Var) const {
   1412   for (const auto &I : captures()) {
   1413     if (!I.capturesVariable() && !I.capturesVariableByCopy())
   1414       continue;
   1415     if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl())
   1416       return true;
   1417   }
   1418 
   1419   return false;
   1420 }
   1421