ClangDiagnosticsEmitter.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. //=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // These tablegen backends emit Clang diagnostics tables.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/DenseSet.h"
  14. #include "llvm/ADT/Optional.h"
  15. #include "llvm/ADT/PointerUnion.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringMap.h"
  21. #include "llvm/ADT/Twine.h"
  22. #include "llvm/Support/Compiler.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/TableGen/Error.h"
  25. #include "llvm/TableGen/Record.h"
  26. #include "llvm/TableGen/StringToOffsetTable.h"
  27. #include "llvm/TableGen/TableGenBackend.h"
  28. #include <algorithm>
  29. #include <cctype>
  30. #include <functional>
  31. #include <map>
  32. #include <set>
  33. using namespace llvm;
  34. //===----------------------------------------------------------------------===//
  35. // Diagnostic category computation code.
  36. //===----------------------------------------------------------------------===//
  37. namespace {
  38. class DiagGroupParentMap {
  39. RecordKeeper &Records;
  40. std::map<const Record*, std::vector<Record*> > Mapping;
  41. public:
  42. DiagGroupParentMap(RecordKeeper &records) : Records(records) {
  43. std::vector<Record*> DiagGroups
  44. = Records.getAllDerivedDefinitions("DiagGroup");
  45. for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
  46. std::vector<Record*> SubGroups =
  47. DiagGroups[i]->getValueAsListOfDefs("SubGroups");
  48. for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
  49. Mapping[SubGroups[j]].push_back(DiagGroups[i]);
  50. }
  51. }
  52. const std::vector<Record*> &getParents(const Record *Group) {
  53. return Mapping[Group];
  54. }
  55. };
  56. } // end anonymous namespace.
  57. static std::string
  58. getCategoryFromDiagGroup(const Record *Group,
  59. DiagGroupParentMap &DiagGroupParents) {
  60. // If the DiagGroup has a category, return it.
  61. std::string CatName = Group->getValueAsString("CategoryName");
  62. if (!CatName.empty()) return CatName;
  63. // The diag group may the subgroup of one or more other diagnostic groups,
  64. // check these for a category as well.
  65. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
  66. for (unsigned i = 0, e = Parents.size(); i != e; ++i) {
  67. CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents);
  68. if (!CatName.empty()) return CatName;
  69. }
  70. return "";
  71. }
  72. /// getDiagnosticCategory - Return the category that the specified diagnostic
  73. /// lives in.
  74. static std::string getDiagnosticCategory(const Record *R,
  75. DiagGroupParentMap &DiagGroupParents) {
  76. // If the diagnostic is in a group, and that group has a category, use it.
  77. if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group"))) {
  78. // Check the diagnostic's diag group for a category.
  79. std::string CatName = getCategoryFromDiagGroup(Group->getDef(),
  80. DiagGroupParents);
  81. if (!CatName.empty()) return CatName;
  82. }
  83. // If the diagnostic itself has a category, get it.
  84. return R->getValueAsString("CategoryName");
  85. }
  86. namespace {
  87. class DiagCategoryIDMap {
  88. RecordKeeper &Records;
  89. StringMap<unsigned> CategoryIDs;
  90. std::vector<std::string> CategoryStrings;
  91. public:
  92. DiagCategoryIDMap(RecordKeeper &records) : Records(records) {
  93. DiagGroupParentMap ParentInfo(Records);
  94. // The zero'th category is "".
  95. CategoryStrings.push_back("");
  96. CategoryIDs[""] = 0;
  97. std::vector<Record*> Diags =
  98. Records.getAllDerivedDefinitions("Diagnostic");
  99. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  100. std::string Category = getDiagnosticCategory(Diags[i], ParentInfo);
  101. if (Category.empty()) continue; // Skip diags with no category.
  102. unsigned &ID = CategoryIDs[Category];
  103. if (ID != 0) continue; // Already seen.
  104. ID = CategoryStrings.size();
  105. CategoryStrings.push_back(Category);
  106. }
  107. }
  108. unsigned getID(StringRef CategoryString) {
  109. return CategoryIDs[CategoryString];
  110. }
  111. typedef std::vector<std::string>::const_iterator const_iterator;
  112. const_iterator begin() const { return CategoryStrings.begin(); }
  113. const_iterator end() const { return CategoryStrings.end(); }
  114. };
  115. struct GroupInfo {
  116. std::vector<const Record*> DiagsInGroup;
  117. std::vector<std::string> SubGroups;
  118. unsigned IDNo;
  119. const Record *ExplicitDef;
  120. GroupInfo() : ExplicitDef(nullptr) {}
  121. };
  122. } // end anonymous namespace.
  123. static bool beforeThanCompare(const Record *LHS, const Record *RHS) {
  124. assert(!LHS->getLoc().empty() && !RHS->getLoc().empty());
  125. return
  126. LHS->getLoc().front().getPointer() < RHS->getLoc().front().getPointer();
  127. }
  128. static bool beforeThanCompareGroups(const GroupInfo *LHS, const GroupInfo *RHS){
  129. assert(!LHS->DiagsInGroup.empty() && !RHS->DiagsInGroup.empty());
  130. return beforeThanCompare(LHS->DiagsInGroup.front(),
  131. RHS->DiagsInGroup.front());
  132. }
  133. static SMRange findSuperClassRange(const Record *R, StringRef SuperName) {
  134. ArrayRef<Record *> Supers = R->getSuperClasses();
  135. for (size_t i = 0, e = Supers.size(); i < e; ++i)
  136. if (Supers[i]->getName() == SuperName)
  137. return R->getSuperClassRanges()[i];
  138. return SMRange();
  139. }
  140. /// \brief Invert the 1-[0/1] mapping of diags to group into a one to many
  141. /// mapping of groups to diags in the group.
  142. static void groupDiagnostics(const std::vector<Record*> &Diags,
  143. const std::vector<Record*> &DiagGroups,
  144. std::map<std::string, GroupInfo> &DiagsInGroup) {
  145. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  146. const Record *R = Diags[i];
  147. DefInit *DI = dyn_cast<DefInit>(R->getValueInit("Group"));
  148. if (!DI)
  149. continue;
  150. assert(R->getValueAsDef("Class")->getName() != "CLASS_NOTE" &&
  151. "Note can't be in a DiagGroup");
  152. std::string GroupName = DI->getDef()->getValueAsString("GroupName");
  153. DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
  154. }
  155. typedef SmallPtrSet<GroupInfo *, 16> GroupSetTy;
  156. GroupSetTy ImplicitGroups;
  157. // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
  158. // groups (these are warnings that GCC supports that clang never produces).
  159. for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
  160. Record *Group = DiagGroups[i];
  161. GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];
  162. if (Group->isAnonymous()) {
  163. if (GI.DiagsInGroup.size() > 1)
  164. ImplicitGroups.insert(&GI);
  165. } else {
  166. if (GI.ExplicitDef)
  167. assert(GI.ExplicitDef == Group);
  168. else
  169. GI.ExplicitDef = Group;
  170. }
  171. std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups");
  172. for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
  173. GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName"));
  174. }
  175. // Assign unique ID numbers to the groups.
  176. unsigned IDNo = 0;
  177. for (std::map<std::string, GroupInfo>::iterator
  178. I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo)
  179. I->second.IDNo = IDNo;
  180. // Sort the implicit groups, so we can warn about them deterministically.
  181. SmallVector<GroupInfo *, 16> SortedGroups(ImplicitGroups.begin(),
  182. ImplicitGroups.end());
  183. for (SmallVectorImpl<GroupInfo *>::iterator I = SortedGroups.begin(),
  184. E = SortedGroups.end();
  185. I != E; ++I) {
  186. MutableArrayRef<const Record *> GroupDiags = (*I)->DiagsInGroup;
  187. std::sort(GroupDiags.begin(), GroupDiags.end(), beforeThanCompare);
  188. }
  189. std::sort(SortedGroups.begin(), SortedGroups.end(), beforeThanCompareGroups);
  190. // Warn about the same group being used anonymously in multiple places.
  191. for (SmallVectorImpl<GroupInfo *>::const_iterator I = SortedGroups.begin(),
  192. E = SortedGroups.end();
  193. I != E; ++I) {
  194. ArrayRef<const Record *> GroupDiags = (*I)->DiagsInGroup;
  195. if ((*I)->ExplicitDef) {
  196. std::string Name = (*I)->ExplicitDef->getValueAsString("GroupName");
  197. for (ArrayRef<const Record *>::const_iterator DI = GroupDiags.begin(),
  198. DE = GroupDiags.end();
  199. DI != DE; ++DI) {
  200. const DefInit *GroupInit = cast<DefInit>((*DI)->getValueInit("Group"));
  201. const Record *NextDiagGroup = GroupInit->getDef();
  202. if (NextDiagGroup == (*I)->ExplicitDef)
  203. continue;
  204. SMRange InGroupRange = findSuperClassRange(*DI, "InGroup");
  205. SmallString<64> Replacement;
  206. if (InGroupRange.isValid()) {
  207. Replacement += "InGroup<";
  208. Replacement += (*I)->ExplicitDef->getName();
  209. Replacement += ">";
  210. }
  211. SMFixIt FixIt(InGroupRange, Replacement);
  212. SrcMgr.PrintMessage(NextDiagGroup->getLoc().front(),
  213. SourceMgr::DK_Error,
  214. Twine("group '") + Name +
  215. "' is referred to anonymously",
  216. None,
  217. InGroupRange.isValid() ? FixIt
  218. : ArrayRef<SMFixIt>());
  219. SrcMgr.PrintMessage((*I)->ExplicitDef->getLoc().front(),
  220. SourceMgr::DK_Note, "group defined here");
  221. }
  222. } else {
  223. // If there's no existing named group, we should just warn once and use
  224. // notes to list all the other cases.
  225. ArrayRef<const Record *>::const_iterator DI = GroupDiags.begin(),
  226. DE = GroupDiags.end();
  227. assert(DI != DE && "We only care about groups with multiple uses!");
  228. const DefInit *GroupInit = cast<DefInit>((*DI)->getValueInit("Group"));
  229. const Record *NextDiagGroup = GroupInit->getDef();
  230. std::string Name = NextDiagGroup->getValueAsString("GroupName");
  231. SMRange InGroupRange = findSuperClassRange(*DI, "InGroup");
  232. SrcMgr.PrintMessage(NextDiagGroup->getLoc().front(),
  233. SourceMgr::DK_Error,
  234. Twine("group '") + Name +
  235. "' is referred to anonymously",
  236. InGroupRange);
  237. for (++DI; DI != DE; ++DI) {
  238. GroupInit = cast<DefInit>((*DI)->getValueInit("Group"));
  239. InGroupRange = findSuperClassRange(*DI, "InGroup");
  240. SrcMgr.PrintMessage(GroupInit->getDef()->getLoc().front(),
  241. SourceMgr::DK_Note, "also referenced here",
  242. InGroupRange);
  243. }
  244. }
  245. }
  246. }
  247. //===----------------------------------------------------------------------===//
  248. // Infer members of -Wpedantic.
  249. //===----------------------------------------------------------------------===//
  250. typedef std::vector<const Record *> RecordVec;
  251. typedef llvm::DenseSet<const Record *> RecordSet;
  252. typedef llvm::PointerUnion<RecordVec*, RecordSet*> VecOrSet;
  253. namespace {
  254. class InferPedantic {
  255. typedef llvm::DenseMap<const Record*,
  256. std::pair<unsigned, Optional<unsigned> > > GMap;
  257. DiagGroupParentMap &DiagGroupParents;
  258. const std::vector<Record*> &Diags;
  259. const std::vector<Record*> DiagGroups;
  260. std::map<std::string, GroupInfo> &DiagsInGroup;
  261. llvm::DenseSet<const Record*> DiagsSet;
  262. GMap GroupCount;
  263. public:
  264. InferPedantic(DiagGroupParentMap &DiagGroupParents,
  265. const std::vector<Record*> &Diags,
  266. const std::vector<Record*> &DiagGroups,
  267. std::map<std::string, GroupInfo> &DiagsInGroup)
  268. : DiagGroupParents(DiagGroupParents),
  269. Diags(Diags),
  270. DiagGroups(DiagGroups),
  271. DiagsInGroup(DiagsInGroup) {}
  272. /// Compute the set of diagnostics and groups that are immediately
  273. /// in -Wpedantic.
  274. void compute(VecOrSet DiagsInPedantic,
  275. VecOrSet GroupsInPedantic);
  276. private:
  277. /// Determine whether a group is a subgroup of another group.
  278. bool isSubGroupOfGroup(const Record *Group,
  279. llvm::StringRef RootGroupName);
  280. /// Determine if the diagnostic is an extension.
  281. bool isExtension(const Record *Diag);
  282. /// Determine if the diagnostic is off by default.
  283. bool isOffByDefault(const Record *Diag);
  284. /// Increment the count for a group, and transitively marked
  285. /// parent groups when appropriate.
  286. void markGroup(const Record *Group);
  287. /// Return true if the diagnostic is in a pedantic group.
  288. bool groupInPedantic(const Record *Group, bool increment = false);
  289. };
  290. } // end anonymous namespace
  291. bool InferPedantic::isSubGroupOfGroup(const Record *Group,
  292. llvm::StringRef GName) {
  293. const std::string &GroupName = Group->getValueAsString("GroupName");
  294. if (GName == GroupName)
  295. return true;
  296. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
  297. for (unsigned i = 0, e = Parents.size(); i != e; ++i)
  298. if (isSubGroupOfGroup(Parents[i], GName))
  299. return true;
  300. return false;
  301. }
  302. /// Determine if the diagnostic is an extension.
  303. bool InferPedantic::isExtension(const Record *Diag) {
  304. const std::string &ClsName = Diag->getValueAsDef("Class")->getName();
  305. return ClsName == "CLASS_EXTENSION";
  306. }
  307. bool InferPedantic::isOffByDefault(const Record *Diag) {
  308. const std::string &DefSeverity =
  309. Diag->getValueAsDef("DefaultSeverity")->getValueAsString("Name");
  310. return DefSeverity == "Ignored";
  311. }
  312. bool InferPedantic::groupInPedantic(const Record *Group, bool increment) {
  313. GMap::mapped_type &V = GroupCount[Group];
  314. // Lazily compute the threshold value for the group count.
  315. if (!V.second.hasValue()) {
  316. const GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];
  317. V.second = GI.SubGroups.size() + GI.DiagsInGroup.size();
  318. }
  319. if (increment)
  320. ++V.first;
  321. // Consider a group in -Wpendatic IFF if has at least one diagnostic
  322. // or subgroup AND all of those diagnostics and subgroups are covered
  323. // by -Wpedantic via our computation.
  324. return V.first != 0 && V.first == V.second.getValue();
  325. }
  326. void InferPedantic::markGroup(const Record *Group) {
  327. // If all the diagnostics and subgroups have been marked as being
  328. // covered by -Wpedantic, increment the count of parent groups. Once the
  329. // group's count is equal to the number of subgroups and diagnostics in
  330. // that group, we can safely add this group to -Wpedantic.
  331. if (groupInPedantic(Group, /* increment */ true)) {
  332. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
  333. for (unsigned i = 0, e = Parents.size(); i != e; ++i)
  334. markGroup(Parents[i]);
  335. }
  336. }
  337. void InferPedantic::compute(VecOrSet DiagsInPedantic,
  338. VecOrSet GroupsInPedantic) {
  339. // All extensions that are not on by default are implicitly in the
  340. // "pedantic" group. For those that aren't explicitly included in -Wpedantic,
  341. // mark them for consideration to be included in -Wpedantic directly.
  342. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  343. Record *R = Diags[i];
  344. if (isExtension(R) && isOffByDefault(R)) {
  345. DiagsSet.insert(R);
  346. if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group"))) {
  347. const Record *GroupRec = Group->getDef();
  348. if (!isSubGroupOfGroup(GroupRec, "pedantic")) {
  349. markGroup(GroupRec);
  350. }
  351. }
  352. }
  353. }
  354. // Compute the set of diagnostics that are directly in -Wpedantic. We
  355. // march through Diags a second time to ensure the results are emitted
  356. // in deterministic order.
  357. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  358. Record *R = Diags[i];
  359. if (!DiagsSet.count(R))
  360. continue;
  361. // Check if the group is implicitly in -Wpedantic. If so,
  362. // the diagnostic should not be directly included in the -Wpedantic
  363. // diagnostic group.
  364. if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group")))
  365. if (groupInPedantic(Group->getDef()))
  366. continue;
  367. // The diagnostic is not included in a group that is (transitively) in
  368. // -Wpedantic. Include it in -Wpedantic directly.
  369. if (RecordVec *V = DiagsInPedantic.dyn_cast<RecordVec*>())
  370. V->push_back(R);
  371. else {
  372. DiagsInPedantic.get<RecordSet*>()->insert(R);
  373. }
  374. }
  375. if (!GroupsInPedantic)
  376. return;
  377. // Compute the set of groups that are directly in -Wpedantic. We
  378. // march through the groups to ensure the results are emitted
  379. /// in a deterministc order.
  380. for (unsigned i = 0, ei = DiagGroups.size(); i != ei; ++i) {
  381. Record *Group = DiagGroups[i];
  382. if (!groupInPedantic(Group))
  383. continue;
  384. unsigned ParentsInPedantic = 0;
  385. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
  386. for (unsigned j = 0, ej = Parents.size(); j != ej; ++j) {
  387. if (groupInPedantic(Parents[j]))
  388. ++ParentsInPedantic;
  389. }
  390. // If all the parents are in -Wpedantic, this means that this diagnostic
  391. // group will be indirectly included by -Wpedantic already. In that
  392. // case, do not add it directly to -Wpedantic. If the group has no
  393. // parents, obviously it should go into -Wpedantic.
  394. if (Parents.size() > 0 && ParentsInPedantic == Parents.size())
  395. continue;
  396. if (RecordVec *V = GroupsInPedantic.dyn_cast<RecordVec*>())
  397. V->push_back(Group);
  398. else {
  399. GroupsInPedantic.get<RecordSet*>()->insert(Group);
  400. }
  401. }
  402. }
  403. //===----------------------------------------------------------------------===//
  404. // Warning Tables (.inc file) generation.
  405. //===----------------------------------------------------------------------===//
  406. static bool isError(const Record &Diag) {
  407. const std::string &ClsName = Diag.getValueAsDef("Class")->getName();
  408. return ClsName == "CLASS_ERROR";
  409. }
  410. static bool isRemark(const Record &Diag) {
  411. const std::string &ClsName = Diag.getValueAsDef("Class")->getName();
  412. return ClsName == "CLASS_REMARK";
  413. }
  414. /// ClangDiagsDefsEmitter - The top-level class emits .def files containing
  415. /// declarations of Clang diagnostics.
  416. namespace clang {
  417. void EmitClangDiagsDefs(RecordKeeper &Records, raw_ostream &OS,
  418. const std::string &Component) {
  419. // Write the #if guard
  420. if (!Component.empty()) {
  421. std::string ComponentName = StringRef(Component).upper();
  422. OS << "#ifdef " << ComponentName << "START\n";
  423. OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName
  424. << ",\n";
  425. OS << "#undef " << ComponentName << "START\n";
  426. OS << "#endif\n\n";
  427. }
  428. const std::vector<Record*> &Diags =
  429. Records.getAllDerivedDefinitions("Diagnostic");
  430. std::vector<Record*> DiagGroups
  431. = Records.getAllDerivedDefinitions("DiagGroup");
  432. std::map<std::string, GroupInfo> DiagsInGroup;
  433. groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
  434. DiagCategoryIDMap CategoryIDs(Records);
  435. DiagGroupParentMap DGParentMap(Records);
  436. // Compute the set of diagnostics that are in -Wpedantic.
  437. RecordSet DiagsInPedantic;
  438. InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);
  439. inferPedantic.compute(&DiagsInPedantic, (RecordVec*)nullptr);
  440. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  441. const Record &R = *Diags[i];
  442. // Check if this is an error that is accidentally in a warning
  443. // group.
  444. if (isError(R)) {
  445. if (DefInit *Group = dyn_cast<DefInit>(R.getValueInit("Group"))) {
  446. const Record *GroupRec = Group->getDef();
  447. const std::string &GroupName = GroupRec->getValueAsString("GroupName");
  448. PrintFatalError(R.getLoc(), "Error " + R.getName() +
  449. " cannot be in a warning group [" + GroupName + "]");
  450. }
  451. }
  452. // Check that all remarks have an associated diagnostic group.
  453. if (isRemark(R)) {
  454. if (!isa<DefInit>(R.getValueInit("Group"))) {
  455. PrintFatalError(R.getLoc(), "Error " + R.getName() +
  456. " not in any diagnostic group");
  457. }
  458. }
  459. // Filter by component.
  460. if (!Component.empty() && Component != R.getValueAsString("Component"))
  461. continue;
  462. OS << "DIAG(" << R.getName() << ", ";
  463. OS << R.getValueAsDef("Class")->getName();
  464. OS << ", (unsigned)diag::Severity::"
  465. << R.getValueAsDef("DefaultSeverity")->getValueAsString("Name");
  466. // Description string.
  467. OS << ", \"";
  468. OS.write_escaped(R.getValueAsString("Text")) << '"';
  469. // Warning associated with the diagnostic. This is stored as an index into
  470. // the alphabetically sorted warning table.
  471. if (DefInit *DI = dyn_cast<DefInit>(R.getValueInit("Group"))) {
  472. std::map<std::string, GroupInfo>::iterator I =
  473. DiagsInGroup.find(DI->getDef()->getValueAsString("GroupName"));
  474. assert(I != DiagsInGroup.end());
  475. OS << ", " << I->second.IDNo;
  476. } else if (DiagsInPedantic.count(&R)) {
  477. std::map<std::string, GroupInfo>::iterator I =
  478. DiagsInGroup.find("pedantic");
  479. assert(I != DiagsInGroup.end() && "pedantic group not defined");
  480. OS << ", " << I->second.IDNo;
  481. } else {
  482. OS << ", 0";
  483. }
  484. // SFINAE response.
  485. OS << ", " << R.getValueAsDef("SFINAE")->getName();
  486. // Default warning has no Werror bit.
  487. if (R.getValueAsBit("WarningNoWerror"))
  488. OS << ", true";
  489. else
  490. OS << ", false";
  491. if (R.getValueAsBit("ShowInSystemHeader"))
  492. OS << ", true";
  493. else
  494. OS << ", false";
  495. // Category number.
  496. OS << ", " << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap));
  497. OS << ")\n";
  498. }
  499. }
  500. } // end namespace clang
  501. //===----------------------------------------------------------------------===//
  502. // Warning Group Tables generation
  503. //===----------------------------------------------------------------------===//
  504. static std::string getDiagCategoryEnum(llvm::StringRef name) {
  505. if (name.empty())
  506. return "DiagCat_None";
  507. SmallString<256> enumName = llvm::StringRef("DiagCat_");
  508. for (llvm::StringRef::iterator I = name.begin(), E = name.end(); I != E; ++I)
  509. enumName += isalnum(*I) ? *I : '_';
  510. return enumName.str();
  511. }
  512. /// \brief Emit the array of diagnostic subgroups.
  513. ///
  514. /// The array of diagnostic subgroups contains for each group a list of its
  515. /// subgroups. The individual lists are separated by '-1'. Groups with no
  516. /// subgroups are skipped.
  517. ///
  518. /// \code
  519. /// static const int16_t DiagSubGroups[] = {
  520. /// /* Empty */ -1,
  521. /// /* DiagSubGroup0 */ 142, -1,
  522. /// /* DiagSubGroup13 */ 265, 322, 399, -1
  523. /// }
  524. /// \endcode
  525. ///
  526. static void emitDiagSubGroups(std::map<std::string, GroupInfo> &DiagsInGroup,
  527. RecordVec &GroupsInPedantic, raw_ostream &OS) {
  528. OS << "static const int16_t DiagSubGroups[] = {\n"
  529. << " /* Empty */ -1,\n";
  530. for (auto const &I : DiagsInGroup) {
  531. const bool IsPedantic = I.first == "pedantic";
  532. const std::vector<std::string> &SubGroups = I.second.SubGroups;
  533. if (!SubGroups.empty() || (IsPedantic && !GroupsInPedantic.empty())) {
  534. OS << " /* DiagSubGroup" << I.second.IDNo << " */ ";
  535. for (auto const &SubGroup : SubGroups) {
  536. std::map<std::string, GroupInfo>::const_iterator RI =
  537. DiagsInGroup.find(SubGroup);
  538. assert(RI != DiagsInGroup.end() && "Referenced without existing?");
  539. OS << RI->second.IDNo << ", ";
  540. }
  541. // Emit the groups implicitly in "pedantic".
  542. if (IsPedantic) {
  543. for (auto const &Group : GroupsInPedantic) {
  544. const std::string &GroupName = Group->getValueAsString("GroupName");
  545. std::map<std::string, GroupInfo>::const_iterator RI =
  546. DiagsInGroup.find(GroupName);
  547. assert(RI != DiagsInGroup.end() && "Referenced without existing?");
  548. OS << RI->second.IDNo << ", ";
  549. }
  550. }
  551. OS << "-1,\n";
  552. }
  553. }
  554. OS << "};\n\n";
  555. }
  556. /// \brief Emit the list of diagnostic arrays.
  557. ///
  558. /// This data structure is a large array that contains itself arrays of varying
  559. /// size. Each array represents a list of diagnostics. The different arrays are
  560. /// separated by the value '-1'.
  561. ///
  562. /// \code
  563. /// static const int16_t DiagArrays[] = {
  564. /// /* Empty */ -1,
  565. /// /* DiagArray1 */ diag::warn_pragma_message,
  566. /// -1,
  567. /// /* DiagArray2 */ diag::warn_abs_too_small,
  568. /// diag::warn_unsigned_abs,
  569. /// diag::warn_wrong_absolute_value_type,
  570. /// -1
  571. /// };
  572. /// \endcode
  573. ///
  574. static void emitDiagArrays(std::map<std::string, GroupInfo> &DiagsInGroup,
  575. RecordVec &DiagsInPedantic, raw_ostream &OS) {
  576. OS << "static const int16_t DiagArrays[] = {\n"
  577. << " /* Empty */ -1,\n";
  578. for (auto const &I : DiagsInGroup) {
  579. const bool IsPedantic = I.first == "pedantic";
  580. const std::vector<const Record *> &V = I.second.DiagsInGroup;
  581. if (!V.empty() || (IsPedantic && !DiagsInPedantic.empty())) {
  582. OS << " /* DiagArray" << I.second.IDNo << " */ ";
  583. for (auto *Record : V)
  584. OS << "diag::" << Record->getName() << ", ";
  585. // Emit the diagnostics implicitly in "pedantic".
  586. if (IsPedantic) {
  587. for (auto const &Diag : DiagsInPedantic)
  588. OS << "diag::" << Diag->getName() << ", ";
  589. }
  590. OS << "-1,\n";
  591. }
  592. }
  593. OS << "};\n\n";
  594. }
  595. /// \brief Emit a list of group names.
  596. ///
  597. /// This creates a long string which by itself contains a list of pascal style
  598. /// strings, which consist of a length byte directly followed by the string.
  599. ///
  600. /// \code
  601. /// static const char DiagGroupNames[] = {
  602. /// \000\020#pragma-messages\t#warnings\020CFString-literal"
  603. /// };
  604. /// \endcode
  605. static void emitDiagGroupNames(StringToOffsetTable &GroupNames,
  606. raw_ostream &OS) {
  607. OS << "static const char DiagGroupNames[] = {\n";
  608. GroupNames.EmitString(OS);
  609. OS << "};\n\n";
  610. }
  611. /// \brief Emit diagnostic arrays and related data structures.
  612. ///
  613. /// This creates the actual diagnostic array, an array of diagnostic subgroups
  614. /// and an array of subgroup names.
  615. ///
  616. /// \code
  617. /// #ifdef GET_DIAG_ARRAYS
  618. /// static const int16_t DiagArrays[];
  619. /// static const int16_t DiagSubGroups[];
  620. /// static const char DiagGroupNames[];
  621. /// #endif
  622. /// \endcode
  623. static void emitAllDiagArrays(std::map<std::string, GroupInfo> &DiagsInGroup,
  624. RecordVec &DiagsInPedantic,
  625. RecordVec &GroupsInPedantic,
  626. StringToOffsetTable &GroupNames,
  627. raw_ostream &OS) {
  628. OS << "\n#ifdef GET_DIAG_ARRAYS\n";
  629. emitDiagArrays(DiagsInGroup, DiagsInPedantic, OS);
  630. emitDiagSubGroups(DiagsInGroup, GroupsInPedantic, OS);
  631. emitDiagGroupNames(GroupNames, OS);
  632. OS << "#endif // GET_DIAG_ARRAYS\n\n";
  633. }
  634. /// \brief Emit diagnostic table.
  635. ///
  636. /// The table is sorted by the name of the diagnostic group. Each element
  637. /// consists of the name of the diagnostic group (given as offset in the
  638. /// group name table), a reference to a list of diagnostics (optional) and a
  639. /// reference to a set of subgroups (optional).
  640. ///
  641. /// \code
  642. /// #ifdef GET_DIAG_TABLE
  643. /// {/* abi */ 159, /* DiagArray11 */ 19, /* Empty */ 0},
  644. /// {/* aggregate-return */ 180, /* Empty */ 0, /* Empty */ 0},
  645. /// {/* all */ 197, /* Empty */ 0, /* DiagSubGroup13 */ 3},
  646. /// {/* deprecated */ 1981,/* DiagArray1 */ 348, /* DiagSubGroup3 */ 9},
  647. /// #endif
  648. /// \endcode
  649. static void emitDiagTable(std::map<std::string, GroupInfo> &DiagsInGroup,
  650. RecordVec &DiagsInPedantic,
  651. RecordVec &GroupsInPedantic,
  652. StringToOffsetTable &GroupNames, raw_ostream &OS) {
  653. unsigned MaxLen = 0;
  654. for (auto const &I: DiagsInGroup)
  655. MaxLen = std::max(MaxLen, (unsigned)I.first.size());
  656. OS << "\n#ifdef GET_DIAG_TABLE\n";
  657. unsigned SubGroupIndex = 1, DiagArrayIndex = 1;
  658. for (auto const &I: DiagsInGroup) {
  659. // Group option string.
  660. OS << " { /* ";
  661. if (I.first.find_first_not_of("abcdefghijklmnopqrstuvwxyz"
  662. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  663. "0123456789!@#$%^*-+=:?") !=
  664. std::string::npos)
  665. PrintFatalError("Invalid character in diagnostic group '" + I.first +
  666. "'");
  667. OS << I.first << " */ " << std::string(MaxLen - I.first.size(), ' ');
  668. // Store a pascal-style length byte at the beginning of the string.
  669. std::string Name = char(I.first.size()) + I.first;
  670. OS << GroupNames.GetOrAddStringOffset(Name, false) << ", ";
  671. // Special handling for 'pedantic'.
  672. const bool IsPedantic = I.first == "pedantic";
  673. // Diagnostics in the group.
  674. const std::vector<const Record *> &V = I.second.DiagsInGroup;
  675. const bool hasDiags =
  676. !V.empty() || (IsPedantic && !DiagsInPedantic.empty());
  677. if (hasDiags) {
  678. OS << "/* DiagArray" << I.second.IDNo << " */ " << DiagArrayIndex
  679. << ", ";
  680. if (IsPedantic)
  681. DiagArrayIndex += DiagsInPedantic.size();
  682. DiagArrayIndex += V.size() + 1;
  683. } else {
  684. OS << "/* Empty */ 0, ";
  685. }
  686. // Subgroups.
  687. const std::vector<std::string> &SubGroups = I.second.SubGroups;
  688. const bool hasSubGroups =
  689. !SubGroups.empty() || (IsPedantic && !GroupsInPedantic.empty());
  690. if (hasSubGroups) {
  691. OS << "/* DiagSubGroup" << I.second.IDNo << " */ " << SubGroupIndex;
  692. if (IsPedantic)
  693. SubGroupIndex += GroupsInPedantic.size();
  694. SubGroupIndex += SubGroups.size() + 1;
  695. } else {
  696. OS << "/* Empty */ 0";
  697. }
  698. OS << " },\n";
  699. }
  700. OS << "#endif // GET_DIAG_TABLE\n\n";
  701. }
  702. /// \brief Emit the table of diagnostic categories.
  703. ///
  704. /// The table has the form of macro calls that have two parameters. The
  705. /// category's name as well as an enum that represents the category. The
  706. /// table can be used by defining the macro 'CATEGORY' and including this
  707. /// table right after.
  708. ///
  709. /// \code
  710. /// #ifdef GET_CATEGORY_TABLE
  711. /// CATEGORY("Semantic Issue", DiagCat_Semantic_Issue)
  712. /// CATEGORY("Lambda Issue", DiagCat_Lambda_Issue)
  713. /// #endif
  714. /// \endcode
  715. static void emitCategoryTable(RecordKeeper &Records, raw_ostream &OS) {
  716. DiagCategoryIDMap CategoriesByID(Records);
  717. OS << "\n#ifdef GET_CATEGORY_TABLE\n";
  718. for (auto const &C : CategoriesByID)
  719. OS << "CATEGORY(\"" << C << "\", " << getDiagCategoryEnum(C) << ")\n";
  720. OS << "#endif // GET_CATEGORY_TABLE\n\n";
  721. }
  722. namespace clang {
  723. void EmitClangDiagGroups(RecordKeeper &Records, raw_ostream &OS) {
  724. // Compute a mapping from a DiagGroup to all of its parents.
  725. DiagGroupParentMap DGParentMap(Records);
  726. std::vector<Record *> Diags = Records.getAllDerivedDefinitions("Diagnostic");
  727. std::vector<Record *> DiagGroups =
  728. Records.getAllDerivedDefinitions("DiagGroup");
  729. std::map<std::string, GroupInfo> DiagsInGroup;
  730. groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
  731. // All extensions are implicitly in the "pedantic" group. Record the
  732. // implicit set of groups in the "pedantic" group, and use this information
  733. // later when emitting the group information for Pedantic.
  734. RecordVec DiagsInPedantic;
  735. RecordVec GroupsInPedantic;
  736. InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);
  737. inferPedantic.compute(&DiagsInPedantic, &GroupsInPedantic);
  738. StringToOffsetTable GroupNames;
  739. for (std::map<std::string, GroupInfo>::const_iterator
  740. I = DiagsInGroup.begin(),
  741. E = DiagsInGroup.end();
  742. I != E; ++I) {
  743. // Store a pascal-style length byte at the beginning of the string.
  744. std::string Name = char(I->first.size()) + I->first;
  745. GroupNames.GetOrAddStringOffset(Name, false);
  746. }
  747. emitAllDiagArrays(DiagsInGroup, DiagsInPedantic, GroupsInPedantic, GroupNames,
  748. OS);
  749. emitDiagTable(DiagsInGroup, DiagsInPedantic, GroupsInPedantic, GroupNames,
  750. OS);
  751. emitCategoryTable(Records, OS);
  752. }
  753. } // end namespace clang
  754. //===----------------------------------------------------------------------===//
  755. // Diagnostic name index generation
  756. //===----------------------------------------------------------------------===//
  757. namespace {
  758. struct RecordIndexElement
  759. {
  760. RecordIndexElement() {}
  761. explicit RecordIndexElement(Record const &R):
  762. Name(R.getName()) {}
  763. std::string Name;
  764. };
  765. } // end anonymous namespace.
  766. namespace clang {
  767. void EmitClangDiagsIndexName(RecordKeeper &Records, raw_ostream &OS) {
  768. const std::vector<Record*> &Diags =
  769. Records.getAllDerivedDefinitions("Diagnostic");
  770. std::vector<RecordIndexElement> Index;
  771. Index.reserve(Diags.size());
  772. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  773. const Record &R = *(Diags[i]);
  774. Index.push_back(RecordIndexElement(R));
  775. }
  776. std::sort(Index.begin(), Index.end(),
  777. [](const RecordIndexElement &Lhs,
  778. const RecordIndexElement &Rhs) { return Lhs.Name < Rhs.Name; });
  779. for (unsigned i = 0, e = Index.size(); i != e; ++i) {
  780. const RecordIndexElement &R = Index[i];
  781. OS << "DIAG_NAME_INDEX(" << R.Name << ")\n";
  782. }
  783. }
  784. } // end namespace clang