Updated to Clang 3.5a.

Change-Id: I8127eb568f674c2e72635b639a3295381fe8af82
diff --git a/utils/TableGen/ClangAttrEmitter.cpp b/utils/TableGen/ClangAttrEmitter.cpp
index 653d7b7..e03afe4 100644
--- a/utils/TableGen/ClangAttrEmitter.cpp
+++ b/utils/TableGen/ClangAttrEmitter.cpp
@@ -12,35 +12,63 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringSwitch.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/TableGen/Error.h"
 #include "llvm/TableGen/Record.h"
 #include "llvm/TableGen/StringMatcher.h"
 #include "llvm/TableGen/TableGenBackend.h"
 #include <algorithm>
 #include <cctype>
+#include <memory>
+#include <set>
+#include <sstream>
 
 using namespace llvm;
 
-static const std::vector<StringRef>
-getValueAsListOfStrings(Record &R, StringRef FieldName) {
-  ListInit *List = R.getValueAsListInit(FieldName);
-  assert (List && "Got a null ListInit");
+class FlattenedSpelling {
+  std::string V, N, NS;
+  bool K;
 
-  std::vector<StringRef> Strings;
-  Strings.reserve(List->getSize());
+public:
+  FlattenedSpelling(const std::string &Variety, const std::string &Name,
+                    const std::string &Namespace, bool KnownToGCC) :
+    V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
+  explicit FlattenedSpelling(const Record &Spelling) :
+    V(Spelling.getValueAsString("Variety")),
+    N(Spelling.getValueAsString("Name")) {
 
-  for (ListInit::const_iterator i = List->begin(), e = List->end();
-       i != e;
-       ++i) {
-    assert(*i && "Got a null element in a ListInit");
-    if (StringInit *S = dyn_cast<StringInit>(*i))
-      Strings.push_back(S->getValue());
-    else
-      assert(false && "Got a non-string, non-code element in a ListInit");
+    assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
+           "flattened!");
+    if (V == "CXX11")
+      NS = Spelling.getValueAsString("Namespace");
+    bool Unset;
+    K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
   }
 
-  return Strings;
+  const std::string &variety() const { return V; }
+  const std::string &name() const { return N; }
+  const std::string &nameSpace() const { return NS; }
+  bool knownToGCC() const { return K; }
+};
+
+std::vector<FlattenedSpelling> GetFlattenedSpellings(const Record &Attr) {
+  std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
+  std::vector<FlattenedSpelling> Ret;
+
+  for (const auto &Spelling : Spellings) {
+    if (Spelling->getValueAsString("Variety") == "GCC") {
+      // Gin up two new spelling objects to add into the list.
+      Ret.push_back(FlattenedSpelling("GNU", Spelling->getValueAsString("Name"),
+                                      "", true));
+      Ret.push_back(FlattenedSpelling(
+          "CXX11", Spelling->getValueAsString("Name"), "gnu", true));
+    } else
+      Ret.push_back(FlattenedSpelling(*Spelling));
+  }
+
+  return Ret;
 }
 
 static std::string ReadPCHRecord(StringRef type) {
@@ -50,7 +78,6 @@
     .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
     .Case("Expr *", "ReadExpr(F)")
     .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
-    .Case("SourceLocation", "ReadSourceLocation(F, Record, Idx)")
     .Default("Record[Idx++]");
 }
 
@@ -64,8 +91,6 @@
     .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
     .Case("IdentifierInfo *", 
           "AddIdentifierRef(" + std::string(name) + ", Record);\n")
-    .Case("SourceLocation", 
-          "AddSourceLocation(" + std::string(name) + ", Record);\n")
     .Default("Record.push_back(" + std::string(name) + ");\n");
 }
 
@@ -82,6 +107,17 @@
   return AttrName;
 }
 
+// Normalize the name by removing any and all leading and trailing underscores.
+// This is different from NormalizeAttrName in that it also handles names like
+// _pascal and __pascal.
+static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
+  while (Name.startswith("_"))
+    Name = Name.substr(1, Name.size());
+  while (Name.endswith("_"))
+    Name = Name.substr(0, Name.size() - 1);
+  return Name;
+}
+
 // Normalize attribute spelling only if the spelling has both leading
 // and trailing underscores. For example, __ms_struct__ will be 
 // normalized to "ms_struct"; __cdecl will remain intact.
@@ -93,6 +129,37 @@
   return AttrSpelling;
 }
 
