Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/utils/TableGen/ClangAttrEmitter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// These tablegen backends emit Clang attribute processing code
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TableGenBackends.h"
14
#include "ASTTableGen.h"
15
16
#include "llvm/ADT/ArrayRef.h"
17
#include "llvm/ADT/DenseMap.h"
18
#include "llvm/ADT/DenseSet.h"
19
#include "llvm/ADT/STLExtras.h"
20
#include "llvm/ADT/SmallString.h"
21
#include "llvm/ADT/StringExtras.h"
22
#include "llvm/ADT/StringRef.h"
23
#include "llvm/ADT/StringSet.h"
24
#include "llvm/ADT/StringSwitch.h"
25
#include "llvm/ADT/iterator_range.h"
26
#include "llvm/Support/ErrorHandling.h"
27
#include "llvm/Support/raw_ostream.h"
28
#include "llvm/TableGen/Error.h"
29
#include "llvm/TableGen/Record.h"
30
#include "llvm/TableGen/StringMatcher.h"
31
#include "llvm/TableGen/TableGenBackend.h"
32
#include <algorithm>
33
#include <cassert>
34
#include <cctype>
35
#include <cstddef>
36
#include <cstdint>
37
#include <map>
38
#include <memory>
39
#include <set>
40
#include <sstream>
41
#include <string>
42
#include <utility>
43
#include <vector>
44
45
using namespace llvm;
46
47
namespace {
48
49
class FlattenedSpelling {
50
  std::string V, N, NS;
51
  bool K = false;
52
53
public:
54
  FlattenedSpelling(const std::string &Variety, const std::string &Name,
55
                    const std::string &Namespace, bool KnownToGCC) :
56
711
    V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
57
  explicit FlattenedSpelling(const Record &Spelling)
58
      : V(std::string(Spelling.getValueAsString("Variety"))),
59
143
        N(std::string(Spelling.getValueAsString("Name"))) {
60
143
    assert(V != "GCC" && V != "Clang" &&
61
143
           "Given a GCC spelling, which means this hasn't been flattened!");
62
143
    if (V == "CXX11" || 
V == "C2x"128
||
V == "Pragma"121
)
63
27
      NS = std::string(Spelling.getValueAsString("Namespace"));
64
143
  }
65
66
390
  const std::string &variety() const { return V; }
67
0
  const std::string &name() const { return N; }
68
0
  const std::string &nameSpace() const { return NS; }
69
0
  bool knownToGCC() const { return K; }
70
};
71
72
} // end anonymous namespace
73
74
static std::vector<FlattenedSpelling>
75
307
GetFlattenedSpellings(const Record &Attr) {
76
307
  std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
77
307
  std::vector<FlattenedSpelling> Ret;
78
79
390
  for (const auto &Spelling : Spellings) {
80
390
    StringRef Variety = Spelling->getValueAsString("Variety");
81
390
    StringRef Name = Spelling->getValueAsString("Name");
82
390
    if (Variety == "GCC") {
83
87
      Ret.emplace_back("GNU", std::string(Name), "", true);
84
87
      Ret.emplace_back("CXX11", std::string(Name), "gnu", true);
85
87
      if (Spelling->getValueAsBit("AllowInC"))
86
85
        Ret.emplace_back("C2x", std::string(Name), "gnu", true);
87
303
    } else if (Variety == "Clang") {
88
160
      Ret.emplace_back("GNU", std::string(Name), "", false);
89
160
      Ret.emplace_back("CXX11", std::string(Name), "clang", false);
90
160
      if (Spelling->getValueAsBit("AllowInC"))
91
132
        Ret.emplace_back("C2x", std::string(Name), "clang", false);
92
160
    } else
93
143
      Ret.push_back(FlattenedSpelling(*Spelling));
94
390
  }
95
96
307
  return Ret;
97
307
}
98
99
0
static std::string ReadPCHRecord(StringRef type) {
100
0
  return StringSwitch<std::string>(type)
101
0
      .EndsWith("Decl *", "Record.GetLocalDeclAs<" +
102
0
                              std::string(type.data(), 0, type.size() - 1) +
103
0
                              ">(Record.readInt())")
104
0
      .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
105
0
      .Case("Expr *", "Record.readExpr()")
106
0
      .Case("IdentifierInfo *", "Record.readIdentifier()")
107
0
      .Case("StringRef", "Record.readString()")
108
0
      .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
109
0
      .Case("OMPTraitInfo *", "Record.readOMPTraitInfo()")
110
0
      .Default("Record.readInt()");
111
0
}
112
113
// Get a type that is suitable for storing an object of the specified type.
114
0
static StringRef getStorageType(StringRef type) {
115
0
  return StringSwitch<StringRef>(type)
116
0
    .Case("StringRef", "std::string")
117
0
    .Default(type);
118
0
}
119
120
// Assumes that the way to get the value is SA->getname()
121
0
static std::string WritePCHRecord(StringRef type, StringRef name) {
122
0
  return "Record." +
123
0
         StringSwitch<std::string>(type)
124
0
             .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
125
0
             .Case("TypeSourceInfo *",
126
0
                   "AddTypeSourceInfo(" + std::string(name) + ");\n")
127
0
             .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
128
0
             .Case("IdentifierInfo *",
129
0
                   "AddIdentifierRef(" + std::string(name) + ");\n")
130
0
             .Case("StringRef", "AddString(" + std::string(name) + ");\n")
131
0
             .Case("ParamIdx",
132
0
                   "push_back(" + std::string(name) + ".serialize());\n")
133
0
             .Case("OMPTraitInfo *",
134
0
                   "writeOMPTraitInfo(" + std::string(name) + ");\n")
135
0
             .Default("push_back(" + std::string(name) + ");\n");
136
0
}
137
138
// Normalize attribute name by removing leading and trailing
139
// underscores. For example, __foo, foo__, __foo__ would
140
// become foo.
141
328
static StringRef NormalizeAttrName(StringRef AttrName) {
142
328
  AttrName.consume_front("__");
143
328
  AttrName.consume_back("__");
144
328
  return AttrName;
145
328
}
146
147
// Normalize the name by removing any and all leading and trailing underscores.
148
// This is different from NormalizeAttrName in that it also handles names like
149
// _pascal and __pascal.
150
0
static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
151
0
  return Name.trim("_");
152
0
}
153
154
// Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
155
// removing "__" if it appears at the beginning and end of the attribute's name.
156
0
static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
157
0
  if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
158
0
    AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
159
0
  }
160
161
0
  return AttrSpelling;
162
0
}
163
164
typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
165
166
static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
167
1
                                       ParsedAttrMap *Dupes = nullptr) {
168
1
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
169
1
  std::set<std::string> Seen;
170
1
  ParsedAttrMap R;
171
360
  for (const auto *Attr : Attrs) {
172
360
    if (Attr->getValueAsBit("SemaHandler")) {
173
335
      std::string AN;
174
335
      if (Attr->isSubClassOf("TargetSpecificAttr") &&
175
335
          
!Attr->isValueUnset("ParseKind")36
) {
176
7
        AN = std::string(Attr->getValueAsString("ParseKind"));
177
178
        // If this attribute has already been handled, it does not need to be
179
        // handled again.
180
7
        if (Seen.find(AN) != Seen.end()) {
181
6
          if (Dupes)
182
0
            Dupes->push_back(std::make_pair(AN, Attr));
183
6
          continue;
184
6
        }
185
1
        Seen.insert(AN);
186
1
      } else
187
328
        AN = NormalizeAttrName(Attr->getName()).str();
188
189
329
      R.push_back(std::make_pair(AN, Attr));
190
329
    }
191
360
  }
192
1
  return R;
193
1
}
194
195
namespace {
196
197
  class Argument {
198
    std::string lowerName, upperName;
199
    StringRef attrName;
200
    bool isOpt;
201
    bool Fake;
202
203
  public:
204
    Argument(const Record &Arg, StringRef Attr)
205
        : lowerName(std::string(Arg.getValueAsString("Name"))),
206
0
          upperName(lowerName), attrName(Attr), isOpt(false), Fake(false) {
207
0
      if (!lowerName.empty()) {
208
0
        lowerName[0] = std::tolower(lowerName[0]);
209
0
        upperName[0] = std::toupper(upperName[0]);
210
0
      }
211
      // Work around MinGW's macro definition of 'interface' to 'struct'. We
212
      // have an attribute argument called 'Interface', so only the lower case
213
      // name conflicts with the macro definition.
214
0
      if (lowerName == "interface")
215
0
        lowerName = "interface_";
216
0
    }
217
0
    virtual ~Argument() = default;
218
219
0
    StringRef getLowerName() const { return lowerName; }
220
0
    StringRef getUpperName() const { return upperName; }
221
0
    StringRef getAttrName() const { return attrName; }
222
223
0
    bool isOptional() const { return isOpt; }
224
0
    void setOptional(bool set) { isOpt = set; }
225
226
0
    bool isFake() const { return Fake; }
227
0
    void setFake(bool fake) { Fake = fake; }
228
229
    // These functions print the argument contents formatted in different ways.
230
    virtual void writeAccessors(raw_ostream &OS) const = 0;
231
0
    virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
232
0
    virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
233
    virtual void writeCloneArgs(raw_ostream &OS) const = 0;
234
    virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
235
0
    virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
236
0
    virtual void writeCtorBody(raw_ostream &OS) const {}
237
    virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
238
    virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
239
    virtual void writeCtorParameters(raw_ostream &OS) const = 0;
240
    virtual void writeDeclarations(raw_ostream &OS) const = 0;
241
    virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
242
    virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
243
    virtual void writePCHWrite(raw_ostream &OS) const = 0;
244
0
    virtual std::string getIsOmitted() const { return "false"; }
245
    virtual void writeValue(raw_ostream &OS) const = 0;
246
    virtual void writeDump(raw_ostream &OS) const = 0;
247
0
    virtual void writeDumpChildren(raw_ostream &OS) const {}
248
0
    virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
249
250
0
    virtual bool isEnumArg() const { return false; }
251
0
    virtual bool isVariadicEnumArg() const { return false; }
252
0
    virtual bool isVariadic() const { return false; }
253
254
0
    virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
255
0
      OS << getUpperName();
256
0
    }
257
  };
258
259
  class SimpleArgument : public Argument {
260
    std::string type;
261
262
  public:
263
    SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
264
0
        : Argument(Arg, Attr), type(std::move(T)) {}
265
266
0
    std::string getType() const { return type; }
267
268
0
    void writeAccessors(raw_ostream &OS) const override {
269
0
      OS << "  " << type << " get" << getUpperName() << "() const {\n";
270
0
      OS << "    return " << getLowerName() << ";\n";
271
0
      OS << "  }";
272
0
    }
273
274
0
    void writeCloneArgs(raw_ostream &OS) const override {
275
0
      OS << getLowerName();
276
0
    }
277
278
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
279
0
      OS << "A->get" << getUpperName() << "()";
280
0
    }
281
282
0
    void writeCtorInitializers(raw_ostream &OS) const override {
283
0
      OS << getLowerName() << "(" << getUpperName() << ")";
284
0
    }
285
286
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
287
0
      OS << getLowerName() << "()";
288
0
    }
289
290
0
    void writeCtorParameters(raw_ostream &OS) const override {
291
0
      OS << type << " " << getUpperName();
292
0
    }
293
294
0
    void writeDeclarations(raw_ostream &OS) const override {
295
0
      OS << type << " " << getLowerName() << ";";
296
0
    }
297
298
0
    void writePCHReadDecls(raw_ostream &OS) const override {
299
0
      std::string read = ReadPCHRecord(type);
300
0
      OS << "    " << type << " " << getLowerName() << " = " << read << ";\n";
301
0
    }
302
303
0
    void writePCHReadArgs(raw_ostream &OS) const override {
304
0
      OS << getLowerName();
305
0
    }
306
307
0
    void writePCHWrite(raw_ostream &OS) const override {
308
0
      OS << "    "
309
0
         << WritePCHRecord(type,
310
0
                           "SA->get" + std::string(getUpperName()) + "()");
311
0
    }
312
313
0
    std::string getIsOmitted() const override {
314
0
      if (type == "IdentifierInfo *")
315
0
        return "!get" + getUpperName().str() + "()";
316
0
      if (type == "TypeSourceInfo *")
317
0
        return "!get" + getUpperName().str() + "Loc()";
318
0
      if (type == "ParamIdx")
319
0
        return "!get" + getUpperName().str() + "().isValid()";
320
0
      return "false";
321
0
    }
322
323
0
    void writeValue(raw_ostream &OS) const override {
324
0
      if (type == "FunctionDecl *")
325
0
        OS << "\" << get" << getUpperName()
326
0
           << "()->getNameInfo().getAsString() << \"";
327
0
      else if (type == "IdentifierInfo *")
328
        // Some non-optional (comma required) identifier arguments can be the
329
        // empty string but are then recorded as a nullptr.
330
0
        OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
331
0
           << "()->getName() : \"\") << \"";
332
0
      else if (type == "VarDecl *")
333
0
        OS << "\" << get" << getUpperName() << "()->getName() << \"";
334
0
      else if (type == "TypeSourceInfo *")
335
0
        OS << "\" << get" << getUpperName() << "().getAsString() << \"";
336
0
      else if (type == "ParamIdx")
337
0
        OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
338
0
      else
339
0
        OS << "\" << get" << getUpperName() << "() << \"";
340
0
    }
341
342
0
    void writeDump(raw_ostream &OS) const override {
343
0
      if (StringRef(type).endswith("Decl *")) {
344
0
        OS << "    OS << \" \";\n";
345
0
        OS << "    dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
346
0
      } else if (type == "IdentifierInfo *") {
347
        // Some non-optional (comma required) identifier arguments can be the
348
        // empty string but are then recorded as a nullptr.
349
0
        OS << "    if (SA->get" << getUpperName() << "())\n"
350
0
           << "      OS << \" \" << SA->get" << getUpperName()
351
0
           << "()->getName();\n";
352
0
      } else if (type == "TypeSourceInfo *") {
353
0
        if (isOptional())
354
0
          OS << "    if (SA->get" << getUpperName() << "Loc())";
355
0
        OS << "    OS << \" \" << SA->get" << getUpperName()
356
0
           << "().getAsString();\n";
357
0
      } else if (type == "bool") {
358
0
        OS << "    if (SA->get" << getUpperName() << "()) OS << \" "
359
0
           << getUpperName() << "\";\n";
360
0
      } else if (type == "int" || type == "unsigned") {
361
0
        OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
362
0
      } else if (type == "ParamIdx") {
363
0
        if (isOptional())
364
0
          OS << "    if (SA->get" << getUpperName() << "().isValid())\n  ";
365
0
        OS << "    OS << \" \" << SA->get" << getUpperName()
366
0
           << "().getSourceIndex();\n";
367
0
      } else if (type == "OMPTraitInfo *") {
368
0
        OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
369
0
      } else {
370
0
        llvm_unreachable("Unknown SimpleArgument type!");
371
0
      }
372
0
    }
373
  };
374
375
  class DefaultSimpleArgument : public SimpleArgument {
376
    int64_t Default;
377
378
  public:
379
    DefaultSimpleArgument(const Record &Arg, StringRef Attr,
380
                          std::string T, int64_t Default)
381
0
      : SimpleArgument(Arg, Attr, T), Default(Default) {}
382
383
0
    void writeAccessors(raw_ostream &OS) const override {
384
0
      SimpleArgument::writeAccessors(OS);
385
386
0
      OS << "\n\n  static const " << getType() << " Default" << getUpperName()
387
0
         << " = ";
388
0
      if (getType() == "bool")
389
0
        OS << (Default != 0 ? "true" : "false");
390
0
      else
391
0
        OS << Default;
392
0
      OS << ";";
393
0
    }
394
  };
395
396
  class StringArgument : public Argument {
397
  public:
398
    StringArgument(const Record &Arg, StringRef Attr)
399
      : Argument(Arg, Attr)
400
0
    {}
401
402
0
    void writeAccessors(raw_ostream &OS) const override {
403
0
      OS << "  llvm::StringRef get" << getUpperName() << "() const {\n";
404
0
      OS << "    return llvm::StringRef(" << getLowerName() << ", "
405
0
         << getLowerName() << "Length);\n";
406
0
      OS << "  }\n";
407
0
      OS << "  unsigned get" << getUpperName() << "Length() const {\n";
408
0
      OS << "    return " << getLowerName() << "Length;\n";
409
0
      OS << "  }\n";
410
0
      OS << "  void set" << getUpperName()
411
0
         << "(ASTContext &C, llvm::StringRef S) {\n";
412
0
      OS << "    " << getLowerName() << "Length = S.size();\n";
413
0
      OS << "    this->" << getLowerName() << " = new (C, 1) char ["
414
0
         << getLowerName() << "Length];\n";
415
0
      OS << "    if (!S.empty())\n";
416
0
      OS << "      std::memcpy(this->" << getLowerName() << ", S.data(), "
417
0
         << getLowerName() << "Length);\n";
418
0
      OS << "  }";
419
0
    }
420
421
0
    void writeCloneArgs(raw_ostream &OS) const override {
422
0
      OS << "get" << getUpperName() << "()";
423
0
    }
424
425
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
426
0
      OS << "A->get" << getUpperName() << "()";
427
0
    }
428
429
0
    void writeCtorBody(raw_ostream &OS) const override {
430
0
      OS << "    if (!" << getUpperName() << ".empty())\n";
431
0
      OS << "      std::memcpy(" << getLowerName() << ", " << getUpperName()
432
0
         << ".data(), " << getLowerName() << "Length);\n";
433
0
    }
434
435
0
    void writeCtorInitializers(raw_ostream &OS) const override {
436
0
      OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
437
0
         << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
438
0
         << "Length])";
439
0
    }
440
441
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
442
0
      OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
443
0
    }
444
445
0
    void writeCtorParameters(raw_ostream &OS) const override {
446
0
      OS << "llvm::StringRef " << getUpperName();
447
0
    }
448
449
0
    void writeDeclarations(raw_ostream &OS) const override {
450
0
      OS << "unsigned " << getLowerName() << "Length;\n";
451
0
      OS << "char *" << getLowerName() << ";";
452
0
    }
453
454
0
    void writePCHReadDecls(raw_ostream &OS) const override {
455
0
      OS << "    std::string " << getLowerName()
456
0
         << "= Record.readString();\n";
457
0
    }
458
459
0
    void writePCHReadArgs(raw_ostream &OS) const override {
460
0
      OS << getLowerName();
461
0
    }
462
463
0
    void writePCHWrite(raw_ostream &OS) const override {
464
0
      OS << "    Record.AddString(SA->get" << getUpperName() << "());\n";
465
0
    }
466
467
0
    void writeValue(raw_ostream &OS) const override {
468
0
      OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
469
0
    }
470
471
0
    void writeDump(raw_ostream &OS) const override {
472
0
      OS << "    OS << \" \\\"\" << SA->get" << getUpperName()
473
0
         << "() << \"\\\"\";\n";
474
0
    }
475
  };
476
477
  class AlignedArgument : public Argument {
478
  public:
479
    AlignedArgument(const Record &Arg, StringRef Attr)
480
      : Argument(Arg, Attr)
481
0
    {}
482
483
0
    void writeAccessors(raw_ostream &OS) const override {
484
0
      OS << "  bool is" << getUpperName() << "Dependent() const;\n";
485
0
      OS << "  bool is" << getUpperName() << "ErrorDependent() const;\n";
486
487
0
      OS << "  unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
488
489
0
      OS << "  bool is" << getUpperName() << "Expr() const {\n";
490
0
      OS << "    return is" << getLowerName() << "Expr;\n";
491
0
      OS << "  }\n";
492
493
0
      OS << "  Expr *get" << getUpperName() << "Expr() const {\n";
494
0
      OS << "    assert(is" << getLowerName() << "Expr);\n";
495
0
      OS << "    return " << getLowerName() << "Expr;\n";
496
0
      OS << "  }\n";
497
498
0
      OS << "  TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
499
0
      OS << "    assert(!is" << getLowerName() << "Expr);\n";
500
0
      OS << "    return " << getLowerName() << "Type;\n";
501
0
      OS << "  }";
502
0
    }
503
504
0
    void writeAccessorDefinitions(raw_ostream &OS) const override {
505
0
      OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
506
0
         << "Dependent() const {\n";
507
0
      OS << "  if (is" << getLowerName() << "Expr)\n";
508
0
      OS << "    return " << getLowerName() << "Expr && (" << getLowerName()
509
0
         << "Expr->isValueDependent() || " << getLowerName()
510
0
         << "Expr->isTypeDependent());\n";
511
0
      OS << "  else\n";
512
0
      OS << "    return " << getLowerName()
513
0
         << "Type->getType()->isDependentType();\n";
514
0
      OS << "}\n";
515
516
0
      OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
517
0
         << "ErrorDependent() const {\n";
518
0
      OS << "  if (is" << getLowerName() << "Expr)\n";
519
0
      OS << "    return " << getLowerName() << "Expr && " << getLowerName()
520
0
         << "Expr->containsErrors();\n";
521
0
      OS << "  return " << getLowerName()
522
0
         << "Type->getType()->containsErrors();\n";
523
0
      OS << "}\n";
524
525
      // FIXME: Do not do the calculation here
526
      // FIXME: Handle types correctly
527
      // A null pointer means maximum alignment
528
0
      OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
529
0
         << "(ASTContext &Ctx) const {\n";
530
0
      OS << "  assert(!is" << getUpperName() << "Dependent());\n";
531
0
      OS << "  if (is" << getLowerName() << "Expr)\n";
532
0
      OS << "    return " << getLowerName() << "Expr ? " << getLowerName()
533
0
         << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
534
0
         << " * Ctx.getCharWidth() : "
535
0
         << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
536
0
      OS << "  else\n";
537
0
      OS << "    return 0; // FIXME\n";
538
0
      OS << "}\n";
539
0
    }
540
541
0
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
542
0
      StringRef Name = getUpperName();
543
0
      OS << "  if (A->is" << Name << "Expr()) {\n"
544
0
         << "    if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
545
0
         << "      return false;\n"
546
0
         << "  } else if (auto *TSI = A->get" << Name << "Type()) {\n"
547
0
         << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
548
0
         << "      return false;\n"
549
0
         << "  }\n";
550
0
    }
551
552
0
    void writeCloneArgs(raw_ostream &OS) const override {
553
0
      OS << "is" << getLowerName() << "Expr, is" << getLowerName()
554
0
         << "Expr ? static_cast<void*>(" << getLowerName()
555
0
         << "Expr) : " << getLowerName()
556
0
         << "Type";
557
0
    }
558
559
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
560
      // FIXME: move the definition in Sema::InstantiateAttrs to here.
561
      // In the meantime, aligned attributes are cloned.
562
0
    }
563
564
0
    void writeCtorBody(raw_ostream &OS) const override {
565
0
      OS << "    if (is" << getLowerName() << "Expr)\n";
566
0
      OS << "       " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
567
0
         << getUpperName() << ");\n";
568
0
      OS << "    else\n";
569
0
      OS << "       " << getLowerName()
570
0
         << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
571
0
         << ");\n";
572
0
    }
573
574
0
    void writeCtorInitializers(raw_ostream &OS) const override {
575
0
      OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
576
0
    }
577
578
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
579
0
      OS << "is" << getLowerName() << "Expr(false)";
580
0
    }
581
582
0
    void writeCtorParameters(raw_ostream &OS) const override {
583
0
      OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
584
0
    }
585
586
0
    void writeImplicitCtorArgs(raw_ostream &OS) const override {
587
0
      OS << "Is" << getUpperName() << "Expr, " << getUpperName();
588
0
    }
