blob: bddd51e9d1e4f8274d62b29cc1f15b699639a1d9 [file] [log] [blame]
Peter Collingbournebee583f2011-10-06 13:03:08 +00001//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These tablegen backends emit Clang attribute processing code
11//
12//===----------------------------------------------------------------------===//
13
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000014#include "llvm/ADT/ArrayRef.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000015#include "llvm/ADT/DenseMap.h"
George Burgess IV1881a572016-12-01 00:13:18 +000016#include "llvm/ADT/DenseSet.h"
Alex Lorenz3bfe9622017-04-18 10:46:41 +000017#include "llvm/ADT/STLExtras.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000018#include "llvm/ADT/SmallString.h"
Aaron Ballman28afa182014-11-17 18:17:19 +000019#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000020#include "llvm/ADT/StringRef.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000021#include "llvm/ADT/StringSet.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000022#include "llvm/ADT/StringSwitch.h"
Alex Lorenz9e7bf162017-04-18 14:33:39 +000023#include "llvm/ADT/iterator_range.h"
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000024#include "llvm/Support/ErrorHandling.h"
25#include "llvm/Support/raw_ostream.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000026#include "llvm/TableGen/Error.h"
Peter Collingbournebee583f2011-10-06 13:03:08 +000027#include "llvm/TableGen/Record.h"
Douglas Gregor377f99b2012-05-02 17:33:51 +000028#include "llvm/TableGen/StringMatcher.h"
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +000029#include "llvm/TableGen/TableGenBackend.h"
Peter Collingbournebee583f2011-10-06 13:03:08 +000030#include <algorithm>
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000031#include <cassert>
Peter Collingbournebee583f2011-10-06 13:03:08 +000032#include <cctype>
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000033#include <cstddef>
34#include <cstdint>
35#include <map>
Aaron Ballman8f1439b2014-03-05 16:49:55 +000036#include <memory>
Aaron Ballman80469032013-11-29 14:57:58 +000037#include <set>
Chandler Carruth5553d0d2014-01-07 11:51:46 +000038#include <sstream>
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000039#include <string>
40#include <utility>
41#include <vector>
Peter Collingbournebee583f2011-10-06 13:03:08 +000042
43using namespace llvm;
44
Benjamin Kramerd910d162015-03-10 18:24:01 +000045namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000046
Aaron Ballmanc669cc02014-01-27 22:10:04 +000047class FlattenedSpelling {
48 std::string V, N, NS;
49 bool K;
50
51public:
52 FlattenedSpelling(const std::string &Variety, const std::string &Name,
53 const std::string &Namespace, bool KnownToGCC) :
54 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
55 explicit FlattenedSpelling(const Record &Spelling) :
56 V(Spelling.getValueAsString("Variety")),
57 N(Spelling.getValueAsString("Name")) {
58
Aaron Ballmanffc43362017-10-26 12:19:02 +000059 assert(V != "GCC" && V != "Clang" &&
60 "Given a GCC spelling, which means this hasn't been flattened!");
Aaron Ballman606093a2017-10-15 15:01:42 +000061 if (V == "CXX11" || V == "C2x" || V == "Pragma")
Aaron Ballmanc669cc02014-01-27 22:10:04 +000062 NS = Spelling.getValueAsString("Namespace");
63 bool Unset;
64 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
65 }
66
67 const std::string &variety() const { return V; }
68 const std::string &name() const { return N; }
69 const std::string &nameSpace() const { return NS; }
70 bool knownToGCC() const { return K; }
71};
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +000072
Hans Wennborgdcfba332015-10-06 23:40:43 +000073} // end anonymous namespace
Aaron Ballmanc669cc02014-01-27 22:10:04 +000074
Benjamin Kramerd910d162015-03-10 18:24:01 +000075static std::vector<FlattenedSpelling>
76GetFlattenedSpellings(const Record &Attr) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +000077 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
78 std::vector<FlattenedSpelling> Ret;
79
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +000080 for (const auto &Spelling : Spellings) {
Aaron Ballmanffc43362017-10-26 12:19:02 +000081 StringRef Variety = Spelling->getValueAsString("Variety");
82 StringRef Name = Spelling->getValueAsString("Name");
83 if (Variety == "GCC") {
Aaron Ballmanc669cc02014-01-27 22:10:04 +000084 // Gin up two new spelling objects to add into the list.
Aaron Ballmanffc43362017-10-26 12:19:02 +000085 Ret.emplace_back("GNU", Name, "", true);
86 Ret.emplace_back("CXX11", Name, "gnu", true);
87 } else if (Variety == "Clang") {
88 Ret.emplace_back("GNU", Name, "", false);
89 Ret.emplace_back("CXX11", Name, "clang", false);
Aaron Ballman10007812018-01-03 22:22:48 +000090 if (Spelling->getValueAsBit("AllowInC"))
91 Ret.emplace_back("C2x", Name, "clang", false);
Aaron Ballmanc669cc02014-01-27 22:10:04 +000092 } else
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +000093 Ret.push_back(FlattenedSpelling(*Spelling));
Aaron Ballmanc669cc02014-01-27 22:10:04 +000094 }
95
96 return Ret;
97}
98
Peter Collingbournebee583f2011-10-06 13:03:08 +000099static std::string ReadPCHRecord(StringRef type) {
100 return StringSwitch<std::string>(type)
David L. Jones267b8842017-01-24 01:04:30 +0000101 .EndsWith("Decl *", "Record.GetLocalDeclAs<"
102 + std::string(type, 0, type.size()-1) + ">(Record.readInt())")
103 .Case("TypeSourceInfo *", "Record.getTypeSourceInfo()")
104 .Case("Expr *", "Record.readExpr()")
105 .Case("IdentifierInfo *", "Record.getIdentifierInfo()")
106 .Case("StringRef", "Record.readString()")
Joel E. Denny81508102018-03-13 14:51:22 +0000107 .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
David L. Jones267b8842017-01-24 01:04:30 +0000108 .Default("Record.readInt()");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000109}
110
Richard Smith19978562016-05-18 00:16:51 +0000111// Get a type that is suitable for storing an object of the specified type.
112static StringRef getStorageType(StringRef type) {
113 return StringSwitch<StringRef>(type)
114 .Case("StringRef", "std::string")
115 .Default(type);
116}
117
Peter Collingbournebee583f2011-10-06 13:03:08 +0000118// Assumes that the way to get the value is SA->getname()
119static std::string WritePCHRecord(StringRef type, StringRef name) {
Richard Smith290d8012016-04-06 17:06:00 +0000120 return "Record." + StringSwitch<std::string>(type)
121 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
122 .Case("TypeSourceInfo *", "AddTypeSourceInfo(" + std::string(name) + ");\n")
Peter Collingbournebee583f2011-10-06 13:03:08 +0000123 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
Richard Smith290d8012016-04-06 17:06:00 +0000124 .Case("IdentifierInfo *", "AddIdentifierRef(" + std::string(name) + ");\n")
125 .Case("StringRef", "AddString(" + std::string(name) + ");\n")
Joel E. Denny81508102018-03-13 14:51:22 +0000126 .Case("ParamIdx", "push_back(" + std::string(name) + ".serialize());\n")
Richard Smith290d8012016-04-06 17:06:00 +0000127 .Default("push_back(" + std::string(name) + ");\n");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000128}
129
Michael Han4a045172012-03-07 00:12:16 +0000130// Normalize attribute name by removing leading and trailing
131// underscores. For example, __foo, foo__, __foo__ would
132// become foo.
133static StringRef NormalizeAttrName(StringRef AttrName) {
George Burgess IV1881a572016-12-01 00:13:18 +0000134 AttrName.consume_front("__");
135 AttrName.consume_back("__");
Michael Han4a045172012-03-07 00:12:16 +0000136 return AttrName;
137}
138
Aaron Ballman36a53502014-01-16 13:03:14 +0000139// Normalize the name by removing any and all leading and trailing underscores.
140// This is different from NormalizeAttrName in that it also handles names like
141// _pascal and __pascal.
142static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
Benjamin Kramer5c404072015-04-10 21:37:21 +0000143 return Name.trim("_");
Aaron Ballman36a53502014-01-16 13:03:14 +0000144}
145
Justin Lebar4086fe52017-01-05 16:51:54 +0000146// Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
147// removing "__" if it appears at the beginning and end of the attribute's name.
148static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
Michael Han4a045172012-03-07 00:12:16 +0000149 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
150 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
151 }
152
153 return AttrSpelling;
154}
155
Aaron Ballman2f22b942014-05-20 19:47:14 +0000156typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
Aaron Ballman64e69862013-12-15 13:05:48 +0000157
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000158static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
Craig Topper8ae12032014-05-07 06:21:57 +0000159 ParsedAttrMap *Dupes = nullptr) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000160 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Aaron Ballman64e69862013-12-15 13:05:48 +0000161 std::set<std::string> Seen;
162 ParsedAttrMap R;
Aaron Ballman2f22b942014-05-20 19:47:14 +0000163 for (const auto *Attr : Attrs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000164 if (Attr->getValueAsBit("SemaHandler")) {
Aaron Ballman64e69862013-12-15 13:05:48 +0000165 std::string AN;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000166 if (Attr->isSubClassOf("TargetSpecificAttr") &&
167 !Attr->isValueUnset("ParseKind")) {
168 AN = Attr->getValueAsString("ParseKind");
Aaron Ballman64e69862013-12-15 13:05:48 +0000169
170 // If this attribute has already been handled, it does not need to be
171 // handled again.
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000172 if (Seen.find(AN) != Seen.end()) {
173 if (Dupes)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000174 Dupes->push_back(std::make_pair(AN, Attr));
Aaron Ballman64e69862013-12-15 13:05:48 +0000175 continue;
Aaron Ballmanab7691c2014-01-09 22:48:32 +0000176 }
Aaron Ballman64e69862013-12-15 13:05:48 +0000177 Seen.insert(AN);
178 } else
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000179 AN = NormalizeAttrName(Attr->getName()).str();
Aaron Ballman64e69862013-12-15 13:05:48 +0000180
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000181 R.push_back(std::make_pair(AN, Attr));
Aaron Ballman64e69862013-12-15 13:05:48 +0000182 }
183 }
184 return R;
185}
186
Peter Collingbournebee583f2011-10-06 13:03:08 +0000187namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000188
Peter Collingbournebee583f2011-10-06 13:03:08 +0000189 class Argument {
190 std::string lowerName, upperName;
191 StringRef attrName;
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000192 bool isOpt;
John McCalla62c1a92015-10-28 00:17:34 +0000193 bool Fake;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000194
195 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000196 Argument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000197 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
John McCalla62c1a92015-10-28 00:17:34 +0000198 attrName(Attr), isOpt(false), Fake(false) {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000199 if (!lowerName.empty()) {
200 lowerName[0] = std::tolower(lowerName[0]);
201 upperName[0] = std::toupper(upperName[0]);
202 }
Reid Klecknerebeb0ca2016-05-31 17:42:56 +0000203 // Work around MinGW's macro definition of 'interface' to 'struct'. We
204 // have an attribute argument called 'Interface', so only the lower case
205 // name conflicts with the macro definition.
206 if (lowerName == "interface")
207 lowerName = "interface_";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000208 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000209 virtual ~Argument() = default;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000210
211 StringRef getLowerName() const { return lowerName; }
212 StringRef getUpperName() const { return upperName; }
213 StringRef getAttrName() const { return attrName; }
214
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000215 bool isOptional() const { return isOpt; }
216 void setOptional(bool set) { isOpt = set; }
217
John McCalla62c1a92015-10-28 00:17:34 +0000218 bool isFake() const { return Fake; }
219 void setFake(bool fake) { Fake = fake; }
220
Peter Collingbournebee583f2011-10-06 13:03:08 +0000221 // These functions print the argument contents formatted in different ways.
222 virtual void writeAccessors(raw_ostream &OS) const = 0;
223 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +0000224 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000225 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000226 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
Daniel Dunbardc51baa2012-02-10 06:00:29 +0000227 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000228 virtual void writeCtorBody(raw_ostream &OS) const {}
229 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000230 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000231 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
232 virtual void writeDeclarations(raw_ostream &OS) const = 0;
233 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
234 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
235 virtual void writePCHWrite(raw_ostream &OS) const = 0;
Aaron Ballman48a533d2018-02-27 23:49:28 +0000236 virtual std::string getIsOmitted() const { return "false"; }
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000237 virtual void writeValue(raw_ostream &OS) const = 0;
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000238 virtual void writeDump(raw_ostream &OS) const = 0;
239 virtual void writeDumpChildren(raw_ostream &OS) const {}
Richard Trieude5cc7d2013-01-31 01:44:26 +0000240 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
Aaron Ballman682ee422013-09-11 19:47:58 +0000241
242 virtual bool isEnumArg() const { return false; }
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000243 virtual bool isVariadicEnumArg() const { return false; }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000244 virtual bool isVariadic() const { return false; }
Aaron Ballman36a53502014-01-16 13:03:14 +0000245
246 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
247 OS << getUpperName();
248 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000249 };
250
251 class SimpleArgument : public Argument {
252 std::string type;
253
254 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000255 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000256 : Argument(Arg, Attr), type(std::move(T)) {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000257
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000258 std::string getType() const { return type; }
259
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000260 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000261 OS << " " << type << " get" << getUpperName() << "() const {\n";
262 OS << " return " << getLowerName() << ";\n";
263 OS << " }";
264 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000265
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000266 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000267 OS << getLowerName();
268 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000269
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000270 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000271 OS << "A->get" << getUpperName() << "()";
272 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000273
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000274 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000275 OS << getLowerName() << "(" << getUpperName() << ")";
276 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000277
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000278 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000279 OS << getLowerName() << "()";
280 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000281
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000282 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000283 OS << type << " " << getUpperName();
284 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000285
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000286 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000287 OS << type << " " << getLowerName() << ";";
288 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000289
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000290 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000291 std::string read = ReadPCHRecord(type);
292 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
293 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000294
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000295 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000296 OS << getLowerName();
297 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000298
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000299 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000300 OS << " " << WritePCHRecord(type, "SA->get" +
301 std::string(getUpperName()) + "()");
302 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000303
Aaron Ballman48a533d2018-02-27 23:49:28 +0000304 std::string getIsOmitted() const override {
305 if (type == "IdentifierInfo *")
306 return "!get" + getUpperName().str() + "()";
Joel E. Denny81508102018-03-13 14:51:22 +0000307 if (type == "ParamIdx")
308 return "!get" + getUpperName().str() + "().isValid()";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000309 return "false";
310 }
311
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000312 void writeValue(raw_ostream &OS) const override {
Aaron Ballman48a533d2018-02-27 23:49:28 +0000313 if (type == "FunctionDecl *")
Richard Smithb87c4652013-10-31 21:23:20 +0000314 OS << "\" << get" << getUpperName()
315 << "()->getNameInfo().getAsString() << \"";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000316 else if (type == "IdentifierInfo *")
317 // Some non-optional (comma required) identifier arguments can be the
318 // empty string but are then recorded as a nullptr.
319 OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
320 << "()->getName() : \"\") << \"";
321 else if (type == "TypeSourceInfo *")
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000322 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
Joel E. Denny81508102018-03-13 14:51:22 +0000323 else if (type == "ParamIdx")
324 OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000325 else
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000326 OS << "\" << get" << getUpperName() << "() << \"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000327 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000328
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000329 void writeDump(raw_ostream &OS) const override {
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +0000330 if (type == "FunctionDecl *" || type == "NamedDecl *") {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000331 OS << " OS << \" \";\n";
332 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
333 } else if (type == "IdentifierInfo *") {
Aaron Ballman48a533d2018-02-27 23:49:28 +0000334 // Some non-optional (comma required) identifier arguments can be the
335 // empty string but are then recorded as a nullptr.
336 OS << " if (SA->get" << getUpperName() << "())\n"
337 << " OS << \" \" << SA->get" << getUpperName()
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000338 << "()->getName();\n";
Richard Smithb87c4652013-10-31 21:23:20 +0000339 } else if (type == "TypeSourceInfo *") {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000340 OS << " OS << \" \" << SA->get" << getUpperName()
341 << "().getAsString();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000342 } else if (type == "bool") {
343 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
344 << getUpperName() << "\";\n";
345 } else if (type == "int" || type == "unsigned") {
346 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
Joel E. Denny81508102018-03-13 14:51:22 +0000347 } else if (type == "ParamIdx") {
348 if (isOptional())
349 OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
350 OS << " OS << \" \" << SA->get" << getUpperName()
351 << "().getSourceIndex();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000352 } else {
353 llvm_unreachable("Unknown SimpleArgument type!");
354 }
355 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000356 };
357
Aaron Ballman18a78382013-11-21 00:28:23 +0000358 class DefaultSimpleArgument : public SimpleArgument {
359 int64_t Default;
360
361 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000362 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
Aaron Ballman18a78382013-11-21 00:28:23 +0000363 std::string T, int64_t Default)
364 : SimpleArgument(Arg, Attr, T), Default(Default) {}
365
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000366 void writeAccessors(raw_ostream &OS) const override {
Aaron Ballman18a78382013-11-21 00:28:23 +0000367 SimpleArgument::writeAccessors(OS);
368
369 OS << "\n\n static const " << getType() << " Default" << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000370 << " = ";
371 if (getType() == "bool")
372 OS << (Default != 0 ? "true" : "false");
373 else
374 OS << Default;
375 OS << ";";
Aaron Ballman18a78382013-11-21 00:28:23 +0000376 }
377 };
378
Peter Collingbournebee583f2011-10-06 13:03:08 +0000379 class StringArgument : public Argument {
380 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000381 StringArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000382 : Argument(Arg, Attr)
383 {}
384
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000385 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000386 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
387 OS << " return llvm::StringRef(" << getLowerName() << ", "
388 << getLowerName() << "Length);\n";
389 OS << " }\n";
390 OS << " unsigned get" << getUpperName() << "Length() const {\n";
391 OS << " return " << getLowerName() << "Length;\n";
392 OS << " }\n";
393 OS << " void set" << getUpperName()
394 << "(ASTContext &C, llvm::StringRef S) {\n";
395 OS << " " << getLowerName() << "Length = S.size();\n";
396 OS << " this->" << getLowerName() << " = new (C, 1) char ["
397 << getLowerName() << "Length];\n";
Chandler Carruth38a45cc2015-08-04 03:53:01 +0000398 OS << " if (!S.empty())\n";
399 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
Peter Collingbournebee583f2011-10-06 13:03:08 +0000400 << getLowerName() << "Length);\n";
401 OS << " }";
402 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000403
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000404 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000405 OS << "get" << getUpperName() << "()";
406 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000407
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000408 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000409 OS << "A->get" << getUpperName() << "()";
410 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000411
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000412 void writeCtorBody(raw_ostream &OS) const override {
Chandler Carruth38a45cc2015-08-04 03:53:01 +0000413 OS << " if (!" << getUpperName() << ".empty())\n";
414 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000415 << ".data(), " << getLowerName() << "Length);\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000416 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000417
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000418 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000419 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
420 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
421 << "Length])";
422 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000423
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000424 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Hans Wennborg59dbe862015-09-29 20:56:43 +0000425 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000426 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000427
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000428 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000429 OS << "llvm::StringRef " << getUpperName();
430 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000431
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000432 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000433 OS << "unsigned " << getLowerName() << "Length;\n";
434 OS << "char *" << getLowerName() << ";";
435 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000436
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000437 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000438 OS << " std::string " << getLowerName()
David L. Jones267b8842017-01-24 01:04:30 +0000439 << "= Record.readString();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000440 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000441
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000442 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000443 OS << getLowerName();
444 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000445
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000446 void writePCHWrite(raw_ostream &OS) const override {
Richard Smith290d8012016-04-06 17:06:00 +0000447 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000448 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000449
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000450 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000451 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
452 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000453
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000454 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000455 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
456 << "() << \"\\\"\";\n";
457 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000458 };
459
460 class AlignedArgument : public Argument {
461 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000462 AlignedArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000463 : Argument(Arg, Attr)
464 {}
465
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000466 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000467 OS << " bool is" << getUpperName() << "Dependent() const;\n";
468
469 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
470
471 OS << " bool is" << getUpperName() << "Expr() const {\n";
472 OS << " return is" << getLowerName() << "Expr;\n";
473 OS << " }\n";
474
475 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
476 OS << " assert(is" << getLowerName() << "Expr);\n";
477 OS << " return " << getLowerName() << "Expr;\n";
478 OS << " }\n";
479
480 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
481 OS << " assert(!is" << getLowerName() << "Expr);\n";
482 OS << " return " << getLowerName() << "Type;\n";
483 OS << " }";
484 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000485
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000486 void writeAccessorDefinitions(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000487 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
488 << "Dependent() const {\n";
489 OS << " if (is" << getLowerName() << "Expr)\n";
490 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
491 << "Expr->isValueDependent() || " << getLowerName()
492 << "Expr->isTypeDependent());\n";
493 OS << " else\n";
494 OS << " return " << getLowerName()
495 << "Type->getType()->isDependentType();\n";
496 OS << "}\n";
497
498 // FIXME: Do not do the calculation here
499 // FIXME: Handle types correctly
500 // A null pointer means maximum alignment
Peter Collingbournebee583f2011-10-06 13:03:08 +0000501 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
502 << "(ASTContext &Ctx) const {\n";
503 OS << " assert(!is" << getUpperName() << "Dependent());\n";
504 OS << " if (is" << getLowerName() << "Expr)\n";
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +0000505 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
506 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
507 << " * Ctx.getCharWidth() : "
508 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000509 OS << " else\n";
510 OS << " return 0; // FIXME\n";
511 OS << "}\n";
512 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000513
Richard Smithf26d5512017-08-15 22:58:45 +0000514 void writeASTVisitorTraversal(raw_ostream &OS) const override {
515 StringRef Name = getUpperName();
516 OS << " if (A->is" << Name << "Expr()) {\n"
517 << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
518 << " return false;\n"
519 << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
520 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
521 << " return false;\n"
522 << " }\n";
523 }
524
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000525 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000526 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
527 << "Expr ? static_cast<void*>(" << getLowerName()
528 << "Expr) : " << getLowerName()
529 << "Type";
530 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000531
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000532 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000533 // FIXME: move the definition in Sema::InstantiateAttrs to here.
534 // In the meantime, aligned attributes are cloned.
535 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000536
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000537 void writeCtorBody(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000538 OS << " if (is" << getLowerName() << "Expr)\n";
539 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
540 << getUpperName() << ");\n";
541 OS << " else\n";
542 OS << " " << getLowerName()
543 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000544 << ");\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000545 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000546
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000547 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000548 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
549 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000550
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000551 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000552 OS << "is" << getLowerName() << "Expr(false)";
553 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000554
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000555 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000556 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
557 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000558
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000559 void writeImplicitCtorArgs(raw_ostream &OS) const override {
Aaron Ballman36a53502014-01-16 13:03:14 +0000560 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
561 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000562
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000563 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000564 OS << "bool is" << getLowerName() << "Expr;\n";
565 OS << "union {\n";
566 OS << "Expr *" << getLowerName() << "Expr;\n";
567 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
568 OS << "};";
569 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000570
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000571 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000572 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
573 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000574
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000575 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000576 OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000577 OS << " void *" << getLowerName() << "Ptr;\n";
578 OS << " if (is" << getLowerName() << "Expr)\n";
David L. Jones267b8842017-01-24 01:04:30 +0000579 OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000580 OS << " else\n";
581 OS << " " << getLowerName()
David L. Jones267b8842017-01-24 01:04:30 +0000582 << "Ptr = Record.getTypeSourceInfo();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000583 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000584
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000585 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000586 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
587 OS << " if (SA->is" << getUpperName() << "Expr())\n";
Richard Smith290d8012016-04-06 17:06:00 +0000588 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000589 OS << " else\n";
Richard Smith290d8012016-04-06 17:06:00 +0000590 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
591 << "Type());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000592 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000593
Aaron Ballman48a533d2018-02-27 23:49:28 +0000594 std::string getIsOmitted() const override {
595 return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
596 + "Expr";
597 }
598
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000599 void writeValue(raw_ostream &OS) const override {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000600 OS << "\";\n";
Aaron Ballman48a533d2018-02-27 23:49:28 +0000601 OS << " " << getLowerName()
602 << "Expr->printPretty(OS, nullptr, Policy);\n";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000603 OS << " OS << \"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000604 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000605
606 void writeDump(raw_ostream &OS) const override {}
607
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000608 void writeDumpChildren(raw_ostream &OS) const override {
Richard Smithf7514452014-10-30 21:02:37 +0000609 OS << " if (SA->is" << getUpperName() << "Expr())\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000610 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
Richard Smithf7514452014-10-30 21:02:37 +0000611 OS << " else\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000612 OS << " dumpType(SA->get" << getUpperName()
613 << "Type()->getType());\n";
614 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000615
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000616 void writeHasChildren(raw_ostream &OS) const override {
Richard Trieude5cc7d2013-01-31 01:44:26 +0000617 OS << "SA->is" << getUpperName() << "Expr()";
618 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000619 };
620
621 class VariadicArgument : public Argument {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000622 std::string Type, ArgName, ArgSizeName, RangeName;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000623
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000624 protected:
625 // Assumed to receive a parameter: raw_ostream OS.
626 virtual void writeValueImpl(raw_ostream &OS) const {
627 OS << " OS << Val;\n";
628 }
Joel E. Denny81508102018-03-13 14:51:22 +0000629 // Assumed to receive a parameter: raw_ostream OS.
630 virtual void writeDumpImpl(raw_ostream &OS) const {
631 OS << " OS << \" \" << Val;\n";
632 }
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000633
Peter Collingbournebee583f2011-10-06 13:03:08 +0000634 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000635 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000636 : Argument(Arg, Attr), Type(std::move(T)),
637 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
638 RangeName(getLowerName()) {}
Peter Collingbournebee583f2011-10-06 13:03:08 +0000639
Benjamin Kramer1b582012016-02-13 18:11:49 +0000640 const std::string &getType() const { return Type; }
641 const std::string &getArgName() const { return ArgName; }
642 const std::string &getArgSizeName() const { return ArgSizeName; }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000643 bool isVariadic() const override { return true; }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000644
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000645 void writeAccessors(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000646 std::string IteratorType = getLowerName().str() + "_iterator";
647 std::string BeginFn = getLowerName().str() + "_begin()";
648 std::string EndFn = getLowerName().str() + "_end()";
649
650 OS << " typedef " << Type << "* " << IteratorType << ";\n";
651 OS << " " << IteratorType << " " << BeginFn << " const {"
652 << " return " << ArgName << "; }\n";
653 OS << " " << IteratorType << " " << EndFn << " const {"
654 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
655 OS << " unsigned " << getLowerName() << "_size() const {"
656 << " return " << ArgSizeName << "; }\n";
657 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
658 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
659 << "); }\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000660 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000661
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000662 void writeCloneArgs(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000663 OS << ArgName << ", " << ArgSizeName;
Peter Collingbournebee583f2011-10-06 13:03:08 +0000664 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000665
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000666 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000667 // This isn't elegant, but we have to go through public methods...
668 OS << "A->" << getLowerName() << "_begin(), "
669 << "A->" << getLowerName() << "_size()";
670 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000671
Richard Smithf26d5512017-08-15 22:58:45 +0000672 void writeASTVisitorTraversal(raw_ostream &OS) const override {
673 // FIXME: Traverse the elements.
674 }
675
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000676 void writeCtorBody(raw_ostream &OS) const override {
Aaron Ballmand6459e52014-05-01 15:21:03 +0000677 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000678 << " + " << ArgSizeName << ", " << ArgName << ");\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000679 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000680
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000681 void writeCtorInitializers(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000682 OS << ArgSizeName << "(" << getUpperName() << "Size), "
683 << ArgName << "(new (Ctx, 16) " << getType() << "["
684 << ArgSizeName << "])";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000685 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000686
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000687 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000688 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000689 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000690
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000691 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000692 OS << getType() << " *" << getUpperName() << ", unsigned "
693 << getUpperName() << "Size";
694 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000695
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000696 void writeImplicitCtorArgs(raw_ostream &OS) const override {
Aaron Ballman36a53502014-01-16 13:03:14 +0000697 OS << getUpperName() << ", " << getUpperName() << "Size";
698 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000699
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000700 void writeDeclarations(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000701 OS << " unsigned " << ArgSizeName << ";\n";
702 OS << " " << getType() << " *" << ArgName << ";";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000703 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000704
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000705 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000706 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
Richard Smith19978562016-05-18 00:16:51 +0000707 OS << " SmallVector<" << getType() << ", 4> "
708 << getLowerName() << ";\n";
709 OS << " " << getLowerName() << ".reserve(" << getLowerName()
Peter Collingbournebee583f2011-10-06 13:03:08 +0000710 << "Size);\n";
Richard Smith19978562016-05-18 00:16:51 +0000711
712 // If we can't store the values in the current type (if it's something
713 // like StringRef), store them in a different type and convert the
714 // container afterwards.
715 std::string StorageType = getStorageType(getType());
716 std::string StorageName = getLowerName();
717 if (StorageType != getType()) {
718 StorageName += "Storage";
719 OS << " SmallVector<" << StorageType << ", 4> "
720 << StorageName << ";\n";
721 OS << " " << StorageName << ".reserve(" << getLowerName()
722 << "Size);\n";
723 }
724
725 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000726 std::string read = ReadPCHRecord(Type);
Richard Smith19978562016-05-18 00:16:51 +0000727 OS << " " << StorageName << ".push_back(" << read << ");\n";
728
729 if (StorageType != getType()) {
730 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
731 OS << " " << getLowerName() << ".push_back("
732 << StorageName << "[i]);\n";
733 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000734 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000735
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000736 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000737 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
738 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000739
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000740 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000741 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000742 OS << " for (auto &Val : SA->" << RangeName << "())\n";
743 OS << " " << WritePCHRecord(Type, "Val");
Peter Collingbournebee583f2011-10-06 13:03:08 +0000744 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000745
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000746 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000747 OS << "\";\n";
748 OS << " bool isFirst = true;\n"
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000749 << " for (const auto &Val : " << RangeName << "()) {\n"
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000750 << " if (isFirst) isFirst = false;\n"
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000751 << " else OS << \", \";\n";
752 writeValueImpl(OS);
753 OS << " }\n";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000754 OS << " OS << \"";
755 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000756
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000757 void writeDump(raw_ostream &OS) const override {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000758 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
Joel E. Denny81508102018-03-13 14:51:22 +0000759 writeDumpImpl(OS);
760 }
761 };
762
763 class VariadicParamIdxArgument : public VariadicArgument {
764 public:
765 VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
766 : VariadicArgument(Arg, Attr, "ParamIdx") {}
767
768 public:
769 void writeValueImpl(raw_ostream &OS) const override {
770 OS << " OS << Val.getSourceIndex();\n";
771 }
772
773 void writeDumpImpl(raw_ostream &OS) const override {
774 OS << " OS << \" \" << Val.getSourceIndex();\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000775 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000776 };
777
Reid Klecknerf526b9482014-02-12 18:22:18 +0000778 // Unique the enums, but maintain the original declaration ordering.
Craig Topper00648582017-05-31 19:01:22 +0000779 std::vector<StringRef>
780 uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
781 std::vector<StringRef> uniques;
George Burgess IV1881a572016-12-01 00:13:18 +0000782 SmallDenseSet<StringRef, 8> unique_set;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000783 for (const auto &i : enums) {
George Burgess IV1881a572016-12-01 00:13:18 +0000784 if (unique_set.insert(i).second)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000785 uniques.push_back(i);
Reid Klecknerf526b9482014-02-12 18:22:18 +0000786 }
787 return uniques;
788 }
789
Peter Collingbournebee583f2011-10-06 13:03:08 +0000790 class EnumArgument : public Argument {
791 std::string type;
Craig Topper00648582017-05-31 19:01:22 +0000792 std::vector<StringRef> values, enums, uniques;
793
Peter Collingbournebee583f2011-10-06 13:03:08 +0000794 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000795 EnumArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +0000796 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
Aaron Ballman0e468c02014-01-05 21:08:29 +0000797 values(Arg.getValueAsListOfStrings("Values")),
798 enums(Arg.getValueAsListOfStrings("Enums")),
Reid Klecknerf526b9482014-02-12 18:22:18 +0000799 uniques(uniqueEnumsInOrder(enums))
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000800 {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000801 // FIXME: Emit a proper error
802 assert(!uniques.empty());
803 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000804
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000805 bool isEnumArg() const override { return true; }
Aaron Ballman682ee422013-09-11 19:47:58 +0000806
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000807 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000808 OS << " " << type << " get" << getUpperName() << "() const {\n";
809 OS << " return " << getLowerName() << ";\n";
810 OS << " }";
811 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000812
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000813 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000814 OS << getLowerName();
815 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000816
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000817 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +0000818 OS << "A->get" << getUpperName() << "()";
819 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000820 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000821 OS << getLowerName() << "(" << getUpperName() << ")";
822 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000823 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +0000824 OS << getLowerName() << "(" << type << "(0))";
825 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000826 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000827 OS << type << " " << getUpperName();
828 }
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000829 void writeDeclarations(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +0000830 auto i = uniques.cbegin(), e = uniques.cend();
Peter Collingbournebee583f2011-10-06 13:03:08 +0000831 // The last one needs to not have a comma.
832 --e;
833
834 OS << "public:\n";
835 OS << " enum " << type << " {\n";
836 for (; i != e; ++i)
837 OS << " " << *i << ",\n";
838 OS << " " << *e << "\n";
839 OS << " };\n";
840 OS << "private:\n";
841 OS << " " << type << " " << getLowerName() << ";";
842 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000843
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000844 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000845 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
846 << "(static_cast<" << getAttrName() << "Attr::" << type
David L. Jones267b8842017-01-24 01:04:30 +0000847 << ">(Record.readInt()));\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +0000848 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000849
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000850 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000851 OS << getLowerName();
852 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000853
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000854 void writePCHWrite(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +0000855 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
856 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000857
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000858 void writeValue(raw_ostream &OS) const override {
Aaron Ballman36d79102014-09-15 16:16:14 +0000859 // FIXME: this isn't 100% correct -- some enum arguments require printing
860 // as a string literal, while others require printing as an identifier.
861 // Tablegen currently does not distinguish between the two forms.
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000862 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
863 << getUpperName() << "()) << \"\\\"";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +0000864 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000865
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000866 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000867 OS << " switch(SA->get" << getUpperName() << "()) {\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000868 for (const auto &I : uniques) {
869 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
870 OS << " OS << \" " << I << "\";\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +0000871 OS << " break;\n";
872 }
873 OS << " }\n";
874 }
Aaron Ballman682ee422013-09-11 19:47:58 +0000875
876 void writeConversion(raw_ostream &OS) const {
877 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
878 OS << type << " &Out) {\n";
879 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000880 OS << type << ">>(Val)\n";
Aaron Ballman682ee422013-09-11 19:47:58 +0000881 for (size_t I = 0; I < enums.size(); ++I) {
882 OS << " .Case(\"" << values[I] << "\", ";
883 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
884 }
885 OS << " .Default(Optional<" << type << ">());\n";
886 OS << " if (R) {\n";
887 OS << " Out = *R;\n return true;\n }\n";
888 OS << " return false;\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000889 OS << " }\n\n";
890
891 // Mapping from enumeration values back to enumeration strings isn't
892 // trivial because some enumeration values have multiple named
893 // enumerators, such as type_visibility(internal) and
894 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
895 OS << " static const char *Convert" << type << "ToStr("
896 << type << " Val) {\n"
897 << " switch(Val) {\n";
George Burgess IV1881a572016-12-01 00:13:18 +0000898 SmallDenseSet<StringRef, 8> Uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000899 for (size_t I = 0; I < enums.size(); ++I) {
900 if (Uniques.insert(enums[I]).second)
901 OS << " case " << getAttrName() << "Attr::" << enums[I]
902 << ": return \"" << values[I] << "\";\n";
903 }
904 OS << " }\n"
905 << " llvm_unreachable(\"No enumerator with that value\");\n"
906 << " }\n";
Aaron Ballman682ee422013-09-11 19:47:58 +0000907 }
Peter Collingbournebee583f2011-10-06 13:03:08 +0000908 };
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000909
910 class VariadicEnumArgument: public VariadicArgument {
911 std::string type, QualifiedTypeName;
Craig Topper00648582017-05-31 19:01:22 +0000912 std::vector<StringRef> values, enums, uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000913
914 protected:
915 void writeValueImpl(raw_ostream &OS) const override {
Aaron Ballman36d79102014-09-15 16:16:14 +0000916 // FIXME: this isn't 100% correct -- some enum arguments require printing
917 // as a string literal, while others require printing as an identifier.
918 // Tablegen currently does not distinguish between the two forms.
Aaron Ballman25a2cb92014-09-15 15:14:13 +0000919 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
920 << "ToStr(Val)" << "<< \"\\\"\";\n";
921 }
922
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000923 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +0000924 VariadicEnumArgument(const Record &Arg, StringRef Attr)
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000925 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
926 type(Arg.getValueAsString("Type")),
Aaron Ballman0e468c02014-01-05 21:08:29 +0000927 values(Arg.getValueAsListOfStrings("Values")),
928 enums(Arg.getValueAsListOfStrings("Enums")),
Reid Klecknerf526b9482014-02-12 18:22:18 +0000929 uniques(uniqueEnumsInOrder(enums))
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000930 {
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000931 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
932
933 // FIXME: Emit a proper error
934 assert(!uniques.empty());
935 }
936
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000937 bool isVariadicEnumArg() const override { return true; }
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000938
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000939 void writeDeclarations(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +0000940 auto i = uniques.cbegin(), e = uniques.cend();
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000941 // The last one needs to not have a comma.
942 --e;
943
944 OS << "public:\n";
945 OS << " enum " << type << " {\n";
946 for (; i != e; ++i)
947 OS << " " << *i << ",\n";
948 OS << " " << *e << "\n";
949 OS << " };\n";
950 OS << "private:\n";
951
952 VariadicArgument::writeDeclarations(OS);
953 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000954
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000955 void writeDump(raw_ostream &OS) const override {
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000956 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
957 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
958 << getLowerName() << "_end(); I != E; ++I) {\n";
959 OS << " switch(*I) {\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000960 for (const auto &UI : uniques) {
961 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
962 OS << " OS << \" " << UI << "\";\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000963 OS << " break;\n";
964 }
965 OS << " }\n";
966 OS << " }\n";
967 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000968
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000969 void writePCHReadDecls(raw_ostream &OS) const override {
David L. Jones267b8842017-01-24 01:04:30 +0000970 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000971 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
972 << ";\n";
973 OS << " " << getLowerName() << ".reserve(" << getLowerName()
974 << "Size);\n";
975 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
976 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
David L. Jones267b8842017-01-24 01:04:30 +0000977 << QualifiedTypeName << ">(Record.readInt()));\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000978 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000979
Aaron Ballman8cbf6332014-03-06 15:09:50 +0000980 void writePCHWrite(raw_ostream &OS) const override {
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000981 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
982 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
983 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
984 << getLowerName() << "_end(); i != e; ++i)\n";
985 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
986 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +0000987
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000988 void writeConversion(raw_ostream &OS) const {
989 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
990 OS << type << " &Out) {\n";
991 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +0000992 OS << type << ">>(Val)\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000993 for (size_t I = 0; I < enums.size(); ++I) {
994 OS << " .Case(\"" << values[I] << "\", ";
995 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
996 }
997 OS << " .Default(Optional<" << type << ">());\n";
998 OS << " if (R) {\n";
999 OS << " Out = *R;\n return true;\n }\n";
1000 OS << " return false;\n";
Aaron Ballman25a2cb92014-09-15 15:14:13 +00001001 OS << " }\n\n";
1002
1003 OS << " static const char *Convert" << type << "ToStr("
1004 << type << " Val) {\n"
1005 << " switch(Val) {\n";
George Burgess IV1881a572016-12-01 00:13:18 +00001006 SmallDenseSet<StringRef, 8> Uniques;
Aaron Ballman25a2cb92014-09-15 15:14:13 +00001007 for (size_t I = 0; I < enums.size(); ++I) {
1008 if (Uniques.insert(enums[I]).second)
1009 OS << " case " << getAttrName() << "Attr::" << enums[I]
1010 << ": return \"" << values[I] << "\";\n";
1011 }
1012 OS << " }\n"
1013 << " llvm_unreachable(\"No enumerator with that value\");\n"
1014 << " }\n";
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001015 }
1016 };
Peter Collingbournebee583f2011-10-06 13:03:08 +00001017
1018 class VersionArgument : public Argument {
1019 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001020 VersionArgument(const Record &Arg, StringRef Attr)
Peter Collingbournebee583f2011-10-06 13:03:08 +00001021 : Argument(Arg, Attr)
1022 {}
1023
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001024 void writeAccessors(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001025 OS << " VersionTuple get" << getUpperName() << "() const {\n";
1026 OS << " return " << getLowerName() << ";\n";
1027 OS << " }\n";
1028 OS << " void set" << getUpperName()
1029 << "(ASTContext &C, VersionTuple V) {\n";
1030 OS << " " << getLowerName() << " = V;\n";
1031 OS << " }";
1032 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001033
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001034 void writeCloneArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001035 OS << "get" << getUpperName() << "()";
1036 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001037
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001038 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001039 OS << "A->get" << getUpperName() << "()";
1040 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001041
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001042 void writeCtorInitializers(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001043 OS << getLowerName() << "(" << getUpperName() << ")";
1044 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001045
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001046 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00001047 OS << getLowerName() << "()";
1048 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001049
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001050 void writeCtorParameters(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001051 OS << "VersionTuple " << getUpperName();
1052 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001053
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001054 void writeDeclarations(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001055 OS << "VersionTuple " << getLowerName() << ";\n";
1056 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001057
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001058 void writePCHReadDecls(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001059 OS << " VersionTuple " << getLowerName()
David L. Jones267b8842017-01-24 01:04:30 +00001060 << "= Record.readVersionTuple();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001061 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001062
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001063 void writePCHReadArgs(raw_ostream &OS) const override {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001064 OS << getLowerName();
1065 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001066
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001067 void writePCHWrite(raw_ostream &OS) const override {
Richard Smith290d8012016-04-06 17:06:00 +00001068 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00001069 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001070
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001071 void writeValue(raw_ostream &OS) const override {
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001072 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1073 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001074
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001075 void writeDump(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001076 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1077 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00001078 };
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001079
1080 class ExprArgument : public SimpleArgument {
1081 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001082 ExprArgument(const Record &Arg, StringRef Attr)
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001083 : SimpleArgument(Arg, Attr, "Expr *")
1084 {}
1085
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001086 void writeASTVisitorTraversal(raw_ostream &OS) const override {
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00001087 OS << " if (!"
1088 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1089 OS << " return false;\n";
1090 }
1091
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001092 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001093 OS << "tempInst" << getUpperName();
1094 }
1095
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001096 void writeTemplateInstantiation(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001097 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1098 OS << " {\n";
1099 OS << " EnterExpressionEvaluationContext "
Faisal Valid143a0c2017-04-01 21:30:49 +00001100 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001101 OS << " ExprResult " << "Result = S.SubstExpr("
1102 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1103 OS << " tempInst" << getUpperName() << " = "
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001104 << "Result.getAs<Expr>();\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001105 OS << " }\n";
1106 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001107
Craig Topper3164f332014-03-11 03:39:26 +00001108 void writeDump(raw_ostream &OS) const override {}
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001109
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001110 void writeDumpChildren(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001111 OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
1112 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001113
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001114 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001115 };
1116
1117 class VariadicExprArgument : public VariadicArgument {
1118 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001119 VariadicExprArgument(const Record &Arg, StringRef Attr)
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001120 : VariadicArgument(Arg, Attr, "Expr *")
1121 {}
1122
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001123 void writeASTVisitorTraversal(raw_ostream &OS) const override {
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00001124 OS << " {\n";
1125 OS << " " << getType() << " *I = A->" << getLowerName()
1126 << "_begin();\n";
1127 OS << " " << getType() << " *E = A->" << getLowerName()
1128 << "_end();\n";
1129 OS << " for (; I != E; ++I) {\n";
1130 OS << " if (!getDerived().TraverseStmt(*I))\n";
1131 OS << " return false;\n";
1132 OS << " }\n";
1133 OS << " }\n";
1134 }
1135
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001136 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001137 OS << "tempInst" << getUpperName() << ", "
1138 << "A->" << getLowerName() << "_size()";
1139 }
1140
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001141 void writeTemplateInstantiation(raw_ostream &OS) const override {
Eugene Zelenko5f02b772015-12-08 18:49:01 +00001142 OS << " auto *tempInst" << getUpperName()
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001143 << " = new (C, 16) " << getType()
1144 << "[A->" << getLowerName() << "_size()];\n";
1145 OS << " {\n";
1146 OS << " EnterExpressionEvaluationContext "
Faisal Valid143a0c2017-04-01 21:30:49 +00001147 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001148 OS << " " << getType() << " *TI = tempInst" << getUpperName()
1149 << ";\n";
1150 OS << " " << getType() << " *I = A->" << getLowerName()
1151 << "_begin();\n";
1152 OS << " " << getType() << " *E = A->" << getLowerName()
1153 << "_end();\n";
1154 OS << " for (; I != E; ++I, ++TI) {\n";
1155 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001156 OS << " *TI = Result.getAs<Expr>();\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001157 OS << " }\n";
1158 OS << " }\n";
1159 }
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001160
Craig Topper3164f332014-03-11 03:39:26 +00001161 void writeDump(raw_ostream &OS) const override {}
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001162
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001163 void writeDumpChildren(raw_ostream &OS) const override {
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001164 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1165 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
Richard Smithf7514452014-10-30 21:02:37 +00001166 << getLowerName() << "_end(); I != E; ++I)\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001167 OS << " dumpStmt(*I);\n";
Richard Trieude5cc7d2013-01-31 01:44:26 +00001168 }
1169
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001170 void writeHasChildren(raw_ostream &OS) const override {
Richard Trieude5cc7d2013-01-31 01:44:26 +00001171 OS << "SA->" << getLowerName() << "_begin() != "
1172 << "SA->" << getLowerName() << "_end()";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00001173 }
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00001174 };
Richard Smithb87c4652013-10-31 21:23:20 +00001175
Peter Collingbourne915df992015-05-15 18:33:32 +00001176 class VariadicStringArgument : public VariadicArgument {
1177 public:
1178 VariadicStringArgument(const Record &Arg, StringRef Attr)
Benjamin Kramer1b582012016-02-13 18:11:49 +00001179 : VariadicArgument(Arg, Attr, "StringRef")
Peter Collingbourne915df992015-05-15 18:33:32 +00001180 {}
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001181
Benjamin Kramer1b582012016-02-13 18:11:49 +00001182 void writeCtorBody(raw_ostream &OS) const override {
1183 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1184 " ++I) {\n"
1185 " StringRef Ref = " << getUpperName() << "[I];\n"
1186 " if (!Ref.empty()) {\n"
1187 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1188 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1189 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1190 " }\n"
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001191 " }\n";
Benjamin Kramer1b582012016-02-13 18:11:49 +00001192 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001193
Peter Collingbourne915df992015-05-15 18:33:32 +00001194 void writeValueImpl(raw_ostream &OS) const override {
1195 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1196 }
1197 };
1198
Richard Smithb87c4652013-10-31 21:23:20 +00001199 class TypeArgument : public SimpleArgument {
1200 public:
Aaron Ballman2f22b942014-05-20 19:47:14 +00001201 TypeArgument(const Record &Arg, StringRef Attr)
Richard Smithb87c4652013-10-31 21:23:20 +00001202 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1203 {}
1204
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001205 void writeAccessors(raw_ostream &OS) const override {
Richard Smithb87c4652013-10-31 21:23:20 +00001206 OS << " QualType get" << getUpperName() << "() const {\n";
1207 OS << " return " << getLowerName() << "->getType();\n";
1208 OS << " }";
1209 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1210 OS << " return " << getLowerName() << ";\n";
1211 OS << " }";
1212 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001213
Richard Smithf26d5512017-08-15 22:58:45 +00001214 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1215 OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1216 OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1217 OS << " return false;\n";
1218 }
1219
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001220 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
Richard Smithb87c4652013-10-31 21:23:20 +00001221 OS << "A->get" << getUpperName() << "Loc()";
1222 }
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001223
Aaron Ballman8cbf6332014-03-06 15:09:50 +00001224 void writePCHWrite(raw_ostream &OS) const override {
Richard Smithb87c4652013-10-31 21:23:20 +00001225 OS << " " << WritePCHRecord(
1226 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1227 }
1228 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001229
Hans Wennborgdcfba332015-10-06 23:40:43 +00001230} // end anonymous namespace
Peter Collingbournebee583f2011-10-06 13:03:08 +00001231
Aaron Ballman2f22b942014-05-20 19:47:14 +00001232static std::unique_ptr<Argument>
1233createArgument(const Record &Arg, StringRef Attr,
1234 const Record *Search = nullptr) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00001235 if (!Search)
1236 Search = &Arg;
1237
David Blaikie28f30ca2014-08-08 23:59:38 +00001238 std::unique_ptr<Argument> Ptr;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001239 llvm::StringRef ArgName = Search->getName();
1240
David Blaikie28f30ca2014-08-08 23:59:38 +00001241 if (ArgName == "AlignedArgument")
1242 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1243 else if (ArgName == "EnumArgument")
1244 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1245 else if (ArgName == "ExprArgument")
1246 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001247 else if (ArgName == "FunctionArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001248 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001249 else if (ArgName == "NamedArgument")
1250 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "NamedDecl *");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001251 else if (ArgName == "IdentifierArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001252 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
David Majnemer4bb09802014-02-10 19:50:15 +00001253 else if (ArgName == "DefaultBoolArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001254 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1255 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1256 else if (ArgName == "BoolArgument")
1257 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
Aaron Ballman18a78382013-11-21 00:28:23 +00001258 else if (ArgName == "DefaultIntArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001259 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1260 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1261 else if (ArgName == "IntArgument")
1262 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1263 else if (ArgName == "StringArgument")
1264 Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1265 else if (ArgName == "TypeArgument")
1266 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001267 else if (ArgName == "UnsignedArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001268 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001269 else if (ArgName == "VariadicUnsignedArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001270 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
Peter Collingbourne915df992015-05-15 18:33:32 +00001271 else if (ArgName == "VariadicStringArgument")
1272 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001273 else if (ArgName == "VariadicEnumArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001274 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001275 else if (ArgName == "VariadicExprArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001276 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
Joel E. Denny81508102018-03-13 14:51:22 +00001277 else if (ArgName == "VariadicParamIdxArgument")
1278 Ptr = llvm::make_unique<VariadicParamIdxArgument>(Arg, Attr);
1279 else if (ArgName == "ParamIdxArgument")
1280 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
Peter Collingbournebee583f2011-10-06 13:03:08 +00001281 else if (ArgName == "VersionArgument")
David Blaikie28f30ca2014-08-08 23:59:38 +00001282 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00001283
1284 if (!Ptr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00001285 // Search in reverse order so that the most-derived type is handled first.
Craig Topper25761242016-01-18 19:52:54 +00001286 ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
David Majnemerf7e36092016-06-23 00:15:04 +00001287 for (const auto &Base : llvm::reverse(Bases)) {
Craig Topper25761242016-01-18 19:52:54 +00001288 if ((Ptr = createArgument(Arg, Attr, Base.first)))
Peter Collingbournebee583f2011-10-06 13:03:08 +00001289 break;
1290 }
1291 }
Aaron Ballman8ee40b72013-09-09 23:33:17 +00001292
1293 if (Ptr && Arg.getValueAsBit("Optional"))
1294 Ptr->setOptional(true);
1295
John McCalla62c1a92015-10-28 00:17:34 +00001296 if (Ptr && Arg.getValueAsBit("Fake"))
1297 Ptr->setFake(true);
1298
David Blaikie28f30ca2014-08-08 23:59:38 +00001299 return Ptr;
Peter Collingbournebee583f2011-10-06 13:03:08 +00001300}
1301
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001302static void writeAvailabilityValue(raw_ostream &OS) {
1303 OS << "\" << getPlatform()->getName();\n"
Manman Ren42e09eb2016-03-10 23:54:12 +00001304 << " if (getStrict()) OS << \", strict\";\n"
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00001305 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1306 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1307 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1308 << " if (getUnavailable()) OS << \", unavailable\";\n"
1309 << " OS << \"";
1310}
1311
Manman Renc7890fe2016-03-16 18:50:49 +00001312static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1313 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1314 // Only GNU deprecated has an optional fixit argument at the second position.
1315 if (Variety == "GNU")
1316 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1317 " << getReplacement() << \"\\\"\";\n";
1318 OS << " OS << \"";
1319}
1320
Aaron Ballman3e424b52013-12-26 18:30:57 +00001321static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001322 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballman3e424b52013-12-26 18:30:57 +00001323
1324 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1325 if (Spellings.empty()) {
1326 OS << " return \"(No spelling)\";\n}\n\n";
1327 return;
1328 }
1329
1330 OS << " switch (SpellingListIndex) {\n"
1331 " default:\n"
1332 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1333 " return \"(No spelling)\";\n";
1334
1335 for (unsigned I = 0; I < Spellings.size(); ++I)
1336 OS << " case " << I << ":\n"
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001337 " return \"" << Spellings[I].name() << "\";\n";
Aaron Ballman3e424b52013-12-26 18:30:57 +00001338 // End of the switch statement.
1339 OS << " }\n";
1340 // End of the getSpelling function.
1341 OS << "}\n\n";
1342}
1343
Aaron Ballman8f1439b2014-03-05 16:49:55 +00001344static void
1345writePrettyPrintFunction(Record &R,
1346 const std::vector<std::unique_ptr<Argument>> &Args,
1347 raw_ostream &OS) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001348 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Michael Han99315932013-01-24 16:46:58 +00001349
1350 OS << "void " << R.getName() << "Attr::printPretty("
1351 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1352
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001353 if (Spellings.empty()) {
Michael Han99315932013-01-24 16:46:58 +00001354 OS << "}\n\n";
1355 return;
1356 }
1357
1358 OS <<
1359 " switch (SpellingListIndex) {\n"
1360 " default:\n"
1361 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1362 " break;\n";
1363
1364 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1365 llvm::SmallString<16> Prefix;
1366 llvm::SmallString<8> Suffix;
1367 // The actual spelling of the name and namespace (if applicable)
1368 // of an attribute without considering prefix and suffix.
1369 llvm::SmallString<64> Spelling;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001370 std::string Name = Spellings[I].name();
1371 std::string Variety = Spellings[I].variety();
Michael Han99315932013-01-24 16:46:58 +00001372
1373 if (Variety == "GNU") {
1374 Prefix = " __attribute__((";
1375 Suffix = "))";
Aaron Ballman606093a2017-10-15 15:01:42 +00001376 } else if (Variety == "CXX11" || Variety == "C2x") {
Michael Han99315932013-01-24 16:46:58 +00001377 Prefix = " [[";
1378 Suffix = "]]";
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001379 std::string Namespace = Spellings[I].nameSpace();
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001380 if (!Namespace.empty()) {
Michael Han99315932013-01-24 16:46:58 +00001381 Spelling += Namespace;
1382 Spelling += "::";
1383 }
1384 } else if (Variety == "Declspec") {
1385 Prefix = " __declspec(";
1386 Suffix = ")";
Nico Weber20e08042016-09-03 02:55:10 +00001387 } else if (Variety == "Microsoft") {
1388 Prefix = "[";
1389 Suffix = "]";
Richard Smith0cdcc982013-01-29 01:24:26 +00001390 } else if (Variety == "Keyword") {
1391 Prefix = " ";
1392 Suffix = "";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001393 } else if (Variety == "Pragma") {
1394 Prefix = "#pragma ";
1395 Suffix = "\n";
1396 std::string Namespace = Spellings[I].nameSpace();
1397 if (!Namespace.empty()) {
1398 Spelling += Namespace;
1399 Spelling += " ";
1400 }
Michael Han99315932013-01-24 16:46:58 +00001401 } else {
Richard Smith0cdcc982013-01-29 01:24:26 +00001402 llvm_unreachable("Unknown attribute syntax variety!");
Michael Han99315932013-01-24 16:46:58 +00001403 }
1404
1405 Spelling += Name;
1406
1407 OS <<
1408 " case " << I << " : {\n"
Yaron Keren09fb7c62015-03-10 07:33:23 +00001409 " OS << \"" << Prefix << Spelling;
Michael Han99315932013-01-24 16:46:58 +00001410
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001411 if (Variety == "Pragma") {
Alexey Bataevcbecfdf2018-02-14 17:38:47 +00001412 OS << "\";\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001413 OS << " printPrettyPragma(OS, Policy);\n";
Alexey Bataev6d455322015-10-12 06:59:48 +00001414 OS << " OS << \"\\n\";";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00001415 OS << " break;\n";
1416 OS << " }\n";
1417 continue;
1418 }
1419
Michael Han99315932013-01-24 16:46:58 +00001420 if (Spelling == "availability") {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001421 OS << "(";
Michael Han99315932013-01-24 16:46:58 +00001422 writeAvailabilityValue(OS);
Aaron Ballman48a533d2018-02-27 23:49:28 +00001423 OS << ")";
Manman Renc7890fe2016-03-16 18:50:49 +00001424 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001425 OS << "(";
1426 writeDeprecatedAttrValue(OS, Variety);
1427 OS << ")";
Michael Han99315932013-01-24 16:46:58 +00001428 } else {
Aaron Ballman48a533d2018-02-27 23:49:28 +00001429 // To avoid printing parentheses around an empty argument list or
1430 // printing spurious commas at the end of an argument list, we need to
1431 // determine where the last provided non-fake argument is.
1432 unsigned NonFakeArgs = 0;
1433 unsigned TrailingOptArgs = 0;
1434 bool FoundNonOptArg = false;
1435 for (const auto &arg : llvm::reverse(Args)) {
1436 if (arg->isFake())
1437 continue;
1438 ++NonFakeArgs;
1439 if (FoundNonOptArg)
1440 continue;
1441 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1442 // any way to detect whether the argument was omitted.
1443 if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1444 FoundNonOptArg = true;
1445 continue;
1446 }
1447 if (!TrailingOptArgs++)
1448 OS << "\";\n"
1449 << " unsigned TrailingOmittedArgs = 0;\n";
1450 OS << " if (" << arg->getIsOmitted() << ")\n"
1451 << " ++TrailingOmittedArgs;\n";
Michael Han99315932013-01-24 16:46:58 +00001452 }
Aaron Ballman48a533d2018-02-27 23:49:28 +00001453 if (TrailingOptArgs)
1454 OS << " OS << \"";
1455 if (TrailingOptArgs < NonFakeArgs)
1456 OS << "(";
1457 else if (TrailingOptArgs)
1458 OS << "\";\n"
1459 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1460 << " OS << \"(\";\n"
1461 << " OS << \"";
1462 unsigned ArgIndex = 0;
1463 for (const auto &arg : Args) {
1464 if (arg->isFake())
1465 continue;
1466 if (ArgIndex) {
1467 if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
1468 OS << "\";\n"
1469 << " if (" << ArgIndex << " < " << NonFakeArgs
1470 << " - TrailingOmittedArgs)\n"
1471 << " OS << \", \";\n"
1472 << " OS << \"";
1473 else
1474 OS << ", ";
1475 }
1476 std::string IsOmitted = arg->getIsOmitted();
1477 if (arg->isOptional() && IsOmitted != "false")
1478 OS << "\";\n"
1479 << " if (!(" << IsOmitted << ")) {\n"
1480 << " OS << \"";
1481 arg->writeValue(OS);
1482 if (arg->isOptional() && IsOmitted != "false")
1483 OS << "\";\n"
1484 << " }\n"
1485 << " OS << \"";
1486 ++ArgIndex;
1487 }
1488 if (TrailingOptArgs < NonFakeArgs)
1489 OS << ")";
1490 else if (TrailingOptArgs)
1491 OS << "\";\n"
1492 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1493 << " OS << \")\";\n"
1494 << " OS << \"";
Michael Han99315932013-01-24 16:46:58 +00001495 }
1496
Yaron Keren09fb7c62015-03-10 07:33:23 +00001497 OS << Suffix + "\";\n";
Michael Han99315932013-01-24 16:46:58 +00001498
1499 OS <<
1500 " break;\n"
1501 " }\n";
1502 }
1503
1504 // End of the switch statement.
1505 OS << "}\n";
1506 // End of the print function.
1507 OS << "}\n\n";
1508}
1509
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001510/// Return the index of a spelling in a spelling list.
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001511static unsigned
1512getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1513 const FlattenedSpelling &Spelling) {
Alexander Kornienko6ee521c2015-01-23 15:36:10 +00001514 assert(!SpellingList.empty() && "Spelling list is empty!");
Michael Hanaf02bbe2013-02-01 01:19:17 +00001515
1516 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001517 const FlattenedSpelling &S = SpellingList[Index];
1518 if (S.variety() != Spelling.variety())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001519 continue;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001520 if (S.nameSpace() != Spelling.nameSpace())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001521 continue;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001522 if (S.name() != Spelling.name())
Michael Hanaf02bbe2013-02-01 01:19:17 +00001523 continue;
1524
1525 return Index;
1526 }
1527
1528 llvm_unreachable("Unknown spelling!");
1529}
1530
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001531static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
Michael Hanaf02bbe2013-02-01 01:19:17 +00001532 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
George Burgess IV1881a572016-12-01 00:13:18 +00001533 if (Accessors.empty())
1534 return;
1535
1536 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1537 assert(!SpellingList.empty() &&
1538 "Attribute with empty spelling list can't have accessors!");
Aaron Ballman2f22b942014-05-20 19:47:14 +00001539 for (const auto *Accessor : Accessors) {
Erich Keane3bff4142017-10-16 23:25:24 +00001540 const StringRef Name = Accessor->getValueAsString("Name");
George Burgess IV1881a572016-12-01 00:13:18 +00001541 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
Michael Hanaf02bbe2013-02-01 01:19:17 +00001542
1543 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1544 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001545 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
George Burgess IV1881a572016-12-01 00:13:18 +00001546 if (Index != Spellings.size() - 1)
Michael Hanaf02bbe2013-02-01 01:19:17 +00001547 OS << " ||\n SpellingListIndex == ";
1548 else
1549 OS << "; }\n";
1550 }
1551 }
1552}
1553
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001554static bool
1555SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
Aaron Ballman36a53502014-01-16 13:03:14 +00001556 assert(!Spellings.empty() && "An empty list of spellings was provided");
1557 std::string FirstName = NormalizeNameForSpellingComparison(
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001558 Spellings.front().name());
Aaron Ballman2f22b942014-05-20 19:47:14 +00001559 for (const auto &Spelling :
1560 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1561 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
Aaron Ballman36a53502014-01-16 13:03:14 +00001562 if (Name != FirstName)
1563 return false;
1564 }
1565 return true;
1566}
1567
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001568typedef std::map<unsigned, std::string> SemanticSpellingMap;
1569static std::string
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001570CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001571 SemanticSpellingMap &Map) {
1572 // The enumerants are automatically generated based on the variety,
1573 // namespace (if present) and name for each attribute spelling. However,
1574 // care is taken to avoid trampling on the reserved namespace due to
1575 // underscores.
1576 std::string Ret(" enum Spelling {\n");
1577 std::set<std::string> Uniques;
1578 unsigned Idx = 0;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001579 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
Aaron Ballmanc669cc02014-01-27 22:10:04 +00001580 const FlattenedSpelling &S = *I;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00001581 const std::string &Variety = S.variety();
1582 const std::string &Spelling = S.name();
1583 const std::string &Namespace = S.nameSpace();
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00001584 std::string EnumName;
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001585
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001586 EnumName += (Variety + "_");
1587 if (!Namespace.empty())
1588 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1589 "_");
1590 EnumName += NormalizeNameForSpellingComparison(Spelling);
1591
1592 // Even if the name is not unique, this spelling index corresponds to a
1593 // particular enumerant name that we've calculated.
1594 Map[Idx] = EnumName;
1595
1596 // Since we have been stripping underscores to avoid trampling on the
1597 // reserved namespace, we may have inadvertently created duplicate
1598 // enumerant names. These duplicates are not considered part of the
1599 // semantic spelling, and can be elided.
1600 if (Uniques.find(EnumName) != Uniques.end())
1601 continue;
1602
1603 Uniques.insert(EnumName);
1604 if (I != Spellings.begin())
1605 Ret += ",\n";
Aaron Ballman9bf6b752015-03-10 17:19:18 +00001606 // Duplicate spellings are not considered part of the semantic spelling
1607 // enumeration, but the spelling index and semantic spelling values are
1608 // meant to be equivalent, so we must specify a concrete value for each
1609 // enumerator.
1610 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001611 }
1612 Ret += "\n };\n\n";
1613 return Ret;
1614}
1615
1616void WriteSemanticSpellingSwitch(const std::string &VarName,
1617 const SemanticSpellingMap &Map,
1618 raw_ostream &OS) {
1619 OS << " switch (" << VarName << ") {\n default: "
1620 << "llvm_unreachable(\"Unknown spelling list index\");\n";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001621 for (const auto &I : Map)
1622 OS << " case " << I.first << ": return " << I.second << ";\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00001623 OS << " }\n";
1624}
1625
Aaron Ballman35db2b32014-01-29 22:13:45 +00001626// Emits the LateParsed property for attributes.
1627static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1628 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1629 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1630
Aaron Ballman2f22b942014-05-20 19:47:14 +00001631 for (const auto *Attr : Attrs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001632 bool LateParsed = Attr->getValueAsBit("LateParsed");
Aaron Ballman35db2b32014-01-29 22:13:45 +00001633
1634 if (LateParsed) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001635 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
Aaron Ballman35db2b32014-01-29 22:13:45 +00001636
1637 // FIXME: Handle non-GNU attributes
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001638 for (const auto &I : Spellings) {
1639 if (I.variety() != "GNU")
Aaron Ballman35db2b32014-01-29 22:13:45 +00001640 continue;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00001641 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
Aaron Ballman35db2b32014-01-29 22:13:45 +00001642 }
1643 }
1644 }
1645 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1646}
1647
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001648static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1649 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1650 for (const auto &I : Spellings) {
1651 if (I.variety() == "GNU" || I.variety() == "CXX11")
1652 return true;
1653 }
1654 return false;
1655}
1656
1657namespace {
1658
1659struct AttributeSubjectMatchRule {
1660 const Record *MetaSubject;
1661 const Record *Constraint;
1662
1663 AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1664 : MetaSubject(MetaSubject), Constraint(Constraint) {
1665 assert(MetaSubject && "Missing subject");
1666 }
1667
1668 bool isSubRule() const { return Constraint != nullptr; }
1669
1670 std::vector<Record *> getSubjects() const {
1671 return (Constraint ? Constraint : MetaSubject)
1672 ->getValueAsListOfDefs("Subjects");
1673 }
1674
1675 std::vector<Record *> getLangOpts() const {
1676 if (Constraint) {
1677 // Lookup the options in the sub-rule first, in case the sub-rule
1678 // overrides the rules options.
1679 std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1680 if (!Opts.empty())
1681 return Opts;
1682 }
1683 return MetaSubject->getValueAsListOfDefs("LangOpts");
1684 }
1685
1686 // Abstract rules are used only for sub-rules
1687 bool isAbstractRule() const { return getSubjects().empty(); }
1688
Erich Keane3bff4142017-10-16 23:25:24 +00001689 StringRef getName() const {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001690 return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1691 }
1692
1693 bool isNegatedSubRule() const {
1694 assert(isSubRule() && "Not a sub-rule");
1695 return Constraint->getValueAsBit("Negated");
1696 }
1697
1698 std::string getSpelling() const {
1699 std::string Result = MetaSubject->getValueAsString("Name");
1700 if (isSubRule()) {
1701 Result += '(';
1702 if (isNegatedSubRule())
1703 Result += "unless(";
1704 Result += getName();
1705 if (isNegatedSubRule())
1706 Result += ')';
1707 Result += ')';
1708 }
1709 return Result;
1710 }
1711
1712 std::string getEnumValueName() const {
Craig Topper00648582017-05-31 19:01:22 +00001713 SmallString<128> Result;
1714 Result += "SubjectMatchRule_";
1715 Result += MetaSubject->getValueAsString("Name");
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001716 if (isSubRule()) {
1717 Result += "_";
1718 if (isNegatedSubRule())
1719 Result += "not_";
1720 Result += Constraint->getValueAsString("Name");
1721 }
1722 if (isAbstractRule())
1723 Result += "_abstract";
Craig Topper00648582017-05-31 19:01:22 +00001724 return Result.str();
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001725 }
1726
1727 std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1728
1729 static const char *EnumName;
1730};
1731
1732const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1733
1734struct PragmaClangAttributeSupport {
1735 std::vector<AttributeSubjectMatchRule> Rules;
Alex Lorenz24952fb2017-04-19 15:52:11 +00001736
1737 class RuleOrAggregateRuleSet {
1738 std::vector<AttributeSubjectMatchRule> Rules;
1739 bool IsRule;
1740 RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1741 bool IsRule)
1742 : Rules(Rules), IsRule(IsRule) {}
1743
1744 public:
1745 bool isRule() const { return IsRule; }
1746
1747 const AttributeSubjectMatchRule &getRule() const {
1748 assert(IsRule && "not a rule!");
1749 return Rules[0];
1750 }
1751
1752 ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1753 return Rules;
1754 }
1755
1756 static RuleOrAggregateRuleSet
1757 getRule(const AttributeSubjectMatchRule &Rule) {
1758 return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1759 }
1760 static RuleOrAggregateRuleSet
1761 getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1762 return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1763 }
1764 };
1765 llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001766
1767 PragmaClangAttributeSupport(RecordKeeper &Records);
1768
1769 bool isAttributedSupported(const Record &Attribute);
1770
1771 void emitMatchRuleList(raw_ostream &OS);
1772
1773 std::string generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
1774
1775 void generateParsingHelpers(raw_ostream &OS);
1776};
1777
1778} // end anonymous namespace
1779
Alex Lorenz24952fb2017-04-19 15:52:11 +00001780static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
1781 const Record *CurrentBase = D->getValueAsDef("Base");
1782 if (!CurrentBase)
1783 return false;
1784 if (CurrentBase == Base)
1785 return true;
1786 return doesDeclDeriveFrom(CurrentBase, Base);
1787}
1788
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001789PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1790 RecordKeeper &Records) {
1791 std::vector<Record *> MetaSubjects =
1792 Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1793 auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1794 const Record *MetaSubject,
Saleem Abdulrasoolbe4773c2017-05-01 00:26:59 +00001795 const Record *Constraint) {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001796 Rules.emplace_back(MetaSubject, Constraint);
1797 std::vector<Record *> ApplicableSubjects =
1798 SubjectContainer->getValueAsListOfDefs("Subjects");
1799 for (const auto *Subject : ApplicableSubjects) {
1800 bool Inserted =
Alex Lorenz24952fb2017-04-19 15:52:11 +00001801 SubjectsToRules
1802 .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1803 AttributeSubjectMatchRule(MetaSubject,
1804 Constraint)))
1805 .second;
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001806 if (!Inserted) {
1807 PrintFatalError("Attribute subject match rules should not represent"
1808 "same attribute subjects.");
1809 }
1810 }
1811 };
1812 for (const auto *MetaSubject : MetaSubjects) {
Saleem Abdulrasoolbe4773c2017-05-01 00:26:59 +00001813 MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001814 std::vector<Record *> Constraints =
1815 MetaSubject->getValueAsListOfDefs("Constraints");
1816 for (const auto *Constraint : Constraints)
1817 MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
1818 }
Alex Lorenz24952fb2017-04-19 15:52:11 +00001819
1820 std::vector<Record *> Aggregates =
1821 Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
1822 std::vector<Record *> DeclNodes = Records.getAllDerivedDefinitions("DDecl");
1823 for (const auto *Aggregate : Aggregates) {
1824 Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
1825
1826 // Gather sub-classes of the aggregate subject that act as attribute
1827 // subject rules.
1828 std::vector<AttributeSubjectMatchRule> Rules;
1829 for (const auto *D : DeclNodes) {
1830 if (doesDeclDeriveFrom(D, SubjectDecl)) {
1831 auto It = SubjectsToRules.find(D);
1832 if (It == SubjectsToRules.end())
1833 continue;
1834 if (!It->second.isRule() || It->second.getRule().isSubRule())
1835 continue; // Assume that the rule will be included as well.
1836 Rules.push_back(It->second.getRule());
1837 }
1838 }
1839
1840 bool Inserted =
1841 SubjectsToRules
1842 .try_emplace(SubjectDecl,
1843 RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
1844 .second;
1845 if (!Inserted) {
1846 PrintFatalError("Attribute subject match rules should not represent"
1847 "same attribute subjects.");
1848 }
1849 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001850}
1851
1852static PragmaClangAttributeSupport &
1853getPragmaAttributeSupport(RecordKeeper &Records) {
1854 static PragmaClangAttributeSupport Instance(Records);
1855 return Instance;
1856}
1857
1858void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
1859 OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
1860 OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
1861 "IsNegated) "
1862 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
1863 OS << "#endif\n";
1864 for (const auto &Rule : Rules) {
1865 OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
1866 OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
1867 << Rule.isAbstractRule();
1868 if (Rule.isSubRule())
1869 OS << ", "
1870 << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
1871 << ", " << Rule.isNegatedSubRule();
1872 OS << ")\n";
1873 }
1874 OS << "#undef ATTR_MATCH_SUB_RULE\n";
1875}
1876
1877bool PragmaClangAttributeSupport::isAttributedSupported(
1878 const Record &Attribute) {
1879 if (Attribute.getValueAsBit("ForcePragmaAttributeSupport"))
1880 return true;
1881 // Opt-out rules:
1882 // FIXME: The documentation check should be moved before
1883 // the ForcePragmaAttributeSupport check after annotate is documented.
1884 // No documentation present.
1885 if (Attribute.isValueUnset("Documentation"))
1886 return false;
1887 std::vector<Record *> Docs = Attribute.getValueAsListOfDefs("Documentation");
1888 if (Docs.empty())
1889 return false;
1890 if (Docs.size() == 1 && Docs[0]->getName() == "Undocumented")
1891 return false;
1892 // An attribute requires delayed parsing (LateParsed is on)
1893 if (Attribute.getValueAsBit("LateParsed"))
1894 return false;
1895 // An attribute has no GNU/CXX11 spelling
1896 if (!hasGNUorCXX11Spelling(Attribute))
1897 return false;
1898 // An attribute subject list has a subject that isn't covered by one of the
1899 // subject match rules or has no subjects at all.
1900 if (Attribute.isValueUnset("Subjects"))
1901 return false;
1902 const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
1903 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1904 if (Subjects.empty())
1905 return false;
1906 for (const auto *Subject : Subjects) {
1907 if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
1908 return false;
1909 }
1910 return true;
1911}
1912
1913std::string
1914PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
1915 raw_ostream &OS) {
1916 if (!isAttributedSupported(Attr))
1917 return "nullptr";
1918 // Generate a function that constructs a set of matching rules that describe
1919 // to which declarations the attribute should apply to.
1920 std::string FnName = "matchRulesFor" + Attr.getName().str();
Erich Keane3bff4142017-10-16 23:25:24 +00001921 OS << "static void " << FnName << "(llvm::SmallVectorImpl<std::pair<"
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001922 << AttributeSubjectMatchRule::EnumName
1923 << ", bool>> &MatchRules, const LangOptions &LangOpts) {\n";
1924 if (Attr.isValueUnset("Subjects")) {
Erich Keane3bff4142017-10-16 23:25:24 +00001925 OS << "}\n\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001926 return FnName;
1927 }
1928 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
1929 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1930 for (const auto *Subject : Subjects) {
1931 auto It = SubjectsToRules.find(Subject);
1932 assert(It != SubjectsToRules.end() &&
1933 "This attribute is unsupported by #pragma clang attribute");
Alex Lorenz24952fb2017-04-19 15:52:11 +00001934 for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
1935 // The rule might be language specific, so only subtract it from the given
1936 // rules if the specific language options are specified.
1937 std::vector<Record *> LangOpts = Rule.getLangOpts();
Erich Keane3bff4142017-10-16 23:25:24 +00001938 OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
Alex Lorenz24952fb2017-04-19 15:52:11 +00001939 << ", /*IsSupported=*/";
1940 if (!LangOpts.empty()) {
1941 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
Erich Keane3bff4142017-10-16 23:25:24 +00001942 const StringRef Part = (*I)->getValueAsString("Name");
Alex Lorenz24952fb2017-04-19 15:52:11 +00001943 if ((*I)->getValueAsBit("Negated"))
Erich Keane3bff4142017-10-16 23:25:24 +00001944 OS << "!";
1945 OS << "LangOpts." << Part;
Alex Lorenz24952fb2017-04-19 15:52:11 +00001946 if (I + 1 != E)
Erich Keane3bff4142017-10-16 23:25:24 +00001947 OS << " || ";
Alex Lorenz24952fb2017-04-19 15:52:11 +00001948 }
1949 } else
Erich Keane3bff4142017-10-16 23:25:24 +00001950 OS << "true";
1951 OS << "));\n";
Alex Lorenz24952fb2017-04-19 15:52:11 +00001952 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001953 }
Erich Keane3bff4142017-10-16 23:25:24 +00001954 OS << "}\n\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001955 return FnName;
1956}
1957
1958void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
1959 // Generate routines that check the names of sub-rules.
1960 OS << "Optional<attr::SubjectMatchRule> "
1961 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
1962 OS << " return None;\n";
1963 OS << "}\n\n";
1964
1965 std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
1966 SubMatchRules;
1967 for (const auto &Rule : Rules) {
1968 if (!Rule.isSubRule())
1969 continue;
1970 SubMatchRules[Rule.MetaSubject].push_back(Rule);
1971 }
1972
1973 for (const auto &SubMatchRule : SubMatchRules) {
1974 OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
1975 << SubMatchRule.first->getValueAsString("Name")
1976 << "(StringRef Name, bool IsUnless) {\n";
1977 OS << " if (IsUnless)\n";
1978 OS << " return "
1979 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
1980 for (const auto &Rule : SubMatchRule.second) {
1981 if (Rule.isNegatedSubRule())
1982 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
1983 << ").\n";
1984 }
1985 OS << " Default(None);\n";
1986 OS << " return "
1987 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
1988 for (const auto &Rule : SubMatchRule.second) {
1989 if (!Rule.isNegatedSubRule())
1990 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
1991 << ").\n";
1992 }
1993 OS << " Default(None);\n";
1994 OS << "}\n\n";
1995 }
1996
1997 // Generate the function that checks for the top-level rules.
1998 OS << "std::pair<Optional<attr::SubjectMatchRule>, "
1999 "Optional<attr::SubjectMatchRule> (*)(StringRef, "
2000 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2001 OS << " return "
2002 "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
2003 "Optional<attr::SubjectMatchRule> (*) (StringRef, "
2004 "bool)>>(Name).\n";
2005 for (const auto &Rule : Rules) {
2006 if (Rule.isSubRule())
2007 continue;
2008 std::string SubRuleFunction;
2009 if (SubMatchRules.count(Rule.MetaSubject))
Erich Keane3bff4142017-10-16 23:25:24 +00002010 SubRuleFunction =
2011 ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002012 else
2013 SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2014 OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
2015 << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2016 }
2017 OS << " Default(std::make_pair(None, "
2018 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2019 OS << "}\n\n";
2020
2021 // Generate the function that checks for the submatch rules.
2022 OS << "const char *validAttributeSubjectMatchSubRules("
2023 << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2024 OS << " switch (Rule) {\n";
2025 for (const auto &SubMatchRule : SubMatchRules) {
2026 OS << " case "
2027 << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2028 << ":\n";
2029 OS << " return \"'";
2030 bool IsFirst = true;
2031 for (const auto &Rule : SubMatchRule.second) {
2032 if (!IsFirst)
2033 OS << ", '";
2034 IsFirst = false;
2035 if (Rule.isNegatedSubRule())
2036 OS << "unless(";
2037 OS << Rule.getName();
2038 if (Rule.isNegatedSubRule())
2039 OS << ')';
2040 OS << "'";
2041 }
2042 OS << "\";\n";
2043 }
2044 OS << " default: return nullptr;\n";
2045 OS << " }\n";
2046 OS << "}\n\n";
2047}
2048
George Burgess IV1881a572016-12-01 00:13:18 +00002049template <typename Fn>
2050static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
2051 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2052 SmallDenseSet<StringRef, 8> Seen;
2053 for (const FlattenedSpelling &S : Spellings) {
2054 if (Seen.insert(S.name()).second)
2055 F(S);
2056 }
2057}
2058
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002059/// Emits the first-argument-is-type property for attributes.
Aaron Ballman35db2b32014-01-29 22:13:45 +00002060static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
2061 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2062 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2063
Aaron Ballman2f22b942014-05-20 19:47:14 +00002064 for (const auto *Attr : Attrs) {
Aaron Ballman35db2b32014-01-29 22:13:45 +00002065 // Determine whether the first argument is a type.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002066 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
Aaron Ballman35db2b32014-01-29 22:13:45 +00002067 if (Args.empty())
2068 continue;
2069
Craig Topper25761242016-01-18 19:52:54 +00002070 if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
Aaron Ballman35db2b32014-01-29 22:13:45 +00002071 continue;
2072
2073 // All these spellings take a single type argument.
George Burgess IV1881a572016-12-01 00:13:18 +00002074 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2075 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2076 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002077 }
2078 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2079}
2080
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002081/// Emits the parse-arguments-in-unevaluated-context property for
Aaron Ballman35db2b32014-01-29 22:13:45 +00002082/// attributes.
2083static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
2084 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2085 ParsedAttrMap Attrs = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002086 for (const auto &I : Attrs) {
2087 const Record &Attr = *I.second;
Aaron Ballman35db2b32014-01-29 22:13:45 +00002088
2089 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2090 continue;
2091
2092 // All these spellings take are parsed unevaluated.
George Burgess IV1881a572016-12-01 00:13:18 +00002093 forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2094 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2095 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002096 }
2097 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2098}
2099
2100static bool isIdentifierArgument(Record *Arg) {
2101 return !Arg->getSuperClasses().empty() &&
Craig Topper25761242016-01-18 19:52:54 +00002102 llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
Aaron Ballman35db2b32014-01-29 22:13:45 +00002103 .Case("IdentifierArgument", true)
2104 .Case("EnumArgument", true)
Aaron Ballman55ef1512014-12-19 16:42:04 +00002105 .Case("VariadicEnumArgument", true)
Aaron Ballman35db2b32014-01-29 22:13:45 +00002106 .Default(false);
2107}
2108
2109// Emits the first-argument-is-identifier property for attributes.
2110static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2111 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2112 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2113
Aaron Ballman2f22b942014-05-20 19:47:14 +00002114 for (const auto *Attr : Attrs) {
Aaron Ballman35db2b32014-01-29 22:13:45 +00002115 // Determine whether the first argument is an identifier.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002116 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
Aaron Ballman35db2b32014-01-29 22:13:45 +00002117 if (Args.empty() || !isIdentifierArgument(Args[0]))
2118 continue;
2119
2120 // All these spellings take an identifier argument.
George Burgess IV1881a572016-12-01 00:13:18 +00002121 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2122 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2123 });
Aaron Ballman35db2b32014-01-29 22:13:45 +00002124 }
2125 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2126}
2127
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002128namespace clang {
2129
2130// Emits the class definitions for attributes.
2131void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002132 emitSourceFileHeader("Attribute classes' definitions", OS);
2133
Peter Collingbournebee583f2011-10-06 13:03:08 +00002134 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2135 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2136
2137 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2138
Aaron Ballman2f22b942014-05-20 19:47:14 +00002139 for (const auto *Attr : Attrs) {
2140 const Record &R = *Attr;
Aaron Ballman06bd44b2014-02-17 18:23:02 +00002141
2142 // FIXME: Currently, documentation is generated as-needed due to the fact
2143 // that there is no way to allow a generated project "reach into" the docs
2144 // directory (for instance, it may be an out-of-tree build). However, we want
2145 // to ensure that every attribute has a Documentation field, and produce an
2146 // error if it has been neglected. Otherwise, the on-demand generation which
2147 // happens server-side will fail. This code is ensuring that functionality,
2148 // even though this Emitter doesn't technically need the documentation.
2149 // When attribute documentation can be generated as part of the build
2150 // itself, this code can be removed.
2151 (void)R.getValueAsListOfDefs("Documentation");
Douglas Gregorb2daf842012-05-02 15:56:52 +00002152
2153 if (!R.getValueAsBit("ASTNode"))
2154 continue;
2155
Craig Topper25761242016-01-18 19:52:54 +00002156 ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002157 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002158 std::string SuperName;
Richard Smith33bddbd2018-01-04 23:42:29 +00002159 bool Inheritable = false;
David Majnemerf7e36092016-06-23 00:15:04 +00002160 for (const auto &Super : llvm::reverse(Supers)) {
Craig Topper25761242016-01-18 19:52:54 +00002161 const Record *R = Super.first;
Aaron Ballmanb9a457a2018-05-03 15:33:50 +00002162 if (R->getName() != "TargetSpecificAttr" &&
2163 R->getName() != "DeclOrTypeAttr" && SuperName.empty())
Craig Topper25761242016-01-18 19:52:54 +00002164 SuperName = R->getName();
Richard Smith33bddbd2018-01-04 23:42:29 +00002165 if (R->getName() == "InheritableAttr")
2166 Inheritable = true;
Aaron Ballman0979e9e2013-07-30 01:44:15 +00002167 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002168
2169 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2170
2171 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002172 std::vector<std::unique_ptr<Argument>> Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002173 Args.reserve(ArgRecords.size());
2174
John McCalla62c1a92015-10-28 00:17:34 +00002175 bool HasOptArg = false;
2176 bool HasFakeArg = false;
Aaron Ballman2f22b942014-05-20 19:47:14 +00002177 for (const auto *ArgRecord : ArgRecords) {
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002178 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2179 Args.back()->writeDeclarations(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002180 OS << "\n\n";
John McCalla62c1a92015-10-28 00:17:34 +00002181
2182 // For these purposes, fake takes priority over optional.
2183 if (Args.back()->isFake()) {
2184 HasFakeArg = true;
2185 } else if (Args.back()->isOptional()) {
2186 HasOptArg = true;
2187 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002188 }
2189
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002190 OS << "public:\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002191
Aaron Ballmanc669cc02014-01-27 22:10:04 +00002192 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballman36a53502014-01-16 13:03:14 +00002193
2194 // If there are zero or one spellings, all spelling-related functionality
2195 // can be elided. If all of the spellings share the same name, the spelling
2196 // functionality can also be elided.
2197 bool ElideSpelling = (Spellings.size() <= 1) ||
2198 SpellingNamesAreCommon(Spellings);
2199
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002200 // This maps spelling index values to semantic Spelling enumerants.
2201 SemanticSpellingMap SemanticToSyntacticMap;
Aaron Ballman36a53502014-01-16 13:03:14 +00002202
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002203 if (!ElideSpelling)
2204 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
Aaron Ballman36a53502014-01-16 13:03:14 +00002205
John McCalla62c1a92015-10-28 00:17:34 +00002206 // Emit CreateImplicit factory methods.
2207 auto emitCreateImplicit = [&](bool emitFake) {
2208 OS << " static " << R.getName() << "Attr *CreateImplicit(";
2209 OS << "ASTContext &Ctx";
2210 if (!ElideSpelling)
2211 OS << ", Spelling S";
2212 for (auto const &ai : Args) {
2213 if (ai->isFake() && !emitFake) continue;
2214 OS << ", ";
2215 ai->writeCtorParameters(OS);
2216 }
2217 OS << ", SourceRange Loc = SourceRange()";
2218 OS << ") {\n";
Eugene Zelenko5f02b772015-12-08 18:49:01 +00002219 OS << " auto *A = new (Ctx) " << R.getName();
John McCalla62c1a92015-10-28 00:17:34 +00002220 OS << "Attr(Loc, Ctx, ";
2221 for (auto const &ai : Args) {
2222 if (ai->isFake() && !emitFake) continue;
2223 ai->writeImplicitCtorArgs(OS);
2224 OS << ", ";
2225 }
2226 OS << (ElideSpelling ? "0" : "S") << ");\n";
2227 OS << " A->setImplicit(true);\n";
2228 OS << " return A;\n }\n\n";
2229 };
Aaron Ballman36a53502014-01-16 13:03:14 +00002230
John McCalla62c1a92015-10-28 00:17:34 +00002231 // Emit a CreateImplicit that takes all the arguments.
2232 emitCreateImplicit(true);
2233
2234 // Emit a CreateImplicit that takes all the non-fake arguments.
2235 if (HasFakeArg) {
2236 emitCreateImplicit(false);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002237 }
Michael Han99315932013-01-24 16:46:58 +00002238
John McCalla62c1a92015-10-28 00:17:34 +00002239 // Emit constructors.
2240 auto emitCtor = [&](bool emitOpt, bool emitFake) {
2241 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2242 if (arg->isFake()) return emitFake;
2243 if (arg->isOptional()) return emitOpt;
2244 return true;
2245 };
Michael Han99315932013-01-24 16:46:58 +00002246
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002247 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002248 for (auto const &ai : Args) {
John McCalla62c1a92015-10-28 00:17:34 +00002249 if (!shouldEmitArg(ai)) continue;
2250 OS << " , ";
2251 ai->writeCtorParameters(OS);
2252 OS << "\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002253 }
2254
2255 OS << " , ";
Aaron Ballman36a53502014-01-16 13:03:14 +00002256 OS << "unsigned SI\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002257
2258 OS << " )\n";
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002259 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
Richard Smith33bddbd2018-01-04 23:42:29 +00002260 << ( R.getValueAsBit("LateParsed") ? "true" : "false" );
2261 if (Inheritable) {
2262 OS << ", "
2263 << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2264 : "false");
2265 }
2266 OS << ")\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002267
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002268 for (auto const &ai : Args) {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002269 OS << " , ";
John McCalla62c1a92015-10-28 00:17:34 +00002270 if (!shouldEmitArg(ai)) {
2271 ai->writeCtorDefaultInitializers(OS);
2272 } else {
2273 ai->writeCtorInitializers(OS);
2274 }
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002275 OS << "\n";
2276 }
2277
2278 OS << " {\n";
2279
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002280 for (auto const &ai : Args) {
John McCalla62c1a92015-10-28 00:17:34 +00002281 if (!shouldEmitArg(ai)) continue;
2282 ai->writeCtorBody(OS);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002283 }
2284 OS << " }\n\n";
John McCalla62c1a92015-10-28 00:17:34 +00002285 };
2286
2287 // Emit a constructor that includes all the arguments.
2288 // This is necessary for cloning.
2289 emitCtor(true, true);
2290
2291 // Emit a constructor that takes all the non-fake arguments.
2292 if (HasFakeArg) {
2293 emitCtor(true, false);
2294 }
2295
2296 // Emit a constructor that takes all the non-fake, non-optional arguments.
2297 if (HasOptArg) {
2298 emitCtor(false, false);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00002299 }
2300
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002301 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
Craig Toppercbce6e92014-03-11 06:22:39 +00002302 OS << " void printPretty(raw_ostream &OS,\n"
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002303 << " const PrintingPolicy &Policy) const;\n";
2304 OS << " const char *getSpelling() const;\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00002305
2306 if (!ElideSpelling) {
2307 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
2308 OS << " Spelling getSemanticSpelling() const {\n";
2309 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
2310 OS);
2311 OS << " }\n";
2312 }
Peter Collingbournebee583f2011-10-06 13:03:08 +00002313
Michael Hanaf02bbe2013-02-01 01:19:17 +00002314 writeAttrAccessorDefinition(R, OS);
2315
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002316 for (auto const &ai : Args) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002317 ai->writeAccessors(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002318 OS << "\n\n";
Aaron Ballman682ee422013-09-11 19:47:58 +00002319
John McCalla62c1a92015-10-28 00:17:34 +00002320 // Don't write conversion routines for fake arguments.
2321 if (ai->isFake()) continue;
2322
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002323 if (ai->isEnumArg())
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002324 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002325 else if (ai->isVariadicEnumArg())
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002326 static_cast<const VariadicEnumArgument *>(ai.get())
2327 ->writeConversion(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002328 }
2329
Jakob Stoklund Olesen6f2288b62012-01-13 04:57:47 +00002330 OS << R.getValueAsString("AdditionalMembers");
Peter Collingbournebee583f2011-10-06 13:03:08 +00002331 OS << "\n\n";
2332
2333 OS << " static bool classof(const Attr *A) { return A->getKind() == "
2334 << "attr::" << R.getName() << "; }\n";
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002335
Peter Collingbournebee583f2011-10-06 13:03:08 +00002336 OS << "};\n\n";
2337 }
2338
Eugene Zelenko5f02b772015-12-08 18:49:01 +00002339 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002340}
2341
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002342// Emits the class method definitions for attributes.
2343void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002344 emitSourceFileHeader("Attribute classes' member function definitions", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002345
2346 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
Peter Collingbournebee583f2011-10-06 13:03:08 +00002347
Aaron Ballman2f22b942014-05-20 19:47:14 +00002348 for (auto *Attr : Attrs) {
2349 Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00002350
2351 if (!R.getValueAsBit("ASTNode"))
2352 continue;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002353
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002354 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2355 std::vector<std::unique_ptr<Argument>> Args;
Aaron Ballman2f22b942014-05-20 19:47:14 +00002356 for (const auto *Arg : ArgRecords)
2357 Args.emplace_back(createArgument(*Arg, R.getName()));
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002358
2359 for (auto const &ai : Args)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002360 ai->writeAccessorDefinitions(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002361
2362 OS << R.getName() << "Attr *" << R.getName()
2363 << "Attr::clone(ASTContext &C) const {\n";
Hans Wennborg613807b2014-05-31 01:30:30 +00002364 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002365 for (auto const &ai : Args) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00002366 OS << ", ";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002367 ai->writeCloneArgs(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002368 }
Hans Wennborg613807b2014-05-31 01:30:30 +00002369 OS << ", getSpellingListIndex());\n";
2370 OS << " A->Inherited = Inherited;\n";
2371 OS << " A->IsPackExpansion = IsPackExpansion;\n";
2372 OS << " A->Implicit = Implicit;\n";
2373 OS << " return A;\n}\n\n";
Douglas Gregor49ccfaa2011-11-19 19:22:57 +00002374
Michael Han99315932013-01-24 16:46:58 +00002375 writePrettyPrintFunction(R, Args, OS);
Aaron Ballman3e424b52013-12-26 18:30:57 +00002376 writeGetSpellingFunction(R, OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002377 }
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002378
2379 // Instead of relying on virtual dispatch we just create a huge dispatch
2380 // switch. This is both smaller and faster than virtual functions.
2381 auto EmitFunc = [&](const char *Method) {
2382 OS << " switch (getKind()) {\n";
2383 for (const auto *Attr : Attrs) {
2384 const Record &R = *Attr;
2385 if (!R.getValueAsBit("ASTNode"))
2386 continue;
2387
2388 OS << " case attr::" << R.getName() << ":\n";
2389 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
2390 << ";\n";
2391 }
Benjamin Kramer845e32c2015-03-19 16:06:49 +00002392 OS << " }\n";
2393 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
2394 OS << "}\n\n";
2395 };
2396
2397 OS << "const char *Attr::getSpelling() const {\n";
2398 EmitFunc("getSpelling()");
2399
2400 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2401 EmitFunc("clone(C)");
2402
2403 OS << "void Attr::printPretty(raw_ostream &OS, "
2404 "const PrintingPolicy &Policy) const {\n";
2405 EmitFunc("printPretty(OS, Policy)");
Peter Collingbournebee583f2011-10-06 13:03:08 +00002406}
2407
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002408} // end namespace clang
2409
John McCall2225c8b2016-03-01 00:18:05 +00002410static void emitAttrList(raw_ostream &OS, StringRef Class,
Peter Collingbournebee583f2011-10-06 13:03:08 +00002411 const std::vector<Record*> &AttrList) {
John McCall2225c8b2016-03-01 00:18:05 +00002412 for (auto Cur : AttrList) {
2413 OS << Class << "(" << Cur->getName() << ")\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002414 }
2415}
2416
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002417// Determines if an attribute has a Pragma spelling.
2418static bool AttrHasPragmaSpelling(const Record *R) {
2419 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
George Burgess IV1881a572016-12-01 00:13:18 +00002420 return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002421 return S.variety() == "Pragma";
2422 }) != Spellings.end();
2423}
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002424
John McCall2225c8b2016-03-01 00:18:05 +00002425namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002426
John McCall2225c8b2016-03-01 00:18:05 +00002427 struct AttrClassDescriptor {
2428 const char * const MacroName;
2429 const char * const TableGenName;
2430 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002431
2432} // end anonymous namespace
John McCall2225c8b2016-03-01 00:18:05 +00002433
2434static const AttrClassDescriptor AttrClassDescriptors[] = {
2435 { "ATTR", "Attr" },
Richard Smith4f902c72016-03-08 00:32:55 +00002436 { "STMT_ATTR", "StmtAttr" },
John McCall2225c8b2016-03-01 00:18:05 +00002437 { "INHERITABLE_ATTR", "InheritableAttr" },
John McCall477f2bb2016-03-03 06:39:32 +00002438 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2439 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
John McCall2225c8b2016-03-01 00:18:05 +00002440};
2441
2442static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2443 const char *superName) {
2444 OS << "#ifndef " << name << "\n";
2445 OS << "#define " << name << "(NAME) ";
2446 if (superName) OS << superName << "(NAME)";
2447 OS << "\n#endif\n\n";
2448}
2449
2450namespace {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002451
John McCall2225c8b2016-03-01 00:18:05 +00002452 /// A class of attributes.
2453 struct AttrClass {
2454 const AttrClassDescriptor &Descriptor;
2455 Record *TheRecord;
2456 AttrClass *SuperClass = nullptr;
2457 std::vector<AttrClass*> SubClasses;
2458 std::vector<Record*> Attrs;
2459
2460 AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2461 : Descriptor(Descriptor), TheRecord(R) {}
2462
2463 void emitDefaultDefines(raw_ostream &OS) const {
2464 // Default the macro unless this is a root class (i.e. Attr).
2465 if (SuperClass) {
2466 emitDefaultDefine(OS, Descriptor.MacroName,
2467 SuperClass->Descriptor.MacroName);
2468 }
2469 }
2470
2471 void emitUndefs(raw_ostream &OS) const {
2472 OS << "#undef " << Descriptor.MacroName << "\n";
2473 }
2474
2475 void emitAttrList(raw_ostream &OS) const {
2476 for (auto SubClass : SubClasses) {
2477 SubClass->emitAttrList(OS);
2478 }
2479
2480 ::emitAttrList(OS, Descriptor.MacroName, Attrs);
2481 }
2482
2483 void classifyAttrOnRoot(Record *Attr) {
2484 bool result = classifyAttr(Attr);
2485 assert(result && "failed to classify on root"); (void) result;
2486 }
2487
2488 void emitAttrRange(raw_ostream &OS) const {
2489 OS << "ATTR_RANGE(" << Descriptor.TableGenName
2490 << ", " << getFirstAttr()->getName()
2491 << ", " << getLastAttr()->getName() << ")\n";
2492 }
2493
2494 private:
2495 bool classifyAttr(Record *Attr) {
2496 // Check all the subclasses.
2497 for (auto SubClass : SubClasses) {
2498 if (SubClass->classifyAttr(Attr))
2499 return true;
2500 }
2501
2502 // It's not more specific than this class, but it might still belong here.
2503 if (Attr->isSubClassOf(TheRecord)) {
2504 Attrs.push_back(Attr);
2505 return true;
2506 }
2507
2508 return false;
2509 }
2510
2511 Record *getFirstAttr() const {
2512 if (!SubClasses.empty())
2513 return SubClasses.front()->getFirstAttr();
2514 return Attrs.front();
2515 }
2516
2517 Record *getLastAttr() const {
2518 if (!Attrs.empty())
2519 return Attrs.back();
2520 return SubClasses.back()->getLastAttr();
2521 }
2522 };
2523
2524 /// The entire hierarchy of attribute classes.
2525 class AttrClassHierarchy {
2526 std::vector<std::unique_ptr<AttrClass>> Classes;
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002527
John McCall2225c8b2016-03-01 00:18:05 +00002528 public:
2529 AttrClassHierarchy(RecordKeeper &Records) {
2530 // Find records for all the classes.
2531 for (auto &Descriptor : AttrClassDescriptors) {
2532 Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2533 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2534 Classes.emplace_back(Class);
2535 }
2536
2537 // Link up the hierarchy.
2538 for (auto &Class : Classes) {
2539 if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2540 Class->SuperClass = SuperClass;
2541 SuperClass->SubClasses.push_back(Class.get());
2542 }
2543 }
2544
2545#ifndef NDEBUG
2546 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2547 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2548 "only the first class should be a root class!");
2549 }
2550#endif
2551 }
2552
2553 void emitDefaultDefines(raw_ostream &OS) const {
2554 for (auto &Class : Classes) {
2555 Class->emitDefaultDefines(OS);
2556 }
2557 }
2558
2559 void emitUndefs(raw_ostream &OS) const {
2560 for (auto &Class : Classes) {
2561 Class->emitUndefs(OS);
2562 }
2563 }
2564
2565 void emitAttrLists(raw_ostream &OS) const {
2566 // Just start from the root class.
2567 Classes[0]->emitAttrList(OS);
2568 }
2569
2570 void emitAttrRanges(raw_ostream &OS) const {
2571 for (auto &Class : Classes)
2572 Class->emitAttrRange(OS);
2573 }
2574
2575 void classifyAttr(Record *Attr) {
2576 // Add the attribute to the root class.
2577 Classes[0]->classifyAttrOnRoot(Attr);
2578 }
2579
2580 private:
2581 AttrClass *findClassByRecord(Record *R) const {
2582 for (auto &Class : Classes) {
2583 if (Class->TheRecord == R)
2584 return Class.get();
2585 }
2586 return nullptr;
2587 }
2588
2589 AttrClass *findSuperClass(Record *R) const {
2590 // TableGen flattens the superclass list, so we just need to walk it
2591 // in reverse.
2592 auto SuperClasses = R->getSuperClasses();
2593 for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2594 auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2595 if (SuperClass) return SuperClass;
2596 }
2597 return nullptr;
2598 }
2599 };
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002600
2601} // end anonymous namespace
John McCall2225c8b2016-03-01 00:18:05 +00002602
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002603namespace clang {
Eugene Zelenkoa9f3e902016-05-12 22:27:08 +00002604
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002605// Emits the enumeration list for attributes.
2606void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002607 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002608
John McCall2225c8b2016-03-01 00:18:05 +00002609 AttrClassHierarchy Hierarchy(Records);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002610
John McCall2225c8b2016-03-01 00:18:05 +00002611 // Add defaulting macro definitions.
2612 Hierarchy.emitDefaultDefines(OS);
2613 emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002614
John McCall2225c8b2016-03-01 00:18:05 +00002615 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2616 std::vector<Record *> PragmaAttrs;
Aaron Ballman2f22b942014-05-20 19:47:14 +00002617 for (auto *Attr : Attrs) {
2618 if (!Attr->getValueAsBit("ASTNode"))
Douglas Gregorb2daf842012-05-02 15:56:52 +00002619 continue;
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002620
John McCall2225c8b2016-03-01 00:18:05 +00002621 // Add the attribute to the ad-hoc groups.
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002622 if (AttrHasPragmaSpelling(Attr))
2623 PragmaAttrs.push_back(Attr);
2624
John McCall2225c8b2016-03-01 00:18:05 +00002625 // Place it in the hierarchy.
2626 Hierarchy.classifyAttr(Attr);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002627 }
2628
John McCall2225c8b2016-03-01 00:18:05 +00002629 // Emit the main attribute list.
2630 Hierarchy.emitAttrLists(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002631
John McCall2225c8b2016-03-01 00:18:05 +00002632 // Emit the ad hoc groups.
2633 emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2634
2635 // Emit the attribute ranges.
2636 OS << "#ifdef ATTR_RANGE\n";
2637 Hierarchy.emitAttrRanges(OS);
2638 OS << "#undef ATTR_RANGE\n";
2639 OS << "#endif\n";
2640
2641 Hierarchy.emitUndefs(OS);
Tyler Nowickic724a83e2014-10-12 20:46:07 +00002642 OS << "#undef PRAGMA_SPELLING_ATTR\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002643}
2644
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002645// Emits the enumeration list for attributes.
2646void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
2647 emitSourceFileHeader(
2648 "List of all attribute subject matching rules that Clang recognizes", OS);
2649 PragmaClangAttributeSupport &PragmaAttributeSupport =
2650 getPragmaAttributeSupport(Records);
2651 emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
2652 PragmaAttributeSupport.emitMatchRuleList(OS);
2653 OS << "#undef ATTR_MATCH_RULE\n";
2654}
2655
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002656// Emits the code to read an attribute from a precompiled header.
2657void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002658 emitSourceFileHeader("Attribute deserialization code", OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002659
2660 Record *InhClass = Records.getClass("InheritableAttr");
2661 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2662 ArgRecords;
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002663 std::vector<std::unique_ptr<Argument>> Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002664
2665 OS << " switch (Kind) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00002666 for (const auto *Attr : Attrs) {
2667 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00002668 if (!R.getValueAsBit("ASTNode"))
2669 continue;
2670
Peter Collingbournebee583f2011-10-06 13:03:08 +00002671 OS << " case attr::" << R.getName() << ": {\n";
2672 if (R.isSubClassOf(InhClass))
David L. Jones267b8842017-01-24 01:04:30 +00002673 OS << " bool isInherited = Record.readInt();\n";
2674 OS << " bool isImplicit = Record.readInt();\n";
2675 OS << " unsigned Spelling = Record.readInt();\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002676 ArgRecords = R.getValueAsListOfDefs("Args");
2677 Args.clear();
Aaron Ballman2f22b942014-05-20 19:47:14 +00002678 for (const auto *Arg : ArgRecords) {
2679 Args.emplace_back(createArgument(*Arg, R.getName()));
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002680 Args.back()->writePCHReadDecls(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002681 }
2682 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00002683 for (auto const &ri : Args) {
Peter Collingbournebee583f2011-10-06 13:03:08 +00002684 OS << ", ";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002685 ri->writePCHReadArgs(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002686 }
Aaron Ballman36a53502014-01-16 13:03:14 +00002687 OS << ", Spelling);\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002688 if (R.isSubClassOf(InhClass))
2689 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002690 OS << " New->setImplicit(isImplicit);\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002691 OS << " break;\n";
2692 OS << " }\n";
2693 }
2694 OS << " }\n";
2695}
2696
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00002697// Emits the code to write an attribute to a precompiled header.
2698void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002699 emitSourceFileHeader("Attribute serialization code", OS);
2700
Peter Collingbournebee583f2011-10-06 13:03:08 +00002701 Record *InhClass = Records.getClass("InheritableAttr");
2702 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002703
2704 OS << " switch (A->getKind()) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00002705 for (const auto *Attr : Attrs) {
2706 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00002707 if (!R.getValueAsBit("ASTNode"))
2708 continue;
Peter Collingbournebee583f2011-10-06 13:03:08 +00002709 OS << " case attr::" << R.getName() << ": {\n";
2710 Args = R.getValueAsListOfDefs("Args");
2711 if (R.isSubClassOf(InhClass) || !Args.empty())
Eugene Zelenko5f02b772015-12-08 18:49:01 +00002712 OS << " const auto *SA = cast<" << R.getName()
Peter Collingbournebee583f2011-10-06 13:03:08 +00002713 << "Attr>(A);\n";
2714 if (R.isSubClassOf(InhClass))
2715 OS << " Record.push_back(SA->isInherited());\n";
Aaron Ballman36a53502014-01-16 13:03:14 +00002716 OS << " Record.push_back(A->isImplicit());\n";
2717 OS << " Record.push_back(A->getSpellingListIndex());\n";
2718
Aaron Ballman2f22b942014-05-20 19:47:14 +00002719 for (const auto *Arg : Args)
2720 createArgument(*Arg, R.getName())->writePCHWrite(OS);
Peter Collingbournebee583f2011-10-06 13:03:08 +00002721 OS << " break;\n";
2722 OS << " }\n";
2723 }
2724 OS << " }\n";
2725}
2726
Erich Keane75449672017-12-20 18:51:08 +00002727// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
2728// parameter with only a single check type, if applicable.
2729static void GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
2730 std::string *FnName,
2731 StringRef ListName,
2732 StringRef CheckAgainst,
2733 StringRef Scope) {
2734 if (!R->isValueUnset(ListName)) {
2735 Test += " && (";
2736 std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
2737 for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
2738 StringRef Part = *I;
2739 Test += CheckAgainst;
2740 Test += " == ";
2741 Test += Scope;
2742 Test += Part;
2743 if (I + 1 != E)
2744 Test += " || ";
2745 if (FnName)
2746 *FnName += Part;
2747 }
2748 Test += ")";
2749 }
2750}
2751
Bob Wilson0058b822015-07-20 22:57:36 +00002752// Generate a conditional expression to check if the current target satisfies
2753// the conditions for a TargetSpecificAttr record, and append the code for
2754// those checks to the Test string. If the FnName string pointer is non-null,
2755// append a unique suffix to distinguish this set of target checks from other
2756// TargetSpecificAttr records.
2757static void GenerateTargetSpecificAttrChecks(const Record *R,
Craig Topper00648582017-05-31 19:01:22 +00002758 std::vector<StringRef> &Arches,
Bob Wilson0058b822015-07-20 22:57:36 +00002759 std::string &Test,
2760 std::string *FnName) {
2761 // It is assumed that there will be an llvm::Triple object
2762 // named "T" and a TargetInfo object named "Target" within
2763 // scope that can be used to determine whether the attribute exists in
2764 // a given target.
Erich Keane75449672017-12-20 18:51:08 +00002765 Test += "true";
2766 // If one or more architectures is specified, check those. Arches are handled
2767 // differently because GenerateTargetRequirements needs to combine the list
2768 // with ParseKind.
2769 if (!Arches.empty()) {
2770 Test += " && (";
2771 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2772 StringRef Part = *I;
2773 Test += "T.getArch() == llvm::Triple::";
2774 Test += Part;
2775 if (I + 1 != E)
2776 Test += " || ";
2777 if (FnName)
2778 *FnName += Part;
2779 }
2780 Test += ")";
Bob Wilson0058b822015-07-20 22:57:36 +00002781 }
Bob Wilson0058b822015-07-20 22:57:36 +00002782
2783 // If the attribute is specific to particular OSes, check those.
Erich Keane75449672017-12-20 18:51:08 +00002784 GenerateTargetSpecificAttrCheck(R, Test, FnName, "OSes", "T.getOS()",
2785 "llvm::Triple::");
Bob Wilson0058b822015-07-20 22:57:36 +00002786
2787 // If one or more CXX ABIs are specified, check those as well.
Erich Keane75449672017-12-20 18:51:08 +00002788 GenerateTargetSpecificAttrCheck(R, Test, FnName, "CXXABIs",
2789 "Target.getCXXABI().getKind()",
2790 "TargetCXXABI::");
2791 // If one or more object formats is specified, check those.
2792 GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
2793 "T.getObjectFormat()", "llvm::Triple::");
Bob Wilson0058b822015-07-20 22:57:36 +00002794}
2795
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002796static void GenerateHasAttrSpellingStringSwitch(
2797 const std::vector<Record *> &Attrs, raw_ostream &OS,
2798 const std::string &Variety = "", const std::string &Scope = "") {
2799 for (const auto *Attr : Attrs) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00002800 // C++11-style attributes have specific version information associated with
2801 // them. If the attribute has no scope, the version information must not
2802 // have the default value (1), as that's incorrect. Instead, the unscoped
2803 // attribute version information should be taken from the SD-6 standing
2804 // document, which can be found at:
2805 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
2806 int Version = 1;
2807
2808 if (Variety == "CXX11") {
2809 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
2810 for (const auto &Spelling : Spellings) {
2811 if (Spelling->getValueAsString("Variety") == "CXX11") {
2812 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
2813 if (Scope.empty() && Version == 1)
2814 PrintError(Spelling->getLoc(), "C++ standard attributes must "
2815 "have valid version information.");
2816 break;
2817 }
2818 }
2819 }
2820
Aaron Ballman0fa06d82014-01-09 22:57:44 +00002821 std::string Test;
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002822 if (Attr->isSubClassOf("TargetSpecificAttr")) {
2823 const Record *R = Attr->getValueAsDef("Target");
Craig Topper00648582017-05-31 19:01:22 +00002824 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
Hans Wennborgdcfba332015-10-06 23:40:43 +00002825 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
Bob Wilson7c730832015-07-20 22:57:31 +00002826
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002827 // If this is the C++11 variety, also add in the LangOpts test.
2828 if (Variety == "CXX11")
2829 Test += " && LangOpts.CPlusPlus11";
Aaron Ballman606093a2017-10-15 15:01:42 +00002830 else if (Variety == "C2x")
2831 Test += " && LangOpts.DoubleSquareBracketAttributes";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002832 } else if (Variety == "CXX11")
2833 // C++11 mode should be checked against LangOpts, which is presumed to be
2834 // present in the caller.
2835 Test = "LangOpts.CPlusPlus11";
Aaron Ballman606093a2017-10-15 15:01:42 +00002836 else if (Variety == "C2x")
2837 Test = "LangOpts.DoubleSquareBracketAttributes";
Aaron Ballman0fa06d82014-01-09 22:57:44 +00002838
Aaron Ballmana0344c52014-11-14 13:44:02 +00002839 std::string TestStr =
Aaron Ballman28afa182014-11-17 18:17:19 +00002840 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002841 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002842 for (const auto &S : Spellings)
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002843 if (Variety.empty() || (Variety == S.variety() &&
2844 (Scope.empty() || Scope == S.nameSpace())))
Aaron Ballmana0344c52014-11-14 13:44:02 +00002845 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002846 }
Aaron Ballmana0344c52014-11-14 13:44:02 +00002847 OS << " .Default(0);\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002848}
2849
2850// Emits the list of spellings for attributes.
2851void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2852 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
2853
2854 // Separate all of the attributes out into four group: generic, C++11, GNU,
2855 // and declspecs. Then generate a big switch statement for each of them.
2856 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Nico Weber20e08042016-09-03 02:55:10 +00002857 std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
Aaron Ballman606093a2017-10-15 15:01:42 +00002858 std::map<std::string, std::vector<Record *>> CXX, C2x;
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002859
2860 // Walk over the list of all attributes, and split them out based on the
2861 // spelling variety.
2862 for (auto *R : Attrs) {
2863 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2864 for (const auto &SI : Spellings) {
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00002865 const std::string &Variety = SI.variety();
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002866 if (Variety == "GNU")
2867 GNU.push_back(R);
2868 else if (Variety == "Declspec")
2869 Declspec.push_back(R);
Nico Weber20e08042016-09-03 02:55:10 +00002870 else if (Variety == "Microsoft")
2871 Microsoft.push_back(R);
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00002872 else if (Variety == "CXX11")
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002873 CXX[SI.nameSpace()].push_back(R);
Aaron Ballman606093a2017-10-15 15:01:42 +00002874 else if (Variety == "C2x")
2875 C2x[SI.nameSpace()].push_back(R);
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00002876 else if (Variety == "Pragma")
2877 Pragma.push_back(R);
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002878 }
2879 }
2880
Bob Wilson7c730832015-07-20 22:57:31 +00002881 OS << "const llvm::Triple &T = Target.getTriple();\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002882 OS << "switch (Syntax) {\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002883 OS << "case AttrSyntax::GNU:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00002884 OS << " return llvm::StringSwitch<int>(Name)\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002885 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
2886 OS << "case AttrSyntax::Declspec:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00002887 OS << " return llvm::StringSwitch<int>(Name)\n";
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002888 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
Nico Weber20e08042016-09-03 02:55:10 +00002889 OS << "case AttrSyntax::Microsoft:\n";
2890 OS << " return llvm::StringSwitch<int>(Name)\n";
2891 GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00002892 OS << "case AttrSyntax::Pragma:\n";
Aaron Ballmana0344c52014-11-14 13:44:02 +00002893 OS << " return llvm::StringSwitch<int>(Name)\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00002894 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
Aaron Ballman606093a2017-10-15 15:01:42 +00002895 auto fn = [&OS](const char *Spelling, const char *Variety,
2896 const std::map<std::string, std::vector<Record *>> &List) {
2897 OS << "case AttrSyntax::" << Variety << ": {\n";
2898 // C++11-style attributes are further split out based on the Scope.
2899 for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
2900 if (I != List.cbegin())
2901 OS << " else ";
2902 if (I->first.empty())
2903 OS << "if (!Scope || Scope->getName() == \"\") {\n";
2904 else
2905 OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
2906 OS << " return llvm::StringSwitch<int>(Name)\n";
2907 GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
2908 OS << "}";
2909 }
Aaron Ballman4ff3b5ab2017-10-18 12:11:58 +00002910 OS << "\n} break;\n";
Aaron Ballman606093a2017-10-15 15:01:42 +00002911 };
2912 fn("CXX11", "CXX", CXX);
2913 fn("C2x", "C", C2x);
Aaron Ballman2fbf9942014-03-31 13:14:44 +00002914 OS << "}\n";
Peter Collingbournebee583f2011-10-06 13:03:08 +00002915}
2916
Michael Han99315932013-01-24 16:46:58 +00002917void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00002918 emitSourceFileHeader("Code to translate different attribute spellings "
2919 "into internal identifiers", OS);
Michael Han99315932013-01-24 16:46:58 +00002920
John McCall2225c8b2016-03-01 00:18:05 +00002921 OS << " switch (AttrKind) {\n";
Michael Han99315932013-01-24 16:46:58 +00002922
Aaron Ballman64e69862013-12-15 13:05:48 +00002923 ParsedAttrMap Attrs = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002924 for (const auto &I : Attrs) {
Aaron Ballman2f22b942014-05-20 19:47:14 +00002925 const Record &R = *I.second;
Aaron Ballmanc669cc02014-01-27 22:10:04 +00002926 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00002927 OS << " case AT_" << I.first << ": {\n";
Richard Smith852e9ce2013-11-27 01:46:48 +00002928 for (unsigned I = 0; I < Spellings.size(); ++ I) {
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00002929 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
2930 << "SyntaxUsed == "
2931 << StringSwitch<unsigned>(Spellings[I].variety())
2932 .Case("GNU", 0)
2933 .Case("CXX11", 1)
Aaron Ballman606093a2017-10-15 15:01:42 +00002934 .Case("C2x", 2)
2935 .Case("Declspec", 3)
2936 .Case("Microsoft", 4)
2937 .Case("Keyword", 5)
2938 .Case("Pragma", 6)
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00002939 .Default(0)
2940 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
2941 << " return " << I << ";\n";
Michael Han99315932013-01-24 16:46:58 +00002942 }
Richard Smith852e9ce2013-11-27 01:46:48 +00002943
2944 OS << " break;\n";
2945 OS << " }\n";
Michael Han99315932013-01-24 16:46:58 +00002946 }
2947
2948 OS << " }\n";
Aaron Ballman64e69862013-12-15 13:05:48 +00002949 OS << " return 0;\n";
Michael Han99315932013-01-24 16:46:58 +00002950}
2951
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00002952// Emits code used by RecursiveASTVisitor to visit attributes
2953void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
2954 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
2955
2956 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2957
2958 // Write method declarations for Traverse* methods.
2959 // We emit this here because we only generate methods for attributes that
2960 // are declared as ASTNodes.
2961 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00002962 for (const auto *Attr : Attrs) {
2963 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00002964 if (!R.getValueAsBit("ASTNode"))
2965 continue;
2966 OS << " bool Traverse"
2967 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
2968 OS << " bool Visit"
2969 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2970 << " return true; \n"
Hans Wennborg4afe5042015-07-22 20:46:26 +00002971 << " }\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00002972 }
2973 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
2974
2975 // Write individual Traverse* methods for each attribute class.
Aaron Ballman2f22b942014-05-20 19:47:14 +00002976 for (const auto *Attr : Attrs) {
2977 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00002978 if (!R.getValueAsBit("ASTNode"))
2979 continue;
2980
2981 OS << "template <typename Derived>\n"
DeLesley Hutchinsbb79c332013-12-30 21:03:02 +00002982 << "bool VISITORCLASS<Derived>::Traverse"
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00002983 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2984 << " if (!getDerived().VisitAttr(A))\n"
2985 << " return false;\n"
2986 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
2987 << " return false;\n";
2988
2989 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman2f22b942014-05-20 19:47:14 +00002990 for (const auto *Arg : ArgRecords)
2991 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00002992
2993 OS << " return true;\n";
2994 OS << "}\n\n";
2995 }
2996
2997 // Write generic Traverse routine
2998 OS << "template <typename Derived>\n"
DeLesley Hutchinsbb79c332013-12-30 21:03:02 +00002999 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003000 << " if (!A)\n"
3001 << " return true;\n"
3002 << "\n"
John McCall2225c8b2016-03-01 00:18:05 +00003003 << " switch (A->getKind()) {\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003004
Aaron Ballman2f22b942014-05-20 19:47:14 +00003005 for (const auto *Attr : Attrs) {
3006 const Record &R = *Attr;
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003007 if (!R.getValueAsBit("ASTNode"))
3008 continue;
3009
3010 OS << " case attr::" << R.getName() << ":\n"
3011 << " return getDerived().Traverse" << R.getName() << "Attr("
3012 << "cast<" << R.getName() << "Attr>(A));\n";
3013 }
John McCall5d7cf772016-03-01 02:09:20 +00003014 OS << " }\n"; // end switch
3015 OS << " llvm_unreachable(\"bad attribute kind\");\n";
DeLesley Hutchinsc4a82432013-12-30 17:24:36 +00003016 OS << "}\n"; // end function
3017 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
3018}
3019
Erich Keanea32910d2017-03-23 18:51:54 +00003020void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3021 raw_ostream &OS,
3022 bool AppliesToDecl) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003023
Erich Keanea32910d2017-03-23 18:51:54 +00003024 OS << " switch (At->getKind()) {\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00003025 for (const auto *Attr : Attrs) {
3026 const Record &R = *Attr;
Douglas Gregorb2daf842012-05-02 15:56:52 +00003027 if (!R.getValueAsBit("ASTNode"))
3028 continue;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003029 OS << " case attr::" << R.getName() << ": {\n";
Erich Keanea32910d2017-03-23 18:51:54 +00003030 bool ShouldClone = R.getValueAsBit("Clone") &&
3031 (!AppliesToDecl ||
3032 R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
Rafael Espindola7f90b7d2012-05-15 14:09:55 +00003033
3034 if (!ShouldClone) {
Hans Wennborg59dbe862015-09-29 20:56:43 +00003035 OS << " return nullptr;\n";
Rafael Espindola7f90b7d2012-05-15 14:09:55 +00003036 OS << " }\n";
3037 continue;
3038 }
3039
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003040 OS << " const auto *A = cast<"
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003041 << R.getName() << "Attr>(At);\n";
3042 bool TDependent = R.getValueAsBit("TemplateDependent");
3043
3044 if (!TDependent) {
3045 OS << " return A->clone(C);\n";
3046 OS << " }\n";
3047 continue;
3048 }
3049
3050 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003051 std::vector<std::unique_ptr<Argument>> Args;
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003052 Args.reserve(ArgRecords.size());
3053
Aaron Ballman2f22b942014-05-20 19:47:14 +00003054 for (const auto *ArgRecord : ArgRecords)
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003055 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003056
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003057 for (auto const &ai : Args)
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003058 ai->writeTemplateInstantiation(OS);
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003059
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003060 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
Aaron Ballman8f1439b2014-03-05 16:49:55 +00003061 for (auto const &ai : Args) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003062 OS << ", ";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003063 ai->writeTemplateInstantiationArgs(OS);
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003064 }
Aaron Ballman36a53502014-01-16 13:03:14 +00003065 OS << ", A->getSpellingListIndex());\n }\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003066 }
3067 OS << " } // end switch\n"
3068 << " llvm_unreachable(\"Unknown attribute!\");\n"
Erich Keanea32910d2017-03-23 18:51:54 +00003069 << " return nullptr;\n";
3070}
3071
3072// Emits code to instantiate dependent attributes on templates.
3073void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3074 emitSourceFileHeader("Template instantiation code for attributes", OS);
3075
3076 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3077
3078 OS << "namespace clang {\n"
3079 << "namespace sema {\n\n"
3080 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3081 << "Sema &S,\n"
3082 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3083 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3084 OS << "}\n\n"
3085 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3086 << " ASTContext &C, Sema &S,\n"
3087 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3088 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3089 OS << "}\n\n"
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00003090 << "} // end namespace sema\n"
3091 << "} // end namespace clang\n";
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00003092}
3093
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003094// Emits the list of parsed attributes.
3095void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3096 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3097
3098 OS << "#ifndef PARSED_ATTR\n";
3099 OS << "#define PARSED_ATTR(NAME) NAME\n";
3100 OS << "#endif\n\n";
3101
3102 ParsedAttrMap Names = getParsedAttrList(Records);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003103 for (const auto &I : Names) {
3104 OS << "PARSED_ATTR(" << I.first << ")\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003105 }
3106}
3107
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003108static bool isArgVariadic(const Record &R, StringRef AttrName) {
3109 return createArgument(R, AttrName)->isVariadic();
3110}
3111
Erich Keanedf9e8ae2017-10-16 22:47:26 +00003112static void emitArgInfo(const Record &R, raw_ostream &OS) {
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003113 // This function will count the number of arguments specified for the
3114 // attribute and emit the number of required arguments followed by the
3115 // number of optional arguments.
3116 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3117 unsigned ArgCount = 0, OptCount = 0;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003118 bool HasVariadic = false;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003119 for (const auto *Arg : Args) {
George Burgess IV8a36ace2016-12-01 17:52:39 +00003120 // If the arg is fake, it's the user's job to supply it: general parsing
3121 // logic shouldn't need to know anything about it.
3122 if (Arg->getValueAsBit("Fake"))
3123 continue;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003124 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003125 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3126 HasVariadic = true;
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003127 }
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00003128
3129 // If there is a variadic argument, we will set the optional argument count
3130 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3131 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003132}
3133
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003134static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
Erich Keanee891aa92018-07-13 15:07:47 +00003135 OS << "static bool defaultAppertainsTo(Sema &, const ParsedAttr &,";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003136 OS << "const Decl *) {\n";
3137 OS << " return true;\n";
3138 OS << "}\n\n";
3139}
3140
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003141static std::string GetDiagnosticSpelling(const Record &R) {
3142 std::string Ret = R.getValueAsString("DiagSpelling");
3143 if (!Ret.empty())
3144 return Ret;
3145
3146 // If we couldn't find the DiagSpelling in this object, we can check to see
3147 // if the object is one that has a base, and if it is, loop up to the Base
3148 // member recursively.
3149 std::string Super = R.getSuperClasses().back().first->getName();
3150 if (Super == "DDecl" || Super == "DStmt")
3151 return GetDiagnosticSpelling(*R.getValueAsDef("Base"));
3152
3153 return "";
3154}
3155
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003156static std::string CalculateDiagnostic(const Record &S) {
3157 // If the SubjectList object has a custom diagnostic associated with it,
3158 // return that directly.
Erich Keane3bff4142017-10-16 23:25:24 +00003159 const StringRef CustomDiag = S.getValueAsString("CustomDiag");
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003160 if (!CustomDiag.empty())
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003161 return ("\"" + Twine(CustomDiag) + "\"").str();
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003162
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003163 std::vector<std::string> DiagList;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003164 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
Aaron Ballman2f22b942014-05-20 19:47:14 +00003165 for (const auto *Subject : Subjects) {
3166 const Record &R = *Subject;
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003167 // Get the diagnostic text from the Decl or Stmt node given.
3168 std::string V = GetDiagnosticSpelling(R);
3169 if (V.empty()) {
3170 PrintError(R.getLoc(),
3171 "Could not determine diagnostic spelling for the node: " +
3172 R.getName() + "; please add one to DeclNodes.td");
3173 } else {
3174 // The node may contain a list of elements itself, so split the elements
3175 // by a comma, and trim any whitespace.
3176 SmallVector<StringRef, 2> Frags;
3177 llvm::SplitString(V, Frags, ",");
3178 for (auto Str : Frags) {
3179 DiagList.push_back(Str.trim());
3180 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003181 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003182 }
3183
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003184 if (DiagList.empty()) {
3185 PrintFatalError(S.getLoc(),
3186 "Could not deduce diagnostic argument for Attr subjects");
3187 return "";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003188 }
3189
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003190 // FIXME: this is not particularly good for localization purposes and ideally
3191 // should be part of the diagnostics engine itself with some sort of list
3192 // specifier.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003193
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003194 // A single member of the list can be returned directly.
3195 if (DiagList.size() == 1)
3196 return '"' + DiagList.front() + '"';
3197
3198 if (DiagList.size() == 2)
3199 return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3200
3201 // If there are more than two in the list, we serialize the first N - 1
3202 // elements with a comma. This leaves the string in the state: foo, bar,
3203 // baz (but misses quux). We can then add ", and " for the last element
3204 // manually.
3205 std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3206 return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003207}
3208
Aaron Ballman12b9f652014-01-16 13:55:42 +00003209static std::string GetSubjectWithSuffix(const Record *R) {
George Burgess IV1881a572016-12-01 00:13:18 +00003210 const std::string &B = R->getName();
Aaron Ballman12b9f652014-01-16 13:55:42 +00003211 if (B == "DeclBase")
3212 return "Decl";
3213 return B + "Decl";
3214}
Hans Wennborgdcfba332015-10-06 23:40:43 +00003215
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003216static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3217 return "is" + Subject.getName().str();
3218}
3219
Aaron Ballman80469032013-11-29 14:57:58 +00003220static std::string GenerateCustomAppertainsTo(const Record &Subject,
3221 raw_ostream &OS) {
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003222 std::string FnName = functionNameForCustomAppertainsTo(Subject);
Aaron Ballmana358c902013-12-02 14:58:17 +00003223
Aaron Ballman80469032013-11-29 14:57:58 +00003224 // If this code has already been generated, simply return the previous
3225 // instance of it.
3226 static std::set<std::string> CustomSubjectSet;
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003227 auto I = CustomSubjectSet.find(FnName);
Aaron Ballman80469032013-11-29 14:57:58 +00003228 if (I != CustomSubjectSet.end())
3229 return *I;
3230
3231 Record *Base = Subject.getValueAsDef("Base");
3232
3233 // Not currently support custom subjects within custom subjects.
3234 if (Base->isSubClassOf("SubsetSubject")) {
3235 PrintFatalError(Subject.getLoc(),
3236 "SubsetSubjects within SubsetSubjects is not supported");
3237 return "";
3238 }
3239
Aaron Ballman80469032013-11-29 14:57:58 +00003240 OS << "static bool " << FnName << "(const Decl *D) {\n";
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003241 OS << " if (const auto *S = dyn_cast<";
Aaron Ballman12b9f652014-01-16 13:55:42 +00003242 OS << GetSubjectWithSuffix(Base);
Aaron Ballman47553042014-01-16 14:32:03 +00003243 OS << ">(D))\n";
3244 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
3245 OS << " return false;\n";
Aaron Ballman80469032013-11-29 14:57:58 +00003246 OS << "}\n\n";
3247
3248 CustomSubjectSet.insert(FnName);
3249 return FnName;
3250}
3251
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003252static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
3253 // If the attribute does not contain a Subjects definition, then use the
3254 // default appertainsTo logic.
3255 if (Attr.isValueUnset("Subjects"))
Aaron Ballman93b5cc62013-12-02 19:36:42 +00003256 return "defaultAppertainsTo";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003257
3258 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3259 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3260
3261 // If the list of subjects is empty, it is assumed that the attribute
3262 // appertains to everything.
3263 if (Subjects.empty())
Aaron Ballman93b5cc62013-12-02 19:36:42 +00003264 return "defaultAppertainsTo";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003265
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003266 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3267
3268 // Otherwise, generate an appertainsTo check specific to this attribute which
3269 // checks all of the given subjects against the Decl passed in. Return the
3270 // name of that check to the caller.
Matthias Braunbbbf5d42016-12-04 05:55:09 +00003271 std::string FnName = "check" + Attr.getName().str() + "AppertainsTo";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003272 std::stringstream SS;
Erich Keanee891aa92018-07-13 15:07:47 +00003273 SS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr, ";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003274 SS << "const Decl *D) {\n";
3275 SS << " if (";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003276 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
Aaron Ballman80469032013-11-29 14:57:58 +00003277 // If the subject has custom code associated with it, generate a function
3278 // for it. The function cannot be inlined into this check (yet) because it
3279 // requires the subject to be of a specific type, and were that information
3280 // inlined here, it would not support an attribute with multiple custom
3281 // subjects.
3282 if ((*I)->isSubClassOf("SubsetSubject")) {
3283 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
3284 } else {
Aaron Ballman12b9f652014-01-16 13:55:42 +00003285 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
Aaron Ballman80469032013-11-29 14:57:58 +00003286 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003287
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003288 if (I + 1 != E)
3289 SS << " && ";
3290 }
3291 SS << ") {\n";
3292 SS << " S.Diag(Attr.getLoc(), diag::";
Aaron Ballmanadf66b62017-11-26 20:01:12 +00003293 SS << (Warn ? "warn_attribute_wrong_decl_type_str" :
3294 "err_attribute_wrong_decl_type_str");
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003295 SS << ")\n";
3296 SS << " << Attr.getName() << ";
3297 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
3298 SS << " return false;\n";
3299 SS << " }\n";
3300 SS << " return true;\n";
3301 SS << "}\n\n";
3302
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003303 OS << SS.str();
3304 return FnName;
3305}
3306
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003307static void
3308emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
3309 raw_ostream &OS) {
3310 OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
3311 << AttributeSubjectMatchRule::EnumName << " rule) {\n";
3312 OS << " switch (rule) {\n";
3313 for (const auto &Rule : PragmaAttributeSupport.Rules) {
3314 if (Rule.isAbstractRule()) {
3315 OS << " case " << Rule.getEnumValue() << ":\n";
3316 OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
3317 OS << " return false;\n";
3318 continue;
3319 }
3320 std::vector<Record *> Subjects = Rule.getSubjects();
3321 assert(!Subjects.empty() && "Missing subjects");
3322 OS << " case " << Rule.getEnumValue() << ":\n";
3323 OS << " return ";
3324 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3325 // If the subject has custom code associated with it, use the function
3326 // that was generated for GenerateAppertainsTo to check if the declaration
3327 // is valid.
3328 if ((*I)->isSubClassOf("SubsetSubject"))
3329 OS << functionNameForCustomAppertainsTo(**I) << "(D)";
3330 else
3331 OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3332
3333 if (I + 1 != E)
3334 OS << " || ";
3335 }
3336 OS << ";\n";
3337 }
3338 OS << " }\n";
3339 OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
3340 OS << "}\n\n";
3341}
3342
Aaron Ballman3aff6332013-12-02 19:30:36 +00003343static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
3344 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
Erich Keanee891aa92018-07-13 15:07:47 +00003345 OS << "const ParsedAttr &) {\n";
Aaron Ballman3aff6332013-12-02 19:30:36 +00003346 OS << " return true;\n";
3347 OS << "}\n\n";
3348}
3349
3350static std::string GenerateLangOptRequirements(const Record &R,
3351 raw_ostream &OS) {
3352 // If the attribute has an empty or unset list of language requirements,
3353 // return the default handler.
3354 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
3355 if (LangOpts.empty())
3356 return "defaultDiagnoseLangOpts";
3357
3358 // Generate the test condition, as well as a unique function name for the
3359 // diagnostic test. The list of options should usually be short (one or two
3360 // options), and the uniqueness isn't strictly necessary (it is just for
3361 // codegen efficiency).
3362 std::string FnName = "check", Test;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003363 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
Erich Keane3bff4142017-10-16 23:25:24 +00003364 const StringRef Part = (*I)->getValueAsString("Name");
Eric Fiselier341e8252016-09-02 18:53:31 +00003365 if ((*I)->getValueAsBit("Negated")) {
3366 FnName += "Not";
Alexis Hunt724f14e2014-11-28 00:53:20 +00003367 Test += "!";
Eric Fiselier341e8252016-09-02 18:53:31 +00003368 }
Erich Keane3bff4142017-10-16 23:25:24 +00003369 Test += "S.LangOpts.";
3370 Test += Part;
Aaron Ballman3aff6332013-12-02 19:30:36 +00003371 if (I + 1 != E)
3372 Test += " || ";
3373 FnName += Part;
3374 }
3375 FnName += "LangOpts";
3376
3377 // If this code has already been generated, simply return the previous
3378 // instance of it.
3379 static std::set<std::string> CustomLangOptsSet;
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003380 auto I = CustomLangOptsSet.find(FnName);
Aaron Ballman3aff6332013-12-02 19:30:36 +00003381 if (I != CustomLangOptsSet.end())
3382 return *I;
3383
Erich Keanee891aa92018-07-13 15:07:47 +00003384 OS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr) {\n";
Aaron Ballman3aff6332013-12-02 19:30:36 +00003385 OS << " if (" << Test << ")\n";
3386 OS << " return true;\n\n";
3387 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
3388 OS << "<< Attr.getName();\n";
3389 OS << " return false;\n";
3390 OS << "}\n\n";
3391
3392 CustomLangOptsSet.insert(FnName);
3393 return FnName;
3394}
3395
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003396static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
Bob Wilson7c730832015-07-20 22:57:31 +00003397 OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003398 OS << " return true;\n";
3399 OS << "}\n\n";
3400}
3401
3402static std::string GenerateTargetRequirements(const Record &Attr,
3403 const ParsedAttrMap &Dupes,
3404 raw_ostream &OS) {
3405 // If the attribute is not a target specific attribute, return the default
3406 // target handler.
3407 if (!Attr.isSubClassOf("TargetSpecificAttr"))
3408 return "defaultTargetRequirements";
3409
3410 // Get the list of architectures to be tested for.
3411 const Record *R = Attr.getValueAsDef("Target");
Craig Topper00648582017-05-31 19:01:22 +00003412 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003413
3414 // If there are other attributes which share the same parsed attribute kind,
3415 // such as target-specific attributes with a shared spelling, collapse the
3416 // duplicate architectures. This is required because a shared target-specific
Erich Keanee891aa92018-07-13 15:07:47 +00003417 // attribute has only one ParsedAttr::Kind enumeration value, but it
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003418 // applies to multiple target architectures. In order for the attribute to be
3419 // considered valid, all of its architectures need to be included.
3420 if (!Attr.isValueUnset("ParseKind")) {
Erich Keane3bff4142017-10-16 23:25:24 +00003421 const StringRef APK = Attr.getValueAsString("ParseKind");
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003422 for (const auto &I : Dupes) {
3423 if (I.first == APK) {
Craig Topper00648582017-05-31 19:01:22 +00003424 std::vector<StringRef> DA =
3425 I.second->getValueAsDef("Target")->getValueAsListOfStrings(
3426 "Arches");
3427 Arches.insert(Arches.end(), DA.begin(), DA.end());
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003428 }
3429 }
3430 }
3431
Bob Wilson0058b822015-07-20 22:57:36 +00003432 std::string FnName = "isTarget";
3433 std::string Test;
3434 GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
Bob Wilson7c730832015-07-20 22:57:31 +00003435
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003436 // If this code has already been generated, simply return the previous
3437 // instance of it.
3438 static std::set<std::string> CustomTargetSet;
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003439 auto I = CustomTargetSet.find(FnName);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003440 if (I != CustomTargetSet.end())
3441 return *I;
3442
Bob Wilson7c730832015-07-20 22:57:31 +00003443 OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
3444 OS << " const llvm::Triple &T = Target.getTriple();\n";
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003445 OS << " return " << Test << ";\n";
3446 OS << "}\n\n";
3447
3448 CustomTargetSet.insert(FnName);
3449 return FnName;
3450}
3451
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003452static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
3453 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
Erich Keanee891aa92018-07-13 15:07:47 +00003454 << "const ParsedAttr &Attr) {\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003455 OS << " return UINT_MAX;\n";
3456 OS << "}\n\n";
3457}
3458
3459static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
3460 raw_ostream &OS) {
3461 // If the attribute does not have a semantic form, we can bail out early.
3462 if (!Attr.getValueAsBit("ASTNode"))
3463 return "defaultSpellingIndexToSemanticSpelling";
3464
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003465 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003466
3467 // If there are zero or one spellings, or all of the spellings share the same
3468 // name, we can also bail out early.
3469 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
3470 return "defaultSpellingIndexToSemanticSpelling";
3471
3472 // Generate the enumeration we will use for the mapping.
3473 SemanticSpellingMap SemanticToSyntacticMap;
3474 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
Matthias Braunbbbf5d42016-12-04 05:55:09 +00003475 std::string Name = Attr.getName().str() + "AttrSpellingMap";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003476
Erich Keanee891aa92018-07-13 15:07:47 +00003477 OS << "static unsigned " << Name << "(const ParsedAttr &Attr) {\n";
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003478 OS << Enum;
3479 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
3480 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
3481 OS << "}\n\n";
3482
3483 return Name;
3484}
3485
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003486static bool IsKnownToGCC(const Record &Attr) {
3487 // Look at the spellings for this subject; if there are any spellings which
3488 // claim to be known to GCC, the attribute is known to GCC.
George Burgess IV1881a572016-12-01 00:13:18 +00003489 return llvm::any_of(
3490 GetFlattenedSpellings(Attr),
3491 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
Aaron Ballman9a99e0d2014-01-20 17:18:35 +00003492}
3493
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003494/// Emits the parsed attribute helpers
3495void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3496 emitSourceFileHeader("Parsed attribute helpers", OS);
3497
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003498 PragmaClangAttributeSupport &PragmaAttributeSupport =
3499 getPragmaAttributeSupport(Records);
3500
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003501 // Get the list of parsed attributes, and accept the optional list of
3502 // duplicates due to the ParseKind.
3503 ParsedAttrMap Dupes;
3504 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003505
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003506 // Generate the default appertainsTo, target and language option diagnostic,
3507 // and spelling list index mapping methods.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003508 GenerateDefaultAppertainsTo(OS);
Aaron Ballman3aff6332013-12-02 19:30:36 +00003509 GenerateDefaultLangOptRequirements(OS);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003510 GenerateDefaultTargetRequirements(OS);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003511 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003512
3513 // Generate the appertainsTo diagnostic methods and write their names into
3514 // another mapping. At the same time, generate the AttrInfoMap object
3515 // contents. Due to the reliance on generated code, use separate streams so
3516 // that code will not be interleaved.
Erich Keanedf9e8ae2017-10-16 22:47:26 +00003517 std::string Buffer;
3518 raw_string_ostream SS {Buffer};
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003519 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003520 // TODO: If the attribute's kind appears in the list of duplicates, that is
3521 // because it is a target-specific attribute that appears multiple times.
3522 // It would be beneficial to test whether the duplicates are "similar
3523 // enough" to each other to not cause problems. For instance, check that
Alp Toker96cf7582014-01-18 21:49:37 +00003524 // the spellings are identical, and custom parsing rules match, etc.
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003525
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003526 // We need to generate struct instances based off ParsedAttrInfo from
Erich Keanee891aa92018-07-13 15:07:47 +00003527 // ParsedAttr.cpp.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003528 SS << " { ";
3529 emitArgInfo(*I->second, SS);
3530 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003531 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
Aaron Ballmanb9a457a2018-05-03 15:33:50 +00003532 SS << ", "
3533 << (I->second->isSubClassOf("TypeAttr") ||
3534 I->second->isSubClassOf("DeclOrTypeAttr"));
Richard Smith4f902c72016-03-08 00:32:55 +00003535 SS << ", " << I->second->isSubClassOf("StmtAttr");
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003536 SS << ", " << IsKnownToGCC(*I->second);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003537 SS << ", " << PragmaAttributeSupport.isAttributedSupported(*I->second);
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003538 SS << ", " << GenerateAppertainsTo(*I->second, OS);
Aaron Ballman3aff6332013-12-02 19:30:36 +00003539 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003540 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
Aaron Ballman81cb8cb2014-01-24 21:32:49 +00003541 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003542 SS << ", "
3543 << PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003544 SS << " }";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003545
3546 if (I + 1 != E)
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003547 SS << ",";
3548
3549 SS << " // AT_" << I->first << "\n";
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003550 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003551
Erich Keanee891aa92018-07-13 15:07:47 +00003552 OS << "static const ParsedAttrInfo AttrInfoMap[ParsedAttr::UnknownAttribute "
3553 "+ 1] = {\n";
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003554 OS << SS.str();
Aaron Ballman8ee40b72013-09-09 23:33:17 +00003555 OS << "};\n\n";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003556
3557 // Generate the attribute match rules.
3558 emitAttributeMatchRules(PragmaAttributeSupport, OS);
Michael Han4a045172012-03-07 00:12:16 +00003559}
3560
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00003561// Emits the kind list of parsed attributes
3562void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00003563 emitSourceFileHeader("Attribute name matcher", OS);
3564
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003565 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Nico Weber20e08042016-09-03 02:55:10 +00003566 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
Aaron Ballman606093a2017-10-15 15:01:42 +00003567 Keywords, Pragma, C2x;
Aaron Ballman64e69862013-12-15 13:05:48 +00003568 std::set<std::string> Seen;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003569 for (const auto *A : Attrs) {
3570 const Record &Attr = *A;
Richard Smith852e9ce2013-11-27 01:46:48 +00003571
Michael Han4a045172012-03-07 00:12:16 +00003572 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003573 bool Ignored = Attr.getValueAsBit("Ignored");
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003574 if (SemaHandler || Ignored) {
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003575 // Attribute spellings can be shared between target-specific attributes,
3576 // and can be shared between syntaxes for the same attribute. For
3577 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3578 // specific attribute, or MSP430-specific attribute. Additionally, an
3579 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3580 // for the same semantic attribute. Ultimately, we need to map each of
Erich Keanee891aa92018-07-13 15:07:47 +00003581 // these to a single ParsedAttr::Kind value, but the StringMatcher
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003582 // class cannot handle duplicate match strings. So we generate a list of
3583 // string to match based on the syntax, and emit multiple string matchers
3584 // depending on the syntax used.
Aaron Ballman64e69862013-12-15 13:05:48 +00003585 std::string AttrName;
3586 if (Attr.isSubClassOf("TargetSpecificAttr") &&
3587 !Attr.isValueUnset("ParseKind")) {
3588 AttrName = Attr.getValueAsString("ParseKind");
3589 if (Seen.find(AttrName) != Seen.end())
3590 continue;
3591 Seen.insert(AttrName);
3592 } else
3593 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3594
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003595 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003596 for (const auto &S : Spellings) {
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003597 const std::string &RawSpelling = S.name();
Craig Topper8ae12032014-05-07 06:21:57 +00003598 std::vector<StringMatcher::StringPair> *Matches = nullptr;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003599 std::string Spelling;
3600 const std::string &Variety = S.variety();
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003601 if (Variety == "CXX11") {
3602 Matches = &CXX11;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003603 Spelling += S.nameSpace();
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003604 Spelling += "::";
Aaron Ballman606093a2017-10-15 15:01:42 +00003605 } else if (Variety == "C2x") {
3606 Matches = &C2x;
3607 Spelling += S.nameSpace();
3608 Spelling += "::";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003609 } else if (Variety == "GNU")
3610 Matches = &GNU;
3611 else if (Variety == "Declspec")
3612 Matches = &Declspec;
Nico Weber20e08042016-09-03 02:55:10 +00003613 else if (Variety == "Microsoft")
3614 Matches = &Microsoft;
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003615 else if (Variety == "Keyword")
3616 Matches = &Keywords;
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003617 else if (Variety == "Pragma")
3618 Matches = &Pragma;
Alexis Hunta0e54d42012-06-18 16:13:52 +00003619
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003620 assert(Matches && "Unsupported spelling variety found");
3621
Justin Lebar4086fe52017-01-05 16:51:54 +00003622 if (Variety == "GNU")
3623 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3624 else
3625 Spelling += RawSpelling;
3626
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003627 if (SemaHandler)
Erich Keanee891aa92018-07-13 15:07:47 +00003628 Matches->push_back(StringMatcher::StringPair(
3629 Spelling, "return ParsedAttr::AT_" + AttrName + ";"));
Douglas Gregor19fbb8f2012-05-02 16:18:45 +00003630 else
Erich Keanee891aa92018-07-13 15:07:47 +00003631 Matches->push_back(StringMatcher::StringPair(
3632 Spelling, "return ParsedAttr::IgnoredAttribute;"));
Michael Han4a045172012-03-07 00:12:16 +00003633 }
3634 }
3635 }
Erich Keanee891aa92018-07-13 15:07:47 +00003636
3637 OS << "static ParsedAttr::Kind getAttrKind(StringRef Name, ";
3638 OS << "ParsedAttr::Syntax Syntax) {\n";
3639 OS << " if (ParsedAttr::AS_GNU == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003640 StringMatcher("Name", GNU, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003641 OS << " } else if (ParsedAttr::AS_Declspec == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003642 StringMatcher("Name", Declspec, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003643 OS << " } else if (ParsedAttr::AS_Microsoft == Syntax) {\n";
Nico Weber20e08042016-09-03 02:55:10 +00003644 StringMatcher("Name", Microsoft, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003645 OS << " } else if (ParsedAttr::AS_CXX11 == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003646 StringMatcher("Name", CXX11, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003647 OS << " } else if (ParsedAttr::AS_C2x == Syntax) {\n";
Aaron Ballman606093a2017-10-15 15:01:42 +00003648 StringMatcher("Name", C2x, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003649 OS << " } else if (ParsedAttr::AS_Keyword == Syntax || ";
3650 OS << "ParsedAttr::AS_ContextSensitiveKeyword == Syntax) {\n";
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003651 StringMatcher("Name", Keywords, OS).Emit();
Erich Keanee891aa92018-07-13 15:07:47 +00003652 OS << " } else if (ParsedAttr::AS_Pragma == Syntax) {\n";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003653 StringMatcher("Name", Pragma, OS).Emit();
Aaron Ballman09e98ff2014-01-13 21:42:39 +00003654 OS << " }\n";
Erich Keanee891aa92018-07-13 15:07:47 +00003655 OS << " return ParsedAttr::UnknownAttribute;\n"
Douglas Gregor377f99b2012-05-02 17:33:51 +00003656 << "}\n";
Michael Han4a045172012-03-07 00:12:16 +00003657}
3658
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003659// Emits the code to dump an attribute.
3660void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
Dmitri Gribenko6b11fca2013-01-30 21:54:20 +00003661 emitSourceFileHeader("Attribute dumper", OS);
3662
John McCall2225c8b2016-03-01 00:18:05 +00003663 OS << " switch (A->getKind()) {\n";
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003664 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003665 for (const auto *Attr : Attrs) {
3666 const Record &R = *Attr;
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003667 if (!R.getValueAsBit("ASTNode"))
3668 continue;
3669 OS << " case attr::" << R.getName() << ": {\n";
Aaron Ballmanbc909612014-01-22 21:51:20 +00003670
3671 // If the attribute has a semantically-meaningful name (which is determined
3672 // by whether there is a Spelling enumeration for it), then write out the
3673 // spelling used for the attribute.
Aaron Ballmanc669cc02014-01-27 22:10:04 +00003674 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
Aaron Ballmanbc909612014-01-22 21:51:20 +00003675 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
3676 OS << " OS << \" \" << A->getSpelling();\n";
3677
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003678 Args = R.getValueAsListOfDefs("Args");
3679 if (!Args.empty()) {
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003680 OS << " const auto *SA = cast<" << R.getName()
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003681 << "Attr>(A);\n";
Aaron Ballman2f22b942014-05-20 19:47:14 +00003682 for (const auto *Arg : Args)
3683 createArgument(*Arg, R.getName())->writeDump(OS);
Richard Trieude5cc7d2013-01-31 01:44:26 +00003684
Eugene Zelenko5f02b772015-12-08 18:49:01 +00003685 for (const auto *AI : Args)
3686 createArgument(*AI, R.getName())->writeDumpChildren(OS);
Alexander Kornienko5bc364e2013-01-07 17:53:08 +00003687 }
3688 OS <<
3689 " break;\n"
3690 " }\n";
3691 }
3692 OS << " }\n";
3693}
3694
Aaron Ballman35db2b32014-01-29 22:13:45 +00003695void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3696 raw_ostream &OS) {
3697 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3698 emitClangAttrArgContextList(Records, OS);
3699 emitClangAttrIdentifierArgList(Records, OS);
3700 emitClangAttrTypeArgList(Records, OS);
3701 emitClangAttrLateParsedList(Records, OS);
3702}
3703
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003704void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
3705 raw_ostream &OS) {
3706 getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
3707}
3708
Aaron Ballman97dba042014-02-17 15:27:10 +00003709class DocumentationData {
3710public:
Aaron Ballman1a3e5852014-02-17 16:18:32 +00003711 const Record *Documentation;
3712 const Record *Attribute;
Erich Keanea98a2be2017-10-16 20:31:05 +00003713 std::string Heading;
3714 unsigned SupportedSpellings;
Aaron Ballman97dba042014-02-17 15:27:10 +00003715
Erich Keanea98a2be2017-10-16 20:31:05 +00003716 DocumentationData(const Record &Documentation, const Record &Attribute,
3717 const std::pair<std::string, unsigned> HeadingAndKinds)
3718 : Documentation(&Documentation), Attribute(&Attribute),
3719 Heading(std::move(HeadingAndKinds.first)),
3720 SupportedSpellings(HeadingAndKinds.second) {}
Aaron Ballman97dba042014-02-17 15:27:10 +00003721};
3722
Aaron Ballman4de1b582014-02-19 22:59:32 +00003723static void WriteCategoryHeader(const Record *DocCategory,
Aaron Ballman97dba042014-02-17 15:27:10 +00003724 raw_ostream &OS) {
Erich Keane3bff4142017-10-16 23:25:24 +00003725 const StringRef Name = DocCategory->getValueAsString("Name");
3726 OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
Aaron Ballman4de1b582014-02-19 22:59:32 +00003727
3728 // If there is content, print that as well.
Erich Keane3bff4142017-10-16 23:25:24 +00003729 const StringRef ContentStr = DocCategory->getValueAsString("Content");
Benjamin Kramer5c404072015-04-10 21:37:21 +00003730 // Trim leading and trailing newlines and spaces.
Erich Keane3bff4142017-10-16 23:25:24 +00003731 OS << ContentStr.trim();
Benjamin Kramer5c404072015-04-10 21:37:21 +00003732
Aaron Ballman4de1b582014-02-19 22:59:32 +00003733 OS << "\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003734}
3735
Aaron Ballmana66b5742014-02-17 15:36:08 +00003736enum SpellingKind {
3737 GNU = 1 << 0,
3738 CXX11 = 1 << 1,
Aaron Ballman606093a2017-10-15 15:01:42 +00003739 C2x = 1 << 2,
3740 Declspec = 1 << 3,
3741 Microsoft = 1 << 4,
3742 Keyword = 1 << 5,
3743 Pragma = 1 << 6
Aaron Ballmana66b5742014-02-17 15:36:08 +00003744};
3745
Erich Keanea98a2be2017-10-16 20:31:05 +00003746static std::pair<std::string, unsigned>
3747GetAttributeHeadingAndSpellingKinds(const Record &Documentation,
3748 const Record &Attribute) {
Aaron Ballman97dba042014-02-17 15:27:10 +00003749 // FIXME: there is no way to have a per-spelling category for the attribute
3750 // documentation. This may not be a limiting factor since the spellings
3751 // should generally be consistently applied across the category.
3752
Erich Keanea98a2be2017-10-16 20:31:05 +00003753 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
Aaron Ballman97dba042014-02-17 15:27:10 +00003754
3755 // Determine the heading to be used for this attribute.
Erich Keanea98a2be2017-10-16 20:31:05 +00003756 std::string Heading = Documentation.getValueAsString("Heading");
Aaron Ballmanea6668c2014-02-21 14:14:04 +00003757 bool CustomHeading = !Heading.empty();
Aaron Ballman97dba042014-02-17 15:27:10 +00003758 if (Heading.empty()) {
3759 // If there's only one spelling, we can simply use that.
3760 if (Spellings.size() == 1)
3761 Heading = Spellings.begin()->name();
3762 else {
3763 std::set<std::string> Uniques;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003764 for (auto I = Spellings.begin(), E = Spellings.end();
3765 I != E && Uniques.size() <= 1; ++I) {
Aaron Ballman97dba042014-02-17 15:27:10 +00003766 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
3767 Uniques.insert(Spelling);
3768 }
3769 // If the semantic map has only one spelling, that is sufficient for our
3770 // needs.
3771 if (Uniques.size() == 1)
3772 Heading = *Uniques.begin();
3773 }
3774 }
3775
3776 // If the heading is still empty, it is an error.
3777 if (Heading.empty())
Erich Keanea98a2be2017-10-16 20:31:05 +00003778 PrintFatalError(Attribute.getLoc(),
Aaron Ballman97dba042014-02-17 15:27:10 +00003779 "This attribute requires a heading to be specified");
3780
3781 // Gather a list of unique spellings; this is not the same as the semantic
3782 // spelling for the attribute. Variations in underscores and other non-
3783 // semantic characters are still acceptable.
3784 std::vector<std::string> Names;
3785
Aaron Ballman97dba042014-02-17 15:27:10 +00003786 unsigned SupportedSpellings = 0;
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003787 for (const auto &I : Spellings) {
3788 SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003789 .Case("GNU", GNU)
3790 .Case("CXX11", CXX11)
Aaron Ballman606093a2017-10-15 15:01:42 +00003791 .Case("C2x", C2x)
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003792 .Case("Declspec", Declspec)
Nico Weber20e08042016-09-03 02:55:10 +00003793 .Case("Microsoft", Microsoft)
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003794 .Case("Keyword", Keyword)
3795 .Case("Pragma", Pragma);
Aaron Ballman97dba042014-02-17 15:27:10 +00003796
3797 // Mask in the supported spelling.
3798 SupportedSpellings |= Kind;
3799
3800 std::string Name;
Aaron Ballman606093a2017-10-15 15:01:42 +00003801 if ((Kind == CXX11 || Kind == C2x) && !I.nameSpace().empty())
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003802 Name = I.nameSpace() + "::";
3803 Name += I.name();
Aaron Ballman97dba042014-02-17 15:27:10 +00003804
3805 // If this name is the same as the heading, do not add it.
3806 if (Name != Heading)
3807 Names.push_back(Name);
3808 }
3809
3810 // Print out the heading for the attribute. If there are alternate spellings,
3811 // then display those after the heading.
Aaron Ballmanea6668c2014-02-21 14:14:04 +00003812 if (!CustomHeading && !Names.empty()) {
Aaron Ballman97dba042014-02-17 15:27:10 +00003813 Heading += " (";
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003814 for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
Aaron Ballman97dba042014-02-17 15:27:10 +00003815 if (I != Names.begin())
3816 Heading += ", ";
3817 Heading += *I;
3818 }
3819 Heading += ")";
3820 }
Aaron Ballman97dba042014-02-17 15:27:10 +00003821 if (!SupportedSpellings)
Erich Keanea98a2be2017-10-16 20:31:05 +00003822 PrintFatalError(Attribute.getLoc(),
Aaron Ballman97dba042014-02-17 15:27:10 +00003823 "Attribute has no supported spellings; cannot be "
3824 "documented");
Erich Keanea98a2be2017-10-16 20:31:05 +00003825 return std::make_pair(std::move(Heading), SupportedSpellings);
3826}
3827
3828static void WriteDocumentation(RecordKeeper &Records,
3829 const DocumentationData &Doc, raw_ostream &OS) {
3830 OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003831
3832 // List what spelling syntaxes the attribute supports.
3833 OS << ".. csv-table:: Supported Syntaxes\n";
Aaron Ballman606093a2017-10-15 15:01:42 +00003834 OS << " :header: \"GNU\", \"C++11\", \"C2x\", \"__declspec\", \"Keyword\",";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003835 OS << " \"Pragma\", \"Pragma clang attribute\"\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003836 OS << " \"";
Erich Keanea98a2be2017-10-16 20:31:05 +00003837 if (Doc.SupportedSpellings & GNU) OS << "X";
Aaron Ballman97dba042014-02-17 15:27:10 +00003838 OS << "\",\"";
Erich Keanea98a2be2017-10-16 20:31:05 +00003839 if (Doc.SupportedSpellings & CXX11) OS << "X";
Aaron Ballman97dba042014-02-17 15:27:10 +00003840 OS << "\",\"";
Erich Keanea98a2be2017-10-16 20:31:05 +00003841 if (Doc.SupportedSpellings & C2x) OS << "X";
Aaron Ballman606093a2017-10-15 15:01:42 +00003842 OS << "\",\"";
Erich Keanea98a2be2017-10-16 20:31:05 +00003843 if (Doc.SupportedSpellings & Declspec) OS << "X";
Aaron Ballman97dba042014-02-17 15:27:10 +00003844 OS << "\",\"";
Erich Keanea98a2be2017-10-16 20:31:05 +00003845 if (Doc.SupportedSpellings & Keyword) OS << "X";
Aaron Ballman120c79f2014-06-25 12:48:06 +00003846 OS << "\", \"";
Erich Keanea98a2be2017-10-16 20:31:05 +00003847 if (Doc.SupportedSpellings & Pragma) OS << "X";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003848 OS << "\", \"";
3849 if (getPragmaAttributeSupport(Records).isAttributedSupported(*Doc.Attribute))
3850 OS << "X";
Tyler Nowickie8b07ed2014-06-13 17:57:25 +00003851 OS << "\"\n\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003852
3853 // If the attribute is deprecated, print a message about it, and possibly
3854 // provide a replacement attribute.
Aaron Ballman1a3e5852014-02-17 16:18:32 +00003855 if (!Doc.Documentation->isValueUnset("Deprecated")) {
Aaron Ballman97dba042014-02-17 15:27:10 +00003856 OS << "This attribute has been deprecated, and may be removed in a future "
3857 << "version of Clang.";
Aaron Ballman1a3e5852014-02-17 16:18:32 +00003858 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
Erich Keane3bff4142017-10-16 23:25:24 +00003859 const StringRef Replacement = Deprecated.getValueAsString("Replacement");
Aaron Ballman97dba042014-02-17 15:27:10 +00003860 if (!Replacement.empty())
Joel E. Denny6053ec22018-02-28 16:57:33 +00003861 OS << " This attribute has been superseded by ``" << Replacement
3862 << "``.";
Aaron Ballman97dba042014-02-17 15:27:10 +00003863 OS << "\n\n";
3864 }
3865
Erich Keane3bff4142017-10-16 23:25:24 +00003866 const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
Aaron Ballman97dba042014-02-17 15:27:10 +00003867 // Trim leading and trailing newlines and spaces.
Erich Keane3bff4142017-10-16 23:25:24 +00003868 OS << ContentStr.trim();
Aaron Ballman97dba042014-02-17 15:27:10 +00003869
3870 OS << "\n\n\n";
3871}
3872
3873void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
3874 // Get the documentation introduction paragraph.
3875 const Record *Documentation = Records.getDef("GlobalDocumentation");
3876 if (!Documentation) {
3877 PrintFatalError("The Documentation top-level definition is missing, "
3878 "no documentation will be generated.");
3879 return;
3880 }
3881
Aaron Ballman4de1b582014-02-19 22:59:32 +00003882 OS << Documentation->getValueAsString("Intro") << "\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003883
Aaron Ballman97dba042014-02-17 15:27:10 +00003884 // Gather the Documentation lists from each of the attributes, based on the
3885 // category provided.
3886 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003887 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
Aaron Ballman2f22b942014-05-20 19:47:14 +00003888 for (const auto *A : Attrs) {
3889 const Record &Attr = *A;
Aaron Ballman97dba042014-02-17 15:27:10 +00003890 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
Aaron Ballman2f22b942014-05-20 19:47:14 +00003891 for (const auto *D : Docs) {
3892 const Record &Doc = *D;
Aaron Ballman4de1b582014-02-19 22:59:32 +00003893 const Record *Category = Doc.getValueAsDef("Category");
Aaron Ballman97dba042014-02-17 15:27:10 +00003894 // If the category is "undocumented", then there cannot be any other
3895 // documentation categories (otherwise, the attribute would become
3896 // documented).
Erich Keane3bff4142017-10-16 23:25:24 +00003897 const StringRef Cat = Category->getValueAsString("Name");
Aaron Ballman4de1b582014-02-19 22:59:32 +00003898 bool Undocumented = Cat == "Undocumented";
Aaron Ballman97dba042014-02-17 15:27:10 +00003899 if (Undocumented && Docs.size() > 1)
3900 PrintFatalError(Doc.getLoc(),
3901 "Attribute is \"Undocumented\", but has multiple "
Erich Keanea98a2be2017-10-16 20:31:05 +00003902 "documentation categories");
Aaron Ballman97dba042014-02-17 15:27:10 +00003903
3904 if (!Undocumented)
Erich Keanea98a2be2017-10-16 20:31:05 +00003905 SplitDocs[Category].push_back(DocumentationData(
3906 Doc, Attr, GetAttributeHeadingAndSpellingKinds(Doc, Attr)));
Aaron Ballman97dba042014-02-17 15:27:10 +00003907 }
3908 }
3909
3910 // Having split the attributes out based on what documentation goes where,
3911 // we can begin to generate sections of documentation.
Erich Keanea98a2be2017-10-16 20:31:05 +00003912 for (auto &I : SplitDocs) {
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003913 WriteCategoryHeader(I.first, OS);
Aaron Ballman97dba042014-02-17 15:27:10 +00003914
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00003915 llvm::sort(I.second.begin(), I.second.end(),
3916 [](const DocumentationData &D1, const DocumentationData &D2) {
3917 return D1.Heading < D2.Heading;
Erich Keanea98a2be2017-10-16 20:31:05 +00003918 });
3919
Aaron Ballman97dba042014-02-17 15:27:10 +00003920 // Walk over each of the attributes in the category and write out their
3921 // documentation.
Aaron Ballmanb097f7fe2014-03-02 17:38:37 +00003922 for (const auto &Doc : I.second)
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003923 WriteDocumentation(Records, Doc, OS);
3924 }
3925}
3926
3927void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
3928 raw_ostream &OS) {
3929 PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
3930 ParsedAttrMap Attrs = getParsedAttrList(Records);
3931 unsigned NumAttrs = 0;
3932 for (const auto &I : Attrs) {
3933 if (Support.isAttributedSupported(*I.second))
3934 ++NumAttrs;
3935 }
3936 OS << "#pragma clang attribute supports " << NumAttrs << " attributes:\n";
3937 for (const auto &I : Attrs) {
3938 if (!Support.isAttributedSupported(*I.second))
3939 continue;
3940 OS << I.first;
3941 if (I.second->isValueUnset("Subjects")) {
3942 OS << " ()\n";
3943 continue;
3944 }
3945 const Record *SubjectObj = I.second->getValueAsDef("Subjects");
3946 std::vector<Record *> Subjects =
3947 SubjectObj->getValueAsListOfDefs("Subjects");
3948 OS << " (";
3949 for (const auto &Subject : llvm::enumerate(Subjects)) {
3950 if (Subject.index())
3951 OS << ", ";
Alex Lorenz24952fb2017-04-19 15:52:11 +00003952 PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
3953 Support.SubjectsToRules.find(Subject.value())->getSecond();
3954 if (RuleSet.isRule()) {
3955 OS << RuleSet.getRule().getEnumValueName();
3956 continue;
3957 }
3958 OS << "(";
3959 for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
3960 if (Rule.index())
3961 OS << ", ";
3962 OS << Rule.value().getEnumValueName();
3963 }
3964 OS << ")";
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003965 }
3966 OS << ")\n";
Aaron Ballman97dba042014-02-17 15:27:10 +00003967 }
3968}
3969
Jakob Stoklund Olesen995e0e12012-06-13 05:12:41 +00003970} // end namespace clang