Coverage Report

Created: 2022-07-16 07:03

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