589
590
0
    void writeDeclarations(raw_ostream &OS) const override {
591
0
      OS << "bool is" << getLowerName() << "Expr;\n";
592
0
      OS << "union {\n";
593
0
      OS << "Expr *" << getLowerName() << "Expr;\n";
594
0
      OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
595
0
      OS << "};";
596
0
    }
597
598
0
    void writePCHReadArgs(raw_ostream &OS) const override {
599
0
      OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
600
0
    }
601
602
0
    void writePCHReadDecls(raw_ostream &OS) const override {
603
0
      OS << "    bool is" << getLowerName() << "Expr = Record.readInt();\n";
604
0
      OS << "    void *" << getLowerName() << "Ptr;\n";
605
0
      OS << "    if (is" << getLowerName() << "Expr)\n";
606
0
      OS << "      " << getLowerName() << "Ptr = Record.readExpr();\n";
607
0
      OS << "    else\n";
608
0
      OS << "      " << getLowerName()
609
0
         << "Ptr = Record.readTypeSourceInfo();\n";
610
0
    }
611
612
0
    void writePCHWrite(raw_ostream &OS) const override {
613
0
      OS << "    Record.push_back(SA->is" << getUpperName() << "Expr());\n";
614
0
      OS << "    if (SA->is" << getUpperName() << "Expr())\n";
615
0
      OS << "      Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
616
0
      OS << "    else\n";
617
0
      OS << "      Record.AddTypeSourceInfo(SA->get" << getUpperName()
618
0
         << "Type());\n";
619
0
    }
620
621
0
    std::string getIsOmitted() const override {
622
0
      return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
623
0
             + "Expr";
624
0
    }
625
626
0
    void writeValue(raw_ostream &OS) const override {
627
0
      OS << "\";\n";
628
0
      OS << "    " << getLowerName()
629
0
         << "Expr->printPretty(OS, nullptr, Policy);\n";
630
0
      OS << "    OS << \"";
631
0
    }
632
633
0
    void writeDump(raw_ostream &OS) const override {
634
0
      OS << "    if (!SA->is" << getUpperName() << "Expr())\n";
635
0
      OS << "      dumpType(SA->get" << getUpperName()
636
0
         << "Type()->getType());\n";
637
0
    }
638
639
0
    void writeDumpChildren(raw_ostream &OS) const override {
640
0
      OS << "    if (SA->is" << getUpperName() << "Expr())\n";
641
0
      OS << "      Visit(SA->get" << getUpperName() << "Expr());\n";
642
0
    }
643
644
0
    void writeHasChildren(raw_ostream &OS) const override {
645
0
      OS << "SA->is" << getUpperName() << "Expr()";
646
0
    }
647
  };
648
649
  class VariadicArgument : public Argument {
650
    std::string Type, ArgName, ArgSizeName, RangeName;
651
652
  protected:
653
    // Assumed to receive a parameter: raw_ostream OS.
654
0
    virtual void writeValueImpl(raw_ostream &OS) const {
655
0
      OS << "    OS << Val;\n";
656
0
    }
657
    // Assumed to receive a parameter: raw_ostream OS.
658
0
    virtual void writeDumpImpl(raw_ostream &OS) const {
659
0
      OS << "      OS << \" \" << Val;\n";
660
0
    }
661
662
  public:
663
    VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
664
        : Argument(Arg, Attr), Type(std::move(T)),
665
          ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
666
0
          RangeName(std::string(getLowerName())) {}
667
668
0
    const std::string &getType() const { return Type; }
669
0
    const std::string &getArgName() const { return ArgName; }
670
0
    const std::string &getArgSizeName() const { return ArgSizeName; }
671
0
    bool isVariadic() const override { return true; }
672
673
0
    void writeAccessors(raw_ostream &OS) const override {
674
0
      std::string IteratorType = getLowerName().str() + "_iterator";
675
0
      std::string BeginFn = getLowerName().str() + "_begin()";
676
0
      std::string EndFn = getLowerName().str() + "_end()";
677
678
0
      OS << "  typedef " << Type << "* " << IteratorType << ";\n";
679
0
      OS << "  " << IteratorType << " " << BeginFn << " const {"
680
0
         << " return " << ArgName << "; }\n";
681
0
      OS << "  " << IteratorType << " " << EndFn << " const {"
682
0
         << " return " << ArgName << " + " << ArgSizeName << "; }\n";
683
0
      OS << "  unsigned " << getLowerName() << "_size() const {"
684
0
         << " return " << ArgSizeName << "; }\n";
685
0
      OS << "  llvm::iterator_range<" << IteratorType << "> " << RangeName
686
0
         << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
687
0
         << "); }\n";
688
0
    }
689
690
0
    void writeCloneArgs(raw_ostream &OS) const override {
691
0
      OS << ArgName << ", " << ArgSizeName;
692
0
    }
693
694
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
695
      // This isn't elegant, but we have to go through public methods...
696
0
      OS << "A->" << getLowerName() << "_begin(), "
697
0
         << "A->" << getLowerName() << "_size()";
698
0
    }
699
700
0
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
701
      // FIXME: Traverse the elements.
702
0
    }
703
704
0
    void writeCtorBody(raw_ostream &OS) const override {
705
0
      OS << "  std::copy(" << getUpperName() << ", " << getUpperName() << " + "
706
0
         << ArgSizeName << ", " << ArgName << ");\n";
707
0
    }
708
709
0
    void writeCtorInitializers(raw_ostream &OS) const override {
710
0
      OS << ArgSizeName << "(" << getUpperName() << "Size), "
711
0
         << ArgName << "(new (Ctx, 16) " << getType() << "["
712
0
         << ArgSizeName << "])";
713
0
    }
714
715
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
716
0
      OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
717
0
    }
718
719
0
    void writeCtorParameters(raw_ostream &OS) const override {
720
0
      OS << getType() << " *" << getUpperName() << ", unsigned "
721
0
         << getUpperName() << "Size";
722
0
    }
723
724
0
    void writeImplicitCtorArgs(raw_ostream &OS) const override {
725
0
      OS << getUpperName() << ", " << getUpperName() << "Size";
726
0
    }
727
728
0
    void writeDeclarations(raw_ostream &OS) const override {
729
0
      OS << "  unsigned " << ArgSizeName << ";\n";
730
0
      OS << "  " << getType() << " *" << ArgName << ";";
731
0
    }
732
733
0
    void writePCHReadDecls(raw_ostream &OS) const override {
734
0
      OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
735
0
      OS << "    SmallVector<" << getType() << ", 4> "
736
0
         << getLowerName() << ";\n";
737
0
      OS << "    " << getLowerName() << ".reserve(" << getLowerName()
738
0
         << "Size);\n";
739
740
      // If we can't store the values in the current type (if it's something
741
      // like StringRef), store them in a different type and convert the
742
      // container afterwards.
743
0
      std::string StorageType = std::string(getStorageType(getType()));
744
0
      std::string StorageName = std::string(getLowerName());
745
0
      if (StorageType != getType()) {
746
0
        StorageName += "Storage";
747
0
        OS << "    SmallVector<" << StorageType << ", 4> "
748
0
           << StorageName << ";\n";
749
0
        OS << "    " << StorageName << ".reserve(" << getLowerName()
750
0
           << "Size);\n";
751
0
      }
752
753
0
      OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
754
0
      std::string read = ReadPCHRecord(Type);
755
0
      OS << "      " << StorageName << ".push_back(" << read << ");\n";
756
757
0
      if (StorageType != getType()) {
758
0
        OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
759
0
        OS << "      " << getLowerName() << ".push_back("
760
0
           << StorageName << "[i]);\n";
761
0
      }
762
0
    }
763
764
0
    void writePCHReadArgs(raw_ostream &OS) const override {
765
0
      OS << getLowerName() << ".data(), " << getLowerName() << "Size";
766
0
    }
767
768
0
    void writePCHWrite(raw_ostream &OS) const override {
769
0
      OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
770
0
      OS << "    for (auto &Val : SA->" << RangeName << "())\n";
771
0
      OS << "      " << WritePCHRecord(Type, "Val");
772
0
    }
773
774
0
    void writeValue(raw_ostream &OS) const override {
775
0
      OS << "\";\n";
776
0
      OS << "  for (const auto &Val : " << RangeName << "()) {\n"
777
0
         << "    DelimitAttributeArgument(OS, IsFirstArgument);\n";
778
0
      writeValueImpl(OS);
779
0
      OS << "  }\n";
780
0
      OS << "  OS << \"";
781
0
    }
782
783
0
    void writeDump(raw_ostream &OS) const override {
784
0
      OS << "    for (const auto &Val : SA->" << RangeName << "())\n";
785
0
      writeDumpImpl(OS);
786
0
    }
787
  };
788
789
  class VariadicParamIdxArgument : public VariadicArgument {
790
  public:
791
    VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
792
0
        : VariadicArgument(Arg, Attr, "ParamIdx") {}
793
794
  public:
795
0
    void writeValueImpl(raw_ostream &OS) const override {
796
0
      OS << "    OS << Val.getSourceIndex();\n";
797
0
    }
798
799
0
    void writeDumpImpl(raw_ostream &OS) const override {
800
0
      OS << "      OS << \" \" << Val.getSourceIndex();\n";
801
0
    }
802
  };
803
804
  struct VariadicParamOrParamIdxArgument : public VariadicArgument {
805
    VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
806
0
        : VariadicArgument(Arg, Attr, "int") {}
807
  };
808
809
  // Unique the enums, but maintain the original declaration ordering.
810
  std::vector<StringRef>
811
0
  uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
812
0
    std::vector<StringRef> uniques;
813
0
    SmallDenseSet<StringRef, 8> unique_set;
814
0
    for (const auto &i : enums) {
815
0
      if (unique_set.insert(i).second)
816
0
        uniques.push_back(i);
817
0
    }
818
0
    return uniques;
819
0
  }
820
821
  class EnumArgument : public Argument {
822
    std::string type;
823
    std::vector<StringRef> values, enums, uniques;
824
825
  public:
826
    EnumArgument(const Record &Arg, StringRef Attr)
827
        : Argument(Arg, Attr), type(std::string(Arg.getValueAsString("Type"))),
828
          values(Arg.getValueAsListOfStrings("Values")),
829
          enums(Arg.getValueAsListOfStrings("Enums")),
830
0
          uniques(uniqueEnumsInOrder(enums)) {
831
      // FIXME: Emit a proper error
832
0
      assert(!uniques.empty());
833
0
    }
834
835
0
    bool isEnumArg() const override { return true; }
836
837
0
    void writeAccessors(raw_ostream &OS) const override {
838
0
      OS << "  " << type << " get" << getUpperName() << "() const {\n";
839
0
      OS << "    return " << getLowerName() << ";\n";
840
0
      OS << "  }";
841
0
    }
842
843
0
    void writeCloneArgs(raw_ostream &OS) const override {
844
0
      OS << getLowerName();
845
0
    }
846
847
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
848
0
      OS << "A->get" << getUpperName() << "()";
849
0
    }
850
0
    void writeCtorInitializers(raw_ostream &OS) const override {
851
0
      OS << getLowerName() << "(" << getUpperName() << ")";
852
0
    }
853
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
854
0
      OS << getLowerName() << "(" << type << "(0))";
855
0
    }
856
0
    void writeCtorParameters(raw_ostream &OS) const override {
857
0
      OS << type << " " << getUpperName();
858
0
    }
859
0
    void writeDeclarations(raw_ostream &OS) const override {
860
0
      auto i = uniques.cbegin(), e = uniques.cend();
861
      // The last one needs to not have a comma.
862
0
      --e;
863
864
0
      OS << "public:\n";
865
0
      OS << "  enum " << type << " {\n";
866
0
      for (; i != e; ++i)
867
0
        OS << "    " << *i << ",\n";
868
0
      OS << "    " << *e << "\n";
869
0
      OS << "  };\n";
870
0
      OS << "private:\n";
871
0
      OS << "  " << type << " " << getLowerName() << ";";
872
0
    }
873
874
0
    void writePCHReadDecls(raw_ostream &OS) const override {
875
0
      OS << "    " << getAttrName() << "Attr::" << type << " " << getLowerName()
876
0
         << "(static_cast<" << getAttrName() << "Attr::" << type
877
0
         << ">(Record.readInt()));\n";
878
0
    }
879
880
0
    void writePCHReadArgs(raw_ostream &OS) const override {
881
0
      OS << getLowerName();
882
0
    }
883
884
0
    void writePCHWrite(raw_ostream &OS) const override {
885
0
      OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
886
0
    }
887
888
0
    void writeValue(raw_ostream &OS) const override {
889
      // FIXME: this isn't 100% correct -- some enum arguments require printing
890
      // as a string literal, while others require printing as an identifier.
891
      // Tablegen currently does not distinguish between the two forms.
892
0
      OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
893
0
         << getUpperName() << "()) << \"\\\"";
894
0
    }
895
896
0
    void writeDump(raw_ostream &OS) const override {
897
0
      OS << "    switch(SA->get" << getUpperName() << "()) {\n";
898
0
      for (const auto &I : uniques) {
899
0
        OS << "    case " << getAttrName() << "Attr::" << I << ":\n";
900
0
        OS << "      OS << \" " << I << "\";\n";
901
0
        OS << "      break;\n";
902
0
      }
903
0
      OS << "    }\n";
904
0
    }
905
906
0
    void writeConversion(raw_ostream &OS, bool Header) const {
907
0
      if (Header) {
908
0
        OS << "  static bool ConvertStrTo" << type << "(StringRef Val, " << type
909
0
           << " &Out);\n";
910
0
        OS << "  static const char *Convert" << type << "ToStr(" << type
911
0
           << " Val);\n";
912
0
        return;
913
0
      }
914
915
0
      OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
916
0
         << "(StringRef Val, " << type << " &Out) {\n";
917
0
      OS << "  Optional<" << type << "> R = llvm::StringSwitch<Optional<";
918
0
      OS << type << ">>(Val)\n";
919
0
      for (size_t I = 0; I < enums.size(); ++I) {
920
0
        OS << "    .Case(\"" << values[I] << "\", ";
921
0
        OS << getAttrName() << "Attr::" << enums[I] << ")\n";
922
0
      }
923
0
      OS << "    .Default(Optional<" << type << ">());\n";
924
0
      OS << "  if (R) {\n";
925
0
      OS << "    Out = *R;\n      return true;\n    }\n";
926
0
      OS << "  return false;\n";
927
0
      OS << "}\n\n";
928
929
      // Mapping from enumeration values back to enumeration strings isn't
930
      // trivial because some enumeration values have multiple named
931
      // enumerators, such as type_visibility(internal) and
932
      // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
933
0
      OS << "const char *" << getAttrName() << "Attr::Convert" << type
934
0
         << "ToStr(" << type << " Val) {\n"
935
0
         << "  switch(Val) {\n";
936
0
      SmallDenseSet<StringRef, 8> Uniques;
937
0
      for (size_t I = 0; I < enums.size(); ++I) {
938
0
        if (Uniques.insert(enums[I]).second)
939
0
          OS << "  case " << getAttrName() << "Attr::" << enums[I]
940
0
             << ": return \"" << values[I] << "\";\n";
941
0
      }
942
0
      OS << "  }\n"
943
0
         << "  llvm_unreachable(\"No enumerator with that value\");\n"
944
0
         << "}\n";
945
0
    }
946
  };
947
948
  class VariadicEnumArgument: public VariadicArgument {
949
    std::string type, QualifiedTypeName;
950
    std::vector<StringRef> values, enums, uniques;
951
952
  protected:
953
0
    void writeValueImpl(raw_ostream &OS) const override {
954
      // FIXME: this isn't 100% correct -- some enum arguments require printing
955
      // as a string literal, while others require printing as an identifier.
956
      // Tablegen currently does not distinguish between the two forms.
957
0
      OS << "    OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
958
0
         << "ToStr(Val)" << "<< \"\\\"\";\n";
959
0
    }
960
961
  public:
962
    VariadicEnumArgument(const Record &Arg, StringRef Attr)
963
        : VariadicArgument(Arg, Attr,
964
                           std::string(Arg.getValueAsString("Type"))),
965
          type(std::string(Arg.getValueAsString("Type"))),
966
          values(Arg.getValueAsListOfStrings("Values")),
967
          enums(Arg.getValueAsListOfStrings("Enums")),
968
0
          uniques(uniqueEnumsInOrder(enums)) {
969
0
      QualifiedTypeName = getAttrName().str() + "Attr::" + type;
970
971
      // FIXME: Emit a proper error
972
0
      assert(!uniques.empty());
973
0
    }
974
975
0
    bool isVariadicEnumArg() const override { return true; }
976
977
0
    void writeDeclarations(raw_ostream &OS) const override {
978
0
      auto i = uniques.cbegin(), e = uniques.cend();
979
      // The last one needs to not have a comma.
980
0
      --e;
981
982
0
      OS << "public:\n";
983
0
      OS << "  enum " << type << " {\n";
984
0
      for (; i != e; ++i)
985
0
        OS << "    " << *i << ",\n";
986
0
      OS << "    " << *e << "\n";
987
0
      OS << "  };\n";
988
0
      OS << "private:\n";
989
990
0
      VariadicArgument::writeDeclarations(OS);
991
0
    }
992
993
0
    void writeDump(raw_ostream &OS) const override {
994
0
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
995
0
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
996
0
         << getLowerName() << "_end(); I != E; ++I) {\n";
997
0
      OS << "      switch(*I) {\n";
998
0
      for (const auto &UI : uniques) {
999
0
        OS << "    case " << getAttrName() << "Attr::" << UI << ":\n";
1000
0
        OS << "      OS << \" " << UI << "\";\n";
1001
0
        OS << "      break;\n";
1002
0
      }
1003
0
      OS << "      }\n";
1004
0
      OS << "    }\n";
1005
0
    }
1006
1007
0
    void writePCHReadDecls(raw_ostream &OS) const override {
1008
0
      OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
1009
0
      OS << "    SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
1010
0
         << ";\n";
1011
0
      OS << "    " << getLowerName() << ".reserve(" << getLowerName()
1012
0
         << "Size);\n";
1013
0
      OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
1014
0
      OS << "      " << getLowerName() << ".push_back(" << "static_cast<"
1015
0
         << QualifiedTypeName << ">(Record.readInt()));\n";
1016
0
    }
1017
1018
0
    void writePCHWrite(raw_ostream &OS) const override {
1019
0
      OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
1020
0
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
1021
0
         << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
1022
0
         << getLowerName() << "_end(); i != e; ++i)\n";
1023
0
      OS << "      " << WritePCHRecord(QualifiedTypeName, "(*i)");
1024
0
    }
1025
1026
0
    void writeConversion(raw_ostream &OS, bool Header) const {
1027
0
      if (Header) {
1028
0
        OS << "  static bool ConvertStrTo" << type << "(StringRef Val, " << type
1029
0
           << " &Out);\n";
1030
0
        OS << "  static const char *Convert" << type << "ToStr(" << type
1031
0
           << " Val);\n";
1032
0
        return;
1033
0
      }
1034
1035
0
      OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
1036
0
         << "(StringRef Val, ";
1037
0
      OS << type << " &Out) {\n";
1038
0
      OS << "  Optional<" << type << "> R = llvm::StringSwitch<Optional<";
1039
0
      OS << type << ">>(Val)\n";
1040
0
      for (size_t I = 0; I < enums.size(); ++I) {
1041
0
        OS << "    .Case(\"" << values[I] << "\", ";
1042
0
        OS << getAttrName() << "Attr::" << enums[I] << ")\n";
1043
0
      }
1044
0
      OS << "    .Default(Optional<" << type << ">());\n";
1045
0
      OS << "  if (R) {\n";
1046
0
      OS << "    Out = *R;\n      return true;\n    }\n";
1047
0
      OS << "  return false;\n";
1048
0
      OS << "}\n\n";
1049
1050
0
      OS << "const char *" << getAttrName() << "Attr::Convert" << type
1051
0
         << "ToStr(" << type << " Val) {\n"
1052
0
         << "  switch(Val) {\n";
1053
0
      SmallDenseSet<StringRef, 8> Uniques;
1054
0
      for (size_t I = 0; I < enums.size(); ++I) {
1055
0
        if (Uniques.insert(enums[I]).second)
1056
0
          OS << "  case " << getAttrName() << "Attr::" << enums[I]
1057
0
             << ": return \"" << values[I] << "\";\n";
1058
0
      }
1059
0
      OS << "  }\n"
1060
0
         << "  llvm_unreachable(\"No enumerator with that value\");\n"
1061
0
         << "}\n";
1062
0
    }
1063
  };
1064
1065
  class VersionArgument : public Argument {
1066
  public:
1067
    VersionArgument(const Record &Arg, StringRef Attr)
1068
      : Argument(Arg, Attr)
1069
0
    {}
1070
1071
0
    void writeAccessors(raw_ostream &OS) const override {
1072
0
      OS << "  VersionTuple get" << getUpperName() << "() const {\n";
1073
0
      OS << "    return " << getLowerName() << ";\n";
1074
0
      OS << "  }\n";
1075
0
      OS << "  void set" << getUpperName()
1076
0
         << "(ASTContext &C, VersionTuple V) {\n";
1077
0
      OS << "    " << getLowerName() << " = V;\n";
1078
0
      OS << "  }";
1079
0
    }
1080
1081
0
    void writeCloneArgs(raw_ostream &OS) const override {
1082
0
      OS << "get" << getUpperName() << "()";
1083
0
    }
1084
1085
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1086
0
      OS << "A->get" << getUpperName() << "()";
1087
0
    }
1088
1089
0
    void writeCtorInitializers(raw_ostream &OS) const override {
1090
0
      OS << getLowerName() << "(" << getUpperName() << ")";
1091
0
    }
1092
1093
0
    void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1094
0
      OS << getLowerName() << "()";
1095
0
    }
1096
1097
0
    void writeCtorParameters(raw_ostream &OS) const override {
1098
0
      OS << "VersionTuple " << getUpperName();
1099
0
    }
1100
1101
0
    void writeDeclarations(raw_ostream &OS) const override {
1102
0
      OS << "VersionTuple " << getLowerName() << ";\n";
1103
0
    }
1104
1105
0
    void writePCHReadDecls(raw_ostream &OS) const override {
1106
0
      OS << "    VersionTuple " << getLowerName()
1107
0
         << "= Record.readVersionTuple();\n";
1108
0
    }
1109
1110
0
    void writePCHReadArgs(raw_ostream &OS) const override {
1111
0
      OS << getLowerName();
1112
0
    }
1113
1114
0
    void writePCHWrite(raw_ostream &OS) const override {
1115
0
      OS << "    Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1116
0
    }
1117
1118
0
    void writeValue(raw_ostream &OS) const override {
1119
0
      OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1120
0
    }
1121
1122
0
    void writeDump(raw_ostream &OS) const override {
1123
0
      OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
1124
0
    }
1125
  };
1126
1127
  class ExprArgument : public SimpleArgument {
1128
  public:
1129
    ExprArgument(const Record &Arg, StringRef Attr)
1130
      : SimpleArgument(Arg, Attr, "Expr *")
1131
0
    {}
1132
1133
0
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
1134
0
      OS << "  if (!"
1135
0
         << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1136
0
      OS << "    return false;\n";
1137
0
    }
1138
1139
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1140
0
      OS << "tempInst" << getUpperName();
1141
0
    }