+typedef std::vector<std::pair<std::string, Record *>> ParsedAttrMap;
+
+static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
+                                       ParsedAttrMap *Dupes = 0) {
+  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
+  std::set<std::string> Seen;
+  ParsedAttrMap R;
+  for (auto Attr : Attrs) {
+    if (Attr->getValueAsBit("SemaHandler")) {
+      std::string AN;
+      if (Attr->isSubClassOf("TargetSpecificAttr") &&
+          !Attr->isValueUnset("ParseKind")) {
+        AN = Attr->getValueAsString("ParseKind");
+
+        // If this attribute has already been handled, it does not need to be
+        // handled again.
+        if (Seen.find(AN) != Seen.end()) {
+          if (Dupes)
+            Dupes->push_back(std::make_pair(AN, Attr));
+          continue;
+        }
+        Seen.insert(AN);
+      } else
+        AN = NormalizeAttrName(Attr->getName()).str();
+
+      R.push_back(std::make_pair(AN, Attr));
+    }
+  }
+  return R;
+}
+
 namespace {
   class Argument {
     std::string lowerName, upperName;
@@ -120,6 +187,7 @@
     // These functions print the argument contents formatted in different ways.
     virtual void writeAccessors(raw_ostream &OS) const = 0;
     virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
+    virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
     virtual void writeCloneArgs(raw_ostream &OS) const = 0;
     virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
     virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
@@ -138,6 +206,10 @@
 
     virtual bool isEnumArg() const { return false; }
     virtual bool isVariadicEnumArg() const { return false; }
+
+    virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
+      OS << getUpperName();
+    }
   };
 
   class SimpleArgument : public Argument {
@@ -150,41 +222,41 @@
 
     std::string getType() const { return type; }
 
-    void writeAccessors(raw_ostream &OS) const {
+    void writeAccessors(raw_ostream &OS) const override {
       OS << "  " << type << " get" << getUpperName() << "() const {\n";
       OS << "    return " << getLowerName() << ";\n";
       OS << "  }";
     }
-    void writeCloneArgs(raw_ostream &OS) const {
+    void writeCloneArgs(raw_ostream &OS) const override {
       OS << getLowerName();
     }
-    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
       OS << "A->get" << getUpperName() << "()";
     }
-    void writeCtorInitializers(raw_ostream &OS) const {
+    void writeCtorInitializers(raw_ostream &OS) const override {
       OS << getLowerName() << "(" << getUpperName() << ")";
     }
-    void writeCtorDefaultInitializers(raw_ostream &OS) const {
+    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
       OS << getLowerName() << "()";
     }
-    void writeCtorParameters(raw_ostream &OS) const {
+    void writeCtorParameters(raw_ostream &OS) const override {
       OS << type << " " << getUpperName();
     }
-    void writeDeclarations(raw_ostream &OS) const {
+    void writeDeclarations(raw_ostream &OS) const override {
       OS << type << " " << getLowerName() << ";";
     }
-    void writePCHReadDecls(raw_ostream &OS) const {
+    void writePCHReadDecls(raw_ostream &OS) const override {
       std::string read = ReadPCHRecord(type);
       OS << "    " << type << " " << getLowerName() << " = " << read << ";\n";
     }
-    void writePCHReadArgs(raw_ostream &OS) const {
+    void writePCHReadArgs(raw_ostream &OS) const override {
       OS << getLowerName();
     }
-    void writePCHWrite(raw_ostream &OS) const {
+    void writePCHWrite(raw_ostream &OS) const override {
       OS << "    " << WritePCHRecord(type, "SA->get" +
                                            std::string(getUpperName()) + "()");
     }
-    void writeValue(raw_ostream &OS) const {
+    void writeValue(raw_ostream &OS) const override {
       if (type == "FunctionDecl *") {
         OS << "\" << get" << getUpperName()
            << "()->getNameInfo().getAsString() << \"";
@@ -192,13 +264,11 @@
         OS << "\" << get" << getUpperName() << "()->getName() << \"";
       } else if (type == "TypeSourceInfo *") {
         OS << "\" << get" << getUpperName() << "().getAsString() << \"";
-      } else if (type == "SourceLocation") {
-        OS << "\" << get" << getUpperName() << "().getRawEncoding() << \"";
       } else {
         OS << "\" << get" << getUpperName() << "() << \"";
       }
     }
-    void writeDump(raw_ostream &OS) const {
+    void writeDump(raw_ostream &OS) const override {
       if (type == "FunctionDecl *") {
         OS << "    OS << \" \";\n";
         OS << "    dumpBareDeclRef(SA->get" << getUpperName() << "());\n"; 
@@ -208,9 +278,6 @@
       } else if (type == "TypeSourceInfo *") {
         OS << "    OS << \" \" << SA->get" << getUpperName()
            << "().getAsString();\n";
-      } else if (type == "SourceLocation") {
-        OS << "    OS << \" \";\n";
-        OS << "    SA->get" << getUpperName() << "().print(OS, *SM);\n";
       } else if (type == "bool") {
         OS << "    if (SA->get" << getUpperName() << "()) OS << \" "
            << getUpperName() << "\";\n";
@@ -222,13 +289,29 @@
     }
   };
 
+  class DefaultSimpleArgument : public SimpleArgument {
+    int64_t Default;
+
+  public:
+    DefaultSimpleArgument(Record &Arg, StringRef Attr,
+                          std::string T, int64_t Default)
+      : SimpleArgument(Arg, Attr, T), Default(Default) {}
+
+    void writeAccessors(raw_ostream &OS) const override {
+      SimpleArgument::writeAccessors(OS);
+
+      OS << "\n\n  static const " << getType() << " Default" << getUpperName()
+         << " = " << Default << ";";
+    }
+  };
+
   class StringArgument : public Argument {
   public:
     StringArgument(Record &Arg, StringRef Attr)
       : Argument(Arg, Attr)
     {}
 
-    void writeAccessors(raw_ostream &OS) const {
+    void writeAccessors(raw_ostream &OS) const override {
       OS << "  llvm::StringRef get" << getUpperName() << "() const {\n";
       OS << "    return llvm::StringRef(" << getLowerName() << ", "
          << getLowerName() << "Length);\n";
@@ -245,45 +328,45 @@
          << getLowerName() << "Length);\n";
       OS << "  }";
     }
-    void writeCloneArgs(raw_ostream &OS) const {
+    void writeCloneArgs(raw_ostream &OS) const override {
       OS << "get" << getUpperName() << "()";
     }
-    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
       OS << "A->get" << getUpperName() << "()";
     }
-    void writeCtorBody(raw_ostream &OS) const {
+    void writeCtorBody(raw_ostream &OS) const override {
       OS << "      std::memcpy(" << getLowerName() << ", " << getUpperName()
          << ".data(), " << getLowerName() << "Length);";
     }
-    void writeCtorInitializers(raw_ostream &OS) const {
+    void writeCtorInitializers(raw_ostream &OS) const override {
       OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
          << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
          << "Length])";
     }
-    void writeCtorDefaultInitializers(raw_ostream &OS) const {
+    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
       OS << getLowerName() << "Length(0)," << getLowerName() << "(0)";
     }
-    void writeCtorParameters(raw_ostream &OS) const {
+    void writeCtorParameters(raw_ostream &OS) const override {
       OS << "llvm::StringRef " << getUpperName();
     }
-    void writeDeclarations(raw_ostream &OS) const {
+    void writeDeclarations(raw_ostream &OS) const override {
       OS << "unsigned " << getLowerName() << "Length;\n";
       OS << "char *" << getLowerName() << ";";
     }
-    void writePCHReadDecls(raw_ostream &OS) const {
+    void writePCHReadDecls(raw_ostream &OS) const override {
       OS << "    std::string " << getLowerName()
          << "= ReadString(Record, Idx);\n";
     }
-    void writePCHReadArgs(raw_ostream &OS) const {
+    void writePCHReadArgs(raw_ostream &OS) const override {
       OS << getLowerName();
     }
-    void writePCHWrite(raw_ostream &OS) const {
+    void writePCHWrite(raw_ostream &OS) const override {
       OS << "    AddString(SA->get" << getUpperName() << "(), Record);\n";
     }
-    void writeValue(raw_ostream &OS) const {
+    void writeValue(raw_ostream &OS) const override {
       OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
     }
-    void writeDump(raw_ostream &OS) const {
+    void writeDump(raw_ostream &OS) const override {
       OS << "    OS << \" \\\"\" << SA->get" << getUpperName()
          << "() << \"\\\"\";\n";
     }
@@ -295,7 +378,7 @@
       : Argument(Arg, Attr)
     {}
 
-    void writeAccessors(raw_ostream &OS) const {
+    void writeAccessors(raw_ostream &OS) const override {
       OS << "  bool is" << getUpperName() << "Dependent() const;\n";
 
       OS << "  unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
@@ -314,7 +397,7 @@
       OS << "    return " << getLowerName() << "Type;\n";
       OS << "  }";
     }
-    void writeAccessorDefinitions(raw_ostream &OS) const {
+    void writeAccessorDefinitions(raw_ostream &OS) const override {
       OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
          << "Dependent() const {\n";
       OS << "  if (is" << getLowerName() << "Expr)\n";
@@ -342,17 +425,17 @@
       OS << "    return 0; // FIXME\n";
       OS << "}\n";
     }
-    void writeCloneArgs(raw_ostream &OS) const {
+    void writeCloneArgs(raw_ostream &OS) const override {
       OS << "is" << getLowerName() << "Expr, is" << getLowerName()
          << "Expr ? static_cast<void*>(" << getLowerName()
          << "Expr) : " << getLowerName()
          << "Type";
     }
-    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
       // FIXME: move the definition in Sema::InstantiateAttrs to here.
       // In the meantime, aligned attributes are cloned.
     }
-    void writeCtorBody(raw_ostream &OS) const {
+    void writeCtorBody(raw_ostream &OS) const override {
       OS << "    if (is" << getLowerName() << "Expr)\n";
       OS << "       " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
          << getUpperName() << ");\n";
@@ -361,26 +444,29 @@
          << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
          << ");";
     }
-    void writeCtorInitializers(raw_ostream &OS) const {
+    void writeCtorInitializers(raw_ostream &OS) const override {
       OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
     }
-    void writeCtorDefaultInitializers(raw_ostream &OS) const {
+    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
       OS << "is" << getLowerName() << "Expr(false)";
     }
-    void writeCtorParameters(raw_ostream &OS) const {
+    void writeCtorParameters(raw_ostream &OS) const override {
       OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
     }
-    void writeDeclarations(raw_ostream &OS) const {
+    void writeImplicitCtorArgs(raw_ostream &OS) const override {
+      OS << "Is" << getUpperName() << "Expr, " << getUpperName();
+    }
+    void writeDeclarations(raw_ostream &OS) const override {
       OS << "bool is" << getLowerName() << "Expr;\n";
       OS << "union {\n";
       OS << "Expr *" << getLowerName() << "Expr;\n";
       OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
       OS << "};";
     }
-    void writePCHReadArgs(raw_ostream &OS) const {
+    void writePCHReadArgs(raw_ostream &OS) const override {
       OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
     }
-    void writePCHReadDecls(raw_ostream &OS) const {
+    void writePCHReadDecls(raw_ostream &OS) const override {
       OS << "    bool is" << getLowerName() << "Expr = Record[Idx++];\n";
       OS << "    void *" << getLowerName() << "Ptr;\n";
       OS << "    if (is" << getLowerName() << "Expr)\n";
@@ -389,7 +475,7 @@
       OS << "      " << getLowerName()
          << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
     }
-    void writePCHWrite(raw_ostream &OS) const {
+    void writePCHWrite(raw_ostream &OS) const override {
       OS << "    Record.push_back(SA->is" << getUpperName() << "Expr());\n";
       OS << "    if (SA->is" << getUpperName() << "Expr())\n";
       OS << "      AddStmt(SA->get" << getUpperName() << "Expr());\n";
@@ -397,14 +483,14 @@
       OS << "      AddTypeSourceInfo(SA->get" << getUpperName()
          << "Type(), Record);\n";
     }
-    void writeValue(raw_ostream &OS) const {
+    void writeValue(raw_ostream &OS) const override {
       OS << "\";\n"
          << "  " << getLowerName() << "Expr->printPretty(OS, 0, Policy);\n"
          << "  OS << \"";
     }
-    void writeDump(raw_ostream &OS) const {
+    void writeDump(raw_ostream &OS) const override {
     }
-    void writeDumpChildren(raw_ostream &OS) const {
+    void writeDumpChildren(raw_ostream &OS) const override {
       OS << "    if (SA->is" << getUpperName() << "Expr()) {\n";
       OS << "      lastChild();\n";
       OS << "      dumpStmt(SA->get" << getUpperName() << "Expr());\n";
@@ -412,7 +498,7 @@
       OS << "      dumpType(SA->get" << getUpperName()
          << "Type()->getType());\n";
     }
-    void writeHasChildren(raw_ostream &OS) const {
+    void writeHasChildren(raw_ostream &OS) const override {
       OS << "SA->is" << getUpperName() << "Expr()";
     }
   };
@@ -427,7 +513,7 @@
 
     std::string getType() const { return type; }
 
-    void writeAccessors(raw_ostream &OS) const {
+    void writeAccessors(raw_ostream &OS) const override {
       OS << "  typedef " << type << "* " << getLowerName() << "_iterator;\n";
       OS << "  " << getLowerName() << "_iterator " << getLowerName()
          << "_begin() const {\n";
@@ -442,36 +528,39 @@
          << "    return " << getLowerName() << "Size;\n";
       OS << "  }";
     }
-    void writeCloneArgs(raw_ostream &OS) const {
+    void writeCloneArgs(raw_ostream &OS) const override {
       OS << getLowerName() << ", " << getLowerName() << "Size";
     }
-    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
       // This isn't elegant, but we have to go through public methods...
       OS << "A->" << getLowerName() << "_begin(), "
          << "A->" << getLowerName() << "_size()";
     }
-    void writeCtorBody(raw_ostream &OS) const {
+    void writeCtorBody(raw_ostream &OS) const override {
       // FIXME: memcpy is not safe on non-trivial types.
       OS << "    std::memcpy(" << getLowerName() << ", " << getUpperName()
          << ", " << getLowerName() << "Size * sizeof(" << getType() << "));\n";
     }
-    void writeCtorInitializers(raw_ostream &OS) const {
+    void writeCtorInitializers(raw_ostream &OS) const override {
       OS << getLowerName() << "Size(" << getUpperName() << "Size), "
          << getLowerName() << "(new (Ctx, 16) " << getType() << "["
          << getLowerName() << "Size])";
     }
-    void writeCtorDefaultInitializers(raw_ostream &OS) const {
+    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
       OS << getLowerName() << "Size(0), " << getLowerName() << "(0)";
     }
-    void writeCtorParameters(raw_ostream &OS) const {
+    void writeCtorParameters(raw_ostream &OS) const override {
       OS << getType() << " *" << getUpperName() << ", unsigned "
          << getUpperName() << "Size";
     }
-    void writeDeclarations(raw_ostream &OS) const {
+    void writeImplicitCtorArgs(raw_ostream &OS) const override {
+      OS << getUpperName() << ", " << getUpperName() << "Size";
+    }
+    void writeDeclarations(raw_ostream &OS) const override {
       OS << "  unsigned " << getLowerName() << "Size;\n";
       OS << "  " << getType() << " *" << getLowerName() << ";";
     }
-    void writePCHReadDecls(raw_ostream &OS) const {
+    void writePCHReadDecls(raw_ostream &OS) const override {
       OS << "  unsigned " << getLowerName() << "Size = Record[Idx++];\n";
       OS << "  SmallVector<" << type << ", 4> " << getLowerName()
          << ";\n";
@@ -482,17 +571,17 @@
       std::string read = ReadPCHRecord(type);
       OS << "    " << getLowerName() << ".push_back(" << read << ");\n";
     }
-    void writePCHReadArgs(raw_ostream &OS) const {
+    void writePCHReadArgs(raw_ostream &OS) const override {
       OS << getLowerName() << ".data(), " << getLowerName() << "Size";
     }
-    void writePCHWrite(raw_ostream &OS) const{
+    void writePCHWrite(raw_ostream &OS) const override {
       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
          << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
          << getLowerName() << "_end(); i != e; ++i)\n";
       OS << "      " << WritePCHRecord(type, "(*i)");
     }
-    void writeValue(raw_ostream &OS) const {
+    void writeValue(raw_ostream &OS) const override {
       OS << "\";\n";
       OS << "  bool isFirst = true;\n"
          << "  for (" << getAttrName() << "Attr::" << getLowerName()
@@ -504,7 +593,7 @@
          << "  }\n";
       OS << "  OS << \"";
     }
-    void writeDump(raw_ostream &OS) const {
+    void writeDump(raw_ostream &OS) const override {
       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
          << getLowerName() << "_end(); I != E; ++I)\n";
@@ -512,48 +601,60 @@
     }
   };
 
+  // Unique the enums, but maintain the original declaration ordering.
+  std::vector<std::string>
+  uniqueEnumsInOrder(const std::vector<std::string> &enums) {
+    std::vector<std::string> uniques;
+    std::set<std::string> unique_set(enums.begin(), enums.end());
+    for (const auto &i : enums) {
+      std::set<std::string>::iterator set_i = unique_set.find(i);
+      if (set_i != unique_set.end()) {
+        uniques.push_back(i);
+        unique_set.erase(set_i);
+      }
+    }
+    return uniques;
+  }
+
   class EnumArgument : public Argument {
     std::string type;
-    std::vector<StringRef> values, enums, uniques;
+    std::vector<std::string> values, enums, uniques;
   public:
     EnumArgument(Record &Arg, StringRef Attr)
       : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
-        values(getValueAsListOfStrings(Arg, "Values")),
-        enums(getValueAsListOfStrings(Arg, "Enums")),
-        uniques(enums)
+        values(Arg.getValueAsListOfStrings("Values")),
+        enums(Arg.getValueAsListOfStrings("Enums")),
+        uniques(uniqueEnumsInOrder(enums))
     {
-      // Calculate the various enum values
-      std::sort(uniques.begin(), uniques.end());
-      uniques.erase(std::unique(uniques.begin(), uniques.end()), uniques.end());
       // FIXME: Emit a proper error
       assert(!uniques.empty());
     }
 
-    bool isEnumArg() const { return true; }
+    bool isEnumArg() const override { return true; }
 
-    void writeAccessors(raw_ostream &OS) const {
+    void writeAccessors(raw_ostream &OS) const override {
       OS << "  " << type << " get" << getUpperName() << "() const {\n";
       OS << "    return " << getLowerName() << ";\n";
       OS << "  }";
     }
-    void writeCloneArgs(raw_ostream &OS) const {
+    void writeCloneArgs(raw_ostream &OS) const override {
       OS << getLowerName();
     }
-    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
       OS << "A->get" << getUpperName() << "()";
     }
-    void writeCtorInitializers(raw_ostream &OS) const {
+    void writeCtorInitializers(raw_ostream &OS) const override {
       OS << getLowerName() << "(" << getUpperName() << ")";
     }
-    void writeCtorDefaultInitializers(raw_ostream &OS) const {
+    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
       OS << getLowerName() << "(" << type << "(0))";
     }
-    void writeCtorParameters(raw_ostream &OS) const {
+    void writeCtorParameters(raw_ostream &OS) const override {
       OS << type << " " << getUpperName();
     }
-    void writeDeclarations(raw_ostream &OS) const {
-      std::vector<StringRef>::const_iterator i = uniques.begin(),
-                                             e = uniques.end();
+    void writeDeclarations(raw_ostream &OS) const override {
+      std::vector<std::string>::const_iterator i = uniques.begin(),
+                                               e = uniques.end();
       // The last one needs to not have a comma.
       --e;
 
@@ -566,26 +667,25 @@
       OS << "private:\n";
       OS << "  " << type << " " << getLowerName() << ";";
     }
-    void writePCHReadDecls(raw_ostream &OS) const {
+    void writePCHReadDecls(raw_ostream &OS) const override {
       OS << "    " << getAttrName() << "Attr::" << type << " " << getLowerName()
          << "(static_cast<" << getAttrName() << "Attr::" << type
          << ">(Record[Idx++]));\n";
     }
-    void writePCHReadArgs(raw_ostream &OS) const {
+    void writePCHReadArgs(raw_ostream &OS) const override {
       OS << getLowerName();
     }
-    void writePCHWrite(raw_ostream &OS) const {
+    void writePCHWrite(raw_ostream &OS) const override {
       OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
     }
-    void writeValue(raw_ostream &OS) const {
+    void writeValue(raw_ostream &OS) const override {
       OS << "\" << get" << getUpperName() << "() << \"";
     }
-    void writeDump(raw_ostream &OS) const {
+    void writeDump(raw_ostream &OS) const override {
       OS << "    switch(SA->get" << getUpperName() << "()) {\n";
-      for (std::vector<StringRef>::const_iterator I = uniques.begin(),
-           E = uniques.end(); I != E; ++I) {
-        OS << "    case " << getAttrName() << "Attr::" << *I << ":\n";
-        OS << "      OS << \" " << *I << "\";\n";
+      for (const auto &I : uniques) {
+        OS << "    case " << getAttrName() << "Attr::" << I << ":\n";
+        OS << "      OS << \" " << I << "\";\n";
         OS << "      break;\n";
       }
       OS << "    }\n";
@@ -595,7 +695,7 @@
       OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
       OS << type << " &Out) {\n";
       OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
-      OS << type << "> >(Val)\n";
+      OS << type << ">>(Val)\n";
       for (size_t I = 0; I < enums.size(); ++I) {
         OS << "      .Case(\"" << values[I] << "\", ";
         OS << getAttrName() << "Attr::" << enums[I] << ")\n";
@@ -610,30 +710,26 @@
   
   class VariadicEnumArgument: public VariadicArgument {
     std::string type, QualifiedTypeName;
-    std::vector<StringRef> values, enums, uniques;
+    std::vector<std::string> values, enums, uniques;
   public:
     VariadicEnumArgument(Record &Arg, StringRef Attr)
       : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
         type(Arg.getValueAsString("Type")),
-        values(getValueAsListOfStrings(Arg, "Values")),
-        enums(getValueAsListOfStrings(Arg, "Enums")),
-        uniques(enums)
+        values(Arg.getValueAsListOfStrings("Values")),
+        enums(Arg.getValueAsListOfStrings("Enums")),
+        uniques(uniqueEnumsInOrder(enums))
     {
-      // Calculate the various enum values
-      std::sort(uniques.begin(), uniques.end());
-      uniques.erase(std::unique(uniques.begin(), uniques.end()), uniques.end());
-      
       QualifiedTypeName = getAttrName().str() + "Attr::" + type;
       
       // FIXME: Emit a proper error
       assert(!uniques.empty());
     }
 
-    bool isVariadicEnumArg() const { return true; }
+    bool isVariadicEnumArg() const override { return true; }
     
-    void writeDeclarations(raw_ostream &OS) const {
-      std::vector<StringRef>::const_iterator i = uniques.begin(),
-                                             e = uniques.end();
+    void writeDeclarations(raw_ostream &OS) const override {
+      std::vector<std::string>::const_iterator i = uniques.begin(),
+                                               e = uniques.end();
       // The last one needs to not have a comma.
       --e;
 
@@ -647,21 +743,20 @@
       
       VariadicArgument::writeDeclarations(OS);
     }
-    void writeDump(raw_ostream &OS) const {
+    void writeDump(raw_ostream &OS) const override {
       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
          << getLowerName() << "_end(); I != E; ++I) {\n";
       OS << "      switch(*I) {\n";
-      for (std::vector<StringRef>::const_iterator UI = uniques.begin(),
-           UE = uniques.end(); UI != UE; ++UI) {
-        OS << "    case " << getAttrName() << "Attr::" << *UI << ":\n";
-        OS << "      OS << \" " << *UI << "\";\n";
+      for (const auto &UI : uniques) {
+        OS << "    case " << getAttrName() << "Attr::" << UI << ":\n";
+        OS << "      OS << \" " << UI << "\";\n";
         OS << "      break;\n";
       }
       OS << "      }\n";
       OS << "    }\n";
     }
-    void writePCHReadDecls(raw_ostream &OS) const {
+    void writePCHReadDecls(raw_ostream &OS) const override {
       OS << "    unsigned " << getLowerName() << "Size = Record[Idx++];\n";
       OS << "    SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
          << ";\n";
@@ -671,7 +766,7 @@
       OS << "      " << getLowerName() << ".push_back(" << "static_cast<"
          << QualifiedTypeName << ">(Record[Idx++]));\n";
     }
-    void writePCHWrite(raw_ostream &OS) const{
+    void writePCHWrite(raw_ostream &OS) const override {
       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
          << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
@@ -682,7 +777,7 @@
       OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
       OS << type << " &Out) {\n";
       OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
-      OS << type << "> >(Val)\n";
+      OS << type << ">>(Val)\n";
       for (size_t I = 0; I < enums.size(); ++I) {
         OS << "      .Case(\"" << values[I] << "\", ";
         OS << getAttrName() << "Attr::" << enums[I] << ")\n";
@@ -701,7 +796,7 @@
       : Argument(Arg, Attr)
     {}
 
-    void writeAccessors(raw_ostream &OS) const {
+    void writeAccessors(raw_ostream &OS) const override {
       OS << "  VersionTuple get" << getUpperName() << "() const {\n";
       OS << "    return " << getLowerName() << ";\n";
       OS << "  }\n";
@@ -710,40 +805,38 @@
       OS << "    " << getLowerName() << " = V;\n";
       OS << "  }";
     }
-    void writeCloneArgs(raw_ostream &OS) const {
+    void writeCloneArgs(raw_ostream &OS) const override {
       OS << "get" << getUpperName() << "()";
     }
-    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
       OS << "A->get" << getUpperName() << "()";
     }
-    void writeCtorBody(raw_ostream &OS) const {
-    }
-    void writeCtorInitializers(raw_ostream &OS) const {
+    void writeCtorInitializers(raw_ostream &OS) const override {
       OS << getLowerName() << "(" << getUpperName() << ")";
     }
-    void writeCtorDefaultInitializers(raw_ostream &OS) const {
+    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
       OS << getLowerName() << "()";
     }
-    void writeCtorParameters(raw_ostream &OS) const {
+    void writeCtorParameters(raw_ostream &OS) const override {
       OS << "VersionTuple " << getUpperName();
     }
-    void writeDeclarations(raw_ostream &OS) const {
+    void writeDeclarations(raw_ostream &OS) const override {
       OS << "VersionTuple " << getLowerName() << ";\n";
     }
-    void writePCHReadDecls(raw_ostream &OS) const {
+    void writePCHReadDecls(raw_ostream &OS) const override {
       OS << "    VersionTuple " << getLowerName()
          << "= ReadVersionTuple(Record, Idx);\n";
     }
-    void writePCHReadArgs(raw_ostream &OS) const {
+    void writePCHReadArgs(raw_ostream &OS) const override {
       OS << getLowerName();
     }
-    void writePCHWrite(raw_ostream &OS) const {
+    void writePCHWrite(raw_ostream &OS) const override {
       OS << "    AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
     }
-    void writeValue(raw_ostream &OS) const {
+    void writeValue(raw_ostream &OS) const override {
       OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
     }
-    void writeDump(raw_ostream &OS) const {
+    void writeDump(raw_ostream &OS) const override {
       OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
     }
   };
@@ -754,11 +847,17 @@
       : SimpleArgument(Arg, Attr, "Expr *")
     {}
 
-    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+    void writeASTVisitorTraversal(raw_ostream &OS) const override {
+      OS << "  if (!"
+         << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
+      OS << "    return false;\n";
+    }
+
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
       OS << "tempInst" << getUpperName();
     }
 
-    void writeTemplateInstantiation(raw_ostream &OS) const {
+    void writeTemplateInstantiation(raw_ostream &OS) const override {
       OS << "      " << getType() << " tempInst" << getUpperName() << ";\n";
       OS << "      {\n";
       OS << "        EnterExpressionEvaluationContext "
@@ -770,14 +869,13 @@
       OS << "      }\n";
     }
 
-    void writeDump(raw_ostream &OS) const {
-    }
+    void writeDump(raw_ostream &OS) const override {}
 
-    void writeDumpChildren(raw_ostream &OS) const {
+    void writeDumpChildren(raw_ostream &OS) const override {
       OS << "    lastChild();\n";
       OS << "    dumpStmt(SA->get" << getUpperName() << "());\n";
     }
-    void writeHasChildren(raw_ostream &OS) const { OS << "true"; }
+    void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
   };
 
   class VariadicExprArgument : public VariadicArgument {
@@ -786,12 +884,25 @@
       : VariadicArgument(Arg, Attr, "Expr *")
     {}
 
-    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+    void writeASTVisitorTraversal(raw_ostream &OS) const override {
+      OS << "  {\n";
+      OS << "    " << getType() << " *I = A->" << getLowerName()
+         << "_begin();\n";
+      OS << "    " << getType() << " *E = A->" << getLowerName()
+         << "_end();\n";
+      OS << "    for (; I != E; ++I) {\n";
+      OS << "      if (!getDerived().TraverseStmt(*I))\n";
+      OS << "        return false;\n";
+      OS << "    }\n";
+      OS << "  }\n";
+    }
+
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
       OS << "tempInst" << getUpperName() << ", "
          << "A->" << getLowerName() << "_size()";
     }
 
-    void writeTemplateInstantiation(raw_ostream &OS) const {
+    void writeTemplateInstantiation(raw_ostream &OS) const override {
       OS << "      " << getType() << " *tempInst" << getUpperName()
          << " = new (C, 16) " << getType()
          << "[A->" << getLowerName() << "_size()];\n";
@@ -811,10 +922,9 @@
       OS << "      }\n";
     }
 
-    void writeDump(raw_ostream &OS) const {
-    }
+    void writeDump(raw_ostream &OS) const override {}
 
-    void writeDumpChildren(raw_ostream &OS) const {
+    void writeDumpChildren(raw_ostream &OS) const override {
       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
          << getLowerName() << "_end(); I != E; ++I) {\n";
@@ -824,7 +934,7 @@
       OS << "    }\n";
     }
 
-    void writeHasChildren(raw_ostream &OS) const {
+    void writeHasChildren(raw_ostream &OS) const override {
       OS << "SA->" << getLowerName() << "_begin() != "
          << "SA->" << getLowerName() << "_end()";
     }
@@ -836,7 +946,7 @@
       : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
     {}
 
-    void writeAccessors(raw_ostream &OS) const {
+    void writeAccessors(raw_ostream &OS) const override {
       OS << "  QualType get" << getUpperName() << "() const {\n";
       OS << "    return " << getLowerName() << "->getType();\n";
       OS << "  }";
@@ -844,18 +954,18 @@
       OS << "    return " << getLowerName() << ";\n";
       OS << "  }";
     }
-    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
       OS << "A->get" << getUpperName() << "Loc()";
     }
-    void writePCHWrite(raw_ostream &OS) const {
+    void writePCHWrite(raw_ostream &OS) const override {
       OS << "    " << WritePCHRecord(
           getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
     }
   };
 }
 
-static Argument *createArgument(Record &Arg, StringRef Attr,
-                                Record *Search = 0) {
+static std::unique_ptr<Argument> createArgument(Record &Arg, StringRef Attr,
+                                                Record *Search = 0) {
   if (!Search)
     Search = &Arg;
 
@@ -869,15 +979,19 @@
     Ptr = new SimpleArgument(Arg, Attr, "FunctionDecl *");
   else if (ArgName == "IdentifierArgument")
     Ptr = new SimpleArgument(Arg, Attr, "IdentifierInfo *");
+  else if (ArgName == "DefaultBoolArgument")
+    Ptr = new DefaultSimpleArgument(Arg, Attr, "bool",
+                                    Arg.getValueAsBit("Default"));
   else if (ArgName == "BoolArgument") Ptr = new SimpleArgument(Arg, Attr, 
                                                                "bool");
+  else if (ArgName == "DefaultIntArgument")
+    Ptr = new DefaultSimpleArgument(Arg, Attr, "int",
+                                    Arg.getValueAsInt("Default"));
   else if (ArgName == "IntArgument") Ptr = new SimpleArgument(Arg, Attr, "int");
   else if (ArgName == "StringArgument") Ptr = new StringArgument(Arg, Attr);
   else if (ArgName == "TypeArgument") Ptr = new TypeArgument(Arg, Attr);
   else if (ArgName == "UnsignedArgument")
     Ptr = new SimpleArgument(Arg, Attr, "unsigned");
-  else if (ArgName == "SourceLocArgument")
-    Ptr = new SimpleArgument(Arg, Attr, "SourceLocation");
   else if (ArgName == "VariadicUnsignedArgument")
     Ptr = new VariadicArgument(Arg, Attr, "unsigned");
   else if (ArgName == "VariadicEnumArgument")
@@ -888,10 +1002,10 @@
     Ptr = new VersionArgument(Arg, Attr);
 
   if (!Ptr) {
+    // Search in reverse order so that the most-derived type is handled first.
     std::vector<Record*> Bases = Search->getSuperClasses();
-    for (std::vector<Record*>::iterator i = Bases.begin(), e = Bases.end();
-         i != e; ++i) {
-      Ptr = createArgument(Arg, Attr, *i);
+    for (auto i = Bases.rbegin(), e = Bases.rend(); i != e; ++i) {
+      Ptr = createArgument(Arg, Attr, *i).release();
       if (Ptr)
         break;
     }
@@ -900,7 +1014,7 @@
   if (Ptr && Arg.getValueAsBit("Optional"))
     Ptr->setOptional(true);
 
-  return Ptr;
+  return std::unique_ptr<Argument>(Ptr);
 }
 
 static void writeAvailabilityValue(raw_ostream &OS) {
@@ -912,9 +1026,34 @@
      << "  OS << \"";
 }
 
-static void writePrettyPrintFunction(Record &R, std::vector<Argument*> &Args,
-                                     raw_ostream &OS) {
-  std::vector<Record*> Spellings = R.getValueAsListOfDefs("Spellings");
+static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
+  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
+
+  OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
+  if (Spellings.empty()) {
+    OS << "  return \"(No spelling)\";\n}\n\n";
+    return;
+  }
+
+  OS << "  switch (SpellingListIndex) {\n"
+        "  default:\n"
+        "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
+        "    return \"(No spelling)\";\n";
+
+  for (unsigned I = 0; I < Spellings.size(); ++I)
+    OS << "  case " << I << ":\n"
+          "    return \"" << Spellings[I].name() << "\";\n";
+  // End of the switch statement.
+  OS << "  }\n";
+  // End of the getSpelling function.
+  OS << "}\n\n";
+}
+
+static void
+writePrettyPrintFunction(Record &R,
+                         const std::vector<std::unique_ptr<Argument>> &Args,
+                         raw_ostream &OS) {
+  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
 
   OS << "void " << R.getName() << "Attr::printPretty("
     << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
@@ -936,8 +1075,8 @@
     // The actual spelling of the name and namespace (if applicable)
     // of an attribute without considering prefix and suffix.
     llvm::SmallString<64> Spelling;
-    std::string Name = Spellings[I]->getValueAsString("Name");
-    std::string Variety = Spellings[I]->getValueAsString("Variety");
+    std::string Name = Spellings[I].name();
+    std::string Variety = Spellings[I].variety();
 
     if (Variety == "GNU") {
       Prefix = " __attribute__((";
@@ -945,7 +1084,7 @@
     } else if (Variety == "CXX11") {
       Prefix = " [[";
       Suffix = "]]";
-      std::string Namespace = Spellings[I]->getValueAsString("Namespace");
+      std::string Namespace = Spellings[I].nameSpace();
       if (Namespace != "") {
         Spelling += Namespace;
         Spelling += "::";
@@ -966,18 +1105,19 @@
       "  case " << I << " : {\n"
       "    OS << \"" + Prefix.str() + Spelling.str();
 
-    if (Args.size()) OS << "(";
+    if (!Args.empty())
+      OS << "(";
     if (Spelling == "availability") {
       writeAvailabilityValue(OS);
     } else {
-      for (std::vector<Argument*>::const_iterator I = Args.begin(),
-           E = Args.end(); I != E; ++ I) {
+      for (auto I = Args.begin(), E = Args.end(); I != E; ++ I) {
         if (I != Args.begin()) OS << ", ";
         (*I)->writeValue(OS);
       }
     }
 
-    if (Args.size()) OS << ")";
+    if (!Args.empty())
+      OS << ")";
     OS << Suffix.str() + "\";\n";
 
     OS <<
@@ -992,19 +1132,18 @@
 }
 
 /// \brief Return the index of a spelling in a spelling list.
-static unsigned getSpellingListIndex(const std::vector<Record*> &SpellingList,
-                                     const Record &Spelling) {
+static unsigned
+getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
+                     const FlattenedSpelling &Spelling) {
   assert(SpellingList.size() && "Spelling list is empty!");
 
   for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
-    Record *S = SpellingList[Index];
-    if (S->getValueAsString("Variety") != Spelling.getValueAsString("Variety"))
+    const FlattenedSpelling &S = SpellingList[Index];
+    if (S.variety() != Spelling.variety())
       continue;
-    if (S->getValueAsString("Variety") == "CXX11" &&
-        S->getValueAsString("Namespace") !=
-        Spelling.getValueAsString("Namespace"))
+    if (S.nameSpace() != Spelling.nameSpace())
       continue;
-    if (S->getValueAsString("Name") != Spelling.getValueAsString("Name"))
+    if (S.name() != Spelling.name())
       continue;
 
     return Index;
@@ -1013,21 +1152,19 @@
   llvm_unreachable("Unknown spelling!");
 }
 
-static void writeAttrAccessorDefinition(Record &R, raw_ostream &OS) {
+static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
   std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
-  for (std::vector<Record*>::const_iterator I = Accessors.begin(),
-       E = Accessors.end(); I != E; ++I) {
-    Record *Accessor = *I;
+  for (auto Accessor : Accessors) {
     std::string Name = Accessor->getValueAsString("Name");
-    std::vector<Record*> Spellings = Accessor->getValueAsListOfDefs(
-      "Spellings");
-    std::vector<Record*> SpellingList = R.getValueAsListOfDefs("Spellings");
+    std::vector<FlattenedSpelling> Spellings = 
+      GetFlattenedSpellings(*Accessor);
+    std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
     assert(SpellingList.size() &&
            "Attribute with empty spelling list can't have accessors!");
 
     OS << "  bool " << Name << "() const { return SpellingListIndex == ";
     for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
-      OS << getSpellingListIndex(SpellingList, *Spellings[Index]);
+      OS << getSpellingListIndex(SpellingList, Spellings[Index]);
       if (Index != Spellings.size() -1)
         OS << " ||\n    SpellingListIndex == ";
       else
@@ -1036,6 +1173,173 @@
   }
 }
 
+static bool
+SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
+  assert(!Spellings.empty() && "An empty list of spellings was provided");
+  std::string FirstName = NormalizeNameForSpellingComparison(
+    Spellings.front().name());
+  for (auto I = std::next(Spellings.begin()), E = Spellings.end();
+       I != E; ++I) {
+    std::string Name = NormalizeNameForSpellingComparison(I->name());
+    if (Name != FirstName)
+      return false;
+  }
+  return true;
+}
+
+typedef std::map<unsigned, std::string> SemanticSpellingMap;
+static std::string
+CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
+                        SemanticSpellingMap &Map) {
+  // The enumerants are automatically generated based on the variety,
+  // namespace (if present) and name for each attribute spelling. However,
+  // care is taken to avoid trampling on the reserved namespace due to
+  // underscores.
+  std::string Ret("  enum Spelling {\n");
+  std::set<std::string> Uniques;
+  unsigned Idx = 0;
+  for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
+    const FlattenedSpelling &S = *I;
+    std::string Variety = S.variety();
+    std::string Spelling = S.name();
+    std::string Namespace = S.nameSpace();
+    std::string EnumName = "";
+
+    EnumName += (Variety + "_");
+    if (!Namespace.empty())
+      EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
+      "_");
+    EnumName += NormalizeNameForSpellingComparison(Spelling);
+
+    // Even if the name is not unique, this spelling index corresponds to a
+    // particular enumerant name that we've calculated.
+    Map[Idx] = EnumName;
+
+    // Since we have been stripping underscores to avoid trampling on the
+    // reserved namespace, we may have inadvertently created duplicate
+    // enumerant names. These duplicates are not considered part of the
+    // semantic spelling, and can be elided.
+    if (Uniques.find(EnumName) != Uniques.end())
+      continue;
+
+    Uniques.insert(EnumName);
+    if (I != Spellings.begin())
+      Ret += ",\n";
+    Ret += "    " + EnumName;
+  }
+  Ret += "\n  };\n\n";
+  return Ret;
+}
+
+void WriteSemanticSpellingSwitch(const std::string &VarName,
+                                 const SemanticSpellingMap &Map,
+                                 raw_ostream &OS) {
+  OS << "  switch (" << VarName << ") {\n    default: "
+    << "llvm_unreachable(\"Unknown spelling list index\");\n";
+  for (const auto &I : Map)
+    OS << "    case " << I.first << ": return " << I.second << ";\n";
+  OS << "  }\n";
+}
+
+// Emits the LateParsed property for attributes.
+static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
+  OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
+  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
+
+  for (auto Attr : Attrs) {
+    bool LateParsed = Attr->getValueAsBit("LateParsed");
+
+    if (LateParsed) {
+      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
+
+      // FIXME: Handle non-GNU attributes
+      for (const auto &I : Spellings) {
+        if (I.variety() != "GNU")
+          continue;
+        OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
+      }
+    }
+  }
+  OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
+}
+
+/// \brief Emits the first-argument-is-type property for attributes.
+static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
+  OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
+  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
+
+  for (auto Attr : Attrs) {
+    // Determine whether the first argument is a type.
+    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
+    if (Args.empty())
+      continue;
+
+    if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
+      continue;
+
+    // All these spellings take a single type argument.
+    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
+    std::set<std::string> Emitted;
+    for (const auto &S : Spellings) {
+      if (Emitted.insert(S.name()).second)
+        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
+    }
+  }
+  OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
+}
+
+/// \brief Emits the parse-arguments-in-unevaluated-context property for
+/// attributes.
+static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
+  OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
+  ParsedAttrMap Attrs = getParsedAttrList(Records);
+  for (const auto &I : Attrs) {
+    const Record &Attr = *I.second;
+
+    if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
+      continue;
+
+    // All these spellings take are parsed unevaluated.
+    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
+    std::set<std::string> Emitted;
+    for (const auto &S : Spellings) {
+      if (Emitted.insert(S.name()).second)
+        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
+    }
+  }
+  OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
+}
+
+static bool isIdentifierArgument(Record *Arg) {
+  return !Arg->getSuperClasses().empty() &&
+    llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
+    .Case("IdentifierArgument", true)
+    .Case("EnumArgument", true)
+    .Default(false);
+}
+
+// Emits the first-argument-is-identifier property for attributes.
+static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
+  OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
+  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
+
+  for (auto Attr : Attrs) {
+    // Determine whether the first argument is an identifier.
+    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
+    if (Args.empty() || !isIdentifierArgument(Args[0]))
+      continue;
+
+    // All these spellings take an identifier argument.
+    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
+    std::set<std::string> Emitted;
+    for (const auto &S : Spellings) {
+      if (Emitted.insert(S.name()).second)
+        OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
+    }
+  }
+  OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
+}
+
 namespace clang {
 
 // Emits the class definitions for attributes.
@@ -1047,9 +1351,19 @@
 
   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
 
-  for (std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end();
-       i != e; ++i) {
-    Record &R = **i;
+  for (auto i : Attrs) {
+    const Record &R = *i;
+
+    // FIXME: Currently, documentation is generated as-needed due to the fact
+    // that there is no way to allow a generated project "reach into" the docs
+    // directory (for instance, it may be an out-of-tree build). However, we want
+    // to ensure that every attribute has a Documentation field, and produce an
+    // error if it has been neglected. Otherwise, the on-demand generation which
+    // happens server-side will fail. This code is ensuring that functionality,
+    // even though this Emitter doesn't technically need the documentation.
+    // When attribute documentation can be generated as part of the build
+    // itself, this code can be removed.
+    (void)R.getValueAsListOfDefs("Documentation");
     
     if (!R.getValueAsBit("ASTNode"))
       continue;
@@ -1057,8 +1371,7 @@
     const std::vector<Record *> Supers = R.getSuperClasses();
     assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
     std::string SuperName;
-    for (std::vector<Record *>::const_reverse_iterator I = Supers.rbegin(),
-         E = Supers.rend(); I != E; ++I) {
+    for (auto I = Supers.rbegin(), E = Supers.rend(); I != E; ++I) {
       const Record &R = **I;
       if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
         SuperName = R.getName();
@@ -1067,52 +1380,78 @@
     OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
 
     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
-    std::vector<Argument*> Args;
-    std::vector<Argument*>::iterator ai, ae;
+    std::vector<std::unique_ptr<Argument>> Args;
     Args.reserve(ArgRecords.size());
 
-    for (std::vector<Record*>::iterator ri = ArgRecords.begin(),
-                                        re = ArgRecords.end();
-         ri != re; ++ri) {
-      Record &ArgRecord = **ri;
-      Argument *Arg = createArgument(ArgRecord, R.getName());
-      assert(Arg);
-      Args.push_back(Arg);
-
-      Arg->writeDeclarations(OS);
+    for (auto ArgRecord : ArgRecords) {
+      Args.emplace_back(createArgument(*ArgRecord, R.getName()));
+      Args.back()->writeDeclarations(OS);
       OS << "\n\n";
     }
 
-    ae = Args.end();
+    OS << "\npublic:\n";
 
-    OS << "\n public:\n";
+    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
+
+    // If there are zero or one spellings, all spelling-related functionality
+    // can be elided. If all of the spellings share the same name, the spelling
+    // functionality can also be elided.
+    bool ElideSpelling = (Spellings.size() <= 1) ||
+                         SpellingNamesAreCommon(Spellings);
+
+    // This maps spelling index values to semantic Spelling enumerants.
+    SemanticSpellingMap SemanticToSyntacticMap;
+
+    if (!ElideSpelling)
+      OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
+
+    OS << "  static " << R.getName() << "Attr *CreateImplicit(";
+    OS << "ASTContext &Ctx";
+    if (!ElideSpelling)
+      OS << ", Spelling S";
+    for (auto const &ai : Args) {
+      OS << ", ";
+      ai->writeCtorParameters(OS);
+    }
+    OS << ", SourceRange Loc = SourceRange()";
+    OS << ") {\n";
+    OS << "    " << R.getName() << "Attr *A = new (Ctx) " << R.getName();
+    OS << "Attr(Loc, Ctx, ";
+    for (auto const &ai : Args) {
+      ai->writeImplicitCtorArgs(OS);
+      OS << ", ";
+    }
+    OS << (ElideSpelling ? "0" : "S") << ");\n";
+    OS << "    A->setImplicit(true);\n";
+    OS << "    return A;\n  }\n\n";
+
     OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
     
     bool HasOpt = false;
-    for (ai = Args.begin(); ai != ae; ++ai) {
+    for (auto const &ai : Args) {
       OS << "              , ";
-      (*ai)->writeCtorParameters(OS);
+      ai->writeCtorParameters(OS);
       OS << "\n";
-      if ((*ai)->isOptional())
+      if (ai->isOptional())
         HasOpt = true;
     }
 
     OS << "              , ";
-    OS << "unsigned SI = 0\n";
+    OS << "unsigned SI\n";
 
     OS << "             )\n";
     OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";
 
-    for (ai = Args.begin(); ai != ae; ++ai) {
+    for (auto const &ai : Args) {
       OS << "              , ";
-      (*ai)->writeCtorInitializers(OS);
+      ai->writeCtorInitializers(OS);
       OS << "\n";
     }
 
     OS << "  {\n";
   
-    for (ai = Args.begin(); ai != ae; ++ai) {
-      (*ai)->writeCtorBody(OS);
+    for (auto const &ai : Args) {
+      ai->writeCtorBody(OS);
       OS << "\n";
     }
     OS << "  }\n\n";
@@ -1121,54 +1460,61 @@
     // optional arguments as well.
     if (HasOpt) {
       OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
-      for (ai = Args.begin(); ai != ae; ++ai) {
-        if (!(*ai)->isOptional()) {
+      for (auto const &ai : Args) {
+        if (!ai->isOptional()) {
           OS << "              , ";
-          (*ai)->writeCtorParameters(OS);
+          ai->writeCtorParameters(OS);
           OS << "\n";
         }
       }
 
       OS << "              , ";
-      OS << "unsigned SI = 0\n";
+      OS << "unsigned SI\n";
 
       OS << "             )\n";
       OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";
 
-      for (ai = Args.begin(); ai != ae; ++ai) {
+      for (auto const &ai : Args) {
         OS << "              , ";
-        (*ai)->writeCtorDefaultInitializers(OS);
+        ai->writeCtorDefaultInitializers(OS);
         OS << "\n";
       }
 
       OS << "  {\n";
   
-      for (ai = Args.begin(); ai != ae; ++ai) {
-        if (!(*ai)->isOptional()) {
-          (*ai)->writeCtorBody(OS);
+      for (auto const &ai : Args) {
+        if (!ai->isOptional()) {
+          ai->writeCtorBody(OS);
           OS << "\n";
         }
       }
       OS << "  }\n\n";
     }
 
-    OS << "  virtual " << R.getName() << "Attr *clone (ASTContext &C) const;\n";
-    OS << "  virtual void printPretty(raw_ostream &OS,\n"
-       << "                           const PrintingPolicy &Policy) const;\n";
+    OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const override;\n";
+    OS << "  void printPretty(raw_ostream &OS,\n"
+       << "                   const PrintingPolicy &Policy) const override;\n";
+    OS << "  const char *getSpelling() const override;\n";
+    
+    if (!ElideSpelling) {
+      assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
+      OS << "  Spelling getSemanticSpelling() const {\n";
+      WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
+                                  OS);
+      OS << "  }\n";
+    }
 
     writeAttrAccessorDefinition(R, OS);
 
-    for (ai = Args.begin(); ai != ae; ++ai) {
-      (*ai)->writeAccessors(OS);
+    for (auto const &ai : Args) {
+      ai->writeAccessors(OS);
       OS << "\n\n";
 
-      if ((*ai)->isEnumArg()) {
-        EnumArgument *EA = (EnumArgument *)*ai;
-        EA->writeConversion(OS);
-      } else if ((*ai)->isVariadicEnumArg()) {
-        VariadicEnumArgument *VEA = (VariadicEnumArgument *)*ai;
-        VEA->writeConversion(OS);
-      }
+      if (ai->isEnumArg())
+        static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
+      else if (ai->isVariadicEnumArg())
+        static_cast<const VariadicEnumArgument *>(ai.get())
+            ->writeConversion(OS);
     }
 
     OS << R.getValueAsString("AdditionalMembers");
@@ -1178,114 +1524,49 @@
        << "attr::" << R.getName() << "; }\n";
 
     bool LateParsed = R.getValueAsBit("LateParsed");
-    OS << "  virtual bool isLateParsed() const { return "
+    OS << "  bool isLateParsed() const override { return "
        << LateParsed << "; }\n";
 
+    if (R.getValueAsBit("DuplicatesAllowedWhileMerging"))
+      OS << "  bool duplicatesAllowed() const override { return true; }\n\n";
+
     OS << "};\n\n";
   }
 
   OS << "#endif\n";
 }
 
-static bool isIdentifierArgument(Record *Arg) {
-  return !Arg->getSuperClasses().empty() &&
-         llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
-             .Case("IdentifierArgument", true)
-             .Case("EnumArgument", true)
-             .Default(false);
-}
-
-/// \brief Emits the first-argument-is-type property for attributes.
-void EmitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
-  emitSourceFileHeader("llvm::StringSwitch code to match attributes with a "
-                       "type argument", OS);
-
-  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
-
-  for (std::vector<Record *>::iterator I = Attrs.begin(), E = Attrs.end();
-       I != E; ++I) {
-    Record &Attr = **I;
-
-    // Determine whether the first argument is a type.
-    std::vector<Record *> Args = Attr.getValueAsListOfDefs("Args");
-    if (Args.empty())
-      continue;
-
-    if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
-      continue;
-
-    // All these spellings take a single type argument.
-    std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");
-    std::set<std::string> Emitted;
-    for (std::vector<Record*>::const_iterator I = Spellings.begin(),
-         E = Spellings.end(); I != E; ++I) {
-      if (Emitted.insert((*I)->getValueAsString("Name")).second)
-        OS << ".Case(\"" << (*I)->getValueAsString("Name") << "\", "
-           << "true" << ")\n";
-    }
-  }
-}
-
-// Emits the first-argument-is-identifier property for attributes.
-void EmitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
-  emitSourceFileHeader("llvm::StringSwitch code to match attributes with "
-                       "an identifier argument", OS);
-
-  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
-
-  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
-       I != E; ++I) {
-    Record &Attr = **I;
-
-    // Determine whether the first argument is an identifier.
-    std::vector<Record *> Args = Attr.getValueAsListOfDefs("Args");
-    if (Args.empty() || !isIdentifierArgument(Args[0]))
-      continue;
-
-    // All these spellings take an identifier argument.
-    std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");
-    std::set<std::string> Emitted;
-    for (std::vector<Record*>::const_iterator I = Spellings.begin(),
-         E = Spellings.end(); I != E; ++I) {
-      if (Emitted.insert((*I)->getValueAsString("Name")).second)
-        OS << ".Case(\"" << (*I)->getValueAsString("Name") << "\", "
-           << "true" << ")\n";
-    }
-  }
-}
-
 // Emits the class method definitions for attributes.
 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
   emitSourceFileHeader("Attribute classes' member function definitions", OS);
 
   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
-  std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end(), ri, re;
-  std::vector<Argument*>::iterator ai, ae;
 
-  for (; i != e; ++i) {
-    Record &R = **i;
+  for (auto i : Attrs) {
+    Record &R = *i;
     
     if (!R.getValueAsBit("ASTNode"))
       continue;
-    
-    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
-    std::vector<Argument*> Args;
-    for (ri = ArgRecords.begin(), re = ArgRecords.end(); ri != re; ++ri)
-      Args.push_back(createArgument(**ri, R.getName()));
 
-    for (ai = Args.begin(), ae = Args.end(); ai != ae; ++ai)
-      (*ai)->writeAccessorDefinitions(OS);
+    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
+    std::vector<std::unique_ptr<Argument>> Args;
+    for (auto ri : ArgRecords)
+      Args.emplace_back(createArgument(*ri, R.getName()));
+
+    for (auto const &ai : Args)
+      ai->writeAccessorDefinitions(OS);
 
     OS << R.getName() << "Attr *" << R.getName()
        << "Attr::clone(ASTContext &C) const {\n";
     OS << "  return new (C) " << R.getName() << "Attr(getLocation(), C";
-    for (ai = Args.begin(); ai != ae; ++ai) {
+    for (auto const &ai : Args) {
       OS << ", ";
-      (*ai)->writeCloneArgs(OS);
+      ai->writeCloneArgs(OS);
     }
     OS << ", getSpellingListIndex());\n}\n\n";
 
     writePrettyPrintFunction(R, Args, OS);
+    writeGetSpellingFunction(R, OS);
   }
 }
 
@@ -1335,46 +1616,30 @@
         " INHERITABLE_PARAM_ATTR(NAME)\n";
   OS << "#endif\n\n";
 
-  OS << "#ifndef MS_INHERITANCE_ATTR\n";
-  OS << "#define MS_INHERITANCE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
-  OS << "#endif\n\n";
-
-  OS << "#ifndef LAST_MS_INHERITANCE_ATTR\n";
-  OS << "#define LAST_MS_INHERITANCE_ATTR(NAME)"
-        " MS_INHERITANCE_ATTR(NAME)\n";
-  OS << "#endif\n\n";
-
   Record *InhClass = Records.getClass("InheritableAttr");
   Record *InhParamClass = Records.getClass("InheritableParamAttr");
-  Record *MSInheritanceClass = Records.getClass("MSInheritanceAttr");
   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
-                       NonInhAttrs, InhAttrs, InhParamAttrs, MSInhAttrs;
-  for (std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end();
-       i != e; ++i) {
-    if (!(*i)->getValueAsBit("ASTNode"))
+                       NonInhAttrs, InhAttrs, InhParamAttrs;
+  for (auto i : Attrs) {
+    if (!i->getValueAsBit("ASTNode"))
       continue;
     
-    if ((*i)->isSubClassOf(InhParamClass))
-      InhParamAttrs.push_back(*i);
-    else if ((*i)->isSubClassOf(MSInheritanceClass))
-      MSInhAttrs.push_back(*i);
-    else if ((*i)->isSubClassOf(InhClass))
-      InhAttrs.push_back(*i);
+    if (i->isSubClassOf(InhParamClass))
+      InhParamAttrs.push_back(i);
+    else if (i->isSubClassOf(InhClass))
+      InhAttrs.push_back(i);
     else
-      NonInhAttrs.push_back(*i);
+      NonInhAttrs.push_back(i);
   }
 
   EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
-  EmitAttrList(OS, "MS_INHERITANCE_ATTR", MSInhAttrs);
   EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
   EmitAttrList(OS, "ATTR", NonInhAttrs);
 
   OS << "#undef LAST_ATTR\n";
   OS << "#undef INHERITABLE_ATTR\n";
-  OS << "#undef MS_INHERITANCE_ATTR\n";
   OS << "#undef LAST_INHERITABLE_ATTR\n";
   OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
-  OS << "#undef LAST_MS_INHERITANCE_ATTR\n";
   OS << "#undef ATTR\n";
 }
 
@@ -1385,37 +1650,37 @@
   Record *InhClass = Records.getClass("InheritableAttr");
   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
                        ArgRecords;
-  std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end(), ai, ae;
-  std::vector<Argument*> Args;
-  std::vector<Argument*>::iterator ri, re;
+  std::vector<std::unique_ptr<Argument>> Args;
 
   OS << "  switch (Kind) {\n";
   OS << "  default:\n";
   OS << "    assert(0 && \"Unknown attribute!\");\n";
   OS << "    break;\n";
-  for (; i != e; ++i) {
-    Record &R = **i;
+  for (auto i : Attrs) {
+    const Record &R = *i;
     if (!R.getValueAsBit("ASTNode"))
       continue;
     
     OS << "  case attr::" << R.getName() << ": {\n";
     if (R.isSubClassOf(InhClass))
       OS << "    bool isInherited = Record[Idx++];\n";
+    OS << "    bool isImplicit = Record[Idx++];\n";
+    OS << "    unsigned Spelling = Record[Idx++];\n";
     ArgRecords = R.getValueAsListOfDefs("Args");
     Args.clear();
-    for (ai = ArgRecords.begin(), ae = ArgRecords.end(); ai != ae; ++ai) {
-      Argument *A = createArgument(**ai, R.getName());
-      Args.push_back(A);
-      A->writePCHReadDecls(OS);
+    for (auto ai : ArgRecords) {
+      Args.emplace_back(createArgument(*ai, R.getName()));
+      Args.back()->writePCHReadDecls(OS);
     }
     OS << "    New = new (Context) " << R.getName() << "Attr(Range, Context";
-    for (ri = Args.begin(), re = Args.end(); ri != re; ++ri) {
+    for (auto const &ri : Args) {
       OS << ", ";
-      (*ri)->writePCHReadArgs(OS);
+      ri->writePCHReadArgs(OS);
     }
-    OS << ");\n";
+    OS << ", Spelling);\n";
     if (R.isSubClassOf(InhClass))
       OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
+    OS << "    New->setImplicit(isImplicit);\n";
     OS << "    break;\n";
     OS << "  }\n";
   }
@@ -1428,14 +1693,13 @@
 
   Record *InhClass = Records.getClass("InheritableAttr");
   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
-  std::vector<Record*>::iterator i = Attrs.begin(), e = Attrs.end(), ai, ae;
 
   OS << "  switch (A->getKind()) {\n";
   OS << "  default:\n";
   OS << "    llvm_unreachable(\"Unknown attribute kind!\");\n";
   OS << "    break;\n";
-  for (; i != e; ++i) {
-    Record &R = **i;
+  for (auto i : Attrs) {
+    const Record &R = *i;
     if (!R.getValueAsBit("ASTNode"))
       continue;
     OS << "  case attr::" << R.getName() << ": {\n";
@@ -1445,31 +1709,124 @@
          << "Attr>(A);\n";
     if (R.isSubClassOf(InhClass))
       OS << "    Record.push_back(SA->isInherited());\n";
-    for (ai = Args.begin(), ae = Args.end(); ai != ae; ++ai)
-      createArgument(**ai, R.getName())->writePCHWrite(OS);
+    OS << "    Record.push_back(A->isImplicit());\n";
+    OS << "    Record.push_back(A->getSpellingListIndex());\n";
+
+    for (auto ai : Args)
+      createArgument(*ai, R.getName())->writePCHWrite(OS);
     OS << "    break;\n";
     OS << "  }\n";
   }
   OS << "  }\n";
 }
 
+static void GenerateHasAttrSpellingStringSwitch(
+    const std::vector<Record *> &Attrs, raw_ostream &OS,
+    const std::string &Variety = "", const std::string &Scope = "") {
+  for (const auto *Attr : Attrs) {
+    // It is assumed that there will be an llvm::Triple object named T within
+    // scope that can be used to determine whether the attribute exists in
+    // a given target.
+    std::string Test;
+    if (Attr->isSubClassOf("TargetSpecificAttr")) {
+      const Record *R = Attr->getValueAsDef("Target");
+      std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
+
+      Test += "(";
+      for (auto AI = Arches.begin(), AE = Arches.end(); AI != AE; ++AI) {
+        std::string Part = *AI;
+        Test += "T.getArch() == llvm::Triple::" + Part;
+        if (AI + 1 != AE)
+          Test += " || ";
+      }
+      Test += ")";
+
+      std::vector<std::string> OSes;
+      if (!R->isValueUnset("OSes")) {
+        Test += " && (";
+        std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
+        for (auto AI = OSes.begin(), AE = OSes.end(); AI != AE; ++AI) {
+          std::string Part = *AI;
+
+          Test += "T.getOS() == llvm::Triple::" + Part;
+          if (AI + 1 != AE)
+            Test += " || ";
+        }
+        Test += ")";
+      }
+      
+      // If this is the C++11 variety, also add in the LangOpts test.
+      if (Variety == "CXX11")
+        Test += " && LangOpts.CPlusPlus11";
+    } else if (Variety == "CXX11")
+      // C++11 mode should be checked against LangOpts, which is presumed to be
+      // present in the caller.
+      Test = "LangOpts.CPlusPlus11";
+    else
+      Test = "true";
+
+    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
+    for (const auto &S : Spellings)
+      if (Variety.empty() || (Variety == S.variety() &&
+                              (Scope.empty() || Scope == S.nameSpace())))
+        OS << "    .Case(\"" << S.name() << "\", " << Test << ")\n";
+  }
+  OS << "    .Default(false);\n";
+}
+
 // Emits the list of spellings for attributes.
-void EmitClangAttrSpellingList(RecordKeeper &Records, raw_ostream &OS) {
-  emitSourceFileHeader("llvm::StringSwitch code to match all known attributes",
-                       OS);
+void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
+  emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
 
-  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
-  
-  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
-    Record &Attr = **I;
+  // Separate all of the attributes out into four group: generic, C++11, GNU,
+  // and declspecs. Then generate a big switch statement for each of them.
+  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
+  std::vector<Record *> Declspec, GNU;
+  std::map<std::string, std::vector<Record *>> CXX;
 
-    std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");
-
-    for (std::vector<Record*>::const_iterator I = Spellings.begin(), E = Spellings.end(); I != E; ++I) {
-      OS << ".Case(\"" << (*I)->getValueAsString("Name") << "\", true)\n";
+  // Walk over the list of all attributes, and split them out based on the
+  // spelling variety.
+  for (auto *R : Attrs) {
+    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
+    for (const auto &SI : Spellings) {
+      std::string Variety = SI.variety();
+      if (Variety == "GNU")
+        GNU.push_back(R);
+      else if (Variety == "Declspec")
+        Declspec.push_back(R);
+      else if (Variety == "CXX11") {
+        CXX[SI.nameSpace()].push_back(R);
+      }
     }
   }
 
+  OS << "switch (Syntax) {\n";
+  OS << "case AttrSyntax::Generic:\n";
+  OS << "  return llvm::StringSwitch<bool>(Name)\n";
+  GenerateHasAttrSpellingStringSwitch(Attrs, OS);
+  OS << "case AttrSyntax::GNU:\n";
+  OS << "  return llvm::StringSwitch<bool>(Name)\n";
+  GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
+  OS << "case AttrSyntax::Declspec:\n";
+  OS << "  return llvm::StringSwitch<bool>(Name)\n";
+  GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
+  OS << "case AttrSyntax::CXX: {\n";
+  // C++11-style attributes are further split out based on the Scope.
+  for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(),
+                                                              E = CXX.end();
+       I != E; ++I) {
+    if (I != CXX.begin())
+      OS << " else ";
+    if (I->first.empty())
+      OS << "if (!Scope || Scope->getName() == \"\") {\n";
+    else
+      OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
+    OS << "  return llvm::StringSwitch<bool>(Name)\n";
+    GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
+    OS << "}";
+  }
+  OS << "\n}\n";
+  OS << "}\n";
 }
 
 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
@@ -1477,88 +1834,105 @@
                        "into internal identifiers", OS);
 
   OS <<
-    "  unsigned Index = 0;\n"
     "  switch (AttrKind) {\n"
     "  default:\n"
     "    llvm_unreachable(\"Unknown attribute kind!\");\n"
     "    break;\n";
 
-  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
-  for (std::vector<Record*>::const_iterator I = Attrs.begin(), E = Attrs.end();
-       I != E; ++I) {
-    Record &R = **I;
-    // We only care about attributes that participate in Sema checking, so
-    // skip those attributes that are not able to make their way to Sema.
-    if (!R.getValueAsBit("SemaHandler"))
-      continue;
-
-    std::vector<Record*> Spellings = R.getValueAsListOfDefs("Spellings");
-    // Each distinct spelling yields an attribute kind.
-    if (R.getValueAsBit("DistinctSpellings")) {
-      for (unsigned I = 0; I < Spellings.size(); ++ I) {
-        OS <<
-          "  case AT_" << Spellings[I]->getValueAsString("Name") << ": \n"
-          "    Index = " << I << ";\n"
-          "  break;\n";
-      }
-    } else {
-      OS << "  case AT_" << R.getName() << " : {\n";
-      for (unsigned I = 0; I < Spellings.size(); ++ I) {
-        SmallString<16> Namespace;
-        if (Spellings[I]->getValueAsString("Variety") == "CXX11")
-          Namespace = Spellings[I]->getValueAsString("Namespace");
-        else
-          Namespace = "";
-
-        OS << "    if (Name == \""
-          << Spellings[I]->getValueAsString("Name") << "\" && "
-          << "SyntaxUsed == "
-          << StringSwitch<unsigned>(Spellings[I]->getValueAsString("Variety"))
-            .Case("GNU", 0)
-            .Case("CXX11", 1)
-            .Case("Declspec", 2)
-            .Case("Keyword", 3)
-            .Default(0)
-          << " && Scope == \"" << Namespace << "\")\n"
-          << "        return " << I << ";\n";
-      }
-
-      OS << "    break;\n";
-      OS << "  }\n";
+  ParsedAttrMap Attrs = getParsedAttrList(Records);
+  for (const auto &I : Attrs) {
+    Record &R = *I.second;
+    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
+    OS << "  case AT_" << I.first << ": {\n";
+    for (unsigned I = 0; I < Spellings.size(); ++ I) {
+      OS << "    if (Name == \""
+        << Spellings[I].name() << "\" && "
+        << "SyntaxUsed == "
+        << StringSwitch<unsigned>(Spellings[I].variety())
+          .Case("GNU", 0)
+          .Case("CXX11", 1)
+          .Case("Declspec", 2)
+          .Case("Keyword", 3)
+          .Default(0)
+        << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
+        << "        return " << I << ";\n";
     }
+
+    OS << "    break;\n";
+    OS << "  }\n";
   }
 
   OS << "  }\n";
-  OS << "  return Index;\n";
+  OS << "  return 0;\n";
 }
 
-// Emits the LateParsed property for attributes.
-void EmitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
-  emitSourceFileHeader("llvm::StringSwitch code to match late parsed "
-                       "attributes", OS);
+// Emits code used by RecursiveASTVisitor to visit attributes
+void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
+  emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
 
   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
 
-  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
-       I != E; ++I) {
-    Record &Attr = **I;
-
-    bool LateParsed = Attr.getValueAsBit("LateParsed");
-
-    if (LateParsed) {
-      std::vector<Record*> Spellings =
-        Attr.getValueAsListOfDefs("Spellings");
-
-      // FIXME: Handle non-GNU attributes
-      for (std::vector<Record*>::const_iterator I = Spellings.begin(),
-           E = Spellings.end(); I != E; ++I) {
-        if ((*I)->getValueAsString("Variety") != "GNU")
-          continue;
-        OS << ".Case(\"" << (*I)->getValueAsString("Name") << "\", "
-           << LateParsed << ")\n";
-      }
-    }
+  // Write method declarations for Traverse* methods.
+  // We emit this here because we only generate methods for attributes that
+  // are declared as ASTNodes.
+  OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
+  for (auto I : Attrs) {
+    const Record &R = *I;
+    if (!R.getValueAsBit("ASTNode"))
+      continue;
+    OS << "  bool Traverse"
+       << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
+    OS << "  bool Visit"
+       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
+       << "    return true; \n"
+       << "  };\n";
   }
+  OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
+
+  // Write individual Traverse* methods for each attribute class.
+  for (auto I : Attrs) {
+    const Record &R = *I;
+    if (!R.getValueAsBit("ASTNode"))
+      continue;
+
+    OS << "template <typename Derived>\n"
+       << "bool VISITORCLASS<Derived>::Traverse"
+       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
+       << "  if (!getDerived().VisitAttr(A))\n"
+       << "    return false;\n"
+       << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
+       << "    return false;\n";
+
+    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
+    for (auto ri : ArgRecords)
+      createArgument(*ri, R.getName())->writeASTVisitorTraversal(OS);
+
+    OS << "  return true;\n";
+    OS << "}\n\n";
+  }
+
+  // Write generic Traverse routine
+  OS << "template <typename Derived>\n"
+     << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
+     << "  if (!A)\n"
+     << "    return true;\n"
+     << "\n"
+     << "  switch (A->getKind()) {\n"
+     << "    default:\n"
+     << "      return true;\n";
+
+  for (auto I : Attrs) {
+    const Record &R = *I;
+    if (!R.getValueAsBit("ASTNode"))
+      continue;
+
+    OS << "    case attr::" << R.getName() << ":\n"
+       << "      return getDerived().Traverse" << R.getName() << "Attr("
+       << "cast<" << R.getName() << "Attr>(A));\n";
+  }
+  OS << "  }\n";  // end case
+  OS << "}\n";  // end function
+  OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
 }
 
 // Emits code to instantiate dependent attributes on templates.
@@ -1576,9 +1950,8 @@
      << "    default:\n"
      << "      break;\n";
 
-  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
-       I != E; ++I) {
-    Record &R = **I;
+  for (auto I : Attrs) {
+    const Record &R = *I;
     if (!R.getValueAsBit("ASTNode"))
       continue;
 
@@ -1602,29 +1975,21 @@
     }
 
     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
-    std::vector<Argument*> Args;
-    std::vector<Argument*>::iterator ai, ae;
+    std::vector<std::unique_ptr<Argument>> Args;
     Args.reserve(ArgRecords.size());
 
-    for (std::vector<Record*>::iterator ri = ArgRecords.begin(),
-                                        re = ArgRecords.end();
-         ri != re; ++ri) {
-      Record &ArgRecord = **ri;
-      Argument *Arg = createArgument(ArgRecord, R.getName());
-      assert(Arg);
-      Args.push_back(Arg);
-    }
-    ae = Args.end();
+    for (auto ArgRecord : ArgRecords)
+      Args.emplace_back(createArgument(*ArgRecord, R.getName()));
 
-    for (ai = Args.begin(); ai != ae; ++ai) {
-      (*ai)->writeTemplateInstantiation(OS);
-    }
+    for (auto const &ai : Args)
+      ai->writeTemplateInstantiation(OS);
+
     OS << "      return new (C) " << R.getName() << "Attr(A->getLocation(), C";
-    for (ai = Args.begin(); ai != ae; ++ai) {
+    for (auto const &ai : Args) {
       OS << ", ";
-      (*ai)->writeTemplateInstantiationArgs(OS);
+      ai->writeTemplateInstantiationArgs(OS);
     }
-    OS << ");\n    }\n";
+    OS << ", A->getSpellingListIndex());\n    }\n";
   }
   OS << "  } // end switch\n"
      << "  llvm_unreachable(\"Unknown attribute!\");\n"
@@ -1634,39 +1999,6 @@
      << "} // end namespace clang\n";
 }
 
-typedef std::vector<std::pair<std::string, Record *> > ParsedAttrMap;
-
-static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records) {
-  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
-  ParsedAttrMap R;
-  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
-       I != E; ++I) {
-    Record &Attr = **I;
-    
-    bool SemaHandler = Attr.getValueAsBit("SemaHandler");
-    bool DistinctSpellings = Attr.getValueAsBit("DistinctSpellings");
-
-    if (SemaHandler) {
-      if (DistinctSpellings) {
-        std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");
-        
-        for (std::vector<Record*>::const_iterator I = Spellings.begin(),
-             E = Spellings.end(); I != E; ++I) {
-          std::string AttrName = (*I)->getValueAsString("Name");
-
-          StringRef Spelling = NormalizeAttrName(AttrName);
-          R.push_back(std::make_pair(Spelling.str(), &Attr));
-        }
-      } else {
-        StringRef AttrName = Attr.getName();
-        AttrName = NormalizeAttrName(AttrName);
-        R.push_back(std::make_pair(AttrName.str(), *I));
-      }
-    }
-  }
-  return R;
-}
-
 // Emits the list of parsed attributes.
 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
   emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
@@ -1676,47 +2008,468 @@
   OS << "#endif\n\n";
   
   ParsedAttrMap Names = getParsedAttrList(Records);
-  for (ParsedAttrMap::iterator I = Names.begin(), E = Names.end(); I != E;
-       ++I) {
-    OS << "PARSED_ATTR(" << I->first << ")\n";
+  for (const auto &I : Names) {
+    OS << "PARSED_ATTR(" << I.first << ")\n";
   }
 }
 
-static void emitArgInfo(const Record &R, raw_ostream &OS) {
+static void emitArgInfo(const Record &R, std::stringstream &OS) {
   // This function will count the number of arguments specified for the
   // attribute and emit the number of required arguments followed by the
   // number of optional arguments.
   std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
   unsigned ArgCount = 0, OptCount = 0;
-  for (std::vector<Record *>::const_iterator I = Args.begin(), E = Args.end();
-       I != E; ++I) {
-    const Record &Arg = **I;
-    Arg.getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
+  for (auto Arg : Args) {
+    Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
   }
   OS << ArgCount << ", " << OptCount;
 }
 
+static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
+  OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
+  OS << "const Decl *) {\n";
+  OS << "  return true;\n";
+  OS << "}\n\n";
+}
+
+static std::string CalculateDiagnostic(const Record &S) {
+  // If the SubjectList object has a custom diagnostic associated with it,
+  // return that directly.
+  std::string CustomDiag = S.getValueAsString("CustomDiag");
+  if (!CustomDiag.empty())
+    return CustomDiag;
+
+  // Given the list of subjects, determine what diagnostic best fits.
+  enum {
+    Func = 1U << 0,
+    Var = 1U << 1,
+    ObjCMethod = 1U << 2,
+    Param = 1U << 3,
+    Class = 1U << 4,
+    GenericRecord = 1U << 5,
+    Type = 1U << 6,
+    ObjCIVar = 1U << 7,
+    ObjCProp = 1U << 8,
+    ObjCInterface = 1U << 9,
+    Block = 1U << 10,
+    Namespace = 1U << 11,
+    FuncTemplate = 1U << 12,
+    Field = 1U << 13,
+    CXXMethod = 1U << 14,
+    ObjCProtocol = 1U << 15
+  };
+  uint32_t SubMask = 0;
+
+  std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
+  for (auto I : Subjects) {
+    const Record &R = *I;
+    std::string Name;
+
+    if (R.isSubClassOf("SubsetSubject")) {
+      PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
+      // As a fallback, look through the SubsetSubject to see what its base
+      // type is, and use that. This needs to be updated if SubsetSubjects
+      // are allowed within other SubsetSubjects.
+      Name = R.getValueAsDef("Base")->getName();
+    } else
+      Name = R.getName();
+
+    uint32_t V = StringSwitch<uint32_t>(Name)
+                   .Case("Function", Func)
+                   .Case("Var", Var)
+                   .Case("ObjCMethod", ObjCMethod)
+                   .Case("ParmVar", Param)
+                   .Case("TypedefName", Type)
+                   .Case("ObjCIvar", ObjCIVar)
+                   .Case("ObjCProperty", ObjCProp)
+                   .Case("Record", GenericRecord)
+                   .Case("ObjCInterface", ObjCInterface)
+                   .Case("ObjCProtocol", ObjCProtocol)
+                   .Case("Block", Block)
+                   .Case("CXXRecord", Class)
+                   .Case("Namespace", Namespace)
+                   .Case("FunctionTemplate", FuncTemplate)
+                   .Case("Field", Field)
+                   .Case("CXXMethod", CXXMethod)
+                   .Default(0);
+    if (!V) {
+      // Something wasn't in our mapping, so be helpful and let the developer
+      // know about it.
+      PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
+      return "";
+    }
+
+    SubMask |= V;
+  }
+
+  switch (SubMask) {
+    // For the simple cases where there's only a single entry in the mask, we
+    // don't have to resort to bit fiddling.
+    case Func:  return "ExpectedFunction";
+    case Var:   return "ExpectedVariable";
+    case Param: return "ExpectedParameter";
+    case Class: return "ExpectedClass";
+    case CXXMethod:
+      // FIXME: Currently, this maps to ExpectedMethod based on existing code,
+      // but should map to something a bit more accurate at some point.
+    case ObjCMethod:  return "ExpectedMethod";
+    case Type:  return "ExpectedType";
+    case ObjCInterface: return "ExpectedObjectiveCInterface";
+    case ObjCProtocol: return "ExpectedObjectiveCProtocol";
+    
+    // "GenericRecord" means struct, union or class; check the language options
+    // and if not compiling for C++, strip off the class part. Note that this
+    // relies on the fact that the context for this declares "Sema &S".
+    case GenericRecord:
+      return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
+                                           "ExpectedStructOrUnion)";
+    case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
+    case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
+    case Func | Param:
+    case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
+    case Func | FuncTemplate:
+    case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
+    case Func | Var: return "ExpectedVariableOrFunction";
+
+    // If not compiling for C++, the class portion does not apply.
+    case Func | Var | Class:
+      return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
+                                           "ExpectedVariableOrFunction)";
+
+    case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
+    case Field | Var: return "ExpectedFieldOrGlobalVar";
+  }
+
+  PrintFatalError(S.getLoc(),
+                  "Could not deduce diagnostic argument for Attr subjects");
+
+  return "";
+}
+
+static std::string GetSubjectWithSuffix(const Record *R) {
+  std::string B = R->getName();
+  if (B == "DeclBase")
+    return "Decl";
+  return B + "Decl";
+}
+static std::string GenerateCustomAppertainsTo(const Record &Subject,
+                                              raw_ostream &OS) {
+  std::string FnName = "is" + Subject.getName();
+
+  // If this code has already been generated, simply return the previous
+  // instance of it.
+  static std::set<std::string> CustomSubjectSet;
+  std::set<std::string>::iterator I = CustomSubjectSet.find(FnName);
+  if (I != CustomSubjectSet.end())
+    return *I;
+
+  Record *Base = Subject.getValueAsDef("Base");
+
+  // Not currently support custom subjects within custom subjects.
+  if (Base->isSubClassOf("SubsetSubject")) {
+    PrintFatalError(Subject.getLoc(),
+                    "SubsetSubjects within SubsetSubjects is not supported");
+    return "";
+  }
+
+  OS << "static bool " << FnName << "(const Decl *D) {\n";
+  OS << "  if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<";
+  OS << GetSubjectWithSuffix(Base);
+  OS << ">(D))\n";
+  OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
+  OS << "  return false;\n";
+  OS << "}\n\n";
+
+  CustomSubjectSet.insert(FnName);
+  return FnName;
+}
+
+static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
+  // If the attribute does not contain a Subjects definition, then use the
+  // default appertainsTo logic.
+  if (Attr.isValueUnset("Subjects"))
+    return "defaultAppertainsTo";
+
+  const Record *SubjectObj = Attr.getValueAsDef("Subjects");
+  std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
+
+  // If the list of subjects is empty, it is assumed that the attribute
+  // appertains to everything.
+  if (Subjects.empty())
+    return "defaultAppertainsTo";
+
+  bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
+
+  // Otherwise, generate an appertainsTo check specific to this attribute which
+  // checks all of the given subjects against the Decl passed in. Return the
+  // name of that check to the caller.
+  std::string FnName = "check" + Attr.getName() + "AppertainsTo";
+  std::stringstream SS;
+  SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
+  SS << "const Decl *D) {\n";
+  SS << "  if (";
+  for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
+    // If the subject has custom code associated with it, generate a function
+    // for it. The function cannot be inlined into this check (yet) because it
+    // requires the subject to be of a specific type, and were that information
+    // inlined here, it would not support an attribute with multiple custom
+    // subjects.
+    if ((*I)->isSubClassOf("SubsetSubject")) {
+      SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
+    } else {
+      SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
+    }
+
+    if (I + 1 != E)
+      SS << " && ";
+  }
+  SS << ") {\n";
+  SS << "    S.Diag(Attr.getLoc(), diag::";
+  SS << (Warn ? "warn_attribute_wrong_decl_type" :
+               "err_attribute_wrong_decl_type");
+  SS << ")\n";
+  SS << "      << Attr.getName() << ";
+  SS << CalculateDiagnostic(*SubjectObj) << ";\n";
+  SS << "    return false;\n";
+  SS << "  }\n";
+  SS << "  return true;\n";
+  SS << "}\n\n";
+
+  OS << SS.str();
+  return FnName;
+}
+
+static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
+  OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
+  OS << "const AttributeList &) {\n";
+  OS << "  return true;\n";
+  OS << "}\n\n";
+}
+
+static std::string GenerateLangOptRequirements(const Record &R,
+                                               raw_ostream &OS) {
+  // If the attribute has an empty or unset list of language requirements,
+  // return the default handler.
+  std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
+  if (LangOpts.empty())
+    return "defaultDiagnoseLangOpts";
+
+  // Generate the test condition, as well as a unique function name for the
+  // diagnostic test. The list of options should usually be short (one or two
+  // options), and the uniqueness isn't strictly necessary (it is just for
+  // codegen efficiency).
+  std::string FnName = "check", Test;
+  for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
+    std::string Part = (*I)->getValueAsString("Name");
+    Test += "S.LangOpts." + Part;
+    if (I + 1 != E)
+      Test += " || ";
+    FnName += Part;
+  }
+  FnName += "LangOpts";
+
+  // If this code has already been generated, simply return the previous
+  // instance of it.
+  static std::set<std::string> CustomLangOptsSet;
+  std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName);
+  if (I != CustomLangOptsSet.end())
+    return *I;
+
+  OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
+  OS << "  if (" << Test << ")\n";
+  OS << "    return true;\n\n";
+  OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
+  OS << "<< Attr.getName();\n";
+  OS << "  return false;\n";
+  OS << "}\n\n";
+
+  CustomLangOptsSet.insert(FnName);
+  return FnName;
+}
+
+static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
+  OS << "static bool defaultTargetRequirements(const llvm::Triple &) {\n";
+  OS << "  return true;\n";
+  OS << "}\n\n";
+}
+
+static std::string GenerateTargetRequirements(const Record &Attr,
+                                              const ParsedAttrMap &Dupes,
+                                              raw_ostream &OS) {
+  // If the attribute is not a target specific attribute, return the default
+  // target handler.
+  if (!Attr.isSubClassOf("TargetSpecificAttr"))
+    return "defaultTargetRequirements";
+
+  // Get the list of architectures to be tested for.
+  const Record *R = Attr.getValueAsDef("Target");
+  std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
+  if (Arches.empty()) {
+    PrintError(Attr.getLoc(), "Empty list of target architectures for a "
+                              "target-specific attr");
+    return "defaultTargetRequirements";
+  }
+
+  // If there are other attributes which share the same parsed attribute kind,
+  // such as target-specific attributes with a shared spelling, collapse the
+  // duplicate architectures. This is required because a shared target-specific
+  // attribute has only one AttributeList::Kind enumeration value, but it
+  // applies to multiple target architectures. In order for the attribute to be
+  // considered valid, all of its architectures need to be included.
+  if (!Attr.isValueUnset("ParseKind")) {
+    std::string APK = Attr.getValueAsString("ParseKind");
+    for (const auto &I : Dupes) {
+      if (I.first == APK) {
+        std::vector<std::string> DA = I.second->getValueAsDef("Target")
+                                          ->getValueAsListOfStrings("Arches");
+        std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
+      }
+    }
+  }
+
+  std::string FnName = "isTarget", Test = "(";
+  for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
+    std::string Part = *I;
+    Test += "Arch == llvm::Triple::" + Part;
+    if (I + 1 != E)
+      Test += " || ";
+    FnName += Part;
+  }
+  Test += ")";
+
+  // If the target also requires OS testing, generate those tests as well.
+  bool UsesOS = false;
+  if (!R->isValueUnset("OSes")) {
+    UsesOS = true;
+    
+    // We know that there was at least one arch test, so we need to and in the
+    // OS tests.
+    Test += " && (";
+    std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
+    for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
+      std::string Part = *I;
+
+      Test += "OS == llvm::Triple::" + Part;
+      if (I + 1 != E)
+        Test += " || ";
+      FnName += Part;
+    }
+    Test += ")";
+  }
+
+  // If this code has already been generated, simply return the previous
+  // instance of it.
+  static std::set<std::string> CustomTargetSet;
+  std::set<std::string>::iterator I = CustomTargetSet.find(FnName);
+  if (I != CustomTargetSet.end())
+    return *I;
+
+  OS << "static bool " << FnName << "(const llvm::Triple &T) {\n";
+  OS << "  llvm::Triple::ArchType Arch = T.getArch();\n";
+  if (UsesOS)
+    OS << "  llvm::Triple::OSType OS = T.getOS();\n";
+  OS << "  return " << Test << ";\n";
+  OS << "}\n\n";
+
+  CustomTargetSet.insert(FnName);
+  return FnName;
+}
+
+static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
+  OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
+     << "const AttributeList &Attr) {\n";
+  OS << "  return UINT_MAX;\n";
+  OS << "}\n\n";
+}
+
+static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
+                                                           raw_ostream &OS) {
+  // If the attribute does not have a semantic form, we can bail out early.
+  if (!Attr.getValueAsBit("ASTNode"))
+    return "defaultSpellingIndexToSemanticSpelling";
+
+  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
+
+  // If there are zero or one spellings, or all of the spellings share the same
+  // name, we can also bail out early.
+  if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
+    return "defaultSpellingIndexToSemanticSpelling";
+
+  // Generate the enumeration we will use for the mapping.
+  SemanticSpellingMap SemanticToSyntacticMap;
+  std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
+  std::string Name = Attr.getName() + "AttrSpellingMap";
+
+  OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
+  OS << Enum;
+  OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
+  WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
+  OS << "}\n\n";
+
+  return Name;
+}
+
+static bool IsKnownToGCC(const Record &Attr) {
+  // Look at the spellings for this subject; if there are any spellings which
+  // claim to be known to GCC, the attribute is known to GCC.
+  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
+  for (const auto &I : Spellings) {
+    if (I.knownToGCC())
+      return true;
+  }
+  return false;
+}
+
 /// Emits the parsed attribute helpers
 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
   emitSourceFileHeader("Parsed attribute helpers", OS);
 
-  ParsedAttrMap Attrs = getParsedAttrList(Records);
+  // Get the list of parsed attributes, and accept the optional list of
+  // duplicates due to the ParseKind.
+  ParsedAttrMap Dupes;
+  ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
 
-  OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
-  for (ParsedAttrMap::iterator I = Attrs.begin(), E = Attrs.end(); I != E;
-       ++I) {
+  // Generate the default appertainsTo, target and language option diagnostic,
+  // and spelling list index mapping methods.
+  GenerateDefaultAppertainsTo(OS);
+  GenerateDefaultLangOptRequirements(OS);
+  GenerateDefaultTargetRequirements(OS);
+  GenerateDefaultSpellingIndexToSemanticSpelling(OS);
+
+  // Generate the appertainsTo diagnostic methods and write their names into
+  // another mapping. At the same time, generate the AttrInfoMap object
+  // contents. Due to the reliance on generated code, use separate streams so
+  // that code will not be interleaved.
+  std::stringstream SS;
+  for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
+    // TODO: If the attribute's kind appears in the list of duplicates, that is
+    // because it is a target-specific attribute that appears multiple times.
+    // It would be beneficial to test whether the duplicates are "similar
+    // enough" to each other to not cause problems. For instance, check that
+    // the spellings are identical, and custom parsing rules match, etc.
+
     // We need to generate struct instances based off ParsedAttrInfo from
     // AttributeList.cpp.
-    OS << "  { ";
-    emitArgInfo(*I->second, OS);
-    OS << ", " << I->second->getValueAsBit("HasCustomParsing");
-    OS << " }";
+    SS << "  { ";
+    emitArgInfo(*I->second, SS);
+    SS << ", " << I->second->getValueAsBit("HasCustomParsing");
+    SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
+    SS << ", " << I->second->isSubClassOf("TypeAttr");
+    SS << ", " << IsKnownToGCC(*I->second);
+    SS << ", " << GenerateAppertainsTo(*I->second, OS);
+    SS << ", " << GenerateLangOptRequirements(*I->second, OS);
+    SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
+    SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
+    SS << " }";
 
     if (I + 1 != E)
-      OS << ",";
-    
-    OS << "  // AT_" << I->first << "\n";
+      SS << ",";
+
+    SS << "  // AT_" << I->first << "\n";
   }
+
+  OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
+  OS << SS.str();
   OS << "};\n\n";
 }
 
@@ -1724,50 +2477,76 @@
 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
   emitSourceFileHeader("Attribute name matcher", OS);
 
-  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
+  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
+  std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords;
+  std::set<std::string> Seen;
+  for (auto I : Attrs) {
+    const Record &Attr = *I;
 
-  std::vector<StringMatcher::StringPair> Matches;
-  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
-       I != E; ++I) {
-    Record &Attr = **I;
-    
     bool SemaHandler = Attr.getValueAsBit("SemaHandler");
     bool Ignored = Attr.getValueAsBit("Ignored");
-    bool DistinctSpellings = Attr.getValueAsBit("DistinctSpellings");
     if (SemaHandler || Ignored) {
-      std::vector<Record*> Spellings = Attr.getValueAsListOfDefs("Spellings");
+      // Attribute spellings can be shared between target-specific attributes,
+      // and can be shared between syntaxes for the same attribute. For
+      // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
+      // specific attribute, or MSP430-specific attribute. Additionally, an
+      // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
+      // for the same semantic attribute. Ultimately, we need to map each of
+      // these to a single AttributeList::Kind value, but the StringMatcher
+      // class cannot handle duplicate match strings. So we generate a list of
+      // string to match based on the syntax, and emit multiple string matchers
+      // depending on the syntax used.
+      std::string AttrName;
+      if (Attr.isSubClassOf("TargetSpecificAttr") &&
+          !Attr.isValueUnset("ParseKind")) {
+        AttrName = Attr.getValueAsString("ParseKind");
+        if (Seen.find(AttrName) != Seen.end())
+          continue;
+        Seen.insert(AttrName);
+      } else
+        AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
 
-      for (std::vector<Record*>::const_iterator I = Spellings.begin(),
-           E = Spellings.end(); I != E; ++I) {
-        std::string RawSpelling = (*I)->getValueAsString("Name");
-        StringRef AttrName = NormalizeAttrName(DistinctSpellings
-                                                 ? StringRef(RawSpelling)
-                                                 : StringRef(Attr.getName()));
-
-        SmallString<64> Spelling;
-        if ((*I)->getValueAsString("Variety") == "CXX11") {
-          Spelling += (*I)->getValueAsString("Namespace");
+      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
+      for (const auto &S : Spellings) {
+        std::string RawSpelling = S.name();
+        std::vector<StringMatcher::StringPair> *Matches = 0;
+        std::string Spelling, Variety = S.variety();
+        if (Variety == "CXX11") {
+          Matches = &CXX11;
+          Spelling += S.nameSpace();
           Spelling += "::";
-        }
-        Spelling += NormalizeAttrSpelling(RawSpelling);
+        } else if (Variety == "GNU")
+          Matches = &GNU;
+        else if (Variety == "Declspec")
+          Matches = &Declspec;
+        else if (Variety == "Keyword")
+          Matches = &Keywords;
 
+        assert(Matches && "Unsupported spelling variety found");
+
+        Spelling += NormalizeAttrSpelling(RawSpelling);
         if (SemaHandler)
-          Matches.push_back(
-            StringMatcher::StringPair(
-              StringRef(Spelling),
-              "return AttributeList::AT_" + AttrName.str() + ";"));
+          Matches->push_back(StringMatcher::StringPair(Spelling,
+                              "return AttributeList::AT_" + AttrName + ";"));
         else
-          Matches.push_back(
-            StringMatcher::StringPair(
-              StringRef(Spelling),
-              "return AttributeList::IgnoredAttribute;"));
+          Matches->push_back(StringMatcher::StringPair(Spelling,
+                              "return AttributeList::IgnoredAttribute;"));
       }
     }
   }
   
-  OS << "static AttributeList::Kind getAttrKind(StringRef Name) {\n";
-  StringMatcher("Name", Matches, OS).Emit();
-  OS << "return AttributeList::UnknownAttribute;\n"
+  OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
+  OS << "AttributeList::Syntax Syntax) {\n";
+  OS << "  if (AttributeList::AS_GNU == Syntax) {\n";
+  StringMatcher("Name", GNU, OS).Emit();
+  OS << "  } else if (AttributeList::AS_Declspec == Syntax) {\n";
+  StringMatcher("Name", Declspec, OS).Emit();
+  OS << "  } else if (AttributeList::AS_CXX11 == Syntax) {\n";
+  StringMatcher("Name", CXX11, OS).Emit();
+  OS << "  } else if (AttributeList::AS_Keyword == Syntax) {\n";
+  StringMatcher("Name", Keywords, OS).Emit();
+  OS << "  }\n";
+  OS << "  return AttributeList::UnknownAttribute;\n"
      << "}\n";
 }
 
@@ -1781,36 +2560,41 @@
     "    llvm_unreachable(\"Unknown attribute kind!\");\n"
     "    break;\n";
   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
-  for (std::vector<Record*>::iterator I = Attrs.begin(), E = Attrs.end();
-       I != E; ++I) {
-    Record &R = **I;
+  for (auto I : Attrs) {
+    const Record &R = *I;
     if (!R.getValueAsBit("ASTNode"))
       continue;
     OS << "  case attr::" << R.getName() << ": {\n";
+
+    // If the attribute has a semantically-meaningful name (which is determined
+    // by whether there is a Spelling enumeration for it), then write out the
+    // spelling used for the attribute.
+    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
+    if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
+      OS << "    OS << \" \" << A->getSpelling();\n";
+
     Args = R.getValueAsListOfDefs("Args");
     if (!Args.empty()) {
       OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
          << "Attr>(A);\n";
-      for (std::vector<Record*>::iterator I = Args.begin(), E = Args.end();
-           I != E; ++I)
-        createArgument(**I, R.getName())->writeDump(OS);
+      for (auto AI : Args)
+        createArgument(*AI, R.getName())->writeDump(OS);
 
       // Code for detecting the last child.
       OS << "    bool OldMoreChildren = hasMoreChildren();\n";
-      OS << "    bool MoreChildren = OldMoreChildren;\n";     
+      OS << "    bool MoreChildren;\n";
 
-      for (std::vector<Record*>::iterator I = Args.begin(), E = Args.end();
-           I != E; ++I) {
+      for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI) {
         // More code for detecting the last child.
         OS << "    MoreChildren = OldMoreChildren";
-        for (std::vector<Record*>::iterator Next = I + 1; Next != E; ++Next) {
+        for (auto Next = AI + 1; Next != AE; ++Next) {
           OS << " || ";
           createArgument(**Next, R.getName())->writeHasChildren(OS);
         }
         OS << ";\n";
         OS << "    setMoreChildren(MoreChildren);\n";
 
-        createArgument(**I, R.getName())->writeDumpChildren(OS);
+        createArgument(**AI, R.getName())->writeDumpChildren(OS);
       }
 
       // Reset the last child.
@@ -1823,4 +2607,216 @@
   OS << "  }\n";
 }
 
+void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
+                                       raw_ostream &OS) {
+  emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
+  emitClangAttrArgContextList(Records, OS);
+  emitClangAttrIdentifierArgList(Records, OS);
+  emitClangAttrTypeArgList(Records, OS);
+  emitClangAttrLateParsedList(Records, OS);
+}
+
+class DocumentationData {
+public:
+  const Record *Documentation;
+  const Record *Attribute;
+
+  DocumentationData(const Record &Documentation, const Record &Attribute)
+      : Documentation(&Documentation), Attribute(&Attribute) {}
+};
+
+static void WriteCategoryHeader(const Record *DocCategory,
+                                raw_ostream &OS) {
+  const std::string &Name = DocCategory->getValueAsString("Name");
+  OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
+
+  // If there is content, print that as well.
+  std::string ContentStr = DocCategory->getValueAsString("Content");
+  if (!ContentStr.empty()) {
+    // Trim leading and trailing newlines and spaces.
+    StringRef Content(ContentStr);
+    while (Content.startswith("\r") || Content.startswith("\n") ||
+           Content.startswith(" ") || Content.startswith("\t"))
+           Content = Content.substr(1);
+    while (Content.endswith("\r") || Content.endswith("\n") ||
+           Content.endswith(" ") || Content.endswith("\t"))
+           Content = Content.substr(0, Content.size() - 1);
+    OS << Content;
+  }
+  OS << "\n\n";
+}
+
+enum SpellingKind {
+  GNU = 1 << 0,
+  CXX11 = 1 << 1,
+  Declspec = 1 << 2,
+  Keyword = 1 << 3
+};
+
+static void WriteDocumentation(const DocumentationData &Doc,
+                               raw_ostream &OS) {
+  // FIXME: there is no way to have a per-spelling category for the attribute
+  // documentation. This may not be a limiting factor since the spellings
+  // should generally be consistently applied across the category.
+
+  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
+
+  // Determine the heading to be used for this attribute.
+  std::string Heading = Doc.Documentation->getValueAsString("Heading");
+  bool CustomHeading = !Heading.empty();
+  if (Heading.empty()) {
+    // If there's only one spelling, we can simply use that.
+    if (Spellings.size() == 1)
+      Heading = Spellings.begin()->name();
+    else {
+      std::set<std::string> Uniques;
+      for (auto I = Spellings.begin(), E = Spellings.end();
+           I != E && Uniques.size() <= 1; ++I) {
+        std::string Spelling = NormalizeNameForSpellingComparison(I->name());
+        Uniques.insert(Spelling);
+      }
+      // If the semantic map has only one spelling, that is sufficient for our
+      // needs.
+      if (Uniques.size() == 1)
+        Heading = *Uniques.begin();
+    }
+  }
+
+  // If the heading is still empty, it is an error.
+  if (Heading.empty())
+    PrintFatalError(Doc.Attribute->getLoc(),
+                    "This attribute requires a heading to be specified");
+
+  // Gather a list of unique spellings; this is not the same as the semantic
+  // spelling for the attribute. Variations in underscores and other non-
+  // semantic characters are still acceptable.
+  std::vector<std::string> Names;
+
+  unsigned SupportedSpellings = 0;
+  for (const auto &I : Spellings) {
+    SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
+      .Case("GNU", GNU)
+      .Case("CXX11", CXX11)
+      .Case("Declspec", Declspec)
+      .Case("Keyword", Keyword);
+
+    // Mask in the supported spelling.
+    SupportedSpellings |= Kind;
+
+    std::string Name;
+    if (Kind == CXX11 && !I.nameSpace().empty())
+      Name = I.nameSpace() + "::";
+    Name += I.name();
+
+    // If this name is the same as the heading, do not add it.
+    if (Name != Heading)
+      Names.push_back(Name);
+  }
+
+  // Print out the heading for the attribute. If there are alternate spellings,
+  // then display those after the heading.
+  if (!CustomHeading && !Names.empty()) {
+    Heading += " (";
+    for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
+      if (I != Names.begin())
+        Heading += ", ";
+      Heading += *I;
+    }
+    Heading += ")";
+  }
+  OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
+
+  if (!SupportedSpellings)
+    PrintFatalError(Doc.Attribute->getLoc(),
+                    "Attribute has no supported spellings; cannot be "
+                    "documented");
+
+  // List what spelling syntaxes the attribute supports.
+  OS << ".. csv-table:: Supported Syntaxes\n";
+  OS << "   :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\"\n\n";
+  OS << "   \"";
+  if (SupportedSpellings & GNU) OS << "X";
+  OS << "\",\"";
+  if (SupportedSpellings & CXX11) OS << "X";
+  OS << "\",\"";
+  if (SupportedSpellings & Declspec) OS << "X";
+  OS << "\",\"";
+  if (SupportedSpellings & Keyword) OS << "X";
+  OS << "\"\n\n";
+
+  // If the attribute is deprecated, print a message about it, and possibly
+  // provide a replacement attribute.
+  if (!Doc.Documentation->isValueUnset("Deprecated")) {
+    OS << "This attribute has been deprecated, and may be removed in a future "
+       << "version of Clang.";
+    const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
+    std::string Replacement = Deprecated.getValueAsString("Replacement");
+    if (!Replacement.empty())
+      OS << "  This attribute has been superseded by ``"
+         << Replacement << "``.";
+    OS << "\n\n";
+  }
+
+  std::string ContentStr = Doc.Documentation->getValueAsString("Content");
+  // Trim leading and trailing newlines and spaces.
+  StringRef Content(ContentStr);
+  while (Content.startswith("\r") || Content.startswith("\n") ||
+         Content.startswith(" ") || Content.startswith("\t"))
+    Content = Content.substr(1);
+  while (Content.endswith("\r") || Content.endswith("\n") ||
+         Content.endswith(" ") || Content.endswith("\t"))
+    Content = Content.substr(0, Content.size() - 1);
+  OS << Content;
+
+  OS << "\n\n\n";
+}
+
+void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
+  // Get the documentation introduction paragraph.
+  const Record *Documentation = Records.getDef("GlobalDocumentation");
+  if (!Documentation) {
+    PrintFatalError("The Documentation top-level definition is missing, "
+                    "no documentation will be generated.");
+    return;
+  }
+
+  OS << Documentation->getValueAsString("Intro") << "\n";
+
+  // Gather the Documentation lists from each of the attributes, based on the
+  // category provided.
+  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
+  std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
+  for (auto I : Attrs) {
+    const Record &Attr = *I;
+    std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
+    for (auto DI : Docs) {
+      const Record &Doc = *DI;
+      const Record *Category = Doc.getValueAsDef("Category");
+      // If the category is "undocumented", then there cannot be any other
+      // documentation categories (otherwise, the attribute would become
+      // documented).
+      std::string Cat = Category->getValueAsString("Name");
+      bool Undocumented = Cat == "Undocumented";
+      if (Undocumented && Docs.size() > 1)
+        PrintFatalError(Doc.getLoc(),
+                        "Attribute is \"Undocumented\", but has multiple "
+                        "documentation categories");      
+
+      if (!Undocumented)
+        SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
+    }
+  }
+
+  // Having split the attributes out based on what documentation goes where,
+  // we can begin to generate sections of documentation.
+  for (const auto &I : SplitDocs) {
+    WriteCategoryHeader(I.first, OS);
+
+    // Walk over each of the attributes in the category and write out their
+    // documentation.
+    for (const auto &Doc : I.second)
+      WriteDocumentation(Doc, OS);
+  }
+}
+
 } // end namespace clang
diff --git a/utils/TableGen/ClangDiagnosticsEmitter.cpp b/utils/TableGen/ClangDiagnosticsEmitter.cpp
index db159d1..40af9f6 100644
--- a/utils/TableGen/ClangDiagnosticsEmitter.cpp
+++ b/utils/TableGen/ClangDiagnosticsEmitter.cpp
@@ -472,6 +472,11 @@
   return ClsName == "CLASS_ERROR";
 }
 
+static bool isRemark(const Record &Diag) {
+  const std::string &ClsName = Diag.getValueAsDef("Class")->getName();
+  return ClsName == "CLASS_REMARK";
+}
+
 /// ClangDiagsDefsEmitter - The top-level class emits .def files containing
 /// declarations of Clang diagnostics.
 namespace clang {
@@ -518,6 +523,14 @@
       }
     }
 
+    // Check that all remarks have an associated diagnostic group.
+    if (isRemark(R)) {
+      if (!isa<DefInit>(R.getValueInit("Group"))) {
+        PrintFatalError(R.getLoc(), "Error " + R.getName() +
+                                        " not in any diagnostic group");
+      }
+    }
+
     // Filter by component.
     if (!Component.empty() && Component != R.getValueAsString("Component"))
       continue;
@@ -748,17 +761,6 @@
 
   std::string Name;
 };
-
-struct RecordIndexElementSorter :
-  public std::binary_function<RecordIndexElement, RecordIndexElement, bool> {
-
-  bool operator()(RecordIndexElement const &Lhs,
-                  RecordIndexElement const &Rhs) const {
-    return Lhs.Name < Rhs.Name;
-  }
-
-};
-
 } // end anonymous namespace.
 
 namespace clang {
@@ -773,7 +775,9 @@
     Index.push_back(RecordIndexElement(R));
   }
 
-  std::sort(Index.begin(), Index.end(), RecordIndexElementSorter());
+  std::sort(Index.begin(), Index.end(),
+            [](const RecordIndexElement &Lhs,
+               const RecordIndexElement &Rhs) { return Lhs.Name < Rhs.Name; });
 
   for (unsigned i = 0, e = Index.size(); i != e; ++i) {
     const RecordIndexElement &R = Index[i];
diff --git a/utils/TableGen/NeonEmitter.cpp b/utils/TableGen/NeonEmitter.cpp
index b0939c9..165e749 100644
--- a/utils/TableGen/NeonEmitter.cpp
+++ b/utils/TableGen/NeonEmitter.cpp
@@ -52,6 +52,7 @@
   OpMla,
   OpMlal,
   OpMullHi,
+  OpMullHiP64,
   OpMullHiN,
   OpMlalHi,
   OpMlalHiN,
@@ -193,6 +194,7 @@
     Poly8,
     Poly16,
     Poly64,
+    Poly128,
     Float16,
     Float32,
     Float64
@@ -234,6 +236,7 @@
     OpMap["OP_MLA"]   = OpMla;
     OpMap["OP_MLAL"]  = OpMlal;
     OpMap["OP_MULLHi"]  = OpMullHi;
+    OpMap["OP_MULLHi_P64"]  = OpMullHiP64;
     OpMap["OP_MULLHi_N"]  = OpMullHiN;
     OpMap["OP_MLALHi"]  = OpMlalHi;
     OpMap["OP_MLALHi_N"]  = OpMlalHiN;
@@ -369,18 +372,15 @@
   void runTests(raw_ostream &o);
 
 private:
+  void emitGuardedIntrinsic(raw_ostream &OS, Record *R,
+                            std::string &CurrentGuard, bool &InGuard,
+                            StringMap<ClassKind> &EmittedMap);
   void emitIntrinsic(raw_ostream &OS, Record *R,
                      StringMap<ClassKind> &EmittedMap);
-  void genBuiltinsDef(raw_ostream &OS, StringMap<ClassKind> &A64IntrinsicMap,
-                      bool isA64GenBuiltinDef);
-  void genOverloadTypeCheckCode(raw_ostream &OS,
-                                StringMap<ClassKind> &A64IntrinsicMap,
-                                bool isA64TypeCheck);
-  void genIntrinsicRangeCheckCode(raw_ostream &OS,
-                                  StringMap<ClassKind> &A64IntrinsicMap,
-                                  bool isA64RangeCheck);
-  void genTargetTest(raw_ostream &OS, StringMap<OpKind> &EmittedMap,
-                     bool isA64TestGen);
+  void genBuiltinsDef(raw_ostream &OS);
+  void genOverloadTypeCheckCode(raw_ostream &OS);
+  void genIntrinsicRangeCheckCode(raw_ostream &OS);
+  void genTargetTest(raw_ostream &OS);
 };
 } // end anonymous namespace
 
@@ -403,6 +403,7 @@
       case 's':
       case 'i':
       case 'l':
+      case 'k':
       case 'h':
       case 'f':
       case 'd':
@@ -427,6 +428,8 @@
       return 'i';
     case 'i':
       return 'l';
+    case 'l':
+      return 'k';
     case 'h':
       return 'f';
     case 'f':
@@ -446,6 +449,8 @@
       return 's';
     case 'l':
       return 'i';
+    case 'k':
+      return 'l';
     case 'f':
       return 'h';
     case 'd':
@@ -469,6 +474,9 @@
       case 'l':
         s += 'i';
         break;
+      case 'k':
+        s += 'l';
+        break;
       default:
         s += ty[i];
         break;
@@ -680,6 +688,9 @@
         break;
       s += quad ? "x2" : "x1";
       break;
+    case 'k':
+      s += "poly128";
+      break;
     case 'h':
       s += "float16";
       if (scal)
@@ -745,6 +756,9 @@
   // Based on the modifying character, change the type and width if necessary.
   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
 
+  usgn = usgn | poly | ((ck == ClassI || ck == ClassW) &&
+                         scal && type != 'f' && type != 'd');
+
   // All pointers are void* pointers.  Change type to 'v' now.
   if (pntr) {
     usgn = false;
@@ -756,8 +770,6 @@
     type = 's';
     usgn = true;
   }
-  usgn = usgn | poly | ((ck == ClassI || ck == ClassW) &&
-                         scal && type != 'f' && type != 'd');
 
   if (scal) {
     SmallString<128> s;
@@ -768,7 +780,9 @@
       s.push_back('S'); // make chars explicitly signed
 
     if (type == 'l') // 64-bit long
-      s += "LLi";
+      s += "Wi";
+    else if (type == 'k') // 128-bit long
+      s = "LLLi";
     else
       s.push_back(type);
 
@@ -795,7 +809,7 @@
     if (ck != ClassB && type == 'i')
       return quad ? "V4i" : "V2i";
     if (ck != ClassB && type == 'l')
-      return quad ? "V2LLi" : "V1LLi";
+      return quad ? "V2Wi" : "V1Wi";
 
     return quad ? "V16Sc" : "V8Sc";
   }
@@ -817,7 +831,7 @@
   if (ck != ClassB && type == 'i')
     return quad ? "V4i" : "V2i";
   if (ck != ClassB && type == 'l')
-    return quad ? "V2LLi" : "V1LLi";
+    return quad ? "V2Wi" : "V1Wi";
 
   return quad ? "V16Sc" : "V8Sc";
 }
@@ -865,6 +879,10 @@
     default: break;
     }
     break;
+  case 'k':
+    assert(poly && "Unrecognized 128 bit integer.");
+    typeCode = "p128";
+    break;
   case 'h':
     switch (ck) {
     case ClassS:
@@ -1197,7 +1215,6 @@
   RegisterSuffix = "";
 
   const StringRef NameRef(Name);
-  const StringRef ProtoRef(Proto);
 
   if ((NameRef.count("vdup") || NameRef.count("vmov")) && HasNPostfix) {
     return;
@@ -1419,7 +1436,7 @@
 
 /// UseMacro - Examine the prototype string to determine if the intrinsic
 /// should be defined as a preprocessor macro instead of an inline function.
-static bool UseMacro(const std::string &proto) {
+static bool UseMacro(const std::string &proto, StringRef typestr) {
   // If this builtin takes an immediate argument, we need to #define it rather
   // than use a standard declaration, so that SemaChecking can range check
   // the immediate passed by the user.
@@ -1432,6 +1449,12 @@
       proto.find('c') != std::string::npos)
     return true;
 
+  // It is not permitted to pass or return an __fp16 by value, so intrinsics
+  // taking a scalar float16_t must be implemented as macros.
+  if (typestr.find('h') != std::string::npos &&
+      proto.find('s') != std::string::npos)
+    return true;
+
   return false;
 }
 
@@ -1446,7 +1469,7 @@
 // Generate the string "(argtype a, argtype b, ...)"
 static std::string GenArgs(const std::string &proto, StringRef typestr,
                            const std::string &name) {
-  bool define = UseMacro(proto);
+  bool define = UseMacro(proto, typestr);
   char arg = 'a';
 
   std::string s;
@@ -1463,9 +1486,6 @@
       s += TypeString(proto[i], typestr) + " __";
     }
     s.push_back(arg);
-    //To avoid argument being multiple defined, add extra number for renaming.
-    if (name == "vcopy_lane" || name == "vcopy_laneq")
-      s.push_back('1');
     if ((i + 1) < e)
       s += ", ";
   }
@@ -1488,18 +1508,10 @@
     if (MacroArgUsedDirectly(proto, i))
       continue;
     generatedLocal = true;
-    bool extranumber = false;
-    if (name == "vcopy_lane" || name == "vcopy_laneq")
-      extranumber = true;
-
     s += TypeString(proto[i], typestr) + " __";
     s.push_back(arg);
-    if(extranumber)
-      s.push_back('1');
     s += " = (";
     s.push_back(arg);
-    if(extranumber)
-      s.push_back('1');
     s += "); ";
   }
 
@@ -1606,6 +1618,7 @@
   case 's': nElts = 4; break;
   case 'i': nElts = 2; break;
   case 'l': nElts = 1; break;
+  case 'k': nElts = 1; break;
   case 'h': nElts = 4; break;
   case 'f': nElts = 2; break;
   case 'd':
@@ -1619,11 +1632,23 @@
 }
 
 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
+//
+// Note that some intrinsic definitions around 'lane' are being implemented
+// with macros, because they all contain constant integer argument, and we
+// statically check the range of the lane index to meet the semantic
+// requirement of different intrinsics.
+//
+// For the intrinsics implemented with macro, if they contain another intrinsic
+// implemented with maco, we have to avoid using the same argument names for
+// the nested instrinsics. For example, macro vfms_lane is being implemented
+// with another macor vfma_lane, so we rename all arguments for vfms_lane by
+// adding a suffix '1'.
+
 static std::string GenOpString(const std::string &name, OpKind op,
                                const std::string &proto, StringRef typestr) {
   bool quad;
   unsigned nElts = GetNumElements(typestr, quad);
-  bool define = UseMacro(proto);
+  bool define = UseMacro(proto, typestr);
 
   std::string ts = TypeString(proto[0], typestr);
   std::string s;
@@ -1718,6 +1743,13 @@
   case OpMullHi:
     s += Gen2OpWith2High(typestr, "vmull", "__a", "__b");
     break;
+  case OpMullHiP64: {
+    std::string Op1 = GetHigh("__a", typestr);
+    std::string Op2 = GetHigh("__b", typestr);
+    s += MangleName("vmull", typestr, ClassS);
+    s += "((poly64_t)" + Op1 + ", (poly64_t)" + Op2 + ");";
+    break;
+  }
   case OpMullHiN:
     s += MangleName("vmull_n", typestr, ClassS);
     s += "(" + GetHigh("__a", typestr) + ", __b);";
@@ -2081,23 +2113,29 @@
     break;
   }
   case OpCopyLane: {
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[3], typestr) + " __c1 = __c; \\\n  ";
     s += TypeString('s', typestr) + " __c2 = " +
-         MangleName("vget_lane", typestr, ClassS) + "(__c1, __d1); \\\n  " +
-         MangleName("vset_lane", typestr, ClassS) + "(__c2, __a1, __b1);";
+         MangleName("vget_lane", typestr, ClassS) + "(__c1, __d); \\\n  " +
+         MangleName("vset_lane", typestr, ClassS) + "(__c2, __a1, __b);";
     break;
   }
   case OpCopyQLane: {
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[3], typestr) + " __c1 = __c; \\\n  ";
     s += TypeString('s', typestr) + " __c2 = vget_lane_" + typeCode +
-         "(__c1, __d1); \\\n  vsetq_lane_" + typeCode + "(__c2, __a1, __b1);";
+         "(__c1, __d); \\\n  vsetq_lane_" + typeCode + "(__c2, __a1, __b);";
     break;
   }
   case OpCopyLaneQ: {
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[3], typestr) + " __c1 = __c; \\\n  ";
     s += TypeString('s', typestr) + " __c2 = vgetq_lane_" + typeCode +
-         "(__c1, __d1); \\\n  vset_lane_" + typeCode + "(__c2, __a1, __b1);";
+         "(__c1, __d); \\\n  vset_lane_" + typeCode + "(__c2, __a1, __b);";
     break;
   }
   case OpScalarMulLane: {
@@ -2110,8 +2148,10 @@
   case OpScalarMulLaneQ: {
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
-        s += TypeString('s', typestr) + " __d1 = vgetq_lane_" + typeCode +
-          "(__b, __c);\\\n  __a * __d1;";
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
+    s += TypeString('s', typestr) + " __d1 = vgetq_lane_" + typeCode +
+      "(__b1, __c);\\\n  __a1 * __d1;";
     break;
   }
   case OpScalarMulXLane: {
@@ -2120,9 +2160,11 @@
     if (type == 'f') type = 's';
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
     s += TypeString('s', typestr) + " __d1 = vget_lane_" + typeCode +
-      "(__b, __c);\\\n  vmulx" + type + "_" +
-      typeCode +  "(__a, __d1);";
+      "(__b1, __c);\\\n  vmulx" + type + "_" +
+      typeCode +  "(__a1, __d1);";
     break;
   }
   case OpScalarMulXLaneQ: {
@@ -2131,9 +2173,11 @@
     if (type == 'f') type = 's';
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
     s += TypeString('s', typestr) + " __d1 = vgetq_lane_" +
-      typeCode + "(__b, __c);\\\n  vmulx" + type +
-      "_" + typeCode +  "(__a, __d1);";
+      typeCode + "(__b1, __c);\\\n  vmulx" + type +
+      "_" + typeCode +  "(__a1, __d1);";
     break;
   }
 
@@ -2143,10 +2187,12 @@
     if (type == 'f') type = 's';
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
     s += TypeString('s', typestr) + " __d1 = vget_lane_" +
-      typeCode + "(__a, 0);\\\n" +
+      typeCode + "(__a1, 0);\\\n" +
       "  " + TypeString('s', typestr) + " __e1 = vget_lane_" +
-      typeCode + "(__b, __c);\\\n" +
+      typeCode + "(__b1, __c);\\\n" +
       "  " + TypeString('s', typestr) + " __f1 = vmulx" + type + "_" +
       typeCode + "(__d1, __e1);\\\n" +
       "  " + TypeString('d', typestr) + " __g1;\\\n" +
@@ -2160,10 +2206,12 @@
     if (type == 'f') type = 's';
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
     s += TypeString('s', typestr) + " __d1 = vget_lane_" +
-      typeCode + "(__a, 0);\\\n" +
+      typeCode + "(__a1, 0);\\\n" +
       "  " + TypeString('s', typestr) + " __e1 = vgetq_lane_" +
-      typeCode + "(__b, __c);\\\n" +
+      typeCode + "(__b1, __c);\\\n" +
       "  " + TypeString('s', typestr) + " __f1 = vmulx" + type + "_" +
       typeCode + "(__d1, __e1);\\\n" +
       "  " + TypeString('d', typestr) + " __g1;\\\n" +
@@ -2173,70 +2221,94 @@
   case OpScalarQDMullLane: {
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
-    s += MangleName("vqdmull", typestr, ClassS) + "(__a, " +
-    "vget_lane_" + typeCode + "(b, __c));";
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
+    s += MangleName("vqdmull", typestr, ClassS) + "(__a1, " +
+    "vget_lane_" + typeCode + "(__b1, __c));";
     break;
   }
   case OpScalarQDMullLaneQ: {
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
-    s += MangleName("vqdmull", typestr, ClassS) + "(__a, " +
-    "vgetq_lane_" + typeCode + "(b, __c));";
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
+    s += MangleName("vqdmull", typestr, ClassS) + "(__a1, " +
+    "vgetq_lane_" + typeCode + "(__b1, __c));";
     break;
   }
   case OpScalarQDMulHiLane: {
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
-    s += MangleName("vqdmulh", typestr, ClassS) + "(__a, " +
-    "vget_lane_" + typeCode + "(__b, __c));";
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
+    s += MangleName("vqdmulh", typestr, ClassS) + "(__a1, " +
+    "vget_lane_" + typeCode + "(__b1, __c));";
     break;
   }
   case OpScalarQDMulHiLaneQ: {
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
-    s += MangleName("vqdmulh", typestr, ClassS) + "(__a, " +
-    "vgetq_lane_" + typeCode + "(__b, __c));";
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
+    s += MangleName("vqdmulh", typestr, ClassS) + "(__a1, " +
+    "vgetq_lane_" + typeCode + "(__b1, __c));";
     break;
   }
   case OpScalarQRDMulHiLane: {
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
-    s += MangleName("vqrdmulh", typestr, ClassS) + "(__a, " +
-    "vget_lane_" + typeCode + "(__b, __c));";
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
+    s += MangleName("vqrdmulh", typestr, ClassS) + "(__a1, " +
+    "vget_lane_" + typeCode + "(__b1, __c));";
     break;
   }
   case OpScalarQRDMulHiLaneQ: {
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
-    s += MangleName("vqrdmulh", typestr, ClassS) + "(__a, " +
-    "vgetq_lane_" + typeCode + "(__b, __c));";
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+    s += TypeString(proto[2], typestr) + " __b1 = __b; \\\n  ";
+    s += MangleName("vqrdmulh", typestr, ClassS) + "(__a1, " +
+    "vgetq_lane_" + typeCode + "(__b1, __c));";
     break;
   }
   case OpScalarGetLane:{
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
-    if (quad) {
-     s += "int16x8_t __a1 = vreinterpretq_s16_f16(__a);\\\n";
-     s += "  vgetq_lane_s16(__a1, __b);";
-    } else {
-     s += "int16x4_t __a1 = vreinterpret_s16_f16(__a);\\\n";
-     s += "  vget_lane_s16(__a1, __b);";
-    }
+    s += TypeString(proto[1], typestr) + " __a1 = __a; \\\n  ";
+
+    std::string intType = quad ? "int16x8_t" : "int16x4_t";
+    std::string intName = quad ? "vgetq" : "vget";
+
+    // reinterpret float16 vector as int16 vector
+    s += intType + " __a2 = *(" + intType + " *)(&__a1);\\\n";
+
+    s += "  int16_t __a3 = " + intName + "_lane_s16(__a2, __b);\\\n";
+
+    // reinterpret int16 vector as float16 vector
+    s += "  float16_t __a4 = *(float16_t *)(&__a3);\\\n";
+    s += "  __a4;";
     break;
   }
   case OpScalarSetLane:{
     std::string typeCode = "";
     InstructionTypeCode(typestr, ClassS, quad, typeCode);
-    s += "int16_t __a1 = (int16_t)__a;\\\n";
-    if (quad) {
-     s += "  int16x8_t __b1 = vreinterpretq_s16_f16(b);\\\n";
-     s += "  int16x8_t __b2 = vsetq_lane_s16(__a1, __b1, __c);\\\n";
-     s += "  vreinterpretq_f16_s16(__b2);";
-    } else {
-     s += "  int16x4_t __b1 = vreinterpret_s16_f16(b);\\\n";
-     s += "  int16x4_t __b2 = vset_lane_s16(__a1, __b1, __c);\\\n";
-     s += "  vreinterpret_f16_s16(__b2);";
-    }
+    s += TypeString(proto[1], typestr) + " __a1 = __a;\\\n  ";
+
+    std::string origType = quad ? "float16x8_t" : "float16x4_t";
+    std::string intType = quad ? "int16x8_t" : "int16x4_t";
+    std::string intName = quad ? "vsetq" : "vset";
+
+    // reinterpret float16_t as int16_t
+    s += "int16_t __a2 = *(int16_t *)(&__a1);\\\n";
+    // reinterpret float16 vector as int16 vector
+    s += "  " + intType + " __b2 = *(" + intType + " *)(&__b);\\\n";
+
+    s += "  " + intType + " __b3 = " + intName + "_lane_s16(__a2, __b2, __c);\\\n";
+
+    // reinterpret int16 vector as float16 vector
+    s += "  " + origType + " __b4 = *(" + origType + " *)(&__b3);\\\n";
+    s += "__b4;";
     break;
   }
 
@@ -2279,6 +2351,9 @@
     case 'l':
       ET = poly ? NeonTypeFlags::Poly64 : NeonTypeFlags::Int64;
       break;
+    case 'k':
+      ET = NeonTypeFlags::Poly128;
+      break;
     case 'h':
       ET = NeonTypeFlags::Float16;
       break;
@@ -2317,7 +2392,7 @@
   // sret-like argument.
   bool sret = IsMultiVecProto(proto[0]);
 
-  bool define = UseMacro(proto);
+  bool define = UseMacro(proto, typestr);
 
   // Check if the prototype has a scalar operand with the type of the vector
   // elements.  If not, bitcasting the args will take care of arg checking.
@@ -2381,7 +2456,7 @@
     } else if (proto[i] >= 'B' && proto[i] <= 'D') {
       NumOfVec = proto[i] - 'A' + 1;
     }
-    
+
     if (NumOfVec > 0) {
       // Check if an explicit cast is needed.
       if (argType != 'c' || argPoly || argUsgn)
@@ -2462,7 +2537,7 @@
                                 StringRef outTypeStr, StringRef inTypeStr,
                                 OpKind kind, ClassKind classKind) {
   assert(!proto.empty() && "");
-  bool define = UseMacro(proto) && kind != OpUnavailable;
+  bool define = UseMacro(proto, outTypeStr) && kind != OpUnavailable;
   std::string s;
 
   // static always inline + return type
@@ -2511,7 +2586,7 @@
 /// run - Read the records in arm_neon.td and output arm_neon.h.  arm_neon.h
 /// is comprised of type definitions and function declarations.
 void NeonEmitter::run(raw_ostream &OS) {
-  OS << 
+  OS <<
     "/*===---- arm_neon.h - ARM Neon intrinsics ------------------------------"
     "---===\n"
     " *\n"
@@ -2551,7 +2626,7 @@
   OS << "#ifndef __ARM_NEON_H\n";
   OS << "#define __ARM_NEON_H\n\n";
 
-  OS << "#if !defined(__ARM_NEON__) && !defined(__ARM_NEON)\n";
+  OS << "#if !defined(__ARM_NEON)\n";
   OS << "#error \"NEON support not enabled\"\n";
   OS << "#endif\n\n";
 
@@ -2570,6 +2645,7 @@
   OS << "typedef uint8_t poly8_t;\n";
   OS << "typedef uint16_t poly16_t;\n";
   OS << "typedef uint64_t poly64_t;\n";
+  OS << "typedef __uint128_t poly128_t;\n";
   OS << "#else\n";
   OS << "typedef int8_t poly8_t;\n";
   OS << "typedef int16_t poly16_t;\n";
@@ -2663,78 +2739,59 @@
   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
 
   StringMap<ClassKind> EmittedMap;
+  std::string CurrentGuard = "";
+  bool InGuard = false;
 
-  // Emit vmovl, vmull and vabd intrinsics first so they can be used by other
-  // intrinsics.  (Some of the saturating multiply instructions are also
-  // used to implement the corresponding "_lane" variants, but tablegen
-  // sorts the records into alphabetical order so that the "_lane" variants
-  // come after the intrinsics they use.)
-  emitIntrinsic(OS, Records.getDef("VMOVL"), EmittedMap);
-  emitIntrinsic(OS, Records.getDef("VMULL"), EmittedMap);
-  emitIntrinsic(OS, Records.getDef("VABD"), EmittedMap);
-  emitIntrinsic(OS, Records.getDef("VABDL"), EmittedMap);
+  // Some intrinsics are used to express others. These need to be emitted near
+  // the beginning so that the declarations are present when needed. This is
+  // rather an ugly, arbitrary list, but probably simpler than actually tracking
+  // dependency info.
+  static const char *EarlyDefsArr[] =
+      { "VFMA",      "VQMOVN",    "VQMOVUN",  "VABD",    "VMOVL",
+        "VABDL",     "VGET_HIGH", "VCOMBINE", "VSHLL_N", "VMOVL_HIGH",
+        "VMULL",     "VMLAL_N",   "VMLSL_N",  "VMULL_N", "VMULL_P64",
+        "VQDMLAL_N", "VQDMLSL_N", "VQDMULL_N" };
+  ArrayRef<const char *> EarlyDefs(EarlyDefsArr);
 
-  // ARM intrinsics must be emitted before AArch64 intrinsics to ensure
-  // common intrinsics appear only once in the output stream.
-  // The check for uniquiness is done in emitIntrinsic.
-  // Emit ARM intrinsics.
-  for (unsigned i = 0, e = RV.size(); i != e; ++i) {
-    Record *R = RV[i];
-
-    // Skip AArch64 intrinsics; they will be emitted at the end.
-    bool isA64 = R->getValueAsBit("isA64");
-    if (isA64)
-      continue;
-
-    if (R->getName() != "VMOVL" && R->getName() != "VMULL" &&
-        R->getName() != "VABD")
-      emitIntrinsic(OS, R, EmittedMap);
+  for (unsigned i = 0; i < EarlyDefs.size(); ++i) {
+    Record *R = Records.getDef(EarlyDefs[i]);
+    emitGuardedIntrinsic(OS, R, CurrentGuard, InGuard, EmittedMap);
   }
 
-  // Emit AArch64-specific intrinsics.
-  OS << "#ifdef __aarch64__\n";
-
-  emitIntrinsic(OS, Records.getDef("VMOVL_HIGH"), EmittedMap);
-  emitIntrinsic(OS, Records.getDef("VMULL_HIGH"), EmittedMap);
-  emitIntrinsic(OS, Records.getDef("VABDL_HIGH"), EmittedMap);
-
   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
     Record *R = RV[i];
-
-    // Skip ARM intrinsics already included above.
-    bool isA64 = R->getValueAsBit("isA64");
-    if (!isA64)
+    if (std::find(EarlyDefs.begin(), EarlyDefs.end(), R->getName()) !=
+        EarlyDefs.end())
       continue;
 
-    // Skip crypto temporarily, and will emit them all together at the end.
-    bool isCrypto = R->getValueAsBit("isCrypto");
-    if (isCrypto)
-      continue;
-
-    emitIntrinsic(OS, R, EmittedMap);
+    emitGuardedIntrinsic(OS, R, CurrentGuard, InGuard, EmittedMap);
   }
 
-  OS << "#ifdef __ARM_FEATURE_CRYPTO\n";
-
-  for (unsigned i = 0, e = RV.size(); i != e; ++i) {
-    Record *R = RV[i];
-
-    // Skip crypto temporarily, and will emit them all together at the end.
-    bool isCrypto = R->getValueAsBit("isCrypto");
-    if (!isCrypto)
-      continue;
-
-    emitIntrinsic(OS, R, EmittedMap);
-  }
-  
-  OS << "#endif\n\n";
-
-  OS << "#endif\n\n";
+  if (InGuard)
+    OS << "#endif\n\n";
 
   OS << "#undef __ai\n\n";
   OS << "#endif /* __ARM_NEON_H */\n";
 }
 
+void NeonEmitter::emitGuardedIntrinsic(raw_ostream &OS, Record *R,
+                                       std::string &CurrentGuard, bool &InGuard,
+                                       StringMap<ClassKind> &EmittedMap) {
+
+  std::string NewGuard = R->getValueAsString("ArchGuard");
+  if (NewGuard != CurrentGuard) {
+    if (InGuard)
+      OS << "#endif\n\n";
+    if (NewGuard.size())
+      OS << "#if " << NewGuard << '\n';
+
+    CurrentGuard = NewGuard;
+    InGuard = NewGuard.size() != 0;
+  }
+
+  emitIntrinsic(OS, R, EmittedMap);
+}
+
 /// emitIntrinsic - Write out the arm_neon.h header file definitions for the
 /// intrinsics specified by record R checking for intrinsic uniqueness.
 void NeonEmitter::emitIntrinsic(raw_ostream &OS, Record *R,
@@ -2775,8 +2832,11 @@
     } else {
       std::string s =
           GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[ti], kind, classKind);
-      if (EmittedMap.count(s))
+      if (EmittedMap.count(s)) {
+        errs() << "warning: duplicate definition: " << name
+               << " (type: " << TypeString('d', TypeVec[ti]) << ")\n";
         continue;
+      }
       EmittedMap[s] = classKind;
       OS << s;
     }
@@ -2802,6 +2862,8 @@
     case 'd':
     case 'l':
       return (1 << (int)quad) - 1;
+    case 'k':
+      return 0;
     default:
       PrintFatalError("unhandled type!");
   }
@@ -2825,6 +2887,8 @@
     case 'd':
     case 'l':
       return 63;
+    case 'k':
+      return 127;
     default:
       PrintFatalError("unhandled type!");
   }
@@ -2833,17 +2897,12 @@
 /// Generate the ARM and AArch64 intrinsic range checking code for
 /// shift/lane immediates, checking for unique declarations.
 void
-NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
-                                        StringMap<ClassKind> &A64IntrinsicMap,
-                                        bool isA64RangeCheck) {
+NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS) {
   std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
   StringMap<OpKind> EmittedMap;
 
   // Generate the intrinsic range checking code for shift/lane immediates.
-  if (isA64RangeCheck)
-    OS << "#ifdef GET_NEON_AARCH64_IMMEDIATE_CHECK\n";
-  else
-    OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
+  OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
 
   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
     Record *R = RV[i];
@@ -2878,19 +2937,6 @@
     if (!ProtoHasScalar(Proto))
       ck = ClassB;
 
-    // Do not include AArch64 range checks if not generating code for AArch64.
-    bool isA64 = R->getValueAsBit("isA64");
-    if (!isA64RangeCheck && isA64)
-      continue;
-
-    // Include ARM range checks in AArch64 but only if ARM intrinsics are not
-    // redefined by AArch64 to handle new types.
-    if (isA64RangeCheck && !isA64 && A64IntrinsicMap.count(Rename)) {
-      ClassKind &A64CK = A64IntrinsicMap[Rename];
-      if (A64CK == ck && ck != ClassNone)
-        continue;
-    }
-
     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
       std::string namestr, shiftstr, rangestr;
 
@@ -2929,6 +2975,14 @@
           rangestr = "l = 1; ";
 
         rangestr += "u = RFT(TV" + shiftstr + ")";
+      } else if (ck == ClassB) {
+        // ClassB intrinsics have a type (and hence lane number) that is only
+        // known at runtime.
+        assert(immPos > 0 && "unexpected immediate operand");
+        if (R->getValueAsBit("isLaneQ"))
+          rangestr = "u = RFT(TV, false, true)";
+        else
+          rangestr = "u = RFT(TV, false, false)";
       } else {
         // The immediate generally refers to a lane in the preceding argument.
         assert(immPos > 0 && "unexpected immediate operand");
@@ -2973,10 +3027,7 @@
           break;
         }
       }
-      if (isA64RangeCheck)
-        OS << "case AArch64::BI__builtin_neon_";
-      else
-        OS << "case ARM::BI__builtin_neon_";
+      OS << "case NEON::BI__builtin_neon_";
       OS << MangleName(name, TypeVec[ti], ck) << ": i = " << immidx << "; "
          << rangestr << "; break;\n";
     }
@@ -2984,20 +3035,25 @@
   OS << "#endif\n\n";
 }
 
+struct OverloadInfo {
+  uint64_t Mask;
+  int PtrArgNum;
+  bool HasConstPtr;
+};
 /// Generate the ARM and AArch64 overloaded type checking code for
 /// SemaChecking.cpp, checking for unique builtin declarations.
 void
-NeonEmitter::genOverloadTypeCheckCode(raw_ostream &OS,
-                                      StringMap<ClassKind> &A64IntrinsicMap,
-                                      bool isA64TypeCheck) {
+NeonEmitter::genOverloadTypeCheckCode(raw_ostream &OS) {
   std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
-  StringMap<OpKind> EmittedMap;
 
   // Generate the overloaded type checking code for SemaChecking.cpp
-  if (isA64TypeCheck)
-    OS << "#ifdef GET_NEON_AARCH64_OVERLOAD_CHECK\n";
-  else
-    OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
+  OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
+
+  // We record each overload check line before emitting because subsequent Inst
+  // definitions may extend the number of permitted types (i.e. augment the
+  // Mask). Use std::map to avoid sorting the table by hash number.
+  std::map<std::string, OverloadInfo> OverloadMap;
+  typedef std::map<std::string, OverloadInfo>::iterator OverloadIterator;
 
   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
     Record *R = RV[i];
@@ -3009,7 +3065,7 @@
     std::string Types = R->getValueAsString("Types");
     std::string name = R->getValueAsString("Name");
     std::string Rename = name + "@" + Proto;
-    
+
     // Functions with 'a' (the splat code) in the type prototype should not get
     // their own builtin as they use the non-splat variant.
     if (Proto.find('a') != std::string::npos)
@@ -3026,21 +3082,6 @@
     if (R->getSuperClasses().size() < 2)
       PrintFatalError(R->getLoc(), "Builtin has no class kind");
 
-    // Do not include AArch64 type checks if not generating code for AArch64.
-    bool isA64 = R->getValueAsBit("isA64");
-    if (!isA64TypeCheck && isA64)
-      continue;
-
-    // Include ARM  type check in AArch64 but only if ARM intrinsics
-    // are not redefined in AArch64 to handle new types, e.g. "vabd" is a SIntr
-    // redefined in AArch64 to handle an additional 2 x f64 type.
-    ClassKind ck = ClassMap[R->getSuperClasses()[1]];
-    if (isA64TypeCheck && !isA64 && A64IntrinsicMap.count(Rename)) {
-      ClassKind &A64CK = A64IntrinsicMap[Rename];
-      if (A64CK == ck && ck != ClassNone)
-        continue;
-    }
-
     int si = -1, qi = -1;
     uint64_t mask = 0, qmask = 0;
     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
@@ -3088,48 +3129,52 @@
     }
 
     if (mask) {
-      if (isA64TypeCheck)
-        OS << "case AArch64::BI__builtin_neon_";
-      else
-        OS << "case ARM::BI__builtin_neon_";
-      OS << MangleName(name, TypeVec[si], ClassB) << ": mask = "
-         << "0x" << utohexstr(mask) << "ULL";
-      if (PtrArgNum >= 0)
-        OS << "; PtrArgNum = " << PtrArgNum;
-      if (HasConstPtr)
-        OS << "; HasConstPtr = true";
-      OS << "; break;\n";
+      std::pair<OverloadIterator, bool> I = OverloadMap.insert(std::make_pair(
+          MangleName(name, TypeVec[si], ClassB), OverloadInfo()));
+      OverloadInfo &Record = I.first->second;
+      if (!I.second)
+        assert(Record.PtrArgNum == PtrArgNum &&
+               Record.HasConstPtr == HasConstPtr);
+      Record.Mask |= mask;
+      Record.PtrArgNum = PtrArgNum;
+      Record.HasConstPtr = HasConstPtr;
     }
     if (qmask) {
-      if (isA64TypeCheck)
-        OS << "case AArch64::BI__builtin_neon_";
-      else
-        OS << "case ARM::BI__builtin_neon_";
-      OS << MangleName(name, TypeVec[qi], ClassB) << ": mask = "
-         << "0x" << utohexstr(qmask) << "ULL";
-      if (PtrArgNum >= 0)
-        OS << "; PtrArgNum = " << PtrArgNum;
-      if (HasConstPtr)
-        OS << "; HasConstPtr = true";
-      OS << "; break;\n";
+      std::pair<OverloadIterator, bool> I = OverloadMap.insert(std::make_pair(
+          MangleName(name, TypeVec[qi], ClassB), OverloadInfo()));
+      OverloadInfo &Record = I.first->second;
+      if (!I.second)
+        assert(Record.PtrArgNum == PtrArgNum &&
+               Record.HasConstPtr == HasConstPtr);
+      Record.Mask |= qmask;
+      Record.PtrArgNum = PtrArgNum;
+      Record.HasConstPtr = HasConstPtr;
     }
   }
+
+  for (OverloadIterator I = OverloadMap.begin(), E = OverloadMap.end(); I != E;
+       ++I) {
+    OverloadInfo &BuiltinOverloads = I->second;
+    OS << "case NEON::BI__builtin_neon_" << I->first << ": ";
+    OS << "mask = " << "0x" << utohexstr(BuiltinOverloads.Mask) << "ULL";
+    if (BuiltinOverloads.PtrArgNum >= 0)
+      OS << "; PtrArgNum = " << BuiltinOverloads.PtrArgNum;
+    if (BuiltinOverloads.HasConstPtr)
+      OS << "; HasConstPtr = true";
+    OS << "; break;\n";
+  }
+
   OS << "#endif\n\n";
 }
 
 /// genBuiltinsDef: Generate the BuiltinsARM.def and  BuiltinsAArch64.def
 /// declaration of builtins, checking for unique builtin declarations.
-void NeonEmitter::genBuiltinsDef(raw_ostream &OS,
-                                 StringMap<ClassKind> &A64IntrinsicMap,
-                                 bool isA64GenBuiltinDef) {
+void NeonEmitter::genBuiltinsDef(raw_ostream &OS) {
   std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
-  StringMap<OpKind> EmittedMap;
 
-  // Generate BuiltinsARM.def and BuiltinsAArch64.def
-  if (isA64GenBuiltinDef)
-    OS << "#ifdef GET_NEON_AARCH64_BUILTINS\n";
-  else
-    OS << "#ifdef GET_NEON_BUILTINS\n";
+  // We want to emit the intrinsics in alphabetical order, so use the more
+  // expensive std::map to gather them together first.
+  std::map<std::string, OpKind> EmittedMap;
 
   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
     Record *R = RV[i];
@@ -3155,21 +3200,6 @@
 
     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
 
-    // Do not include AArch64 BUILTIN() macros if not generating
-    // code for AArch64
-    bool isA64 = R->getValueAsBit("isA64");
-    if (!isA64GenBuiltinDef && isA64)
-      continue;
-
-    // Include ARM  BUILTIN() macros  in AArch64 but only if ARM intrinsics
-    // are not redefined in AArch64 to handle new types, e.g. "vabd" is a SIntr
-    // redefined in AArch64 to handle an additional 2 x f64 type.
-    if (isA64GenBuiltinDef && !isA64 && A64IntrinsicMap.count(Rename)) {
-      ClassKind &A64CK = A64IntrinsicMap[Rename];
-      if (A64CK == ck && ck != ClassNone)
-        continue;
-    }
-
     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
       // Generate the declaration for this builtin, ensuring
       // that each unique BUILTIN() macro appears only once in the output
@@ -3179,9 +3209,17 @@
         continue;
 
       EmittedMap[bd] = OpNone;
-      OS << bd << "\n";
     }
   }
+
+  // Generate BuiltinsNEON.
+  OS << "#ifdef GET_NEON_BUILTINS\n";
+
+  for (std::map<std::string, OpKind>::iterator I = EmittedMap.begin(),
+                                               E = EmittedMap.end();
+       I != E; ++I)
+    OS << I->first << "\n";
+
   OS << "#endif\n\n";
 }
 
@@ -3192,44 +3230,14 @@
 void NeonEmitter::runHeader(raw_ostream &OS) {
   std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
 
-  // build a map of AArch64 intriniscs to be used in uniqueness checks.
-  StringMap<ClassKind> A64IntrinsicMap;
-  for (unsigned i = 0, e = RV.size(); i != e; ++i) {
-    Record *R = RV[i];
-
-    bool isA64 = R->getValueAsBit("isA64");
-    if (!isA64)
-      continue;
-
-    ClassKind CK = ClassNone;
-    if (R->getSuperClasses().size() >= 2)
-      CK = ClassMap[R->getSuperClasses()[1]];
-
-    std::string Name = R->getValueAsString("Name");
-    std::string Proto = R->getValueAsString("Prototype");
-    std::string Rename = Name + "@" + Proto;
-    if (A64IntrinsicMap.count(Rename))
-      continue;
-    A64IntrinsicMap[Rename] = CK;
-  }
-
-  // Generate BuiltinsARM.def for ARM
-  genBuiltinsDef(OS, A64IntrinsicMap, false);
-
-  // Generate BuiltinsAArch64.def for AArch64
-  genBuiltinsDef(OS, A64IntrinsicMap, true);
+  // Generate shared BuiltinsXXX.def
+  genBuiltinsDef(OS);
 
   // Generate ARM overloaded type checking code for SemaChecking.cpp
-  genOverloadTypeCheckCode(OS, A64IntrinsicMap, false);
-
-  // Generate AArch64 overloaded type checking code for SemaChecking.cpp
-  genOverloadTypeCheckCode(OS, A64IntrinsicMap, true);
+  genOverloadTypeCheckCode(OS);
 
   // Generate ARM range checking code for shift/lane immediates.
-  genIntrinsicRangeCheckCode(OS, A64IntrinsicMap, false);
-
-  // Generate the AArch64 range checking code for shift/lane immediates.
-  genIntrinsicRangeCheckCode(OS, A64IntrinsicMap, true);
+  genIntrinsicRangeCheckCode(OS);
 }
 
 /// GenTest - Write out a test for the intrinsic specified by the name and
@@ -3259,9 +3267,9 @@
   // for aarch64 instructions yet
   std::vector<std::string> FileCheckPatterns;
   if (!isA64) {
-	GenerateChecksForIntrinsic(name, proto, outTypeStr, inTypeStr, ck, InstName,
-							   isHiddenLOp, FileCheckPatterns);
-	s+= "// CHECK_ARM: test_" + mangledName + "\n";
+    GenerateChecksForIntrinsic(name, proto, outTypeStr, inTypeStr, ck, InstName,
+                               isHiddenLOp, FileCheckPatterns);
+    s+= "// CHECK_ARM: test_" + mangledName + "\n";
   }
   s += "// CHECK_AARCH64: test_" + mangledName + "\n";
 
@@ -3319,10 +3327,10 @@
 
 /// Write out all intrinsic tests for the specified target, checking
 /// for intrinsic test uniqueness.
-void NeonEmitter::genTargetTest(raw_ostream &OS, StringMap<OpKind> &EmittedMap,
-                                bool isA64GenTest) {
-  if (isA64GenTest)
-	OS << "#ifdef __aarch64__\n";
+void NeonEmitter::genTargetTest(raw_ostream &OS) {
+  StringMap<OpKind> EmittedMap;
+  std::string CurrentGuard = "";
+  bool InGuard = false;
 
   std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
@@ -3333,12 +3341,17 @@
     bool isShift = R->getValueAsBit("isShift");
     std::string InstName = R->getValueAsString("InstName");
     bool isHiddenLOp = R->getValueAsBit("isHiddenLInst");
-    bool isA64 = R->getValueAsBit("isA64");
 
-    // do not include AArch64 intrinsic test if not generating
-    // code for AArch64
-    if (!isA64GenTest && isA64)
-      continue;
+    std::string NewGuard = R->getValueAsString("ArchGuard");
+    if (NewGuard != CurrentGuard) {
+      if (InGuard)
+        OS << "#endif\n\n";
+      if (NewGuard.size())
+        OS << "#if " << NewGuard << '\n';
+
+      CurrentGuard = NewGuard;
+      InGuard = NewGuard.size() != 0;
+    }
 
     SmallVector<StringRef, 16> TypeVec;
     ParseTypes(R, Types, TypeVec);
@@ -3358,29 +3371,27 @@
           (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
           if (srcti == ti || inQuad != outQuad)
             continue;
-		  std::string testFuncProto;
+          std::string testFuncProto;
           std::string s = GenTest(name, Proto, TypeVec[ti], TypeVec[srcti],
-                                  isShift, isHiddenLOp, ck, InstName, isA64,
-								  testFuncProto);
+                                  isShift, isHiddenLOp, ck, InstName,
+                                  CurrentGuard.size(), testFuncProto);
           if (EmittedMap.count(testFuncProto))
             continue;
           EmittedMap[testFuncProto] = kind;
           OS << s << "\n";
         }
       } else {
-		std::string testFuncProto;
-        std::string s = GenTest(name, Proto, TypeVec[ti], TypeVec[ti], isShift,
-                                isHiddenLOp, ck, InstName, isA64, testFuncProto);
-        if (EmittedMap.count(testFuncProto))
-          continue;
-        EmittedMap[testFuncProto] = kind;
+        std::string testFuncProto;
+        std::string s =
+            GenTest(name, Proto, TypeVec[ti], TypeVec[ti], isShift, isHiddenLOp,
+                    ck, InstName, CurrentGuard.size(), testFuncProto);
         OS << s << "\n";
       }
     }
   }
 
-  if (isA64GenTest)
-	OS << "#endif\n";
+  if (InGuard)
+    OS << "#endif\n";
 }
 /// runTests - Write out a complete set of tests for all of the Neon
 /// intrinsics.
@@ -3389,25 +3400,17 @@
         "apcs-gnu\\\n"
         "// RUN:  -target-cpu swift -ffreestanding -Os -S -o - %s\\\n"
         "// RUN:  | FileCheck %s -check-prefix=CHECK_ARM\n"
-		"\n"
-	    "// RUN: %clang_cc1 -triple aarch64-none-linux-gnu \\\n"
-	    "// RUN -target-feature +neon  -ffreestanding -S -o - %s \\\n"
-	    "// RUN:  | FileCheck %s -check-prefix=CHECK_AARCH64\n"
+        "\n"
+        "// RUN: %clang_cc1 -triple aarch64-none-linux-gnu \\\n"
+        "// RUN -target-feature +neon  -ffreestanding -S -o - %s \\\n"
+        "// RUN:  | FileCheck %s -check-prefix=CHECK_AARCH64\n"
         "\n"
         "// REQUIRES: long_tests\n"
         "\n"
         "#include <arm_neon.h>\n"
         "\n";
 
-  // ARM tests must be emitted before AArch64 tests to ensure
-  // tests for intrinsics that are common to ARM and AArch64
-  // appear only once in the output stream.
-  // The check for uniqueness is done in genTargetTest.
-  StringMap<OpKind> EmittedMap;
-
-  genTargetTest(OS, EmittedMap, false);
-
-  genTargetTest(OS, EmittedMap, true);
+  genTargetTest(OS);
 }
 
 namespace clang {
diff --git a/utils/TableGen/TableGen.cpp b/utils/TableGen/TableGen.cpp
index 0e45d81..4484e65 100644
--- a/utils/TableGen/TableGen.cpp
+++ b/utils/TableGen/TableGen.cpp
@@ -24,15 +24,14 @@
 
 enum ActionType {
   GenClangAttrClasses,
-  GenClangAttrIdentifierArgList,
-  GenClangAttrTypeArgList,
+  GenClangAttrParserStringSwitches,
   GenClangAttrImpl,
   GenClangAttrList,
   GenClangAttrPCHRead,
   GenClangAttrPCHWrite,
-  GenClangAttrSpellingList,
+  GenClangAttrHasAttributeImpl,
   GenClangAttrSpellingListIndex,
-  GenClangAttrLateParsedList,
+  GenClangAttrASTVisitor,
   GenClangAttrTemplateInstantiate,
   GenClangAttrParsedAttrList,
   GenClangAttrParsedAttrImpl,
@@ -52,7 +51,8 @@
   GenClangCommentCommandList,
   GenArmNeon,
   GenArmNeonSema,
-  GenArmNeonTest
+  GenArmNeonTest,
+  GenAttrDocs
 };
 
 namespace {
@@ -61,14 +61,9 @@
     cl::values(
         clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
                    "Generate clang attribute clases"),
-        clEnumValN(GenClangAttrIdentifierArgList,
-                   "gen-clang-attr-identifier-arg-list",
-                   "Generate a list of attributes that take an "
-                   "identifier as their first argument"),
-        clEnumValN(GenClangAttrTypeArgList,
-                   "gen-clang-attr-type-arg-list",
-                   "Generate a list of attributes that take a type as their "
-                   "first argument"),
+        clEnumValN(GenClangAttrParserStringSwitches,
+                   "gen-clang-attr-parser-string-switches",
+                   "Generate all parser-related attribute string switches"),
         clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl",
                    "Generate clang attribute implementations"),
         clEnumValN(GenClangAttrList, "gen-clang-attr-list",
@@ -77,14 +72,15 @@
                    "Generate clang PCH attribute reader"),
         clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write",
                    "Generate clang PCH attribute writer"),
-        clEnumValN(GenClangAttrSpellingList, "gen-clang-attr-spelling-list",
+        clEnumValN(GenClangAttrHasAttributeImpl,
+                   "gen-clang-attr-has-attribute-impl",
                    "Generate a clang attribute spelling list"),
         clEnumValN(GenClangAttrSpellingListIndex,
                    "gen-clang-attr-spelling-index",
                    "Generate a clang attribute spelling index"),
-        clEnumValN(GenClangAttrLateParsedList,
-                   "gen-clang-attr-late-parsed-list",
-                   "Generate a clang attribute LateParsed list"),
+        clEnumValN(GenClangAttrASTVisitor,
+                   "gen-clang-attr-ast-visitor",
+                   "Generate a recursive AST visitor for clang attributes"),
         clEnumValN(GenClangAttrTemplateInstantiate,
                    "gen-clang-attr-template-instantiate",
                    "Generate a clang template instantiate code"),
@@ -135,6 +131,8 @@
                    "Generate ARM NEON sema support for clang"),
         clEnumValN(GenArmNeonTest, "gen-arm-neon-test",
                    "Generate ARM NEON tests for clang"),
+        clEnumValN(GenAttrDocs, "gen-attr-docs",
+                   "Generate attribute documentation"),
         clEnumValEnd));
 
 cl::opt<std::string>
@@ -147,11 +145,8 @@
   case GenClangAttrClasses:
     EmitClangAttrClass(Records, OS);
     break;
-  case GenClangAttrIdentifierArgList:
-    EmitClangAttrIdentifierArgList(Records, OS);
-    break;
-  case GenClangAttrTypeArgList:
-    EmitClangAttrTypeArgList(Records, OS);
+  case GenClangAttrParserStringSwitches:
+    EmitClangAttrParserStringSwitches(Records, OS);
     break;
   case GenClangAttrImpl:
     EmitClangAttrImpl(Records, OS);
@@ -165,14 +160,14 @@
   case GenClangAttrPCHWrite:
     EmitClangAttrPCHWrite(Records, OS);
     break;
-  case GenClangAttrSpellingList:
-    EmitClangAttrSpellingList(Records, OS);
+  case GenClangAttrHasAttributeImpl:
+    EmitClangAttrHasAttrImpl(Records, OS);
     break;
   case GenClangAttrSpellingListIndex:
     EmitClangAttrSpellingListIndex(Records, OS);
     break;
-  case GenClangAttrLateParsedList:
-    EmitClangAttrLateParsedList(Records, OS);
+  case GenClangAttrASTVisitor:
+    EmitClangAttrASTVisitor(Records, OS);
     break;
   case GenClangAttrTemplateInstantiate:
     EmitClangAttrTemplateInstantiate(Records, OS);
@@ -235,6 +230,9 @@
   case GenArmNeonTest:
     EmitNeonTest(Records, OS);
     break;
+  case GenAttrDocs:
+    EmitClangAttrDocs(Records, OS);
+    break;
   }
 
   return false;
@@ -248,3 +246,12 @@
 
   return TableGenMain(argv[0], &ClangTableGenMain);
 }
+
+#ifdef __has_feature
+#if __has_feature(address_sanitizer)
+#include <sanitizer/lsan_interface.h>
+// Disable LeakSanitizer for this binary as it has too many leaks that are not
+// very interesting to fix. See compiler-rt/include/sanitizer/lsan_interface.h .
+int __lsan_is_turned_off() { return 1; }
+#endif  // __has_feature(address_sanitizer)
+#endif  // defined(__has_feature)
diff --git a/utils/TableGen/TableGenBackends.h b/utils/TableGen/TableGenBackends.h
index 8904287..7e05496 100644
--- a/utils/TableGen/TableGenBackends.h
+++ b/utils/TableGen/TableGenBackends.h
@@ -29,16 +29,15 @@
 void EmitClangASTNodes(RecordKeeper &RK, raw_ostream &OS,
                        const std::string &N, const std::string &S);
 
+void EmitClangAttrParserStringSwitches(RecordKeeper &Records, raw_ostream &OS);
 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS);
-void EmitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS);
-void EmitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS);
 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS);
 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS);
 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS);
 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS);
-void EmitClangAttrSpellingList(RecordKeeper &Records, raw_ostream &OS);
+void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS);
 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS);
-void EmitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS);
+void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS);
 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS);
 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS);
 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS);
@@ -63,4 +62,6 @@
 void EmitNeonSema(RecordKeeper &Records, raw_ostream &OS);
 void EmitNeonTest(RecordKeeper &Records, raw_ostream &OS);
 
+void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS);
+
 } // end namespace clang
diff --git a/utils/analyzer/SATestBuild.py b/utils/analyzer/SATestBuild.py
index 51bc6e2..441032e 100755
--- a/utils/analyzer/SATestBuild.py
+++ b/utils/analyzer/SATestBuild.py
@@ -168,7 +168,7 @@
 SBOutputDirReferencePrefix = "Ref"
 
 # The list of checkers used during analyzes.
-# Currently, consists of all the non experimental checkers, plus a few alpha
+# Currently, consists of all the non-experimental checkers, plus a few alpha
 # checkers we don't want to regress on.
 Checkers="alpha.unix.SimpleStream,alpha.security.taint,alpha.cplusplus.NewDeleteLeaks,core,cplusplus,deadcode,security,unix,osx"
 
@@ -363,7 +363,7 @@
     if TotalFailed == 0:
         CleanUpEmptyPlists(SBOutputDir)
         Plists = glob.glob(SBOutputDir + "/*/*.plist")
-        print "Number of bug reports (non empty plist files) produced: %d" %\
+        print "Number of bug reports (non-empty plist files) produced: %d" %\
            len(Plists)
         return;
     
diff --git a/utils/clang.natvis b/utils/clang.natvis
new file mode 100644
index 0000000..1f956f1
--- /dev/null
+++ b/utils/clang.natvis
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="utf-8"?>

+<!--

+Visual Studio 2012 Native Debugging Visualizers for LLVM

+

+Put this file into "%USERPROFILE%\Documents\Visual Studio 2012\Visualizers"

+or create a symbolic link so it updates automatically.

+-->

+<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">

+  <Type Name="clang::IdentifierInfo">

+    <DisplayString Condition="Entry != 0">({((llvm::StringMapEntry&lt;clang::IdentifierInfo *&gt;*)Entry)+1,s})</DisplayString>

+    <Expand>

+      <Item Condition="Entry != 0" Name="[Identifier]">((llvm::StringMapEntry&lt;clang::IdentifierInfo *&gt;*)Entry)+1,s</Item>

+      <Item Name="Token Kind">(clang::tok::TokenKind)TokenID</Item>

+    </Expand>

+  </Type>

+  <Type Name="clang::DeclarationName">

+    <DisplayString Condition="Ptr == 0">Empty</DisplayString>

+    <DisplayString Condition="(Ptr &amp; PtrMask) == StoredIdentifier">{{Identifier ({(clang::IdentifierInfo *)(Ptr &amp; ~PtrMask)})}}</DisplayString>

+    <DisplayString Condition="(Ptr &amp; PtrMask) == StoredObjCZeroArgSelector">{{ObjC Zero Arg Selector ({(clang::IdentifierInfo *)(Ptr &amp; ~PtrMask)})}}</DisplayString>

+    <DisplayString Condition="(Ptr &amp; PtrMask) == StoredObjCOneArgSelector">{{ObjC One Arg Selector ({(clang::IdentifierInfo *)(Ptr &amp; ~PtrMask)})}}</DisplayString>

+    <DisplayString Condition="(Ptr &amp; PtrMask) == StoredDeclarationNameExtra">{{Extra ({(clang::DeclarationNameExtra::ExtraKind)((clang::DeclarationNameExtra *)(Ptr &amp; ~PtrMask))-&gt;ExtraKindOrNumArgs})}}</DisplayString>

+    <Expand>

+      <Item Condition="(Ptr &amp; PtrMask) == StoredIdentifier" Name="[Identifier]">(clang::IdentifierInfo *)(Ptr &amp; ~PtrMask)</Item>

+      <Item Condition="(Ptr &amp; PtrMask) == StoredObjCZeroArgSelector" Name="[ObjC Zero Arg Selector]">(clang::IdentifierInfo *)(Ptr &amp; ~PtrMask)</Item>

+      <Item Condition="(Ptr &amp; PtrMask) == StoredObjCOneArgSelector" Name="[ObjC One Arg Selector]">(clang::IdentifierInfo *)(Ptr &amp; ~PtrMask)</Item>

+      <Item Condition="(Ptr &amp; PtrMask) == StoredDeclarationNameExtra" Name="[Extra]">(clang::DeclarationNameExtra::ExtraKind)((clang::DeclarationNameExtra *)(Ptr &amp; ~PtrMask))-&gt;ExtraKindOrNumArgs</Item>

+    </Expand>

+  </Type>

+  <Type Name="clang::Token">

+    <DisplayString>{(clang::tok::TokenKind)Kind}</DisplayString>

+  </Type>

+  <Type Name="clang::DeclSpec">

+    <DisplayString>[{(clang::DeclSpec::SCS)StorageClassSpec}], [{(clang::TypeSpecifierType)TypeSpecType}]</DisplayString>

+  </Type>

+  <Type Name="clang::PragmaHandler">

+    <DisplayString>{Name,s}</DisplayString>

+  </Type>

+  <Type Name="clang::FileEntry">

+    <DisplayString>{Name,s}</DisplayString>

+  </Type>

+  <Type Name="clang::DirectoryEntry">

+    <DisplayString>{Name,s}</DisplayString>

+  </Type>

+</AutoVisualizer>

diff --git a/utils/clangVisualizers.txt b/utils/clangVisualizers.txt
deleted file mode 100644
index 8019b9c..0000000
--- a/utils/clangVisualizers.txt
+++ /dev/null
@@ -1,391 +0,0 @@
-
-[Visualizer]
-
-llvm::SmallVector<*,*>{
-	preview (
-		#if ((($T1*)$e.EndX - ($T1*)$e.BeginX) == 0) ( "empty" )
-		#else (
-			#(
-				"[",
-				($T1*)$e.EndX - ($T1*)$e.BeginX,
-				"](",
-				#array(
-					expr: (($T1*)$e.BeginX)[$i],
-					size: ($T1*)$e.EndX - ($T1*)$e.BeginX
-				),
-				")"
-			)
-		)
-	)
-
-	children (
-		#(
-			#([size] : ($T1*)$e.EndX - ($T1*)$e.BeginX),
-			#([capacity] : ($T1*)$e.CapacityX - ($T1*)$e.BeginX),
-			#array(
-				expr: (($T1*)$e.BeginX)[$i],
-				size: ($T1*)$e.EndX - ($T1*)$e.BeginX
-			)
-		)
-	)
-}
-
-llvm::SmallVectorImpl<*>{
-	preview (
-		#if ((($T1*)$e.EndX - ($T1*)$e.BeginX) == 0) ( "empty" )
-		#else (
-			#(
-				"[",
-				($T1*)$e.EndX - ($T1*)$e.BeginX,
-				"](",
-				#array(
-					expr: (($T1*)$e.BeginX)[$i],
-					size: ($T1*)$e.EndX - ($T1*)$e.BeginX
-				),
-				")"
-			)
-		)
-	)
-
-	children (
-		#(
-			#([size] : ($T1*)$e.EndX - ($T1*)$e.BeginX),
-			#([capacity] : ($T1*)$e.CapacityX - ($T1*)$e.BeginX),
-			#array(
-				expr: (($T1*)$e.BeginX)[$i],
-				size: ($T1*)$e.EndX - ($T1*)$e.BeginX
-			)
-		)
-	)
-}
-
-llvm::SmallString<*>{
-	preview ([$e.BeginX,s])
-	stringview ([$e.BeginX,sb])
-}
-
-llvm::StringRef{
-	preview ([$e.Data,s])
-	stringview ([$e.Data,sb])
-
-	children (
-		#(
-			#([size] : $e.Length),
-			#array(expr: $e.Data[$i], size: $e.Length)
-		)
-	)
-}
-
-clang::Token{
-	preview((clang::tok::TokenKind)(int)$e.Kind)
-}
-
-llvm::PointerIntPair<*,*,*,*>{
-	preview (
-		#(
-			($T1*)($e.Value & $e.PointerBitMask),
-			" [",
-			($T3)(($e.Value >> $e.IntShift) & $e.IntMask),
-			"]"
-		)
-	)
-	
-	children (
-		#(
-			#([raw members] : [$e,!]),
-			#([ptr] : ($T1*)($e.Value & $e.PointerBitMask)),
-			#([int] : ($T3)($e.Value >> $e.IntShift) & $e.IntMask)
-		)
-	)
-}
-
-llvm::PointerUnion<*,*>{
-	preview (
-		#if ((($e.Val.Value >> $e.Val.IntShift) & $e.Val.IntMask) == 0) ( "PT1" )
-		#else ( "PT2" )
-	)
-	
-	children (
-		#(
-			#([raw members] : [$e,!]),
-			#if ((($e.Val.Value >> $e.Val.IntShift) & $e.Val.IntMask) == 0) (
-				#([ptr] : ($T1)($e.Val.Value & $e.Val.PointerBitMask))
-			) #else (
-				#([ptr] : ($T2)($e.Val.Value & $e.Val.PointerBitMask))
-			)
-		)
-	)
-}
-
-llvm::PointerUnion3<*,*,*>{
-	preview (
-		#if (($e.Val.Val.Value & 0x2) == 2) ( "PT2" )
-		#elif (($e.Val.Val.Value & 0x1) == 1) ( "PT3" )
-		#else ( "PT1" )
-	)
-	
-	children (
-		#(
-			#if (($e.Val.Val.Value & 0x2) == 2) (
-				#([ptr] : ($T2)(($e.Val.Val.Value >> 2) << 2))
-			) #elif (($e.Val.Val.Value & 0x1) == 1) (
-				#([ptr] : ($T3)(($e.Val.Val.Value >> 2) << 2))
-			) #else (
-				#([ptr] : ($T1)(($e.Val.Val.Value >> 2) << 2))
-			)
-		)
-	)
-}
-
-llvm::PointerUnion4<*,*,*,*>{
-	preview (
-		#if (($e.Val.Val.Value & 0x3) == 3) ( "PT4" )
-		#elif (($e.Val.Val.Value & 0x2) == 2) ( "PT2" )
-		#elif (($e.Val.Val.Value & 0x1) == 1) ( "PT3" )
-		#else ( "PT1" )
-	)
-	
-	children (
-		#(
-			#if (($e.Val.Val.Value & 0x3) == 3) (
-				#([ptr] : ($T4)(($e.Val.Val.Value >> 2) << 2))
-			) #elif (($e.Val.Val.Value & 0x2) == 2) (
-				#([ptr] : ($T2)(($e.Val.Val.Value >> 2) << 2))
-			) #elif (($e.Val.Val.Value & 0x1) == 1) (
-				#([ptr] : ($T3)(($e.Val.Val.Value >> 2) << 2))
-			) #else (
-				#([ptr] : ($T1)(($e.Val.Val.Value >> 2) << 2))
-			)
-		)
-	)
-}
-
-llvm::IntrusiveRefCntPtr<*>{
-	preview (
-		#if ($e.Obj == 0) ( "empty" )
-		#else (
-			#(
-				"[RefCnt=", $e.Obj->ref_cnt,
-				", ",
-				"Obj=", $e.Obj,
-				"]"
-			)
-		)
-	)
-
-	children (
-		#if ($e.Obj == 0) ( #array(expr: 0, size: 0) )
-		#else (
-			#(
-				#(RefCnt : $e.Obj->ref_cnt),
-				#(Obj : $e.Obj)
-			)
-		)
-	)
-}
-
-llvm::OwningPtr<*>{
-	preview (
-		#if ($e.Ptr == 0) ( "empty" )
-		#else ( $e.Ptr )
-	)
-
-	children (
-		#if ($e.Ptr == 0) ( #array(expr: 0, size: 0) )
-		#else ( #(Ptr : $e.Ptr) )
-	)	
-}
-
-llvm::SmallPtrSet<*,*>{
-	preview (
-		#(
-			#if (($e.CurArray) == ($e.SmallArray)) ( "[Small Mode] " )
-			#else ( "[Big Mode] " ),
-			"NumElements=", $e.NumElements,
-			" CurArraySize=", $e.CurArraySize
-		)
-	)
-
-	children (
-		#(
-			#([raw members] : [$c,!]),
-			#(NumElements : $e.NumElements),
-			#(CurArraySize : $e.CurArraySize),
-			#array(
-				expr: $e.CurArray[$i],
-				size: $e.CurArraySize + 1
-			) : ($T1*)&$e
-		)
-	)
-}
-
-llvm::DenseMap<*,*,*>{
-	preview (
-		#if ($e.NumEntries == 0) ( "empty" )
-		#else (
-			#(
-				"[NumEntries=", $e.NumEntries,
-				" NumBuckets=", $e.NumBuckets,
-				"]"
-			)
-		)
-	)
-
-	children (
-		#if ($e.NumEntries == 0) ( #array(expr: 0, size: 0) )
-		#else (
-			#(
-				#([raw members] : [$c,!]),
-				#(NumEntries : $e.NumEntries),
-				#(NumBuckets : $e.NumBuckets),
-				#array(
-					expr: $e.Buckets[$i],
-					size: $e.NumBuckets
-				)
-			)
-		)
-	)
-}
-
-llvm::StringMap<*,*>{
-	preview (
-		#(
-			"[NumBuckets=", $e.NumBuckets,
-			" ItemSize=", $e.ItemSize,
-			"]"
-		)
-	)
-
-	children (
-		#(
-			#([raw members] : [$c,!]),
-			#(NumBuckets : $e.NumBuckets),
-			#(ItemSize : $e.ItemSize),
-			#array(
-				expr: $e.TheTable[$i],
-				size: $e.NumBuckets,
-			) : (llvm::StringMapEntry<$T1>*)&$e
-		)
-	)
-}
-
-llvm::StringMapEntry<*>{
-	preview (
-		#if ($e.StrLen == 0) ( "empty" )
-		#else (	#(Entry : $e.second) )
-	)
-
-	children (
-		#if ($e.StrLen == 0) ( "empty" )
-		#else ( #(Entry : $e.second) )	
-	)
-}
-
-clang::DirectoryEntry|clang::FileEntry|clang::PragmaHandler{
-	preview ( [$e.Name,s] )
-	children (
-		#(
-			#([raw members] : [$c,!]),
-			#(Name : [$e.Name,s])
-		)
-	)
-}
-
-clang::DeclarationName{
-	preview (
-		; enum values from clang::DeclarationName::StoredNameKind
-		#if ($e.Ptr == 0) (
-			"empty"
-		) #elif (($e.Ptr & $e.PtrMask) == $e.StoredIdentifier) (
-			#else ( #("Identifier, ", (clang::IdentifierInfo*)($e.Ptr & ~$e.PtrMask)) )
-		) #elif (($e.Ptr & $e.PtrMask) == $e.StoredObjCZeroArgSelector) (
-			#("ZeroArgSelector, ", (clang::IdentifierInfo*)($e.Ptr & ~$e.PtrMask))
-		) #elif (($e.Ptr & $e.PtrMask) == $e.StoredObjCOneArgSelector) (
-			#("OneArgSelector, ", (clang::IdentifierInfo*)($e.Ptr & ~$e.PtrMask))
-		) #elif (($e.Ptr & $e.PtrMask) == $e.StoredDeclarationNameExtra) (
-			#switch (((clang::DeclarationNameExtra*)($e.Ptr & ~$e.PtrMask)).ExtraKindOrNumArgs)
-			#case 0 ( ;DeclarationNameExtra::CXXConstructor
-				#("CXXConstructorName, ", (clang::CXXSpecialName*)($e.Ptr & ~$e.PtrMask))
-			)
-			#case 1 ( ;DeclarationNameExtra::CXXDestructor
-				#("CXXDestructorName, ", (clang::CXXSpecialName*)($e.Ptr & ~$e.PtrMask))
-			)
-			#case 2 ( ;DeclarationNameExtra::CXXConversionFunction
-				#("CXXConversionFunctionName, ", (clang::CXXSpecialName*)($e.Ptr & ~$e.PtrMask))
-			)
-			#case 46 ( ;DeclarationNameExtra::CXXLiteralOperator
-				#("CXXLiteralOperatorName, ", (clang::CXXLiteralOperatorIdName*)($e.Ptr & ~$e.PtrMask))
-			)
-			#case 47 ( ;DeclarationNameExtra::CXXUsingDirective
-				#("CXXUsingDirective")	;TODO What to add here?
-			)
-			#default (
-				#if (((clang::DeclarationNameExtra*)($e.Ptr & ~$e.PtrMask)).ExtraKindOrNumArgs < 47) (
-					#("CXXOperatorName, ", (clang::CXXOperatorIdName*)($e.Ptr & ~$e.PtrMask))
-				) #else (
-					#("ObjCMultiArgSelector, ", (clang::MultiKeywordSelector*)($e.Ptr & ~$e.PtrMask))
-				)
-			)
-		)
-	)
-
-	children (
-		#(
-			; enum values from clang::DeclarationName::StoredNameKind
-			#if ($e.Ptr == 0) (
-				#array( expr: 0, size: 0 )
-			) #else (
-				#(
-					#([raw members] : [$e.Ptr,!]),
-					if (($e.Ptr & $e.PtrMask) == $e.StoredIdentifier) (
-						#(Ptr : (clang::IdentifierInfo*)($e.Ptr & ~$e.PtrMask))
-					) #elif (($e.Ptr & $e.PtrMask) == $e.StoredObjCZeroArgSelector) (
-						#(Ptr : (clang::IdentifierInfo*)($e.Ptr & ~$e.PtrMask))
-					) #elif (($e.Ptr & $e.PtrMask) == $e.StoredObjCOneArgSelector) (
-						#(Ptr : (clang::IdentifierInfo*)($e.Ptr & ~$e.PtrMask))
-					) #elif (($e.Ptr & $e.PtrMask) == $e.StoredDeclarationNameExtra) (
-						#switch (((clang::DeclarationNameExtra*)($e.Ptr & ~$e.PtrMask)).ExtraKindOrNumArgs)
-						#case 0 ( ;DeclarationNameExtra::CXXConstructor
-							#(Ptr : (clang::CXXSpecialName*)($e.Ptr & ~$e.PtrMask))
-						)
-						#case 1 ( ;DeclarationNameExtra::CXXDestructor
-							#(Ptr : (clang::CXXSpecialName*)($e.Ptr & ~$e.PtrMask))
-						)
-						#case 2 ( ;DeclarationNameExtra::CXXConversionFunction
-							#(Ptr : (clang::CXXSpecialName*)($e.Ptr & ~$e.PtrMask))
-						)
-						#case 46 ( ;DeclarationNameExtra::CXXLiteralOperator
-							#(Ptr : (clang::CXXLiteralOperatorIdName*)($e.Ptr & ~$e.PtrMask))
-						)
-						#case 47 ( ;DeclarationNameExtra::CXXUsingDirective
-							#(Ptr : $e.Ptr)	;TODO What to add here?
-						)
-						#default (
-							#if (((clang::DeclarationNameExtra*)($e.Ptr & ~$e.PtrMask)).ExtraKindOrNumArgs < 47) (
-								#(Ptr : (CXXOperatorIdName*)($e.Ptr & ~$e.PtrMask))
-							) #else (
-								#(Ptr : (clang::MultiKeywordSelector*)($e.Ptr & ~$e.PtrMask))
-							)
-						)
-					)
-				)
-			)
-		)
-	)
-}
-
-clang::DeclSpec{
-	preview (
-		#(
-			"[",
-			(clang::DeclSpec::SCS)$e.StorageClassSpec,
-			", ",
-			(clang::TypeSpecifierType)$e.TypeSpecType,
-			"]"
-		)
-	)
-}
-
-llvm::Triple{
-	preview ( $e.Data )
-}