1142
1143
0
    void writeTemplateInstantiation(raw_ostream &OS) const override {
1144
0
      OS << "      " << getType() << " tempInst" << getUpperName() << ";\n";
1145
0
      OS << "      {\n";
1146
0
      OS << "        EnterExpressionEvaluationContext "
1147
0
         << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1148
0
      OS << "        ExprResult " << "Result = S.SubstExpr("
1149
0
         << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1150
0
      OS << "        if (Result.isInvalid())\n";
1151
0
      OS << "          return nullptr;\n";
1152
0
      OS << "        tempInst" << getUpperName() << " = Result.get();\n";
1153
0
      OS << "      }\n";
1154
0
    }
1155
1156
0
    void writeDump(raw_ostream &OS) const override {}
1157
1158
0
    void writeDumpChildren(raw_ostream &OS) const override {
1159
0
      OS << "    Visit(SA->get" << getUpperName() << "());\n";
1160
0
    }
1161
1162
0
    void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1163
  };
1164
1165
  class VariadicExprArgument : public VariadicArgument {
1166
  public:
1167
    VariadicExprArgument(const Record &Arg, StringRef Attr)
1168
      : VariadicArgument(Arg, Attr, "Expr *")
1169
0
    {}
1170
1171
0
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
1172
0
      OS << "  {\n";
1173
0
      OS << "    " << getType() << " *I = A->" << getLowerName()
1174
0
         << "_begin();\n";
1175
0
      OS << "    " << getType() << " *E = A->" << getLowerName()
1176
0
         << "_end();\n";
1177
0
      OS << "    for (; I != E; ++I) {\n";
1178
0
      OS << "      if (!getDerived().TraverseStmt(*I))\n";
1179
0
      OS << "        return false;\n";
1180
0
      OS << "    }\n";
1181
0
      OS << "  }\n";
1182
0
    }
1183
1184
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1185
0
      OS << "tempInst" << getUpperName() << ", "
1186
0
         << "A->" << getLowerName() << "_size()";
1187
0
    }
1188
1189
0
    void writeTemplateInstantiation(raw_ostream &OS) const override {
1190
0
      OS << "      auto *tempInst" << getUpperName()
1191
0
         << " = new (C, 16) " << getType()
1192
0
         << "[A->" << getLowerName() << "_size()];\n";
1193
0
      OS << "      {\n";
1194
0
      OS << "        EnterExpressionEvaluationContext "
1195
0
         << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1196
0
      OS << "        " << getType() << " *TI = tempInst" << getUpperName()
1197
0
         << ";\n";
1198
0
      OS << "        " << getType() << " *I = A->" << getLowerName()
1199
0
         << "_begin();\n";
1200
0
      OS << "        " << getType() << " *E = A->" << getLowerName()
1201
0
         << "_end();\n";
1202
0
      OS << "        for (; I != E; ++I, ++TI) {\n";
1203
0
      OS << "          ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1204
0
      OS << "          if (Result.isInvalid())\n";
1205
0
      OS << "            return nullptr;\n";
1206
0
      OS << "          *TI = Result.get();\n";
1207
0
      OS << "        }\n";
1208
0
      OS << "      }\n";
1209
0
    }
1210
1211
0
    void writeDump(raw_ostream &OS) const override {}
1212
1213
0
    void writeDumpChildren(raw_ostream &OS) const override {
1214
0
      OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
1215
0
         << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1216
0
         << getLowerName() << "_end(); I != E; ++I)\n";
1217
0
      OS << "      Visit(*I);\n";
1218
0
    }
1219
1220
0
    void writeHasChildren(raw_ostream &OS) const override {
1221
0
      OS << "SA->" << getLowerName() << "_begin() != "
1222
0
         << "SA->" << getLowerName() << "_end()";
1223
0
    }
1224
  };
1225
1226
  class VariadicIdentifierArgument : public VariadicArgument {
1227
  public:
1228
    VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1229
      : VariadicArgument(Arg, Attr, "IdentifierInfo *")
1230
0
    {}
1231
  };
1232
1233
  class VariadicStringArgument : public VariadicArgument {
1234
  public:
1235
    VariadicStringArgument(const Record &Arg, StringRef Attr)
1236
      : VariadicArgument(Arg, Attr, "StringRef")
1237
0
    {}
1238
1239
0
    void writeCtorBody(raw_ostream &OS) const override {
1240
0
      OS << "  for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1241
0
            "       ++I) {\n"
1242
0
            "    StringRef Ref = " << getUpperName() << "[I];\n"
1243
0
            "    if (!Ref.empty()) {\n"
1244
0
            "      char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1245
0
            "      std::memcpy(Mem, Ref.data(), Ref.size());\n"
1246
0
            "      " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1247
0
            "    }\n"
1248
0
            "  }\n";
1249
0
    }
1250
1251
0
    void writeValueImpl(raw_ostream &OS) const override {
1252
0
      OS << "    OS << \"\\\"\" << Val << \"\\\"\";\n";
1253
0
    }
1254
  };
1255
1256
  class TypeArgument : public SimpleArgument {
1257
  public:
1258
    TypeArgument(const Record &Arg, StringRef Attr)
1259
      : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1260
0
    {}
1261
1262
0
    void writeAccessors(raw_ostream &OS) const override {
1263
0
      OS << "  QualType get" << getUpperName() << "() const {\n";
1264
0
      OS << "    return " << getLowerName() << "->getType();\n";
1265
0
      OS << "  }";
1266
0
      OS << "  " << getType() << " get" << getUpperName() << "Loc() const {\n";
1267
0
      OS << "    return " << getLowerName() << ";\n";
1268
0
      OS << "  }";
1269
0
    }
1270
1271
0
    void writeASTVisitorTraversal(raw_ostream &OS) const override {
1272
0
      OS << "  if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1273
0
      OS << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1274
0
      OS << "      return false;\n";
1275
0
    }
1276
1277
0
    void writeTemplateInstantiation(raw_ostream &OS) const override {
1278
0
      OS << "      " << getType() << " tempInst" << getUpperName() << " =\n";
1279
0
      OS << "        S.SubstType(A->get" << getUpperName() << "Loc(), "
1280
0
         << "TemplateArgs, A->getLoc(), A->getAttrName());\n";
1281
0
      OS << "      if (!tempInst" << getUpperName() << ")\n";
1282
0
      OS << "        return nullptr;\n";
1283
0
    }
1284
1285
0
    void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1286
0
      OS << "tempInst" << getUpperName();
1287
0
    }
1288
1289
0
    void writePCHWrite(raw_ostream &OS) const override {
1290
0
      OS << "    "
1291
0
         << WritePCHRecord(getType(),
1292
0
                           "SA->get" + std::string(getUpperName()) + "Loc()");
1293
0
    }
1294
  };
1295
1296
} // end anonymous namespace
1297
1298
static std::unique_ptr<Argument>
1299
createArgument(const Record &Arg, StringRef Attr,
1300
0
               const Record *Search = nullptr) {
1301
0
  if (!Search)
1302
0
    Search = &Arg;
1303
1304
0
  std::unique_ptr<Argument> Ptr;
1305
0
  llvm::StringRef ArgName = Search->getName();
1306
1307
0
  if (ArgName == "AlignedArgument")
1308
0
    Ptr = std::make_unique<AlignedArgument>(Arg, Attr);
1309
0
  else if (ArgName == "EnumArgument")
1310
0
    Ptr = std::make_unique<EnumArgument>(Arg, Attr);
1311
0
  else if (ArgName == "ExprArgument")
1312
0
    Ptr = std::make_unique<ExprArgument>(Arg, Attr);
1313
0
  else if (ArgName == "DeclArgument")
1314
0
    Ptr = std::make_unique<SimpleArgument>(
1315
0
        Arg, Attr, (Arg.getValueAsDef("Kind")->getName() + "Decl *").str());
1316
0
  else if (ArgName == "IdentifierArgument")
1317
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1318
0
  else if (ArgName == "DefaultBoolArgument")
1319
0
    Ptr = std::make_unique<DefaultSimpleArgument>(
1320
0
        Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1321
0
  else if (ArgName == "BoolArgument")
1322
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "bool");
1323
0
  else if (ArgName == "DefaultIntArgument")
1324
0
    Ptr = std::make_unique<DefaultSimpleArgument>(
1325
0
        Arg, Attr, "int", Arg.getValueAsInt("Default"));
1326
0
  else if (ArgName == "IntArgument")
1327
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "int");
1328
0
  else if (ArgName == "StringArgument")
1329
0
    Ptr = std::make_unique<StringArgument>(Arg, Attr);
1330
0
  else if (ArgName == "TypeArgument")
1331
0
    Ptr = std::make_unique<TypeArgument>(Arg, Attr);
1332
0
  else if (ArgName == "UnsignedArgument")
1333
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1334
0
  else if (ArgName == "VariadicUnsignedArgument")
1335
0
    Ptr = std::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1336
0
  else if (ArgName == "VariadicStringArgument")
1337
0
    Ptr = std::make_unique<VariadicStringArgument>(Arg, Attr);
1338
0
  else if (ArgName == "VariadicEnumArgument")
1339
0
    Ptr = std::make_unique<VariadicEnumArgument>(Arg, Attr);
1340
0
  else if (ArgName == "VariadicExprArgument")
1341
0
    Ptr = std::make_unique<VariadicExprArgument>(Arg, Attr);
1342
0
  else if (ArgName == "VariadicParamIdxArgument")
1343
0
    Ptr = std::make_unique<VariadicParamIdxArgument>(Arg, Attr);
1344
0
  else if (ArgName == "VariadicParamOrParamIdxArgument")
1345
0
    Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(Arg, Attr);
1346
0
  else if (ArgName == "ParamIdxArgument")
1347
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
1348
0
  else if (ArgName == "VariadicIdentifierArgument")
1349
0
    Ptr = std::make_unique<VariadicIdentifierArgument>(Arg, Attr);
1350
0
  else if (ArgName == "VersionArgument")
1351
0
    Ptr = std::make_unique<VersionArgument>(Arg, Attr);
1352
0
  else if (ArgName == "OMPTraitInfoArgument")
1353
0
    Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "OMPTraitInfo *");
1354
1355
0
  if (!Ptr) {
1356
    // Search in reverse order so that the most-derived type is handled first.
1357
0
    ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
1358
0
    for (const auto &Base : llvm::reverse(Bases)) {
1359
0
      if ((Ptr = createArgument(Arg, Attr, Base.first)))
1360
0
        break;
1361
0
    }
1362
0
  }
1363
1364
0
  if (Ptr && Arg.getValueAsBit("Optional"))
1365
0
    Ptr->setOptional(true);
1366
1367
0
  if (Ptr && Arg.getValueAsBit("Fake"))
1368
0
    Ptr->setFake(true);
1369
1370
0
  return Ptr;
1371
0
}
1372
1373
0
static void writeAvailabilityValue(raw_ostream &OS) {
1374
0
  OS << "\" << getPlatform()->getName();\n"
1375
0
     << "  if (getStrict()) OS << \", strict\";\n"
1376
0
     << "  if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1377
0
     << "  if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1378
0
     << "  if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1379
0
     << "  if (getUnavailable()) OS << \", unavailable\";\n"
1380
0
     << "  OS << \"";
1381
0
}
1382
1383
0
static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1384
0
  OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1385
  // Only GNU deprecated has an optional fixit argument at the second position.
1386
0
  if (Variety == "GNU")
1387
0
     OS << "    if (!getReplacement().empty()) OS << \", \\\"\""
1388
0
           " << getReplacement() << \"\\\"\";\n";
1389
0
  OS << "    OS << \"";
1390
0
}
1391
1392
0
static void writeGetSpellingFunction(const Record &R, raw_ostream &OS) {
1393
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1394
1395
0
  OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1396
0
  if (Spellings.empty()) {
1397
0
    OS << "  return \"(No spelling)\";\n}\n\n";
1398
0
    return;
1399
0
  }
1400
1401
0
  OS << "  switch (getAttributeSpellingListIndex()) {\n"
1402
0
        "  default:\n"
1403
0
        "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1404
0
        "    return \"(No spelling)\";\n";
1405
1406
0
  for (unsigned I = 0; I < Spellings.size(); ++I)
1407
0
    OS << "  case " << I << ":\n"
1408
0
          "    return \"" << Spellings[I].name() << "\";\n";
1409
  // End of the switch statement.
1410
0
  OS << "  }\n";
1411
  // End of the getSpelling function.
1412
0
  OS << "}\n\n";
1413
0
}
1414
1415
static void
1416
writePrettyPrintFunction(const Record &R,
1417
                         const std::vector<std::unique_ptr<Argument>> &Args,
1418
0
                         raw_ostream &OS) {
1419
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1420
1421
0
  OS << "void " << R.getName() << "Attr::printPretty("
1422
0
    << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1423
1424
0
  if (Spellings.empty()) {
1425
0
    OS << "}\n\n";
1426
0
    return;
1427
0
  }
1428
1429
0
  OS << "  bool IsFirstArgument = true; (void)IsFirstArgument;\n"
1430
0
     << "  unsigned TrailingOmittedArgs = 0; (void)TrailingOmittedArgs;\n"
1431
0
     << "  switch (getAttributeSpellingListIndex()) {\n"
1432
0
     << "  default:\n"
1433
0
     << "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1434
0
     << "    break;\n";
1435
1436
0
  for (unsigned I = 0; I < Spellings.size(); ++ I) {
1437
0
    llvm::SmallString<16> Prefix;
1438
0
    llvm::SmallString<8> Suffix;
1439
    // The actual spelling of the name and namespace (if applicable)
1440
    // of an attribute without considering prefix and suffix.
1441
0
    llvm::SmallString<64> Spelling;
1442
0
    std::string Name = Spellings[I].name();
1443
0
    std::string Variety = Spellings[I].variety();
1444
1445
0
    if (Variety == "GNU") {
1446
0
      Prefix = " __attribute__((";
1447
0
      Suffix = "))";
1448
0
    } else if (Variety == "CXX11" || Variety == "C2x") {
1449
0
      Prefix = " [[";
1450
0
      Suffix = "]]";
1451
0
      std::string Namespace = Spellings[I].nameSpace();
1452
0
      if (!Namespace.empty()) {
1453
0
        Spelling += Namespace;
1454
0
        Spelling += "::";
1455
0
      }
1456
0
    } else if (Variety == "Declspec") {
1457
0
      Prefix = " __declspec(";
1458
0
      Suffix = ")";
1459
0
    } else if (Variety == "Microsoft") {
1460
0
      Prefix = "[";
1461
0
      Suffix = "]";
1462
0
    } else if (Variety == "Keyword") {
1463
0
      Prefix = " ";
1464
0
      Suffix = "";
1465
0
    } else if (Variety == "Pragma") {
1466
0
      Prefix = "#pragma ";
1467
0
      Suffix = "\n";
1468
0
      std::string Namespace = Spellings[I].nameSpace();
1469
0
      if (!Namespace.empty()) {
1470
0
        Spelling += Namespace;
1471
0
        Spelling += " ";
1472
0
      }
1473
0
    } else {
1474
0
      llvm_unreachable("Unknown attribute syntax variety!");
1475
0
    }
1476
1477
0
    Spelling += Name;
1478
1479
0
    OS << "  case " << I << " : {\n"
1480
0
       << "    OS << \"" << Prefix << Spelling << "\";\n";
1481
1482
0
    if (Variety == "Pragma") {
1483
0
      OS << "    printPrettyPragma(OS, Policy);\n";
1484
0
      OS << "    OS << \"\\n\";";
1485
0
      OS << "    break;\n";
1486
0
      OS << "  }\n";
1487
0
      continue;
1488
0
    }
1489
1490
0
    if (Spelling == "availability") {
1491
0
      OS << "    OS << \"(";
1492
0
      writeAvailabilityValue(OS);
1493
0
      OS << ")\";\n";
1494
0
    } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1495
0
      OS << "    OS << \"(";
1496
0
      writeDeprecatedAttrValue(OS, Variety);
1497
0
      OS << ")\";\n";
1498
0
    } else {
1499
      // To avoid printing parentheses around an empty argument list or
1500
      // printing spurious commas at the end of an argument list, we need to
1501
      // determine where the last provided non-fake argument is.
1502
0
      unsigned NonFakeArgs = 0;
1503
0
      bool FoundNonOptArg = false;
1504
0
      for (const auto &arg : llvm::reverse(Args)) {
1505
0
        if (arg->isFake())
1506
0
          continue;
1507
0
        ++NonFakeArgs;
1508
0
        if (FoundNonOptArg)
1509
0
          continue;
1510
        // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1511
        // any way to detect whether the argument was omitted.
1512
0
        if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1513
0
          FoundNonOptArg = true;
1514
0
          continue;
1515
0
        }
1516
0
        OS << "    if (" << arg->getIsOmitted() << ")\n"
1517
0
           << "      ++TrailingOmittedArgs;\n";
1518
0
      }
1519
0
      unsigned ArgIndex = 0;
1520
0
      for (const auto &arg : Args) {
1521
0
        if (arg->isFake())
1522
0
          continue;
1523
0
        std::string IsOmitted = arg->getIsOmitted();
1524
0
        if (arg->isOptional() && IsOmitted != "false")
1525
0
          OS << "    if (!(" << IsOmitted << ")) {\n";
1526
        // Variadic arguments print their own leading comma.
1527
0
        if (!arg->isVariadic())
1528
0
          OS << "    DelimitAttributeArgument(OS, IsFirstArgument);\n";
1529
0
        OS << "    OS << \"";
1530
0
        arg->writeValue(OS);
1531
0
        OS << "\";\n";
1532
0
        if (arg->isOptional() && IsOmitted != "false")
1533
0
          OS << "    }\n";
1534
0
        ++ArgIndex;
1535
0
      }
1536
0
      if (ArgIndex != 0)
1537
0
        OS << "    if (!IsFirstArgument)\n"
1538
0
           << "      OS << \")\";\n";
1539
0
    }
1540
0
    OS << "    OS << \"" << Suffix << "\";\n"
1541
0
       << "    break;\n"
1542
0
       << "  }\n";
1543
0
  }
1544
1545
  // End of the switch statement.
1546
0
  OS << "}\n";
1547
  // End of the print function.
1548
0
  OS << "}\n\n";
1549
0
}
1550
1551
/// Return the index of a spelling in a spelling list.
1552
static unsigned
1553
getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1554
0
                     const FlattenedSpelling &Spelling) {
1555
0
  assert(!SpellingList.empty() && "Spelling list is empty!");
1556
1557
0
  for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1558
0
    const FlattenedSpelling &S = SpellingList[Index];
1559
0
    if (S.variety() != Spelling.variety())
1560
0
      continue;
1561
0
    if (S.nameSpace() != Spelling.nameSpace())
1562
0
      continue;
1563
0
    if (S.name() != Spelling.name())
1564
0
      continue;
1565
1566
0
    return Index;
1567
0
  }
1568
1569
0
  llvm_unreachable("Unknown spelling!");
1570
0
}
1571
1572
0
static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1573
0
  std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1574
0
  if (Accessors.empty())
1575
0
    return;
1576
1577
0
  const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1578
0
  assert(!SpellingList.empty() &&
1579
0
         "Attribute with empty spelling list can't have accessors!");
1580
0
  for (const auto *Accessor : Accessors) {
1581
0
    const StringRef Name = Accessor->getValueAsString("Name");
1582
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
1583
1584
0
    OS << "  bool " << Name
1585
0
       << "() const { return getAttributeSpellingListIndex() == ";
1586
0
    for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1587
0
      OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1588
0
      if (Index != Spellings.size() - 1)
1589
0
        OS << " ||\n    getAttributeSpellingListIndex() == ";
1590
0
      else
1591
0
        OS << "; }\n";
1592
0
    }
1593
0
  }
1594
0
}
1595
1596
static bool
1597
0
SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1598
0
  assert(!Spellings.empty() && "An empty list of spellings was provided");
1599
0
  std::string FirstName =
1600
0
      std::string(NormalizeNameForSpellingComparison(Spellings.front().name()));
1601
0
  for (const auto &Spelling :
1602
0
       llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1603
0
    std::string Name =
1604
0
        std::string(NormalizeNameForSpellingComparison(Spelling.name()));
1605
0
    if (Name != FirstName)
1606
0
      return false;
1607
0
  }
1608
0
  return true;
1609
0
}
1610
1611
typedef std::map<unsigned, std::string> SemanticSpellingMap;
1612
static std::string
1613
CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1614
0
                        SemanticSpellingMap &Map) {
1615
  // The enumerants are automatically generated based on the variety,
1616
  // namespace (if present) and name for each attribute spelling. However,
1617
  // care is taken to avoid trampling on the reserved namespace due to
1618
  // underscores.
1619
0
  std::string Ret("  enum Spelling {\n");
1620
0
  std::set<std::string> Uniques;
1621
0
  unsigned Idx = 0;
1622
1623
  // If we have a need to have this many spellings we likely need to add an
1624
  // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1625
  // value of SpellingNotCalculated there and here.
1626
0
  assert(Spellings.size() < 15 &&
1627
0
         "Too many spellings, would step on SpellingNotCalculated in "
1628
0
         "AttributeCommonInfo");
1629
0
  for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1630
0
    const FlattenedSpelling &S = *I;
1631
0
    const std::string &Variety = S.variety();
1632
0
    const std::string &Spelling = S.name();
1633
0
    const std::string &Namespace = S.nameSpace();
1634
0
    std::string EnumName;
1635
1636
0
    EnumName += (Variety + "_");
1637
0
    if (!Namespace.empty())
1638
0
      EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1639
0
      "_");
1640
0
    EnumName += NormalizeNameForSpellingComparison(Spelling);
1641
1642
    // Even if the name is not unique, this spelling index corresponds to a
1643
    // particular enumerant name that we've calculated.
1644
0
    Map[Idx] = EnumName;
1645
1646
    // Since we have been stripping underscores to avoid trampling on the
1647
    // reserved namespace, we may have inadvertently created duplicate
1648
    // enumerant names. These duplicates are not considered part of the
1649
    // semantic spelling, and can be elided.
1650
0
    if (Uniques.find(EnumName) != Uniques.end())
1651
0
      continue;
1652
1653
0
    Uniques.insert(EnumName);
1654
0
    if (I != Spellings.begin())
1655
0
      Ret += ",\n";
1656
    // Duplicate spellings are not considered part of the semantic spelling
1657
    // enumeration, but the spelling index and semantic spelling values are
1658
    // meant to be equivalent, so we must specify a concrete value for each
1659
    // enumerator.
1660
0
    Ret += "    " + EnumName + " = " + llvm::utostr(Idx);
1661
0
  }
1662
0
  Ret += ",\n  SpellingNotCalculated = 15\n";
1663
0
  Ret += "\n  };\n\n";
1664
0
  return Ret;
1665
0
}
1666
1667
void WriteSemanticSpellingSwitch(const std::string &VarName,
1668
                                 const SemanticSpellingMap &Map,
1669
0
                                 raw_ostream &OS) {
1670
0
  OS << "  switch (" << VarName << ") {\n    default: "
1671
0
    << "llvm_unreachable(\"Unknown spelling list index\");\n";
1672
0
  for (const auto &I : Map)
1673
0
    OS << "    case " << I.first << ": return " << I.second << ";\n";
1674
0
  OS << "  }\n";
1675
0
}
1676
1677
// Emits the LateParsed property for attributes.
1678
0
static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1679
0
  OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1680
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1681
1682
0
  for (const auto *Attr : Attrs) {
1683
0
    bool LateParsed = Attr->getValueAsBit("LateParsed");
1684
1685
0
    if (LateParsed) {
1686
0
      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1687
1688
      // FIXME: Handle non-GNU attributes
1689
0
      for (const auto &I : Spellings) {
1690
0
        if (I.variety() != "GNU")
1691
0
          continue;
1692
0
        OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1693
0
      }
1694
0
    }
1695
0
  }
1696
0
  OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1697
0
}
1698
1699
307
static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1700
307
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1701
327
  for (const auto &I : Spellings) {
1702
327
    if (I.variety() == "GNU" || 
I.variety() == "CXX11"63
)
1703
275
      return true;
1704
327
  }
1705
32
  return false;
1706
307
}
1707
1708
namespace {
1709
1710
struct AttributeSubjectMatchRule {
1711
  const Record *MetaSubject;
1712
  const Record *Constraint;
1713
1714
  AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1715
50
      : MetaSubject(MetaSubject), Constraint(Constraint) {
1716
50
    assert(MetaSubject && "Missing subject");
1717
50
  }
1718
1719
348
  bool isSubRule() const { return Constraint != nullptr; }
1720
1721
287
  std::vector<Record *> getSubjects() const {
1722
287
    return (Constraint ? 
Constraint44
:
MetaSubject243
)
1723
287
        ->getValueAsListOfDefs("Subjects");
1724
287
  }
1725
1726
0
  std::vector<Record *> getLangOpts() const {
1727
0
    if (Constraint) {
1728
      // Lookup the options in the sub-rule first, in case the sub-rule
1729
      // overrides the rules options.
1730
0
      std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1731
0
      if (!Opts.empty())
1732
0
        return Opts;
1733
0
    }
1734
0
    return MetaSubject->getValueAsListOfDefs("LangOpts");
1735
0
  }
1736
1737
  // Abstract rules are used only for sub-rules
1738
287
  bool isAbstractRule() const { return getSubjects().empty(); }
1739
1740
0
  StringRef getName() const {
1741
0
    return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1742
0
  }
1743
1744
44
  bool isNegatedSubRule() const {
1745
44
    assert(isSubRule() && "Not a sub-rule");
1746
0
    return Constraint->getValueAsBit("Negated");
1747
44
  }
1748
1749
0
  std::string getSpelling() const {
1750
0
    std::string Result = std::string(MetaSubject->getValueAsString("Name"));
1751
0
    if (isSubRule()) {
1752
0
      Result += '(';
1753
0
      if (isNegatedSubRule())
1754
0
        Result += "unless(";
1755
0
      Result += getName();
1756
0
      if (isNegatedSubRule())
1757
0
        Result += ')';
1758
0
      Result += ')';
1759
0
    }
1760
0
    return Result;
1761
0
  }
1762
1763
287
  std::string getEnumValueName() const {
1764
287
    SmallString<128> Result;
1765
287
    Result += "SubjectMatchRule_";
1766
287
    Result += MetaSubject->getValueAsString("Name");
1767
287
    if (isSubRule()) {
1768
44
      Result += "_";
1769
44
      if (isNegatedSubRule())
1770
5
        Result += "not_";
1771
44
      Result += Constraint->getValueAsString("Name");
1772
44
    }
1773
287
    if (isAbstractRule())
1774
0
      Result += "_abstract";
1775
287
    return std::string(Result.str());
1776
287
  }
1777
1778
0
  std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1779
1780
  static const char *EnumName;
1781
};
1782
1783
const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1784
1785
struct PragmaClangAttributeSupport {
1786
  std::vector<AttributeSubjectMatchRule> Rules;
1787
1788
  class RuleOrAggregateRuleSet {
1789
    std::vector<AttributeSubjectMatchRule> Rules;
1790
    bool IsRule;
1791
    RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1792
                           bool IsRule)
1793
26
        : Rules(Rules), IsRule(IsRule) {}
1794
1795
  public:
1796
276
    bool isRule() const { return IsRule; }
1797
1798
289
    const AttributeSubjectMatchRule &getRule() const {
1799
289
      assert(IsRule && "not a rule!");
1800
0
      return Rules[0];
1801
289
    }
1802
1803
2
    ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1804
2
      return Rules;
1805
2
    }
1806
1807
    static RuleOrAggregateRuleSet
1808
25
    getRule(const AttributeSubjectMatchRule &Rule) {
1809
25
      return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1810
25
    }
1811
    static RuleOrAggregateRuleSet
1812
1
    getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1813
1
      return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1814
1
    }
1815
  };
1816
  llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
1817
1818
  PragmaClangAttributeSupport(RecordKeeper &Records);
1819
1820
  bool isAttributedSupported(const Record &Attribute);
1821
1822
  void emitMatchRuleList(raw_ostream &OS);
1823
1824
  void generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
1825
1826
  void generateParsingHelpers(raw_ostream &OS);
1827
};
1828
1829
} // end anonymous namespace
1830
1831
614
static bool isSupportedPragmaClangAttributeSubject(const Record &Subject) {
1832
  // FIXME: #pragma clang attribute does not currently support statement
1833
  // attributes, so test whether the subject is one that appertains to a
1834
  // declaration node. However, it may be reasonable for support for statement
1835
  // attributes to be added.
1836
614
  if (Subject.isSubClassOf("DeclNode") || 
Subject.isSubClassOf("DeclBase")85
||
1837
614
      
Subject.getName() == "DeclBase"85
)
1838
546
    return true;
1839
1840
68
  if (Subject.isSubClassOf("SubsetSubject"))
1841
59
    return isSupportedPragmaClangAttributeSubject(
1842
59
        *Subject.getValueAsDef("Base"));
1843
1844
9
  return false;
1845
68
}
1846
1847
229
static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
1848
229
  const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
1849
229
  if (!CurrentBase)
1850
24
    return false;
1851
205
  if (CurrentBase == Base)
1852
71
    return true;
1853
134
  return doesDeclDeriveFrom(CurrentBase, Base);
1854
205
}
1855
1856
PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1857
1
    RecordKeeper &Records) {
1858
1
  std::vector<Record *> MetaSubjects =
1859
1
      Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1860
1
  auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1861
1
                                       const Record *MetaSubject,
1862
25
                                       const Record *Constraint) {
1863
25
    Rules.emplace_back(MetaSubject, Constraint);
1864
25
    std::vector<Record *> ApplicableSubjects =
1865
25
        SubjectContainer->getValueAsListOfDefs("Subjects");
1866
25
    for (const auto *Subject : ApplicableSubjects) {
1867
25
      bool Inserted =
1868
25
          SubjectsToRules
1869
25
              .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1870
25
                                        AttributeSubjectMatchRule(MetaSubject,
1871
25
                                                                  Constraint)))
1872
25
              .second;
1873
25
      if (!Inserted) {
1874
0
        PrintFatalError("Attribute subject match rules should not represent"
1875
0
                        "same attribute subjects.");
1876
0
      }
1877
25
    }
1878
25
  };
1879
16
  for (const auto *MetaSubject : MetaSubjects) {
1880
16
    MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
1881
16
    std::vector<Record *> Constraints =
1882
16
        MetaSubject->getValueAsListOfDefs("Constraints");
1883
16
    for (const auto *Constraint : Constraints)
1884
9
      MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
1885
16
  }
1886
1887
1
  std::vector<Record *> Aggregates =
1888
1
      Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
1889
1
  std::vector<Record *> DeclNodes =
1890
1
    Records.getAllDerivedDefinitions(DeclNodeClassName);
1891
1
  for (const auto *Aggregate : Aggregates) {
1892
1
    Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
1893
1894
    // Gather sub-classes of the aggregate subject that act as attribute
1895
    // subject rules.
1896
1
    std::vector<AttributeSubjectMatchRule> Rules;
1897
95
    for (const auto *D : DeclNodes) {
1898
95
      if (doesDeclDeriveFrom(D, SubjectDecl)) {
1899
71
        auto It = SubjectsToRules.find(D);
1900
71
        if (It == SubjectsToRules.end())
1901
54
          continue;
1902
17
        if (!It->second.isRule() || It->second.getRule().isSubRule())
1903
2
          continue; // Assume that the rule will be included as well.
1904
15
        Rules.push_back(It->second.getRule());
1905
15
      }
1906
95
    }
1907
1908
1
    bool Inserted =
1909
1
        SubjectsToRules
1910
1
            .try_emplace(SubjectDecl,
1911
1
                         RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
1912
1
            .second;
1913
1
    if (!Inserted) {
1914
0
      PrintFatalError("Attribute subject match rules should not represent"
1915
0
                      "same attribute subjects.");
1916
0
    }
1917
1
  }
1918
1
}
1919
1920
static PragmaClangAttributeSupport &
1921
1
getPragmaAttributeSupport(RecordKeeper &Records) {
1922
1
  static PragmaClangAttributeSupport Instance(Records);
1923
1
  return Instance;
1924
1
}
1925
1926
0
void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
1927
0
  OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
1928
0
  OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
1929
0
        "IsNegated) "
1930
0
     << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
1931
0
  OS << "#endif\n";
1932
0
  for (const auto &Rule : Rules) {
1933
0
    OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
1934
0
    OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
1935
0
       << Rule.isAbstractRule();
1936
0
    if (Rule.isSubRule())
1937
0
      OS << ", "
1938
0
         << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
1939
0
         << ", " << Rule.isNegatedSubRule();
1940
0
    OS << ")\n";
1941
0
  }
1942
0
  OS << "#undef ATTR_MATCH_SUB_RULE\n";
1943
0
}
1944
1945
bool PragmaClangAttributeSupport::isAttributedSupported(
1946
329
    const Record &Attribute) {
1947
  // If the attribute explicitly specified whether to support #pragma clang
1948
  // attribute, use that setting.
1949
329
  bool Unset;
1950
329
  bool SpecifiedResult =
1951
329
    Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
1952
329
  if (!Unset)
1953
6
    return SpecifiedResult;
1954
1955
  // Opt-out rules:
1956
  // An attribute requires delayed parsing (LateParsed is on)
1957
323
  if (Attribute.getValueAsBit("LateParsed"))
1958
16
    return false;
1959
  // An attribute has no GNU/CXX11 spelling
1960
307
  if (!hasGNUorCXX11Spelling(Attribute))
1961
32
    return false;
1962
  // An attribute subject list has a subject that isn't covered by one of the
1963
  // subject match rules or has no subjects at all.
1964
275
  if (Attribute.isValueUnset("Subjects"))
1965
68
    return false;
1966
207
  const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
1967
207
  std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1968
207
  bool HasAtLeastOneValidSubject = false;
1969
295
  for (const auto *Subject : Subjects) {
1970
295
    if (!isSupportedPragmaClangAttributeSubject(*Subject))
1971
8
      continue;
1972
287
    if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
1973
21
      return false;
1974
266
    HasAtLeastOneValidSubject = true;
1975
266
  }
1976
186
  return HasAtLeastOneValidSubject;
1977
207
}
1978
1979
0
static std::string GenerateTestExpression(ArrayRef<Record *> LangOpts) {
1980
0
  std::string Test;
1981
1982
0
  for (auto *E : LangOpts) {
1983
0
    if (!Test.empty())
1984
0
      Test += " || ";
1985
1986
0
    const StringRef Code = E->getValueAsString("CustomCode");
1987
0
    if (!Code.empty()) {
1988
0
      Test += "(";
1989
0
      Test += Code;
1990
0
      Test += ")";
1991
0
      if (!E->getValueAsString("Name").empty()) {
1992
0
        PrintWarning(
1993
0
            E->getLoc(),
1994
0
            "non-empty 'Name' field ignored because 'CustomCode' was supplied");
1995
0
      }
1996
0
    } else {
1997
0
      Test += "LangOpts.";
1998
0
      Test += E->getValueAsString("Name");
1999
0
    }
2000
0
  }
2001
2002
0
  if (Test.empty())
2003
0
    return "true";
2004
2005
0
  return Test;
2006
0
}
2007
2008
void
2009
PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
2010
0
                                                      raw_ostream &OS) {
2011
0
  if (!isAttributedSupported(Attr) || Attr.isValueUnset("Subjects"))
2012
0
    return;
2013
  // Generate a function that constructs a set of matching rules that describe
2014
  // to which declarations the attribute should apply to.
2015
0
  OS << "void getPragmaAttributeMatchRules("
2016
0
     << "llvm::SmallVectorImpl<std::pair<"
2017
0
     << AttributeSubjectMatchRule::EnumName
2018
0
     << ", bool>> &MatchRules, const LangOptions &LangOpts) const override {\n";
2019
0
  const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2020
0
  std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2021
0
  for (const auto *Subject : Subjects) {
2022
0
    if (!isSupportedPragmaClangAttributeSubject(*Subject))
2023
0
      continue;
2024
0
    auto It = SubjectsToRules.find(Subject);
2025
0
    assert(It != SubjectsToRules.end() &&
2026
0
           "This attribute is unsupported by #pragma clang attribute");
2027
0
    for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
2028
      // The rule might be language specific, so only subtract it from the given
2029
      // rules if the specific language options are specified.
2030
0
      std::vector<Record *> LangOpts = Rule.getLangOpts();
2031
0
      OS << "  MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
2032
0
         << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
2033
0
         << "));\n";
2034
0
    }
2035
0
  }
2036
0
  OS << "}\n\n";
2037
0
}
2038
2039
0
void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
2040
  // Generate routines that check the names of sub-rules.
2041
0
  OS << "Optional<attr::SubjectMatchRule> "
2042
0
        "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2043
0
  OS << "  return None;\n";
2044
0
  OS << "}\n\n";
2045
2046
0
  std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
2047
0
      SubMatchRules;
2048
0
  for (const auto &Rule : Rules) {
2049
0
    if (!Rule.isSubRule())
2050
0
      continue;
2051
0
    SubMatchRules[Rule.MetaSubject].push_back(Rule);
2052
0
  }
2053
2054
0
  for (const auto &SubMatchRule : SubMatchRules) {
2055
0
    OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
2056
0
       << SubMatchRule.first->getValueAsString("Name")
2057
0
       << "(StringRef Name, bool IsUnless) {\n";
2058
0
    OS << "  if (IsUnless)\n";
2059
0
    OS << "    return "
2060
0
          "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
2061
0
    for (const auto &Rule : SubMatchRule.second) {
2062
0
      if (Rule.isNegatedSubRule())
2063
0
        OS << "    Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2064
0
           << ").\n";
2065
0
    }
2066
0
    OS << "    Default(None);\n";
2067
0
    OS << "  return "
2068
0
          "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
2069
0
    for (const auto &Rule : SubMatchRule.second) {
2070
0
      if (!Rule.isNegatedSubRule())
2071
0
        OS << "  Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2072
0
           << ").\n";
2073
0
    }
2074
0
    OS << "  Default(None);\n";
2075
0
    OS << "}\n\n";
2076
0
  }
2077
2078
  // Generate the function that checks for the top-level rules.
2079
0
  OS << "std::pair<Optional<attr::SubjectMatchRule>, "
2080
0
        "Optional<attr::SubjectMatchRule> (*)(StringRef, "
2081
0
        "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2082
0
  OS << "  return "
2083
0
        "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
2084
0
        "Optional<attr::SubjectMatchRule> (*) (StringRef, "
2085
0
        "bool)>>(Name).\n";
2086
0
  for (const auto &Rule : Rules) {
2087
0
    if (Rule.isSubRule())
2088
0
      continue;
2089
0
    std::string SubRuleFunction;
2090
0
    if (SubMatchRules.count(Rule.MetaSubject))
2091
0
      SubRuleFunction =
2092
0
          ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
2093
0
    else
2094
0
      SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2095
0
    OS << "  Case(\"" << Rule.getName() << "\", std::make_pair("
2096
0
       << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2097
0
  }
2098
0
  OS << "  Default(std::make_pair(None, "
2099
0
        "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2100
0
  OS << "}\n\n";
2101
2102
  // Generate the function that checks for the submatch rules.
2103
0
  OS << "const char *validAttributeSubjectMatchSubRules("
2104
0
     << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2105
0
  OS << "  switch (Rule) {\n";
2106
0
  for (const auto &SubMatchRule : SubMatchRules) {
2107
0
    OS << "  case "
2108
0
       << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2109
0
       << ":\n";
2110
0
    OS << "  return \"'";
2111
0
    bool IsFirst = true;
2112
0
    for (const auto &Rule : SubMatchRule.second) {
2113
0
      if (!IsFirst)
2114
0
        OS << ", '";
2115
0
      IsFirst = false;
2116
0
      if (Rule.isNegatedSubRule())
2117
0
        OS << "unless(";
2118
0
      OS << Rule.getName();
2119
0
      if (Rule.isNegatedSubRule())
2120
0
        OS << ')';
2121
0
      OS << "'";
2122
0
    }
2123
0
    OS << "\";\n";
2124
0
  }
2125
0
  OS << "  default: return nullptr;\n";
2126
0
  OS << "  }\n";
2127
0
  OS << "}\n\n";
2128
0
}
2129
2130
template <typename Fn>
2131
0
static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
2132
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2133
0
  SmallDenseSet<StringRef, 8> Seen;
2134
0
  for (const FlattenedSpelling &S : Spellings) {
2135
0
    if (Seen.insert(S.name()).second)
2136
0
      F(S);
2137
0
  }
2138
0
}
Unexecuted instantiation: ClangAttrEmitter.cpp:void forEachUniqueSpelling<emitClangAttrArgContextList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_6>(llvm::Record const&, emitClangAttrArgContextList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_6&&)
Unexecuted instantiation: ClangAttrEmitter.cpp:void forEachUniqueSpelling<emitClangAttrIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_8>(llvm::Record const&, emitClangAttrIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_8&&)
Unexecuted instantiation: ClangAttrEmitter.cpp:void forEachUniqueSpelling<emitClangAttrVariadicIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_7>(llvm::Record const&, emitClangAttrVariadicIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_7&&)
Unexecuted instantiation: ClangAttrEmitter.cpp:void forEachUniqueSpelling<emitClangAttrThisIsaIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_9>(llvm::Record const&, emitClangAttrThisIsaIdentifierArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_9&&)
Unexecuted instantiation: ClangAttrEmitter.cpp:void forEachUniqueSpelling<emitClangAttrTypeArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_5>(llvm::Record const&, emitClangAttrTypeArgList(llvm::RecordKeeper&, llvm::raw_ostream&)::$_5&&)
2139
2140
/// Emits the first-argument-is-type property for attributes.
2141
0
static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
2142
0
  OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2143
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2144
2145
0
  for (const auto *Attr : Attrs) {
2146
    // Determine whether the first argument is a type.
2147
0
    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2148
0
    if (Args.empty())
2149
0
      continue;
2150
2151
0
    if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
2152
0
      continue;
2153
2154
    // All these spellings take a single type argument.
2155
0
    forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2156
0
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2157
0
    });
2158
0
  }
2159
0
  OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2160
0
}
2161
2162
/// Emits the parse-arguments-in-unevaluated-context property for
2163
/// attributes.
2164
0
static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
2165
0
  OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2166
0
  ParsedAttrMap Attrs = getParsedAttrList(Records);
2167
0
  for (const auto &I : Attrs) {
2168
0
    const Record &Attr = *I.second;
2169
2170
0
    if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2171
0
      continue;
2172
2173
    // All these spellings take are parsed unevaluated.
2174
0
    forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2175
0
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2176
0
    });
2177
0
  }
2178
0
  OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2179
0
}
2180
2181
0
static bool isIdentifierArgument(Record *Arg) {
2182
0
  return !Arg->getSuperClasses().empty() &&
2183
0
    llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2184
0
    .Case("IdentifierArgument", true)
2185
0
    .Case("EnumArgument", true)
2186
0
    .Case("VariadicEnumArgument", true)
2187
0
    .Default(false);
2188
0
}
2189
2190
0
static bool isVariadicIdentifierArgument(Record *Arg) {
2191
0
  return !Arg->getSuperClasses().empty() &&
2192
0
         llvm::StringSwitch<bool>(
2193
0
             Arg->getSuperClasses().back().first->getName())
2194
0
             .Case("VariadicIdentifierArgument", true)
2195
0
             .Case("VariadicParamOrParamIdxArgument", true)
2196
0
             .Default(false);
2197
0
}
2198
2199
static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
2200
0
                                                   raw_ostream &OS) {
2201
0
  OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2202
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2203
0
  for (const auto *A : Attrs) {
2204
    // Determine whether the first argument is a variadic identifier.
2205
0
    std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2206
0
    if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
2207
0
      continue;
2208
2209
    // All these spellings take an identifier argument.
2210
0
    forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2211
0
      OS << ".Case(\"" << S.name() << "\", "
2212
0
         << "true"
2213
0
         << ")\n";
2214
0
    });
2215
0
  }
2216
0
  OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2217
0
}
2218
2219
// Emits the first-argument-is-identifier property for attributes.
2220
0
static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2221
0
  OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2222
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2223
2224
0
  for (const auto *Attr : Attrs) {
2225
    // Determine whether the first argument is an identifier.
2226
0
    std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2227
0
    if (Args.empty() || !isIdentifierArgument(Args[0]))
2228
0
      continue;
2229
2230
    // All these spellings take an identifier argument.
2231
0
    forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2232
0
      OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2233
0
    });
2234
0
  }
2235
0
  OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2236
0
}
2237
2238
0
static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
2239
0
  return !Arg->getSuperClasses().empty() &&
2240
0
         llvm::StringSwitch<bool>(
2241
0
             Arg->getSuperClasses().back().first->getName())
2242
0
             .Case("VariadicParamOrParamIdxArgument", true)
2243
0
             .Default(false);
2244
0
}
2245
2246
static void emitClangAttrThisIsaIdentifierArgList(RecordKeeper &Records,
2247
0
                                                  raw_ostream &OS) {
2248
0
  OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2249
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2250
0
  for (const auto *A : Attrs) {
2251
    // Determine whether the first argument is a variadic identifier.
2252
0
    std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2253
0
    if (Args.empty() || !keywordThisIsaIdentifierInArgument(Args[0]))
2254
0
      continue;
2255
2256
    // All these spellings take an identifier argument.
2257
0
    forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2258
0
      OS << ".Case(\"" << S.name() << "\", "
2259
0
         << "true"
2260
0
         << ")\n";
2261
0
    });
2262
0
  }
2263
0
  OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2264
0
}
2265
2266
static void emitAttributes(RecordKeeper &Records, raw_ostream &OS,
2267
0
                           bool Header) {
2268
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2269
0
  ParsedAttrMap AttrMap = getParsedAttrList(Records);
2270
2271
  // Helper to print the starting character of an attribute argument. If there
2272
  // hasn't been an argument yet, it prints an opening parenthese; otherwise it
2273
  // prints a comma.
2274
0
  OS << "static inline void DelimitAttributeArgument("
2275
0
     << "raw_ostream& OS, bool& IsFirst) {\n"
2276
0
     << "  if (IsFirst) {\n"
2277
0
     << "    IsFirst = false;\n"
2278
0
     << "    OS << \"(\";\n"
2279
0
     << "  } else\n"
2280
0
     << "    OS << \", \";\n"
2281
0
     << "}\n";
2282
2283
0
  for (const auto *Attr : Attrs) {
2284
0
    const Record &R = *Attr;
2285
2286
    // FIXME: Currently, documentation is generated as-needed due to the fact
2287
    // that there is no way to allow a generated project "reach into" the docs
2288
    // directory (for instance, it may be an out-of-tree build). However, we want
2289
    // to ensure that every attribute has a Documentation field, and produce an
2290
    // error if it has been neglected. Otherwise, the on-demand generation which
2291
    // happens server-side will fail. This code is ensuring that functionality,
2292
    // even though this Emitter doesn't technically need the documentation.
2293
    // When attribute documentation can be generated as part of the build
2294
    // itself, this code can be removed.
2295
0
    (void)R.getValueAsListOfDefs("Documentation");
2296
2297
0
    if (!R.getValueAsBit("ASTNode"))
2298
0
      continue;
2299
2300
0
    ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
2301
0
    assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
2302
0
    std::string SuperName;
2303
0
    bool Inheritable = false;
2304
0
    for (const auto &Super : llvm::reverse(Supers)) {
2305
0
      const Record *R = Super.first;
2306
0
      if (R->getName() != "TargetSpecificAttr" &&
2307
0
          R->getName() != "DeclOrTypeAttr" && SuperName.empty())
2308
0
        SuperName = std::string(R->getName());
2309
0
      if (R->getName() == "InheritableAttr")
2310
0
        Inheritable = true;
2311
0
    }
2312
2313
0
    if (Header)
2314
0
      OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2315
0
    else
2316
0
      OS << "\n// " << R.getName() << "Attr implementation\n\n";
2317
2318
0
    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2319
0
    std::vector<std::unique_ptr<Argument>> Args;
2320
0
    Args.reserve(ArgRecords.size());
2321
2322
0
    bool HasOptArg = false;
2323
0
    bool HasFakeArg = false;
2324
0
    for (const auto *ArgRecord : ArgRecords) {
2325
0
      Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2326
0
      if (Header) {
2327
0
        Args.back()->writeDeclarations(OS);
2328
0
        OS << "\n\n";
2329
0
      }
2330
2331
      // For these purposes, fake takes priority over optional.
2332
0
      if (Args.back()->isFake()) {
2333
0
        HasFakeArg = true;
2334
0
      } else if (Args.back()->isOptional()) {
2335
0
        HasOptArg = true;
2336
0
      }
2337
0
    }
2338
2339
0
    if (Header)
2340
0
      OS << "public:\n";
2341
2342
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2343
2344
    // If there are zero or one spellings, all spelling-related functionality
2345
    // can be elided. If all of the spellings share the same name, the spelling
2346
    // functionality can also be elided.
2347
0
    bool ElideSpelling = (Spellings.size() <= 1) ||
2348
0
                         SpellingNamesAreCommon(Spellings);
2349
2350
    // This maps spelling index values to semantic Spelling enumerants.
2351
0
    SemanticSpellingMap SemanticToSyntacticMap;
2352
2353
0
    std::string SpellingEnum;
2354
0
    if (Spellings.size() > 1)
2355
0
      SpellingEnum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2356
0
    if (Header)
2357
0
      OS << SpellingEnum;
2358
2359
0
    const auto &ParsedAttrSpellingItr = llvm::find_if(
2360
0
        AttrMap, [R](const std::pair<std::string, const Record *> &P) {
2361
0
          return &R == P.second;
2362
0
        });
2363
2364
    // Emit CreateImplicit factory methods.
2365
0
    auto emitCreate = [&](bool Implicit, bool emitFake) {
2366
0
      if (Header)
2367
0
        OS << "  static ";
2368
0
      OS << R.getName() << "Attr *";
2369
0
      if (!Header)
2370
0
        OS << R.getName() << "Attr::";
2371
0
      OS << "Create";
2372
0
      if (Implicit)
2373
0
        OS << "Implicit";
2374
0
      OS << "(";
2375
0
      OS << "ASTContext &Ctx";
2376
0
      for (auto const &ai : Args) {
2377
0
        if (ai->isFake() && !emitFake) continue;
2378
0
        OS << ", ";
2379
0
        ai->writeCtorParameters(OS);
2380
0
      }
2381
0
      OS << ", const AttributeCommonInfo &CommonInfo";
2382
0
      if (Header && Implicit)
2383
0
        OS << " = {SourceRange{}}";
2384
0
      OS << ")";
2385
0
      if (Header) {
2386
0
        OS << ";\n";
2387
0
        return;
2388
0
      }
2389
2390
0
      OS << " {\n";
2391
0
      OS << "  auto *A = new (Ctx) " << R.getName();
2392
0
      OS << "Attr(Ctx, CommonInfo";
2393
0
      for (auto const &ai : Args) {
2394
0
        if (ai->isFake() && !emitFake) continue;
2395
0
        OS << ", ";
2396
0
        ai->writeImplicitCtorArgs(OS);
2397
0
      }
2398
0
      OS << ");\n";
2399
0
      if (Implicit) {
2400
0
        OS << "  A->setImplicit(true);\n";
2401
0
      }
2402
0
      if (Implicit || ElideSpelling) {
2403
0
        OS << "  if (!A->isAttributeSpellingListCalculated() && "
2404
0
              "!A->getAttrName())\n";
2405
0
        OS << "    A->setAttributeSpellingListIndex(0);\n";
2406
0
      }
2407
0
      OS << "  return A;\n}\n\n";
2408
0
    };
2409
2410
0
    auto emitCreateNoCI = [&](bool Implicit, bool emitFake) {
2411
0
      if (Header)
2412
0
        OS << "  static ";
2413
0
      OS << R.getName() << "Attr *";
2414
0
      if (!Header)
2415
0
        OS << R.getName() << "Attr::";
2416
0
      OS << "Create";
2417
0
      if (Implicit)
2418
0
        OS << "Implicit";
2419
0
      OS << "(";
2420
0
      OS << "ASTContext &Ctx";
2421
0
      for (auto const &ai : Args) {
2422
0
        if (ai->isFake() && !emitFake) continue;
2423
0
        OS << ", ";
2424
0
        ai->writeCtorParameters(OS);
2425
0
      }
2426
0
      OS << ", SourceRange Range, AttributeCommonInfo::Syntax Syntax";
2427
0
      if (!ElideSpelling) {
2428
0
        OS << ", " << R.getName() << "Attr::Spelling S";
2429
0
        if (Header)
2430
0
          OS << " = static_cast<Spelling>(SpellingNotCalculated)";
2431
0
      }
2432
0
      OS << ")";
2433
0
      if (Header) {
2434
0
        OS << ";\n";
2435
0
        return;
2436
0
      }
2437
2438
0
      OS << " {\n";
2439
0
      OS << "  AttributeCommonInfo I(Range, ";
2440
2441
0
      if (ParsedAttrSpellingItr != std::end(AttrMap))
2442
0
        OS << "AT_" << ParsedAttrSpellingItr->first;
2443
0
      else
2444
0
        OS << "NoSemaHandlerAttribute";
2445
2446
0
      OS << ", Syntax";
2447
0
      if (!ElideSpelling)
2448
0
        OS << ", S";
2449
0
      OS << ");\n";
2450
0
      OS << "  return Create";
2451
0
      if (Implicit)
2452
0
        OS << "Implicit";
2453
0
      OS << "(Ctx";
2454
0
      for (auto const &ai : Args) {
2455
0
        if (ai->isFake() && !emitFake) continue;
2456
0
        OS << ", ";
2457
0
        ai->writeImplicitCtorArgs(OS);
2458
0
      }
2459
0
      OS << ", I);\n";
2460
0
      OS << "}\n\n";
2461
0
    };
2462
2463
0
    auto emitCreates = [&](bool emitFake) {
2464
0
      emitCreate(true, emitFake);
2465
0
      emitCreate(false, emitFake);
2466
0
      emitCreateNoCI(true, emitFake);
2467
0
      emitCreateNoCI(false, emitFake);
2468
0
    };
2469
2470
0
    if (Header)
2471
0
      OS << "  // Factory methods\n";
2472
2473
    // Emit a CreateImplicit that takes all the arguments.
2474
0
    emitCreates(true);
2475
2476
    // Emit a CreateImplicit that takes all the non-fake arguments.
2477
0
    if (HasFakeArg)
2478
0
      emitCreates(false);
2479
2480
    // Emit constructors.
2481
0
    auto emitCtor = [&](bool emitOpt, bool emitFake) {
2482
0
      auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2483
0
        if (arg->isFake()) return emitFake;
2484
0
        if (arg->isOptional()) return emitOpt;
2485
0
        return true;
2486
0
      };
2487
0
      if (Header)
2488
0
        OS << "  ";
2489
0
      else
2490
0
        OS << R.getName() << "Attr::";
2491
0
      OS << R.getName()
2492
0
         << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
2493
0
      OS << '\n';
2494
0
      for (auto const &ai : Args) {
2495
0
        if (!shouldEmitArg(ai)) continue;
2496
0
        OS << "              , ";
2497
0
        ai->writeCtorParameters(OS);
2498
0
        OS << "\n";
2499
0
      }
2500
2501
0
      OS << "             )";
2502
0
      if (Header) {
2503
0
        OS << ";\n";
2504
0
        return;
2505
0
      }
2506
0
      OS << "\n  : " << SuperName << "(Ctx, CommonInfo, ";
2507
0
      OS << "attr::" << R.getName() << ", "
2508
0
         << (R.getValueAsBit("LateParsed") ? "true" : "false");
2509
0
      if (Inheritable) {
2510
0
        OS << ", "
2511
0
           << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2512
0
                                                              : "false");
2513
0
      }
2514
0
      OS << ")\n";
2515
2516
0
      for (auto const &ai : Args) {
2517
0
        OS << "              , ";
2518
0
        if (!shouldEmitArg(ai)) {
2519
0
          ai->writeCtorDefaultInitializers(OS);
2520
0
        } else {
2521
0
          ai->writeCtorInitializers(OS);
2522
0
        }
2523
0
        OS << "\n";
2524
0
      }
2525
2526
0
      OS << "  {\n";
2527
2528
0
      for (auto const &ai : Args) {
2529
0
        if (!shouldEmitArg(ai)) continue;
2530
0
        ai->writeCtorBody(OS);
2531
0
      }
2532
0
      OS << "}\n\n";
2533
0
    };
2534
2535
0
    if (Header)
2536
0
      OS << "\n  // Constructors\n";
2537
2538
    // Emit a constructor that includes all the arguments.
2539
    // This is necessary for cloning.
2540
0
    emitCtor(true, true);
2541
2542
    // Emit a constructor that takes all the non-fake arguments.
2543
0
    if (HasFakeArg)
2544
0
      emitCtor(true, false);
2545
2546
    // Emit a constructor that takes all the non-fake, non-optional arguments.
2547
0
    if (HasOptArg)
2548
0
      emitCtor(false, false);
2549
2550
0
    if (Header) {
2551
0
      OS << '\n';
2552
0
      OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
2553
0
      OS << "  void printPretty(raw_ostream &OS,\n"
2554
0
         << "                   const PrintingPolicy &Policy) const;\n";
2555
0
      OS << "  const char *getSpelling() const;\n";
2556
0
    }
2557
2558
0
    if (!ElideSpelling) {
2559
0
      assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
2560
0
      if (Header)
2561
0
        OS << "  Spelling getSemanticSpelling() const;\n";
2562
0
      else {
2563
0
        OS << R.getName() << "Attr::Spelling " << R.getName()
2564
0
           << "Attr::getSemanticSpelling() const {\n";
2565
0
        WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
2566
0
                                    SemanticToSyntacticMap, OS);
2567
0
        OS << "}\n";
2568
0
      }
2569
0
    }
2570
2571
0
    if (Header)
2572
0
      writeAttrAccessorDefinition(R, OS);
2573
2574
0
    for (auto const &ai : Args) {
2575
0
      if (Header) {
2576
0
        ai->writeAccessors(OS);
2577
0
      } else {
2578
0
        ai->writeAccessorDefinitions(OS);
2579
0
      }
2580
0
      OS << "\n\n";
2581
2582
      // Don't write conversion routines for fake arguments.
2583
0
      if (ai->isFake()) continue;
2584
2585
0
      if (ai->isEnumArg())
2586
0
        static_cast<const EnumArgument *>(ai.get())->writeConversion(OS,
2587
0
                                                                     Header);
2588
0
      else if (ai->isVariadicEnumArg())
2589
0
        static_cast<const VariadicEnumArgument *>(ai.get())->writeConversion(
2590
0
            OS, Header);
2591
0
    }
2592
2593
0
    if (Header) {
2594
0
      OS << R.getValueAsString("AdditionalMembers");
2595
0
      OS << "\n\n";
2596
2597
0
      OS << "  static bool classof(const Attr *A) { return A->getKind() == "
2598
0
         << "attr::" << R.getName() << "; }\n";
2599
2600
0
      OS << "};\n\n";
2601
0
    } else {
2602
0
      OS << R.getName() << "Attr *" << R.getName()
2603
0
         << "Attr::clone(ASTContext &C) const {\n";
2604
0
      OS << "  auto *A = new (C) " << R.getName() << "Attr(C, *this";
2605
0
      for (auto const &ai : Args) {
2606
0
        OS << ", ";
2607
0
        ai->writeCloneArgs(OS);
2608
0
      }
2609
0
      OS << ");\n";
2610
0
      OS << "  A->Inherited = Inherited;\n";
2611
0
      OS << "  A->IsPackExpansion = IsPackExpansion;\n";
2612
0
      OS << "  A->setImplicit(Implicit);\n";
2613
0
      OS << "  return A;\n}\n\n";
2614
2615
0
      writePrettyPrintFunction(R, Args, OS);
2616
0
      writeGetSpellingFunction(R, OS);
2617
0
    }
2618
0
  }
2619
0
}
2620
// Emits the class definitions for attributes.
2621
0
void clang::EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
2622
0
  emitSourceFileHeader("Attribute classes' definitions", OS);
2623
2624
0
  OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2625
0
  OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2626
2627
0
  emitAttributes(Records, OS, true);
2628
2629
0
  OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
2630
0
}
2631
2632
// Emits the class method definitions for attributes.
2633
0
void clang::EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2634
0
  emitSourceFileHeader("Attribute classes' member function definitions", OS);
2635
2636
0
  emitAttributes(Records, OS, false);
2637
2638
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2639
2640
  // Instead of relying on virtual dispatch we just create a huge dispatch
2641
  // switch. This is both smaller and faster than virtual functions.
2642
0
  auto EmitFunc = [&](const char *Method) {
2643
0
    OS << "  switch (getKind()) {\n";
2644
0
    for (const auto *Attr : Attrs) {
2645
0
      const Record &R = *Attr;
2646
0
      if (!R.getValueAsBit("ASTNode"))
2647
0
        continue;
2648
2649
0
      OS << "  case attr::" << R.getName() << ":\n";
2650
0
      OS << "    return cast<" << R.getName() << "Attr>(this)->" << Method
2651
0
         << ";\n";
2652
0
    }
2653
0
    OS << "  }\n";
2654
0
    OS << "  llvm_unreachable(\"Unexpected attribute kind!\");\n";
2655
0
    OS << "}\n\n";
2656
0
  };
2657
2658
0
  OS << "const char *Attr::getSpelling() const {\n";
2659
0
  EmitFunc("getSpelling()");
2660
2661
0
  OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2662
0
  EmitFunc("clone(C)");
2663
2664
0
  OS << "void Attr::printPretty(raw_ostream &OS, "
2665
0
        "const PrintingPolicy &Policy) const {\n";
2666
0
  EmitFunc("printPretty(OS, Policy)");
2667
0
}
2668
2669
static void emitAttrList(raw_ostream &OS, StringRef Class,
2670
0
                         const std::vector<Record*> &AttrList) {
2671
0
  for (auto Cur : AttrList) {
2672
0
    OS << Class << "(" << Cur->getName() << ")\n";
2673
0
  }
2674
0
}
2675
2676
// Determines if an attribute has a Pragma spelling.
2677
0
static bool AttrHasPragmaSpelling(const Record *R) {
2678
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2679
0
  return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
2680
0
           return S.variety() == "Pragma";
2681
0
         }) != Spellings.end();
2682
0
}
2683
2684
namespace {
2685
2686
  struct AttrClassDescriptor {
2687
    const char * const MacroName;
2688
    const char * const TableGenName;
2689
  };
2690
2691
} // end anonymous namespace
2692
2693
static const AttrClassDescriptor AttrClassDescriptors[] = {
2694
  { "ATTR", "Attr" },
2695
  { "TYPE_ATTR", "TypeAttr" },
2696
  { "STMT_ATTR", "StmtAttr" },
2697
  { "DECL_OR_STMT_ATTR", "DeclOrStmtAttr" },
2698
  { "INHERITABLE_ATTR", "InheritableAttr" },
2699
  { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
2700
  { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2701
  { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
2702
};
2703
2704
static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2705
0
                              const char *superName) {
2706
0
  OS << "#ifndef " << name << "\n";
2707
0
  OS << "#define " << name << "(NAME) ";
2708
0
  if (superName) OS << superName << "(NAME)";
2709
0
  OS << "\n#endif\n\n";
2710
0
}
2711
2712
namespace {
2713
2714
  /// A class of attributes.
2715
  struct AttrClass {
2716
    const AttrClassDescriptor &Descriptor;
2717
    Record *TheRecord;
2718
    AttrClass *SuperClass = nullptr;
2719
    std::vector<AttrClass*> SubClasses;
2720
    std::vector<Record*> Attrs;
2721
2722
    AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2723
0
      : Descriptor(Descriptor), TheRecord(R) {}
2724
2725
0
    void emitDefaultDefines(raw_ostream &OS) const {
2726
      // Default the macro unless this is a root class (i.e. Attr).
2727
0
      if (SuperClass) {
2728
0
        emitDefaultDefine(OS, Descriptor.MacroName,
2729
0
                          SuperClass->Descriptor.MacroName);
2730
0
      }
2731
0
    }
2732
2733
0
    void emitUndefs(raw_ostream &OS) const {
2734
0
      OS << "#undef " << Descriptor.MacroName << "\n";
2735
0
    }
2736
2737
0
    void emitAttrList(raw_ostream &OS) const {
2738
0
      for (auto SubClass : SubClasses) {
2739
0
        SubClass->emitAttrList(OS);
2740
0
      }
2741
2742
0
      ::emitAttrList(OS, Descriptor.MacroName, Attrs);
2743
0
    }
2744
2745
0
    void classifyAttrOnRoot(Record *Attr) {
2746
0
      bool result = classifyAttr(Attr);
2747
0
      assert(result && "failed to classify on root"); (void) result;
2748
0
    }
2749
2750
0
    void emitAttrRange(raw_ostream &OS) const {
2751
0
      OS << "ATTR_RANGE(" << Descriptor.TableGenName
2752
0
         << ", " << getFirstAttr()->getName()
2753
0
         << ", " << getLastAttr()->getName() << ")\n";
2754
0
    }
2755
2756
  private:
2757
0
    bool classifyAttr(Record *Attr) {
2758
      // Check all the subclasses.
2759
0
      for (auto SubClass : SubClasses) {
2760
0
        if (SubClass->classifyAttr(Attr))
2761
0
          return true;
2762
0
      }
2763
2764
      // It's not more specific than this class, but it might still belong here.
2765
0
      if (Attr->isSubClassOf(TheRecord)) {
2766
0
        Attrs.push_back(Attr);
2767
0
        return true;
2768
0
      }
2769
2770
0
      return false;
2771
0
    }
2772
2773
0
    Record *getFirstAttr() const {
2774
0
      if (!SubClasses.empty())
2775
0
        return SubClasses.front()->getFirstAttr();
2776
0
      return Attrs.front();
2777
0
    }
2778
2779
0
    Record *getLastAttr() const {
2780
0
      if (!Attrs.empty())
2781
0
        return Attrs.back();
2782
0
      return SubClasses.back()->getLastAttr();
2783
0
    }
2784
  };
2785
2786
  /// The entire hierarchy of attribute classes.
2787
  class AttrClassHierarchy {
2788
    std::vector<std::unique_ptr<AttrClass>> Classes;
2789
2790
  public:
2791
0
    AttrClassHierarchy(RecordKeeper &Records) {
2792
      // Find records for all the classes.
2793
0
      for (auto &Descriptor : AttrClassDescriptors) {
2794
0
        Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2795
0
        AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2796
0
        Classes.emplace_back(Class);
2797
0
      }
2798
2799
      // Link up the hierarchy.
2800
0
      for (auto &Class : Classes) {
2801
0
        if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2802
0
          Class->SuperClass = SuperClass;
2803
0
          SuperClass->SubClasses.push_back(Class.get());
2804
0
        }
2805
0
      }
2806
2807
0
#ifndef NDEBUG
2808
0
      for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2809
0
        assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2810
0
               "only the first class should be a root class!");
2811
0
      }
2812
0
#endif
2813
0
    }
2814
2815
0
    void emitDefaultDefines(raw_ostream &OS) const {
2816
0
      for (auto &Class : Classes) {
2817
0
        Class->emitDefaultDefines(OS);
2818
0
      }
2819
0
    }
2820
2821
0
    void emitUndefs(raw_ostream &OS) const {
2822
0
      for (auto &Class : Classes) {
2823
0
        Class->emitUndefs(OS);
2824
0
      }
2825
0
    }
2826
2827
0
    void emitAttrLists(raw_ostream &OS) const {
2828
      // Just start from the root class.
2829
0
      Classes[0]->emitAttrList(OS);
2830
0
    }
2831
2832
0
    void emitAttrRanges(raw_ostream &OS) const {
2833
0
      for (auto &Class : Classes)
2834
0
        Class->emitAttrRange(OS);
2835
0
    }
2836
2837
0
    void classifyAttr(Record *Attr) {
2838
      // Add the attribute to the root class.
2839
0
      Classes[0]->classifyAttrOnRoot(Attr);
2840
0
    }
2841
2842
  private:
2843
0
    AttrClass *findClassByRecord(Record *R) const {
2844
0
      for (auto &Class : Classes) {
2845
0
        if (Class->TheRecord == R)
2846
0
          return Class.get();
2847
0
      }
2848
0
      return nullptr;
2849
0
    }
2850
2851
0
    AttrClass *findSuperClass(Record *R) const {
2852
      // TableGen flattens the superclass list, so we just need to walk it
2853
      // in reverse.
2854
0
      auto SuperClasses = R->getSuperClasses();
2855
0
      for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2856
0
        auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2857
0
        if (SuperClass) return SuperClass;
2858
0
      }
2859
0
      return nullptr;
2860
0
    }
2861
  };
2862
2863
} // end anonymous namespace
2864
2865
namespace clang {
2866
2867
// Emits the enumeration list for attributes.
2868
0
void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
2869
0
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2870
2871
0
  AttrClassHierarchy Hierarchy(Records);
2872
2873
  // Add defaulting macro definitions.
2874
0
  Hierarchy.emitDefaultDefines(OS);
2875
0
  emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
2876
2877
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2878
0
  std::vector<Record *> PragmaAttrs;
2879
0
  for (auto *Attr : Attrs) {
2880
0
    if (!Attr->getValueAsBit("ASTNode"))
2881
0
      continue;
2882
2883
    // Add the attribute to the ad-hoc groups.
2884
0
    if (AttrHasPragmaSpelling(Attr))
2885
0
      PragmaAttrs.push_back(Attr);
2886
2887
    // Place it in the hierarchy.
2888
0
    Hierarchy.classifyAttr(Attr);
2889
0
  }
2890
2891
  // Emit the main attribute list.
2892
0
  Hierarchy.emitAttrLists(OS);
2893
2894
  // Emit the ad hoc groups.
2895
0
  emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2896
2897
  // Emit the attribute ranges.
2898
0
  OS << "#ifdef ATTR_RANGE\n";
2899
0
  Hierarchy.emitAttrRanges(OS);
2900
0
  OS << "#undef ATTR_RANGE\n";
2901
0
  OS << "#endif\n";
2902
2903
0
  Hierarchy.emitUndefs(OS);
2904
0
  OS << "#undef PRAGMA_SPELLING_ATTR\n";
2905
0
}
2906
2907
// Emits the enumeration list for attributes.
2908
0
void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
2909
0
  emitSourceFileHeader(
2910
0
      "List of all attribute subject matching rules that Clang recognizes", OS);
2911
0
  PragmaClangAttributeSupport &PragmaAttributeSupport =
2912
0
      getPragmaAttributeSupport(Records);
2913
0
  emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
2914
0
  PragmaAttributeSupport.emitMatchRuleList(OS);
2915
0
  OS << "#undef ATTR_MATCH_RULE\n";
2916
0
}
2917
2918
// Emits the code to read an attribute from a precompiled header.
2919
0
void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
2920
0
  emitSourceFileHeader("Attribute deserialization code", OS);
2921
2922
0
  Record *InhClass = Records.getClass("InheritableAttr");
2923
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2924
0
                       ArgRecords;
2925
0
  std::vector<std::unique_ptr<Argument>> Args;
2926
2927
0
  OS << "  switch (Kind) {\n";
2928
0
  for (const auto *Attr : Attrs) {
2929
0
    const Record &R = *Attr;
2930
0
    if (!R.getValueAsBit("ASTNode"))
2931
0
      continue;
2932
2933
0
    OS << "  case attr::" << R.getName() << ": {\n";
2934
0
    if (R.isSubClassOf(InhClass))
2935
0
      OS << "    bool isInherited = Record.readInt();\n";
2936
0
    OS << "    bool isImplicit = Record.readInt();\n";
2937
0
    OS << "    bool isPackExpansion = Record.readInt();\n";
2938
0
    ArgRecords = R.getValueAsListOfDefs("Args");
2939
0
    Args.clear();
2940
0
    for (const auto *Arg : ArgRecords) {
2941
0
      Args.emplace_back(createArgument(*Arg, R.getName()));
2942
0
      Args.back()->writePCHReadDecls(OS);
2943
0
    }
2944
0
    OS << "    New = new (Context) " << R.getName() << "Attr(Context, Info";
2945
0
    for (auto const &ri : Args) {
2946
0
      OS << ", ";
2947
0
      ri->writePCHReadArgs(OS);
2948
0
    }
2949
0
    OS << ");\n";
2950
0
    if (R.isSubClassOf(InhClass))
2951
0
      OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
2952
0
    OS << "    New->setImplicit(isImplicit);\n";
2953
0
    OS << "    New->setPackExpansion(isPackExpansion);\n";
2954
0
    OS << "    break;\n";
2955
0
    OS << "  }\n";
2956
0
  }
2957
0
  OS << "  }\n";
2958
0
}
2959
2960
// Emits the code to write an attribute to a precompiled header.
2961
0
void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
2962
0
  emitSourceFileHeader("Attribute serialization code", OS);
2963
2964
0
  Record *InhClass = Records.getClass("InheritableAttr");
2965
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2966
2967
0
  OS << "  switch (A->getKind()) {\n";
2968
0
  for (const auto *Attr : Attrs) {
2969
0
    const Record &R = *Attr;
2970
0
    if (!R.getValueAsBit("ASTNode"))
2971
0
      continue;
2972
0
    OS << "  case attr::" << R.getName() << ": {\n";
2973
0
    Args = R.getValueAsListOfDefs("Args");
2974
0
    if (R.isSubClassOf(InhClass) || !Args.empty())
2975
0
      OS << "    const auto *SA = cast<" << R.getName()
2976
0
         << "Attr>(A);\n";
2977
0
    if (R.isSubClassOf(InhClass))
2978
0
      OS << "    Record.push_back(SA->isInherited());\n";
2979
0
    OS << "    Record.push_back(A->isImplicit());\n";
2980
0
    OS << "    Record.push_back(A->isPackExpansion());\n";
2981
2982
0
    for (const auto *Arg : Args)
2983
0
      createArgument(*Arg, R.getName())->writePCHWrite(OS);
2984
0
    OS << "    break;\n";
2985
0
    OS << "  }\n";
2986
0
  }
2987
0
  OS << "  }\n";
2988
0
}
2989
2990
// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
2991
// parameter with only a single check type, if applicable.
2992
static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
2993
                                            std::string *FnName,
2994
                                            StringRef ListName,
2995
                                            StringRef CheckAgainst,
2996
0
                                            StringRef Scope) {
2997
0
  if (!R->isValueUnset(ListName)) {
2998
0
    Test += " && (";
2999
0
    std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
3000
0
    for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
3001
0
      StringRef Part = *I;
3002
0
      Test += CheckAgainst;
3003
0
      Test += " == ";
3004
0
      Test += Scope;
3005
0
      Test += Part;
3006
0
      if (I + 1 != E)
3007
0
        Test += " || ";
3008
0
      if (FnName)
3009
0
        *FnName += Part;
3010
0
    }
3011
0
    Test += ")";
3012
0
    return true;
3013
0
  }
3014
0
  return false;
3015
0
}
3016
3017
// Generate a conditional expression to check if the current target satisfies
3018
// the conditions for a TargetSpecificAttr record, and append the code for
3019
// those checks to the Test string. If the FnName string pointer is non-null,
3020
// append a unique suffix to distinguish this set of target checks from other
3021
// TargetSpecificAttr records.
3022
static bool GenerateTargetSpecificAttrChecks(const Record *R,
3023
                                             std::vector<StringRef> &Arches,
3024
                                             std::string &Test,
3025
0
                                             std::string *FnName) {
3026
0
  bool AnyTargetChecks = false;
3027
3028
  // It is assumed that there will be an llvm::Triple object
3029
  // named "T" and a TargetInfo object named "Target" within
3030
  // scope that can be used to determine whether the attribute exists in
3031
  // a given target.
3032
0
  Test += "true";
3033
  // If one or more architectures is specified, check those.  Arches are handled
3034
  // differently because GenerateTargetRequirements needs to combine the list
3035
  // with ParseKind.
3036
0
  if (!Arches.empty()) {
3037
0
    AnyTargetChecks = true;
3038
0
    Test += " && (";
3039
0
    for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
3040
0
      StringRef Part = *I;
3041
0
      Test += "T.getArch() == llvm::Triple::";
3042
0
      Test += Part;
3043
0
      if (I + 1 != E)
3044
0
        Test += " || ";
3045
0
      if (FnName)
3046
0
        *FnName += Part;
3047
0
    }
3048
0
    Test += ")";
3049
0
  }
3050
3051
  // If the attribute is specific to particular OSes, check those.
3052
0
  AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
3053
0
      R, Test, FnName, "OSes", "T.getOS()", "llvm::Triple::");
3054
3055
  // If one or more object formats is specified, check those.
3056
0
  AnyTargetChecks |=
3057
0
      GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
3058
0
                                      "T.getObjectFormat()", "llvm::Triple::");
3059
3060
  // If custom code is specified, emit it.
3061
0
  StringRef Code = R->getValueAsString("CustomCode");
3062
0
  if (!Code.empty()) {
3063
0
    AnyTargetChecks = true;
3064
0
    Test += " && (";
3065
0
    Test += Code;
3066
0
    Test += ")";
3067
0
  }
3068
3069
0
  return AnyTargetChecks;
3070
0
}
3071
3072
static void GenerateHasAttrSpellingStringSwitch(
3073
    const std::vector<Record *> &Attrs, raw_ostream &OS,
3074
0
    const std::string &Variety = "", const std::string &Scope = "") {
3075
0
  for (const auto *Attr : Attrs) {
3076
    // C++11-style attributes have specific version information associated with
3077
    // them. If the attribute has no scope, the version information must not
3078
    // have the default value (1), as that's incorrect. Instead, the unscoped
3079
    // attribute version information should be taken from the SD-6 standing
3080
    // document, which can be found at:
3081
    // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3082
    //
3083
    // C2x-style attributes have the same kind of version information
3084
    // associated with them. The unscoped attribute version information should
3085
    // be taken from the specification of the attribute in the C Standard.
3086
0
    int Version = 1;
3087
3088
0
    if (Variety == "CXX11" || Variety == "C2x") {
3089
0
      std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
3090
0
      for (const auto &Spelling : Spellings) {
3091
0
        if (Spelling->getValueAsString("Variety") == Variety) {
3092
0
          Version = static_cast<int>(Spelling->getValueAsInt("Version"));
3093
0
          if (Scope.empty() && Version == 1)
3094
0
            PrintError(Spelling->getLoc(), "Standard attributes must have "
3095
0
                                           "valid version information.");
3096
0
          break;
3097
0
        }
3098
0
      }
3099
0
    }
3100
3101
0
    std::string Test;
3102
0
    if (Attr->isSubClassOf("TargetSpecificAttr")) {
3103
0
      const Record *R = Attr->getValueAsDef("Target");
3104
0
      std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3105
0
      GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
3106
3107
      // If this is the C++11 variety, also add in the LangOpts test.
3108
0
      if (Variety == "CXX11")
3109
0
        Test += " && LangOpts.CPlusPlus11";
3110
0
      else if (Variety == "C2x")
3111
0
        Test += " && LangOpts.DoubleSquareBracketAttributes";
3112
0
    } else if (Variety == "CXX11")
3113
      // C++11 mode should be checked against LangOpts, which is presumed to be
3114
      // present in the caller.
3115
0
      Test = "LangOpts.CPlusPlus11";
3116
0
    else if (Variety == "C2x")
3117
0
      Test = "LangOpts.DoubleSquareBracketAttributes";
3118
3119
0
    std::string TestStr =
3120
0
        !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
3121
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
3122
0
    for (const auto &S : Spellings)
3123
0
      if (Variety.empty() || (Variety == S.variety() &&
3124
0
                              (Scope.empty() || Scope == S.nameSpace())))
3125
0
        OS << "    .Case(\"" << S.name() << "\", " << TestStr << ")\n";
3126
0
  }
3127
0
  OS << "    .Default(0);\n";
3128
0
}
3129
3130
// Emits the list of spellings for attributes.
3131
0
void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3132
0
  emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
3133
3134
  // Separate all of the attributes out into four group: generic, C++11, GNU,
3135
  // and declspecs. Then generate a big switch statement for each of them.
3136
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3137
0
  std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
3138
0
  std::map<std::string, std::vector<Record *>> CXX, C2x;
3139
3140
  // Walk over the list of all attributes, and split them out based on the
3141
  // spelling variety.
3142
0
  for (auto *R : Attrs) {
3143
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
3144
0
    for (const auto &SI : Spellings) {
3145
0
      const std::string &Variety = SI.variety();
3146
0
      if (Variety == "GNU")
3147
0
        GNU.push_back(R);
3148
0
      else if (Variety == "Declspec")
3149
0
        Declspec.push_back(R);
3150
0
      else if (Variety == "Microsoft")
3151
0
        Microsoft.push_back(R);
3152
0
      else if (Variety == "CXX11")
3153
0
        CXX[SI.nameSpace()].push_back(R);
3154
0
      else if (Variety == "C2x")
3155
0
        C2x[SI.nameSpace()].push_back(R);
3156
0
      else if (Variety == "Pragma")
3157
0
        Pragma.push_back(R);
3158
0
    }
3159
0
  }
3160
3161
0
  OS << "const llvm::Triple &T = Target.getTriple();\n";
3162
0
  OS << "switch (Syntax) {\n";
3163
0
  OS << "case AttrSyntax::GNU:\n";
3164
0
  OS << "  return llvm::StringSwitch<int>(Name)\n";
3165
0
  GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
3166
0
  OS << "case AttrSyntax::Declspec:\n";
3167
0
  OS << "  return llvm::StringSwitch<int>(Name)\n";
3168
0
  GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
3169
0
  OS << "case AttrSyntax::Microsoft:\n";
3170
0
  OS << "  return llvm::StringSwitch<int>(Name)\n";
3171
0
  GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
3172
0
  OS << "case AttrSyntax::Pragma:\n";
3173
0
  OS << "  return llvm::StringSwitch<int>(Name)\n";
3174
0
  GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
3175
0
  auto fn = [&OS](const char *Spelling, const char *Variety,
3176
0
                  const std::map<std::string, std::vector<Record *>> &List) {
3177
0
    OS << "case AttrSyntax::" << Variety << ": {\n";
3178
    // C++11-style attributes are further split out based on the Scope.
3179
0
    for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
3180
0
      if (I != List.cbegin())
3181
0
        OS << " else ";
3182
0
      if (I->first.empty())
3183
0
        OS << "if (ScopeName == \"\") {\n";
3184
0
      else
3185
0
        OS << "if (ScopeName == \"" << I->first << "\") {\n";
3186
0
      OS << "  return llvm::StringSwitch<int>(Name)\n";
3187
0
      GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
3188
0
      OS << "}";
3189
0
    }
3190
0
    OS << "\n} break;\n";
3191
0
  };
3192
0
  fn("CXX11", "CXX", CXX);
3193
0
  fn("C2x", "C", C2x);
3194
0
  OS << "}\n";
3195
0
}
3196
3197
0
void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
3198
0
  emitSourceFileHeader("Code to translate different attribute spellings "
3199
0
                       "into internal identifiers", OS);
3200
3201
0
  OS << "  switch (getParsedKind()) {\n";
3202
0
  OS << "    case IgnoredAttribute:\n";
3203
0
  OS << "    case UnknownAttribute:\n";
3204
0
  OS << "    case NoSemaHandlerAttribute:\n";
3205
0
  OS << "      llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
3206
3207
0
  ParsedAttrMap Attrs = getParsedAttrList(Records);
3208
0
  for (const auto &I : Attrs) {
3209
0
    const Record &R = *I.second;
3210
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3211
0
    OS << "  case AT_" << I.first << ": {\n";
3212
0
    for (unsigned I = 0; I < Spellings.size(); ++ I) {
3213
0
      OS << "    if (Name == \"" << Spellings[I].name() << "\" && "
3214
0
         << "getSyntax() == AttributeCommonInfo::AS_" << Spellings[I].variety()
3215
0
         << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
3216
0
         << "        return " << I << ";\n";
3217
0
    }
3218
3219
0
    OS << "    break;\n";
3220
0
    OS << "  }\n";
3221
0
  }
3222
3223
0
  OS << "  }\n";
3224
0
  OS << "  return 0;\n";
3225
0
}
3226
3227
// Emits code used by RecursiveASTVisitor to visit attributes
3228
0
void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
3229
0
  emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
3230
3231
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3232
3233
  // Write method declarations for Traverse* methods.
3234
  // We emit this here because we only generate methods for attributes that
3235
  // are declared as ASTNodes.
3236
0
  OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
3237
0
  for (const auto *Attr : Attrs) {
3238
0
    const Record &R = *Attr;
3239
0
    if (!R.getValueAsBit("ASTNode"))
3240
0
      continue;
3241
0
    OS << "  bool Traverse"
3242
0
       << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3243
0
    OS << "  bool Visit"
3244
0
       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3245
0
       << "    return true; \n"
3246
0
       << "  }\n";
3247
0
  }
3248
0
  OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3249
3250
  // Write individual Traverse* methods for each attribute class.
3251
0
  for (const auto *Attr : Attrs) {
3252
0
    const Record &R = *Attr;
3253
0
    if (!R.getValueAsBit("ASTNode"))
3254
0
      continue;
3255
3256
0
    OS << "template <typename Derived>\n"
3257
0
       << "bool VISITORCLASS<Derived>::Traverse"
3258
0
       << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3259
0
       << "  if (!getDerived().VisitAttr(A))\n"
3260
0
       << "    return false;\n"
3261
0
       << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3262
0
       << "    return false;\n";
3263
3264
0
    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3265
0
    for (const auto *Arg : ArgRecords)
3266
0
      createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
3267
3268
0
    OS << "  return true;\n";
3269
0
    OS << "}\n\n";
3270
0
  }
3271
3272
  // Write generic Traverse routine
3273
0
  OS << "template <typename Derived>\n"
3274
0
     << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
3275
0
     << "  if (!A)\n"
3276
0
     << "    return true;\n"
3277
0
     << "\n"
3278
0
     << "  switch (A->getKind()) {\n";
3279
3280
0
  for (const auto *Attr : Attrs) {
3281
0
    const Record &R = *Attr;
3282
0
    if (!R.getValueAsBit("ASTNode"))
3283
0
      continue;
3284
3285
0
    OS << "    case attr::" << R.getName() << ":\n"
3286
0
       << "      return getDerived().Traverse" << R.getName() << "Attr("
3287
0
       << "cast<" << R.getName() << "Attr>(A));\n";
3288
0
  }
3289
0
  OS << "  }\n";  // end switch
3290
0
  OS << "  llvm_unreachable(\"bad attribute kind\");\n";
3291
0
  OS << "}\n";  // end function
3292
0
  OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
3293
0
}
3294
3295
void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3296
                                            raw_ostream &OS,
3297
0
                                            bool AppliesToDecl) {
3298
3299
0
  OS << "  switch (At->getKind()) {\n";
3300
0
  for (const auto *Attr : Attrs) {
3301
0
    const Record &R = *Attr;
3302
0
    if (!R.getValueAsBit("ASTNode"))
3303
0
      continue;
3304
0
    OS << "    case attr::" << R.getName() << ": {\n";
3305
0
    bool ShouldClone = R.getValueAsBit("Clone") &&
3306
0
                       (!AppliesToDecl ||
3307
0
                        R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
3308
3309
0
    if (!ShouldClone) {
3310
0
      OS << "      return nullptr;\n";
3311
0
      OS << "    }\n";
3312
0
      continue;
3313
0
    }
3314
3315
0
    OS << "      const auto *A = cast<"
3316
0
       << R.getName() << "Attr>(At);\n";
3317
0
    bool TDependent = R.getValueAsBit("TemplateDependent");
3318
3319
0
    if (!TDependent) {
3320
0
      OS << "      return A->clone(C);\n";
3321
0
      OS << "    }\n";
3322
0
      continue;
3323
0
    }
3324
3325
0
    std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3326
0
    std::vector<std::unique_ptr<Argument>> Args;
3327
0
    Args.reserve(ArgRecords.size());
3328
3329
0
    for (const auto *ArgRecord : ArgRecords)
3330
0
      Args.emplace_back(createArgument(*ArgRecord, R.getName()));
3331
3332
0
    for (auto const &ai : Args)
3333
0
      ai->writeTemplateInstantiation(OS);
3334
3335
0
    OS << "      return new (C) " << R.getName() << "Attr(C, *A";
3336
0
    for (auto const &ai : Args) {
3337
0
      OS << ", ";
3338
0
      ai->writeTemplateInstantiationArgs(OS);
3339
0
    }
3340
0
    OS << ");\n"
3341
0
       << "    }\n";
3342
0
  }
3343
0
  OS << "  } // end switch\n"
3344
0
     << "  llvm_unreachable(\"Unknown attribute!\");\n"
3345
0
     << "  return nullptr;\n";
3346
0
}
3347
3348
// Emits code to instantiate dependent attributes on templates.
3349
0
void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3350
0
  emitSourceFileHeader("Template instantiation code for attributes", OS);
3351
3352
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3353
3354
0
  OS << "namespace clang {\n"
3355
0
     << "namespace sema {\n\n"
3356
0
     << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3357
0
     << "Sema &S,\n"
3358
0
     << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3359
0
  EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3360
0
  OS << "}\n\n"
3361
0
     << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3362
0
     << " ASTContext &C, Sema &S,\n"
3363
0
     << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3364
0
  EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3365
0
  OS << "}\n\n"
3366
0
     << "} // end namespace sema\n"
3367
0
     << "} // end namespace clang\n";
3368
0
}
3369
3370
// Emits the list of parsed attributes.
3371
0
void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3372
0
  emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3373
3374
0
  OS << "#ifndef PARSED_ATTR\n";
3375
0
  OS << "#define PARSED_ATTR(NAME) NAME\n";
3376
0
  OS << "#endif\n\n";
3377
3378
0
  ParsedAttrMap Names = getParsedAttrList(Records);
3379
0
  for (const auto &I : Names) {
3380
0
    OS << "PARSED_ATTR(" << I.first << ")\n";
3381
0
  }
3382
0
}
3383
3384
0
static bool isArgVariadic(const Record &R, StringRef AttrName) {
3385
0
  return createArgument(R, AttrName)->isVariadic();
3386
0
}
3387
3388
0
static void emitArgInfo(const Record &R, raw_ostream &OS) {
3389
  // This function will count the number of arguments specified for the
3390
  // attribute and emit the number of required arguments followed by the
3391
  // number of optional arguments.
3392
0
  std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3393
0
  unsigned ArgCount = 0, OptCount = 0;
3394
0
  bool HasVariadic = false;
3395
0
  for (const auto *Arg : Args) {
3396
    // If the arg is fake, it's the user's job to supply it: general parsing
3397
    // logic shouldn't need to know anything about it.
3398
0
    if (Arg->getValueAsBit("Fake"))
3399
0
      continue;
3400
0
    Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
3401
0
    if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3402
0
      HasVariadic = true;
3403
0
  }
3404
3405
  // If there is a variadic argument, we will set the optional argument count
3406
  // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3407
0
  OS << "    NumArgs = " << ArgCount << ";\n";
3408
0
  OS << "    OptArgs = " << (HasVariadic ? 15 : OptCount) << ";\n";
3409
0
}
3410
3411
0
static std::string GetDiagnosticSpelling(const Record &R) {
3412
0
  std::string Ret = std::string(R.getValueAsString("DiagSpelling"));
3413
0
  if (!Ret.empty())
3414
0
    return Ret;
3415
3416
  // If we couldn't find the DiagSpelling in this object, we can check to see
3417
  // if the object is one that has a base, and if it is, loop up to the Base
3418
  // member recursively.
3419
0
  if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
3420
0
    return GetDiagnosticSpelling(*Base);
3421
3422
0
  return "";
3423
0
}
3424
3425
0
static std::string CalculateDiagnostic(const Record &S) {
3426
  // If the SubjectList object has a custom diagnostic associated with it,
3427
  // return that directly.
3428
0
  const StringRef CustomDiag = S.getValueAsString("CustomDiag");
3429
0
  if (!CustomDiag.empty())
3430
0
    return ("\"" + Twine(CustomDiag) + "\"").str();
3431
3432
0
  std::vector<std::string> DiagList;
3433
0
  std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
3434
0
  for (const auto *Subject : Subjects) {
3435
0
    const Record &R = *Subject;
3436
    // Get the diagnostic text from the Decl or Stmt node given.
3437
0
    std::string V = GetDiagnosticSpelling(R);
3438
0
    if (V.empty()) {
3439
0
      PrintError(R.getLoc(),
3440
0
                 "Could not determine diagnostic spelling for the node: " +
3441
0
                     R.getName() + "; please add one to DeclNodes.td");
3442
0
    } else {
3443
      // The node may contain a list of elements itself, so split the elements
3444
      // by a comma, and trim any whitespace.
3445
0
      SmallVector<StringRef, 2> Frags;
3446
0
      llvm::SplitString(V, Frags, ",");
3447
0
      for (auto Str : Frags) {
3448
0
        DiagList.push_back(std::string(Str.trim()));
3449
0
      }
3450
0
    }
3451
0
  }
3452
3453
0
  if (DiagList.empty()) {
3454
0
    PrintFatalError(S.getLoc(),
3455
0
                    "Could not deduce diagnostic argument for Attr subjects");
3456
0
    return "";
3457
0
  }
3458
3459
  // FIXME: this is not particularly good for localization purposes and ideally
3460
  // should be part of the diagnostics engine itself with some sort of list
3461
  // specifier.
3462
3463
  // A single member of the list can be returned directly.
3464
0
  if (DiagList.size() == 1)
3465
0
    return '"' + DiagList.front() + '"';
3466
3467
0
  if (DiagList.size() == 2)
3468
0
    return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3469
3470
  // If there are more than two in the list, we serialize the first N - 1
3471
  // elements with a comma. This leaves the string in the state: foo, bar,
3472
  // baz (but misses quux). We can then add ", and " for the last element
3473
  // manually.
3474
0
  std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3475
0
  return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
3476
0
}
3477
3478
0
static std::string GetSubjectWithSuffix(const Record *R) {
3479
0
  const std::string &B = std::string(R->getName());
3480
0
  if (B == "DeclBase")
3481
0
    return "Decl";
3482
0
  return B + "Decl";
3483
0
}
3484
3485
0
static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3486
0
  return "is" + Subject.getName().str();
3487
0
}
3488
3489
0
static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
3490
0
  std::string FnName = functionNameForCustomAppertainsTo(Subject);
3491
3492
  // If this code has already been generated, we don't need to do anything.
3493
0
  static std::set<std::string> CustomSubjectSet;
3494
0
  auto I = CustomSubjectSet.find(FnName);
3495
0
  if (I != CustomSubjectSet.end())
3496
0
    return;
3497
3498
  // This only works with non-root Decls.
3499
0
  Record *Base = Subject.getValueAsDef(BaseFieldName);
3500
3501
  // Not currently support custom subjects within custom subjects.
3502
0
  if (Base->isSubClassOf("SubsetSubject")) {
3503
0
    PrintFatalError(Subject.getLoc(),
3504
0
                    "SubsetSubjects within SubsetSubjects is not supported");
3505
0
    return;
3506
0
  }
3507
3508
0
  OS << "static bool " << FnName << "(const Decl *D) {\n";
3509
0
  OS << "  if (const auto *S = dyn_cast<";
3510
0
  OS << GetSubjectWithSuffix(Base);
3511
0
  OS << ">(D))\n";
3512
0
  OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
3513
0
  OS << "  return false;\n";
3514
0
  OS << "}\n\n";
3515
3516
0
  CustomSubjectSet.insert(FnName);
3517
0
}
3518
3519
0
static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
3520
  // If the attribute does not contain a Subjects definition, then use the
3521
  // default appertainsTo logic.
3522
0
  if (Attr.isValueUnset("Subjects"))
3523
0
    return;
3524
3525
0
  const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3526
0
  std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3527
3528
  // If the list of subjects is empty, it is assumed that the attribute
3529
  // appertains to everything.
3530
0
  if (Subjects.empty())
3531
0
    return;
3532
3533
0
  bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3534
3535
  // Split the subjects into declaration subjects and statement subjects.
3536
  // FIXME: subset subjects are added to the declaration list until there are
3537
  // enough statement attributes with custom subject needs to warrant
3538
  // the implementation effort.
3539
0
  std::vector<Record *> DeclSubjects, StmtSubjects;
3540
0
  llvm::copy_if(
3541
0
      Subjects, std::back_inserter(DeclSubjects), [](const Record *R) {
3542
0
        return R->isSubClassOf("SubsetSubject") || !R->isSubClassOf("StmtNode");
3543
0
      });
3544
0
  llvm::copy_if(Subjects, std::back_inserter(StmtSubjects),
3545
0
                [](const Record *R) { return R->isSubClassOf("StmtNode"); });
3546
3547
  // We should have sorted all of the subjects into two lists.
3548
  // FIXME: this assertion will be wrong if we ever add type attribute subjects.
3549
0
  assert(DeclSubjects.size() + StmtSubjects.size() == Subjects.size());
3550
3551
0
  if (DeclSubjects.empty()) {
3552
    // If there are no decl subjects but there are stmt subjects, diagnose
3553
    // trying to apply a statement attribute to a declaration.
3554
0
    if (!StmtSubjects.empty()) {
3555
0
      OS << "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
3556
0
      OS << "const Decl *D) const override {\n";
3557
0
      OS << "  S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)\n";
3558
0
      OS << "    << AL << D->getLocation();\n";
3559
0
      OS << "  return false;\n";
3560
0
      OS << "}\n\n";
3561
0
    }
3562
0
  } else {
3563
    // Otherwise, generate an appertainsTo check specific to this attribute
3564
    // which checks all of the given subjects against the Decl passed in.
3565
0
    OS << "bool diagAppertainsToDecl(Sema &S, ";
3566
0
    OS << "const ParsedAttr &Attr, const Decl *D) const override {\n";
3567
0
    OS << "  if (";
3568
0
    for (auto I = DeclSubjects.begin(), E = DeclSubjects.end(); I != E; ++I) {
3569
      // If the subject has custom code associated with it, use the generated
3570
      // function for it. The function cannot be inlined into this check (yet)
3571
      // because it requires the subject to be of a specific type, and were that
3572
      // information inlined here, it would not support an attribute with
3573
      // multiple custom subjects.
3574
0
      if ((*I)->isSubClassOf("SubsetSubject"))
3575
0
        OS << "!" << functionNameForCustomAppertainsTo(**I) << "(D)";
3576
0
      else
3577
0
        OS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3578
3579
0
      if (I + 1 != E)
3580
0
        OS << " && ";
3581
0
    }
3582
0
    OS << ") {\n";
3583
0
    OS << "    S.Diag(Attr.getLoc(), diag::";
3584
0
    OS << (Warn ? "warn_attribute_wrong_decl_type_str"
3585
0
                : "err_attribute_wrong_decl_type_str");
3586
0
    OS << ")\n";
3587
0
    OS << "      << Attr << ";
3588
0
    OS << CalculateDiagnostic(*SubjectObj) << ";\n";
3589
0
    OS << "    return false;\n";
3590
0
    OS << "  }\n";
3591
0
    OS << "  return true;\n";
3592
0
    OS << "}\n\n";
3593
0
  }
3594
3595
0
  if (StmtSubjects.empty()) {
3596
    // If there are no stmt subjects but there are decl subjects, diagnose
3597
    // trying to apply a declaration attribute to a statement.
3598
0
    if (!DeclSubjects.empty()) {
3599
0
      OS << "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
3600
0
      OS << "const Stmt *St) const override {\n";
3601
0
      OS << "  S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
3602
0
      OS << "    << AL << St->getBeginLoc();\n";
3603
0
      OS << "  return false;\n";
3604
0
      OS << "}\n\n";
3605
0
    }
3606
0
  } else {
3607
    // Now, do the same for statements.
3608
0
    OS << "bool diagAppertainsToStmt(Sema &S, ";
3609
0
    OS << "const ParsedAttr &Attr, const Stmt *St) const override {\n";
3610
0
    OS << "  if (";
3611
0
    for (auto I = StmtSubjects.begin(), E = StmtSubjects.end(); I != E; ++I) {
3612
0
      OS << "!isa<" << (*I)->getName() << ">(St)";
3613
0
      if (I + 1 != E)
3614
0
        OS << " && ";
3615
0
    }
3616
0
    OS << ") {\n";
3617
0
    OS << "    S.Diag(Attr.getLoc(), diag::";
3618
0
    OS << (Warn ? "warn_attribute_wrong_decl_type_str"
3619
0
                : "err_attribute_wrong_decl_type_str");
3620
0
    OS << ")\n";
3621
0
    OS << "      << Attr << ";
3622
0
    OS << CalculateDiagnostic(*SubjectObj) << ";\n";
3623
0
    OS << "    return false;\n";
3624
0
    OS << "  }\n";
3625
0
    OS << "  return true;\n";
3626
0
    OS << "}\n\n";
3627
0
  }
3628
0
}
3629
3630
// Generates the mutual exclusion checks. The checks for parsed attributes are
3631
// written into OS and the checks for merging declaration attributes are
3632
// written into MergeOS.
3633
static void GenerateMutualExclusionsChecks(const Record &Attr,
3634
                                           const RecordKeeper &Records,
3635
                                           raw_ostream &OS,
3636
                                           raw_ostream &MergeDeclOS,
3637
0
                                           raw_ostream &MergeStmtOS) {
3638
  // Find all of the definitions that inherit from MutualExclusions and include
3639
  // the given attribute in the list of exclusions to generate the
3640
  // diagMutualExclusion() check.
3641
0
  std::vector<Record *> ExclusionsList =
3642
0
      Records.getAllDerivedDefinitions("MutualExclusions");
3643
3644
  // We don't do any of this magic for type attributes yet.
3645
0
  if (Attr.isSubClassOf("TypeAttr"))
3646
0
    return;
3647
3648
  // This means the attribute is either a statement attribute, a decl
3649
  // attribute, or both; find out which.
3650
0
  bool CurAttrIsStmtAttr =
3651
0
      Attr.isSubClassOf("StmtAttr") || Attr.isSubClassOf("DeclOrStmtAttr");
3652
0
  bool CurAttrIsDeclAttr =
3653
0
      !CurAttrIsStmtAttr || Attr.isSubClassOf("DeclOrStmtAttr");
3654
3655
0
  std::vector<std::string> DeclAttrs, StmtAttrs;
3656
3657
0
  for (const Record *Exclusion : ExclusionsList) {
3658
0
    std::vector<Record *> MutuallyExclusiveAttrs =
3659
0
        Exclusion->getValueAsListOfDefs("Exclusions");
3660
0
    auto IsCurAttr = [Attr](const Record *R) {
3661
0
      return R->getName() == Attr.getName();
3662
0
    };
3663
0
    if (llvm::any_of(MutuallyExclusiveAttrs, IsCurAttr)) {
3664
      // This list of exclusions includes the attribute we're looking for, so
3665
      // add the exclusive attributes to the proper list for checking.
3666
0
      for (const Record *AttrToExclude : MutuallyExclusiveAttrs) {
3667
0
        if (IsCurAttr(AttrToExclude))
3668
0
          continue;
3669
3670
0
        if (CurAttrIsStmtAttr)
3671
0
          StmtAttrs.push_back((AttrToExclude->getName() + "Attr").str());
3672
0
        if (CurAttrIsDeclAttr)
3673
0
          DeclAttrs.push_back((AttrToExclude->getName() + "Attr").str());
3674
0
      }
3675
0
    }
3676
0
  }
3677
3678
  // If there are any decl or stmt attributes, silence -Woverloaded-virtual
3679
  // warnings for them both.
3680
0
  if (!DeclAttrs.empty() || !StmtAttrs.empty())
3681
0
    OS << "  using ParsedAttrInfo::diagMutualExclusion;\n\n";
3682
3683
  // If we discovered any decl or stmt attributes to test for, generate the
3684
  // predicates for them now.
3685
0
  if (!DeclAttrs.empty()) {
3686
    // Generate the ParsedAttrInfo subclass logic for declarations.
3687
0
    OS << "  bool diagMutualExclusion(Sema &S, const ParsedAttr &AL, "
3688
0
       << "const Decl *D) const override {\n";
3689
0
    for (const std::string &A : DeclAttrs) {
3690
0
      OS << "    if (const auto *A = D->getAttr<" << A << ">()) {\n";
3691
0
      OS << "      S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
3692
0
         << " << AL << A;\n";
3693
0
      OS << "      S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
3694
0
      OS << "      \nreturn false;\n";
3695
0
      OS << "    }\n";
3696
0
    }
3697
0
    OS << "    return true;\n";
3698
0
    OS << "  }\n\n";
3699
3700
    // Also generate the declaration attribute merging logic if the current
3701
    // attribute is one that can be inheritted on a declaration. It is assumed
3702
    // this code will be executed in the context of a function with parameters:
3703
    // Sema &S, Decl *D, Attr *A and that returns a bool (false on diagnostic,
3704
    // true on success).
3705
0
    if (Attr.isSubClassOf("InheritableAttr")) {
3706
0
      MergeDeclOS << "  if (const auto *Second = dyn_cast<"
3707
0
                  << (Attr.getName() + "Attr").str() << ">(A)) {\n";
3708
0
      for (const std::string &A : DeclAttrs) {
3709
0
        MergeDeclOS << "    if (const auto *First = D->getAttr<" << A
3710
0
                    << ">()) {\n";
3711
0
        MergeDeclOS << "      S.Diag(First->getLocation(), "
3712
0
                    << "diag::err_attributes_are_not_compatible) << First << "
3713
0
                    << "Second;\n";
3714
0
        MergeDeclOS << "      S.Diag(Second->getLocation(), "
3715
0
                    << "diag::note_conflicting_attribute);\n";
3716
0
        MergeDeclOS << "      return false;\n";
3717
0
        MergeDeclOS << "    }\n";
3718
0
      }
3719
0
      MergeDeclOS << "    return true;\n";
3720
0
      MergeDeclOS << "  }\n";
3721
0
    }
3722
0
  }
3723
3724
  // Statement attributes are a bit different from declarations. With
3725
  // declarations, each attribute is added to the declaration as it is
3726
  // processed, and so you can look on the Decl * itself to see if there is a
3727
  // conflicting attribute. Statement attributes are processed as a group
3728
  // because AttributedStmt needs to tail-allocate all of the attribute nodes
3729
  // at once. This means we cannot check whether the statement already contains
3730
  // an attribute to check for the conflict. Instead, we need to check whether
3731
  // the given list of semantic attributes contain any conflicts. It is assumed
3732
  // this code will be executed in the context of a function with parameters:
3733
  // Sema &S, const SmallVectorImpl<const Attr *> &C. The code will be within a
3734
  // loop which loops over the container C with a loop variable named A to
3735
  // represent the current attribute to check for conflicts.
3736
  //
3737
  // FIXME: it would be nice not to walk over the list of potential attributes
3738
  // to apply to the statement more than once, but statements typically don't
3739
  // have long lists of attributes on them, so re-walking the list should not
3740
  // be an expensive operation.
3741
0
  if (!StmtAttrs.empty()) {
3742
0
    MergeStmtOS << "    if (const auto *Second = dyn_cast<"
3743
0
                << (Attr.getName() + "Attr").str() << ">(A)) {\n";
3744
0
    MergeStmtOS << "      auto Iter = llvm::find_if(C, [](const Attr *Check) "
3745
0
                << "{ return isa<";
3746
0
    interleave(
3747
0
        StmtAttrs, [&](const std::string &Name) { MergeStmtOS << Name; },
3748
0
        [&] { MergeStmtOS << ", "; });
3749
0
    MergeStmtOS << ">(Check); });\n";
3750
0
    MergeStmtOS << "      if (Iter != C.end()) {\n";
3751
0
    MergeStmtOS << "        S.Diag((*Iter)->getLocation(), "
3752
0
                << "diag::err_attributes_are_not_compatible) << *Iter << "
3753
0
                << "Second;\n";
3754
0
    MergeStmtOS << "        S.Diag(Second->getLocation(), "
3755
0
                << "diag::note_conflicting_attribute);\n";
3756
0
    MergeStmtOS << "        return false;\n";
3757
0
    MergeStmtOS << "      }\n";
3758
0
    MergeStmtOS << "    }\n";
3759
0
  }
3760
0
}
3761
3762
static void
3763
emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
3764
0
                        raw_ostream &OS) {
3765
0
  OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
3766
0
     << AttributeSubjectMatchRule::EnumName << " rule) {\n";
3767
0
  OS << "  switch (rule) {\n";
3768
0
  for (const auto &Rule : PragmaAttributeSupport.Rules) {
3769
0
    if (Rule.isAbstractRule()) {
3770
0
      OS << "  case " << Rule.getEnumValue() << ":\n";
3771
0
      OS << "    assert(false && \"Abstract matcher rule isn't allowed\");\n";
3772
0
      OS << "    return false;\n";
3773
0
      continue;
3774
0
    }
3775
0
    std::vector<Record *> Subjects = Rule.getSubjects();
3776
0
    assert(!Subjects.empty() && "Missing subjects");
3777
0
    OS << "  case " << Rule.getEnumValue() << ":\n";
3778
0
    OS << "    return ";
3779
0
    for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3780
      // If the subject has custom code associated with it, use the function
3781
      // that was generated for GenerateAppertainsTo to check if the declaration
3782
      // is valid.
3783
0
      if ((*I)->isSubClassOf("SubsetSubject"))
3784
0
        OS << functionNameForCustomAppertainsTo(**I) << "(D)";
3785
0
      else
3786
0
        OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3787
3788
0
      if (I + 1 != E)
3789
0
        OS << " || ";
3790
0
    }
3791
0
    OS << ";\n";
3792
0
  }
3793
0
  OS << "  }\n";
3794
0
  OS << "  llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
3795
0
  OS << "}\n\n";
3796
0
}
3797
3798
static void GenerateLangOptRequirements(const Record &R,
3799
0
                                        raw_ostream &OS) {
3800
  // If the attribute has an empty or unset list of language requirements,
3801
  // use the default handler.
3802
0
  std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
3803
0
  if (LangOpts.empty())
3804
0
    return;
3805
3806
0
  OS << "bool acceptsLangOpts(const LangOptions &LangOpts) const override {\n";
3807
0
  OS << "  return " << GenerateTestExpression(LangOpts) << ";\n";
3808
0
  OS << "}\n\n";
3809
0
}
3810
3811
static void GenerateTargetRequirements(const Record &Attr,
3812
                                       const ParsedAttrMap &Dupes,
3813
0
                                       raw_ostream &OS) {
3814
  // If the attribute is not a target specific attribute, use the default
3815
  // target handler.
3816
0
  if (!Attr.isSubClassOf("TargetSpecificAttr"))
3817
0
    return;
3818
3819
  // Get the list of architectures to be tested for.
3820
0
  const Record *R = Attr.getValueAsDef("Target");
3821
0
  std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3822
3823
  // If there are other attributes which share the same parsed attribute kind,
3824
  // such as target-specific attributes with a shared spelling, collapse the
3825
  // duplicate architectures. This is required because a shared target-specific
3826
  // attribute has only one ParsedAttr::Kind enumeration value, but it
3827
  // applies to multiple target architectures. In order for the attribute to be
3828
  // considered valid, all of its architectures need to be included.
3829
0
  if (!Attr.isValueUnset("ParseKind")) {
3830
0
    const StringRef APK = Attr.getValueAsString("ParseKind");
3831
0
    for (const auto &I : Dupes) {
3832
0
      if (I.first == APK) {
3833
0
        std::vector<StringRef> DA =
3834
0
            I.second->getValueAsDef("Target")->getValueAsListOfStrings(
3835
0
                "Arches");
3836
0
        Arches.insert(Arches.end(), DA.begin(), DA.end());
3837
0
      }
3838
0
    }
3839
0
  }
3840
3841
0
  std::string FnName = "isTarget";
3842
0
  std::string Test;
3843
0
  bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
3844
3845
0
  OS << "bool existsInTarget(const TargetInfo &Target) const override {\n";
3846
0
  if (UsesT)
3847
0
    OS << "  const llvm::Triple &T = Target.getTriple(); (void)T;\n";
3848
0
  OS << "  return " << Test << ";\n";
3849
0
  OS << "}\n\n";
3850
0
}
3851
3852
static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
3853
0
                                                    raw_ostream &OS) {
3854
  // If the attribute does not have a semantic form, we can bail out early.
3855
0
  if (!Attr.getValueAsBit("ASTNode"))
3856
0
    return;
3857
3858
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3859
3860
  // If there are zero or one spellings, or all of the spellings share the same
3861
  // name, we can also bail out early.
3862
0
  if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
3863
0
    return;
3864
3865
  // Generate the enumeration we will use for the mapping.
3866
0
  SemanticSpellingMap SemanticToSyntacticMap;
3867
0
  std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
3868
0
  std::string Name = Attr.getName().str() + "AttrSpellingMap";
3869
3870
0
  OS << "unsigned spellingIndexToSemanticSpelling(";
3871
0
  OS << "const ParsedAttr &Attr) const override {\n";
3872
0
  OS << Enum;
3873
0
  OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
3874
0
  WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
3875
0
  OS << "}\n\n";
3876
0
}
3877
3878
0
static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
3879
  // Only generate if Attr can be handled simply.
3880
0
  if (!Attr.getValueAsBit("SimpleHandler"))
3881
0
    return;
3882
3883
  // Generate a function which just converts from ParsedAttr to the Attr type.
3884
0
  OS << "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
3885
0
  OS << "const ParsedAttr &Attr) const override {\n";
3886
0
  OS << "  D->addAttr(::new (S.Context) " << Attr.getName();
3887
0
  OS << "Attr(S.Context, Attr));\n";
3888
0
  OS << "  return AttributeApplied;\n";
3889
0
  OS << "}\n\n";
3890
0
}
3891
3892
0
static bool IsKnownToGCC(const Record &Attr) {
3893
  // Look at the spellings for this subject; if there are any spellings which
3894
  // claim to be known to GCC, the attribute is known to GCC.
3895
0
  return llvm::any_of(
3896
0
      GetFlattenedSpellings(Attr),
3897
0
      [](const FlattenedSpelling &S) { return S.knownToGCC(); });
3898
0
}
3899
3900
/// Emits the parsed attribute helpers
3901
0
void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3902
0
  emitSourceFileHeader("Parsed attribute helpers", OS);
3903
3904
0
  OS << "#if !defined(WANT_DECL_MERGE_LOGIC) && "
3905
0
     << "!defined(WANT_STMT_MERGE_LOGIC)\n";
3906
0
  PragmaClangAttributeSupport &PragmaAttributeSupport =
3907
0
      getPragmaAttributeSupport(Records);
3908
3909
  // Get the list of parsed attributes, and accept the optional list of
3910
  // duplicates due to the ParseKind.
3911
0
  ParsedAttrMap Dupes;
3912
0
  ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
3913
3914
  // Generate all of the custom appertainsTo functions that the attributes
3915
  // will be using.
3916
0
  for (auto I : Attrs) {
3917
0
    const Record &Attr = *I.second;
3918
0
    if (Attr.isValueUnset("Subjects"))
3919
0
      continue;
3920
0
    const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3921
0
    for (auto Subject : SubjectObj->getValueAsListOfDefs("Subjects"))
3922
0
      if (Subject->isSubClassOf("SubsetSubject"))
3923
0
        GenerateCustomAppertainsTo(*Subject, OS);
3924
0
  }
3925
3926
  // This stream is used to collect all of the declaration attribute merging
3927
  // logic for performing mutual exclusion checks. This gets emitted at the
3928
  // end of the file in a helper function of its own.
3929
0
  std::string DeclMergeChecks, StmtMergeChecks;
3930
0
  raw_string_ostream MergeDeclOS(DeclMergeChecks), MergeStmtOS(StmtMergeChecks);
3931
3932
  // Generate a ParsedAttrInfo struct for each of the attributes.
3933
0
  for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
3934
    // TODO: If the attribute's kind appears in the list of duplicates, that is
3935
    // because it is a target-specific attribute that appears multiple times.
3936
    // It would be beneficial to test whether the duplicates are "similar
3937
    // enough" to each other to not cause problems. For instance, check that
3938
    // the spellings are identical, and custom parsing rules match, etc.
3939
3940
    // We need to generate struct instances based off ParsedAttrInfo from
3941
    // ParsedAttr.cpp.
3942
0
    const std::string &AttrName = I->first;
3943
0
    const Record &Attr = *I->second;
3944
0
    auto Spellings = GetFlattenedSpellings(Attr);
3945
0
    if (!Spellings.empty()) {
3946
0
      OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
3947
0
         << "Spellings[] = {\n";
3948
0
      for (const auto &S : Spellings) {
3949
0
        const std::string &RawSpelling = S.name();
3950
0
        std::string Spelling;
3951
0
        if (!S.nameSpace().empty())
3952
0
          Spelling += S.nameSpace() + "::";
3953
0
        if (S.variety() == "GNU")
3954
0
          Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3955
0
        else
3956
0
          Spelling += RawSpelling;
3957
0
        OS << "  {AttributeCommonInfo::AS_" << S.variety();
3958
0
        OS << ", \"" << Spelling << "\"},\n";
3959
0
      }
3960
0
      OS << "};\n";
3961
0
    }
3962
3963
0
    std::vector<std::string> ArgNames;
3964
0
    for (const auto &Arg : Attr.getValueAsListOfDefs("Args")) {
3965
0
      bool UnusedUnset;
3966
0
      if (Arg->getValueAsBitOrUnset("Fake", UnusedUnset))
3967
0
        continue;
3968
0
      ArgNames.push_back(Arg->getValueAsString("Name").str());
3969
0
      for (const auto &Class : Arg->getSuperClasses()) {
3970
0
        if (Class.first->getName().startswith("Variadic")) {
3971
0
          ArgNames.back().append("...");
3972
0
          break;
3973
0
        }
3974
0
      }
3975
0
    }
3976
0
    if (!ArgNames.empty()) {
3977
0
      OS << "static constexpr const char *" << I->first << "ArgNames[] = {\n";
3978
0
      for (const auto &N : ArgNames)
3979
0
        OS << '"' << N << "\",";
3980
0
      OS << "};\n";
3981
0
    }
3982
3983
0
    OS << "struct ParsedAttrInfo" << I->first
3984
0
       << " final : public ParsedAttrInfo {\n";
3985
0
    OS << "  ParsedAttrInfo" << I->first << "() {\n";
3986
0
    OS << "    AttrKind = ParsedAttr::AT_" << AttrName << ";\n";
3987
0
    emitArgInfo(Attr, OS);
3988
0
    OS << "    HasCustomParsing = ";
3989
0
    OS << Attr.getValueAsBit("HasCustomParsing") << ";\n";
3990
0
    OS << "    IsTargetSpecific = ";
3991
0
    OS << Attr.isSubClassOf("TargetSpecificAttr") << ";\n";
3992
0
    OS << "    IsType = ";
3993
0
    OS << (Attr.isSubClassOf("TypeAttr") ||
3994
0
           Attr.isSubClassOf("DeclOrTypeAttr")) << ";\n";
3995
0
    OS << "    IsStmt = ";
3996
0
    OS << (Attr.isSubClassOf("StmtAttr") || Attr.isSubClassOf("DeclOrStmtAttr"))
3997
0
       << ";\n";
3998
0
    OS << "    IsKnownToGCC = ";
3999
0
    OS << IsKnownToGCC(Attr) << ";\n";
4000
0
    OS << "    IsSupportedByPragmaAttribute = ";
4001
0
    OS << PragmaAttributeSupport.isAttributedSupported(*I->second) << ";\n";
4002
0
    if (!Spellings.empty())
4003
0
      OS << "    Spellings = " << I->first << "Spellings;\n";
4004
0
    if (!ArgNames.empty())
4005
0
      OS << "    ArgNames = " << I->first << "ArgNames;\n";
4006
0
    OS << "  }\n";
4007
0
    GenerateAppertainsTo(Attr, OS);
4008
0
    GenerateMutualExclusionsChecks(Attr, Records, OS, MergeDeclOS, MergeStmtOS);
4009
0
    GenerateLangOptRequirements(Attr, OS);
4010
0
    GenerateTargetRequirements(Attr, Dupes, OS);
4011
0
    GenerateSpellingIndexToSemanticSpelling(Attr, OS);
4012
0
    PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
4013
0
    GenerateHandleDeclAttribute(Attr, OS);
4014
0
    OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
4015
0
    OS << "};\n";
4016
0
    OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
4017
0
       << "::Instance;\n";
4018
0
  }
4019
4020
0
  OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
4021
0
  for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
4022
0
    OS << "&ParsedAttrInfo" << I->first << "::Instance,\n";
4023
0
  }
4024
0
  OS << "};\n\n";
4025
4026
  // Generate the attribute match rules.
4027
0
  emitAttributeMatchRules(PragmaAttributeSupport, OS);
4028
4029
0
  OS << "#elif defined(WANT_DECL_MERGE_LOGIC)\n\n";
4030
4031
  // Write out the declaration merging check logic.
4032
0
  OS << "static bool DiagnoseMutualExclusions(Sema &S, const NamedDecl *D, "
4033
0
     << "const Attr *A) {\n";
4034
0
  OS << MergeDeclOS.str();
4035
0
  OS << "  return true;\n";
4036
0
  OS << "}\n\n";
4037
4038
0
  OS << "#elif defined(WANT_STMT_MERGE_LOGIC)\n\n";
4039
4040
  // Write out the statement merging check logic.
4041
0
  OS << "static bool DiagnoseMutualExclusions(Sema &S, "
4042
0
     << "const SmallVectorImpl<const Attr *> &C) {\n";
4043
0
  OS << "  for (const Attr *A : C) {\n";
4044
0
  OS << MergeStmtOS.str();
4045
0
  OS << "  }\n";
4046
0
  OS << "  return true;\n";
4047
0
  OS << "}\n\n";
4048
4049
0
  OS << "#endif\n";
4050
0
}
4051
4052
// Emits the kind list of parsed attributes
4053
0
void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
4054
0
  emitSourceFileHeader("Attribute name matcher", OS);
4055
4056
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4057
0
  std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
4058
0
      Keywords, Pragma, C2x;
4059
0
  std::set<std::string> Seen;
4060
0
  for (const auto *A : Attrs) {
4061
0
    const Record &Attr = *A;
4062
4063
0
    bool SemaHandler = Attr.getValueAsBit("SemaHandler");
4064
0
    bool Ignored = Attr.getValueAsBit("Ignored");
4065
0
    if (SemaHandler || Ignored) {
4066
      // Attribute spellings can be shared between target-specific attributes,
4067
      // and can be shared between syntaxes for the same attribute. For
4068
      // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
4069
      // specific attribute, or MSP430-specific attribute. Additionally, an
4070
      // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
4071
      // for the same semantic attribute. Ultimately, we need to map each of
4072
      // these to a single AttributeCommonInfo::Kind value, but the
4073
      // StringMatcher class cannot handle duplicate match strings. So we
4074
      // generate a list of string to match based on the syntax, and emit
4075
      // multiple string matchers depending on the syntax used.
4076
0
      std::string AttrName;
4077
0
      if (Attr.isSubClassOf("TargetSpecificAttr") &&
4078
0
          !Attr.isValueUnset("ParseKind")) {
4079
0
        AttrName = std::string(Attr.getValueAsString("ParseKind"));
4080
0
        if (Seen.find(AttrName) != Seen.end())
4081
0
          continue;
4082
0
        Seen.insert(AttrName);
4083
0
      } else
4084
0
        AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
4085
4086
0
      std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
4087
0
      for (const auto &S : Spellings) {
4088
0
        const std::string &RawSpelling = S.name();
4089
0
        std::vector<StringMatcher::StringPair> *Matches = nullptr;
4090
0
        std::string Spelling;
4091
0
        const std::string &Variety = S.variety();
4092
0
        if (Variety == "CXX11") {
4093
0
          Matches = &CXX11;
4094
0
          if (!S.nameSpace().empty())
4095
0
            Spelling += S.nameSpace() + "::";
4096
0
        } else if (Variety == "C2x") {
4097
0
          Matches = &C2x;
4098
0
          if (!S.nameSpace().empty())
4099
0
            Spelling += S.nameSpace() + "::";
4100
0
        } else if (Variety == "GNU")
4101
0
          Matches = &GNU;
4102
0
        else if (Variety == "Declspec")
4103
0
          Matches = &Declspec;
4104
0
        else if (Variety == "Microsoft")
4105
0
          Matches = &Microsoft;
4106
0
        else if (Variety == "Keyword")
4107
0
          Matches = &Keywords;
4108
0
        else if (Variety == "Pragma")
4109
0
          Matches = &Pragma;
4110
4111
0
        assert(Matches && "Unsupported spelling variety found");
4112
4113
0
        if (Variety == "GNU")
4114
0
          Spelling += NormalizeGNUAttrSpelling(RawSpelling);
4115
0
        else
4116
0
          Spelling += RawSpelling;
4117
4118
0
        if (SemaHandler)
4119
0
          Matches->push_back(StringMatcher::StringPair(
4120
0
              Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
4121
0
        else
4122
0
          Matches->push_back(StringMatcher::StringPair(
4123
0
              Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
4124
0
      }
4125
0
    }
4126
0
  }
4127
4128
0
  OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
4129
0
  OS << "AttributeCommonInfo::Syntax Syntax) {\n";
4130
0
  OS << "  if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
4131
0
  StringMatcher("Name", GNU, OS).Emit();
4132
0
  OS << "  } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
4133
0
  StringMatcher("Name", Declspec, OS).Emit();
4134
0
  OS << "  } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
4135
0
  StringMatcher("Name", Microsoft, OS).Emit();
4136
0
  OS << "  } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
4137
0
  StringMatcher("Name", CXX11, OS).Emit();
4138
0
  OS << "  } else if (AttributeCommonInfo::AS_C2x == Syntax) {\n";
4139
0
  StringMatcher("Name", C2x, OS).Emit();
4140
0
  OS << "  } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
4141
0
  OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
4142
0
  StringMatcher("Name", Keywords, OS).Emit();
4143
0
  OS << "  } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
4144
0
  StringMatcher("Name", Pragma, OS).Emit();
4145
0
  OS << "  }\n";
4146
0
  OS << "  return AttributeCommonInfo::UnknownAttribute;\n"
4147
0
     << "}\n";
4148
0
}
4149
4150
// Emits the code to dump an attribute.
4151
0
void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
4152
0
  emitSourceFileHeader("Attribute text node dumper", OS);
4153
4154
0
  std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
4155
0
  for (const auto *Attr : Attrs) {
4156
0
    const Record &R = *Attr;
4157
0
    if (!R.getValueAsBit("ASTNode"))
4158
0
      continue;
4159
4160
    // If the attribute has a semantically-meaningful name (which is determined
4161
    // by whether there is a Spelling enumeration for it), then write out the
4162
    // spelling used for the attribute.
4163
4164
0
    std::string FunctionContent;
4165
0
    llvm::raw_string_ostream SS(FunctionContent);
4166
4167
0
    std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
4168
0
    if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
4169
0
      SS << "    OS << \" \" << A->getSpelling();\n";
4170
4171
0
    Args = R.getValueAsListOfDefs("Args");
4172
0
    for (const auto *Arg : Args)
4173
0
      createArgument(*Arg, R.getName())->writeDump(SS);
4174
4175
0
    if (SS.tell()) {
4176
0
      OS << "  void Visit" << R.getName() << "Attr(const " << R.getName()
4177
0
         << "Attr *A) {\n";
4178
0
      if (!Args.empty())
4179
0
        OS << "    const auto *SA = cast<" << R.getName()
4180
0
           << "Attr>(A); (void)SA;\n";
4181
0
      OS << SS.str();
4182
0
      OS << "  }\n";
4183
0
    }
4184
0
  }
4185
0
}
4186
4187
0
void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
4188
0
  emitSourceFileHeader("Attribute text node traverser", OS);
4189
4190
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
4191
0
  for (const auto *Attr : Attrs) {
4192
0
    const Record &R = *Attr;
4193
0
    if (!R.getValueAsBit("ASTNode"))
4194
0
      continue;
4195
4196
0
    std::string FunctionContent;
4197
0
    llvm::raw_string_ostream SS(FunctionContent);
4198
4199
0
    Args = R.getValueAsListOfDefs("Args");
4200
0
    for (const auto *Arg : Args)
4201
0
      createArgument(*Arg, R.getName())->writeDumpChildren(SS);
4202
0
    if (SS.tell()) {
4203
0
      OS << "  void Visit" << R.getName() << "Attr(const " << R.getName()
4204
0
         << "Attr *A) {\n";
4205
0
      if (!Args.empty())
4206
0
        OS << "    const auto *SA = cast<" << R.getName()
4207
0
           << "Attr>(A); (void)SA;\n";
4208
0
      OS << SS.str();
4209
0
      OS << "  }\n";
4210
0
    }
4211
0
  }
4212
0
}
4213
4214
void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
4215
0
                                       raw_ostream &OS) {
4216
0
  emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
4217
0
  emitClangAttrArgContextList(Records, OS);
4218
0
  emitClangAttrIdentifierArgList(Records, OS);
4219
0
  emitClangAttrVariadicIdentifierArgList(Records, OS);
4220
0
  emitClangAttrThisIsaIdentifierArgList(Records, OS);
4221
0
  emitClangAttrTypeArgList(Records, OS);
4222
0
  emitClangAttrLateParsedList(Records, OS);
4223
0
}
4224
4225
void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
4226
0
                                                        raw_ostream &OS) {
4227
0
  getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
4228
0
}
4229
4230
0
void EmitClangAttrDocTable(RecordKeeper &Records, raw_ostream &OS) {
4231
0
  emitSourceFileHeader("Clang attribute documentation", OS);
4232
4233
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4234
0
  for (const auto *A : Attrs) {
4235
0
    if (!A->getValueAsBit("ASTNode"))
4236
0
      continue;
4237
0
    std::vector<Record *> Docs = A->getValueAsListOfDefs("Documentation");
4238
0
    assert(!Docs.empty());
4239
    // Only look at the first documentation if there are several.
4240
    // (Currently there's only one such attr, revisit if this becomes common).
4241
0
    StringRef Text =
4242
0
        Docs.front()->getValueAsOptionalString("Content").getValueOr("");
4243
0
    OS << "\nstatic const char AttrDoc_" << A->getName() << "[] = "
4244
0
       << "R\"reST(" << Text.trim() << ")reST\";\n";
4245
0
  }
4246
0
}
4247
4248
enum class SpellingKind {
4249
  GNU,
4250
  CXX11,
4251
  C2x,
4252
  Declspec,
4253
  Microsoft,
4254
  Keyword,
4255
  Pragma,
4256
};
4257
static const size_t NumSpellingKinds = (size_t)SpellingKind::Pragma + 1;
4258
4259
class SpellingList {
4260
  std::vector<std::string> Spellings[NumSpellingKinds];
4261
4262
public:
4263
0
  ArrayRef<std::string> operator[](SpellingKind K) const {
4264
0
    return Spellings[(size_t)K];
4265
0
  }
4266
4267
0
  void add(const Record &Attr, FlattenedSpelling Spelling) {
4268
0
    SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
4269
0
                            .Case("GNU", SpellingKind::GNU)
4270
0
                            .Case("CXX11", SpellingKind::CXX11)
4271
0
                            .Case("C2x", SpellingKind::C2x)
4272
0
                            .Case("Declspec", SpellingKind::Declspec)
4273
0
                            .Case("Microsoft", SpellingKind::Microsoft)
4274
0
                            .Case("Keyword", SpellingKind::Keyword)
4275
0
                            .Case("Pragma", SpellingKind::Pragma);
4276
0
    std::string Name;
4277
0
    if (!Spelling.nameSpace().empty()) {
4278
0
      switch (Kind) {
4279
0
      case SpellingKind::CXX11:
4280
0
      case SpellingKind::C2x:
4281
0
        Name = Spelling.nameSpace() + "::";
4282
0
        break;
4283
0
      case SpellingKind::Pragma:
4284
0
        Name = Spelling.nameSpace() + " ";
4285
0
        break;
4286
0
      default:
4287
0
        PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
4288
0
      }
4289
0
    }
4290
0
    Name += Spelling.name();
4291
4292
0
    Spellings[(size_t)Kind].push_back(Name);
4293
0
  }
4294
};
4295
4296
class DocumentationData {
4297
public:
4298
  const Record *Documentation;
4299
  const Record *Attribute;
4300
  std::string Heading;
4301
  SpellingList SupportedSpellings;
4302
4303
  DocumentationData(const Record &Documentation, const Record &Attribute,
4304
                    std::pair<std::string, SpellingList> HeadingAndSpellings)
4305
      : Documentation(&Documentation), Attribute(&Attribute),
4306
        Heading(std::move(HeadingAndSpellings.first)),
4307
0
        SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
4308
};
4309
4310
static void WriteCategoryHeader(const Record *DocCategory,
4311
0
                                raw_ostream &OS) {
4312
0
  const StringRef Name = DocCategory->getValueAsString("Name");
4313
0
  OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
4314
4315
  // If there is content, print that as well.
4316
0
  const StringRef ContentStr = DocCategory->getValueAsString("Content");
4317
  // Trim leading and trailing newlines and spaces.
4318
0
  OS << ContentStr.trim();
4319
4320
0
  OS << "\n\n";
4321
0
}
4322
4323
static std::pair<std::string, SpellingList>
4324
GetAttributeHeadingAndSpellings(const Record &Documentation,
4325
0
                                const Record &Attribute) {
4326
  // FIXME: there is no way to have a per-spelling category for the attribute
4327
  // documentation. This may not be a limiting factor since the spellings
4328
  // should generally be consistently applied across the category.
4329
4330
0
  std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
4331
0
  if (Spellings.empty())
4332
0
    PrintFatalError(Attribute.getLoc(),
4333
0
                    "Attribute has no supported spellings; cannot be "
4334
0
                    "documented");
4335
4336
  // Determine the heading to be used for this attribute.
4337
0
  std::string Heading = std::string(Documentation.getValueAsString("Heading"));
4338
0
  if (Heading.empty()) {
4339
    // If there's only one spelling, we can simply use that.
4340
0
    if (Spellings.size() == 1)
4341
0
      Heading = Spellings.begin()->name();
4342
0
    else {
4343
0
      std::set<std::string> Uniques;
4344
0
      for (auto I = Spellings.begin(), E = Spellings.end();
4345
0
           I != E && Uniques.size() <= 1; ++I) {
4346
0
        std::string Spelling =
4347
0
            std::string(NormalizeNameForSpellingComparison(I->name()));
4348
0
        Uniques.insert(Spelling);
4349
0
      }
4350
      // If the semantic map has only one spelling, that is sufficient for our
4351
      // needs.
4352
0
      if (Uniques.size() == 1)
4353
0
        Heading = *Uniques.begin();
4354
0
    }
4355
0
  }
4356
4357
  // If the heading is still empty, it is an error.
4358
0
  if (Heading.empty())
4359
0
    PrintFatalError(Attribute.getLoc(),
4360
0
                    "This attribute requires a heading to be specified");
4361
4362
0
  SpellingList SupportedSpellings;
4363
0
  for (const auto &I : Spellings)
4364
0
    SupportedSpellings.add(Attribute, I);
4365
4366
0
  return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
4367
0
}
4368
4369
static void WriteDocumentation(RecordKeeper &Records,
4370
0
                               const DocumentationData &Doc, raw_ostream &OS) {
4371
0
  OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
4372
4373
  // List what spelling syntaxes the attribute supports.
4374
0
  OS << ".. csv-table:: Supported Syntaxes\n";
4375
0
  OS << "   :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
4376
0
  OS << " \"Keyword\", \"``#pragma``\", \"``#pragma clang attribute``\"\n\n";
4377
0
  OS << "   \"";
4378
0
  for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
4379
0
    SpellingKind K = (SpellingKind)Kind;
4380
    // TODO: List Microsoft (IDL-style attribute) spellings once we fully
4381
    // support them.
4382
0
    if (K == SpellingKind::Microsoft)
4383
0
      continue;
4384
4385
0
    bool PrintedAny = false;
4386
0
    for (StringRef Spelling : Doc.SupportedSpellings[K]) {
4387
0
      if (PrintedAny)
4388
0
        OS << " |br| ";
4389
0
      OS << "``" << Spelling << "``";
4390
0
      PrintedAny = true;
4391
0
    }
4392
4393
0
    OS << "\",\"";
4394
0
  }
4395
4396
0
  if (getPragmaAttributeSupport(Records).isAttributedSupported(
4397
0
          *Doc.Attribute))
4398
0
    OS << "Yes";
4399
0
  OS << "\"\n\n";
4400
4401
  // If the attribute is deprecated, print a message about it, and possibly
4402
  // provide a replacement attribute.
4403
0
  if (!Doc.Documentation->isValueUnset("Deprecated")) {
4404
0
    OS << "This attribute has been deprecated, and may be removed in a future "
4405
0
       << "version of Clang.";
4406
0
    const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
4407
0
    const StringRef Replacement = Deprecated.getValueAsString("Replacement");
4408
0
    if (!Replacement.empty())
4409
0
      OS << "  This attribute has been superseded by ``" << Replacement
4410
0
         << "``.";
4411
0
    OS << "\n\n";
4412
0
  }
4413
4414
0
  const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
4415
  // Trim leading and trailing newlines and spaces.
4416
0
  OS << ContentStr.trim();
4417
4418
0
  OS << "\n\n\n";
4419
0
}
4420
4421
0
void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
4422
  // Get the documentation introduction paragraph.
4423
0
  const Record *Documentation = Records.getDef("GlobalDocumentation");
4424
0
  if (!Documentation) {
4425
0
    PrintFatalError("The Documentation top-level definition is missing, "
4426
0
                    "no documentation will be generated.");
4427
0
    return;
4428
0
  }
4429
4430
0
  OS << Documentation->getValueAsString("Intro") << "\n";
4431
4432
  // Gather the Documentation lists from each of the attributes, based on the
4433
  // category provided.
4434
0
  std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4435
0
  std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
4436
0
  for (const auto *A : Attrs) {
4437
0
    const Record &Attr = *A;
4438
0
    std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
4439
0
    for (const auto *D : Docs) {
4440
0
      const Record &Doc = *D;
4441
0
      const Record *Category = Doc.getValueAsDef("Category");
4442
      // If the category is "undocumented", then there cannot be any other
4443
      // documentation categories (otherwise, the attribute would become
4444
      // documented).
4445
0
      const StringRef Cat = Category->getValueAsString("Name");
4446
0
      bool Undocumented = Cat == "Undocumented";
4447
0
      if (Undocumented && Docs.size() > 1)
4448
0
        PrintFatalError(Doc.getLoc(),
4449
0
                        "Attribute is \"Undocumented\", but has multiple "
4450
0
                        "documentation categories");
4451
4452
0
      if (!Undocumented)
4453
0
        SplitDocs[Category].push_back(DocumentationData(
4454
0
            Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr)));
4455
0
    }
4456
0
  }
4457
4458
  // Having split the attributes out based on what documentation goes where,
4459
  // we can begin to generate sections of documentation.
4460
0
  for (auto &I : SplitDocs) {
4461
0
    WriteCategoryHeader(I.first, OS);
4462
4463
0
    llvm::sort(I.second,
4464
0
               [](const DocumentationData &D1, const DocumentationData &D2) {
4465
0
                 return D1.Heading < D2.Heading;
4466
0
               });
4467
4468
    // Walk over each of the attributes in the category and write out their
4469
    // documentation.
4470
0
    for (const auto &Doc : I.second)
4471
0
      WriteDocumentation(Records, Doc, OS);
4472
0
  }
4473
0
}
4474
4475
void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
4476
1
                                                raw_ostream &OS) {
4477
1
  PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
4478
1
  ParsedAttrMap Attrs = getParsedAttrList(Records);
4479
1
  OS << "#pragma clang attribute supports the following attributes:\n";
4480
329
  for (const auto &I : Attrs) {
4481
329
    if (!Support.isAttributedSupported(*I.second))
4482
144
      continue;
4483
185
    OS << I.first;
4484
185
    if (I.second->isValueUnset("Subjects")) {
4485
1
      OS << " ()\n";
4486
1
      continue;
4487
1
    }
4488
184
    const Record *SubjectObj = I.second->getValueAsDef("Subjects");
4489
184
    std::vector<Record *> Subjects =
4490
184
        SubjectObj->getValueAsListOfDefs("Subjects");
4491
184
    OS << " (";
4492
184
    bool PrintComma = false;
4493
260
    for (const auto &Subject : llvm::enumerate(Subjects)) {
4494
260
      if (!isSupportedPragmaClangAttributeSubject(*Subject.value()))
4495
1
        continue;
4496
259
      if (PrintComma)
4497
75
        OS << ", ";
4498
259
      PrintComma = true;
4499