Module.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. //===- Module.cpp - Describe a module -------------------------------------===//
  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. // This file defines the Module class, which describes a module in the source
  11. // code.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Basic/Module.h"
  15. #include "clang/Basic/CharInfo.h"
  16. #include "clang/Basic/FileManager.h"
  17. #include "clang/Basic/LangOptions.h"
  18. #include "clang/Basic/SourceLocation.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/StringMap.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/ADT/StringSwitch.h"
  25. #include "llvm/Support/Compiler.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <functional>
  31. #include <string>
  32. #include <utility>
  33. #include <vector>
  34. using namespace clang;
  35. Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
  36. bool IsFramework, bool IsExplicit, unsigned VisibilityID)
  37. : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent),
  38. VisibilityID(VisibilityID), IsMissingRequirement(false),
  39. HasIncompatibleModuleFile(false), IsAvailable(true),
  40. IsFromModuleFile(false), IsFramework(IsFramework), IsExplicit(IsExplicit),
  41. IsSystem(false), IsExternC(false), IsInferred(false),
  42. InferSubmodules(false), InferExplicitSubmodules(false),
  43. InferExportWildcard(false), ConfigMacrosExhaustive(false),
  44. NoUndeclaredIncludes(false), NameVisibility(Hidden) {
  45. if (Parent) {
  46. if (!Parent->isAvailable())
  47. IsAvailable = false;
  48. if (Parent->IsSystem)
  49. IsSystem = true;
  50. if (Parent->IsExternC)
  51. IsExternC = true;
  52. if (Parent->NoUndeclaredIncludes)
  53. NoUndeclaredIncludes = true;
  54. IsMissingRequirement = Parent->IsMissingRequirement;
  55. Parent->SubModuleIndex[Name] = Parent->SubModules.size();
  56. Parent->SubModules.push_back(this);
  57. }
  58. }
  59. Module::~Module() {
  60. for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
  61. I != IEnd; ++I) {
  62. delete *I;
  63. }
  64. }
  65. /// \brief Determine whether a translation unit built using the current
  66. /// language options has the given feature.
  67. static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
  68. const TargetInfo &Target) {
  69. bool HasFeature = llvm::StringSwitch<bool>(Feature)
  70. .Case("altivec", LangOpts.AltiVec)
  71. .Case("blocks", LangOpts.Blocks)
  72. .Case("coroutines", LangOpts.CoroutinesTS)
  73. .Case("cplusplus", LangOpts.CPlusPlus)
  74. .Case("cplusplus11", LangOpts.CPlusPlus11)
  75. .Case("freestanding", LangOpts.Freestanding)
  76. .Case("gnuinlineasm", LangOpts.GNUAsm)
  77. .Case("objc", LangOpts.ObjC1)
  78. .Case("objc_arc", LangOpts.ObjCAutoRefCount)
  79. .Case("opencl", LangOpts.OpenCL)
  80. .Case("tls", Target.isTLSSupported())
  81. .Case("zvector", LangOpts.ZVector)
  82. .Default(Target.hasFeature(Feature));
  83. if (!HasFeature)
  84. HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
  85. LangOpts.ModuleFeatures.end(),
  86. Feature) != LangOpts.ModuleFeatures.end();
  87. return HasFeature;
  88. }
  89. bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
  90. Requirement &Req,
  91. UnresolvedHeaderDirective &MissingHeader) const {
  92. if (IsAvailable)
  93. return true;
  94. for (const Module *Current = this; Current; Current = Current->Parent) {
  95. for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
  96. if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
  97. Current->Requirements[I].second) {
  98. Req = Current->Requirements[I];
  99. return false;
  100. }
  101. }
  102. if (!Current->MissingHeaders.empty()) {
  103. MissingHeader = Current->MissingHeaders.front();
  104. return false;
  105. }
  106. }
  107. llvm_unreachable("could not find a reason why module is unavailable");
  108. }
  109. bool Module::isSubModuleOf(const Module *Other) const {
  110. const Module *This = this;
  111. do {
  112. if (This == Other)
  113. return true;
  114. This = This->Parent;
  115. } while (This);
  116. return false;
  117. }
  118. const Module *Module::getTopLevelModule() const {
  119. const Module *Result = this;
  120. while (Result->Parent)
  121. Result = Result->Parent;
  122. return Result;
  123. }
  124. static StringRef getModuleNameFromComponent(
  125. const std::pair<std::string, SourceLocation> &IdComponent) {
  126. return IdComponent.first;
  127. }
  128. static StringRef getModuleNameFromComponent(StringRef R) { return R; }
  129. template<typename InputIter>
  130. static void printModuleId(raw_ostream &OS, InputIter Begin, InputIter End,
  131. bool AllowStringLiterals = true) {
  132. for (InputIter It = Begin; It != End; ++It) {
  133. if (It != Begin)
  134. OS << ".";
  135. StringRef Name = getModuleNameFromComponent(*It);
  136. if (!AllowStringLiterals || isValidIdentifier(Name))
  137. OS << Name;
  138. else {
  139. OS << '"';
  140. OS.write_escaped(Name);
  141. OS << '"';
  142. }
  143. }
  144. }
  145. template<typename Container>
  146. static void printModuleId(raw_ostream &OS, const Container &C) {
  147. return printModuleId(OS, C.begin(), C.end());
  148. }
  149. std::string Module::getFullModuleName(bool AllowStringLiterals) const {
  150. SmallVector<StringRef, 2> Names;
  151. // Build up the set of module names (from innermost to outermost).
  152. for (const Module *M = this; M; M = M->Parent)
  153. Names.push_back(M->Name);
  154. std::string Result;
  155. llvm::raw_string_ostream Out(Result);
  156. printModuleId(Out, Names.rbegin(), Names.rend(), AllowStringLiterals);
  157. Out.flush();
  158. return Result;
  159. }
  160. bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
  161. for (const Module *M = this; M; M = M->Parent) {
  162. if (nameParts.empty() || M->Name != nameParts.back())
  163. return false;
  164. nameParts = nameParts.drop_back();
  165. }
  166. return nameParts.empty();
  167. }
  168. Module::DirectoryName Module::getUmbrellaDir() const {
  169. if (Header U = getUmbrellaHeader())
  170. return {"", U.Entry->getDir()};
  171. return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
  172. }
  173. ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
  174. if (!TopHeaderNames.empty()) {
  175. for (std::vector<std::string>::iterator
  176. I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
  177. if (const FileEntry *FE = FileMgr.getFile(*I))
  178. TopHeaders.insert(FE);
  179. }
  180. TopHeaderNames.clear();
  181. }
  182. return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
  183. }
  184. bool Module::directlyUses(const Module *Requested) const {
  185. auto *Top = getTopLevelModule();
  186. // A top-level module implicitly uses itself.
  187. if (Requested->isSubModuleOf(Top))
  188. return true;
  189. for (auto *Use : Top->DirectUses)
  190. if (Requested->isSubModuleOf(Use))
  191. return true;
  192. // Anyone is allowed to use our builtin stddef.h and its accompanying module.
  193. if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t")
  194. return true;
  195. return false;
  196. }
  197. void Module::addRequirement(StringRef Feature, bool RequiredState,
  198. const LangOptions &LangOpts,
  199. const TargetInfo &Target) {
  200. Requirements.push_back(Requirement(Feature, RequiredState));
  201. // If this feature is currently available, we're done.
  202. if (hasFeature(Feature, LangOpts, Target) == RequiredState)
  203. return;
  204. markUnavailable(/*MissingRequirement*/true);
  205. }
  206. void Module::markUnavailable(bool MissingRequirement) {
  207. auto needUpdate = [MissingRequirement](Module *M) {
  208. return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
  209. };
  210. if (!needUpdate(this))
  211. return;
  212. SmallVector<Module *, 2> Stack;
  213. Stack.push_back(this);
  214. while (!Stack.empty()) {
  215. Module *Current = Stack.back();
  216. Stack.pop_back();
  217. if (!needUpdate(Current))
  218. continue;
  219. Current->IsAvailable = false;
  220. Current->IsMissingRequirement |= MissingRequirement;
  221. for (submodule_iterator Sub = Current->submodule_begin(),
  222. SubEnd = Current->submodule_end();
  223. Sub != SubEnd; ++Sub) {
  224. if (needUpdate(*Sub))
  225. Stack.push_back(*Sub);
  226. }
  227. }
  228. }
  229. Module *Module::findSubmodule(StringRef Name) const {
  230. llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
  231. if (Pos == SubModuleIndex.end())
  232. return nullptr;
  233. return SubModules[Pos->getValue()];
  234. }
  235. void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
  236. // All non-explicit submodules are exported.
  237. for (std::vector<Module *>::const_iterator I = SubModules.begin(),
  238. E = SubModules.end();
  239. I != E; ++I) {
  240. Module *Mod = *I;
  241. if (!Mod->IsExplicit)
  242. Exported.push_back(Mod);
  243. }
  244. // Find re-exported modules by filtering the list of imported modules.
  245. bool AnyWildcard = false;
  246. bool UnrestrictedWildcard = false;
  247. SmallVector<Module *, 4> WildcardRestrictions;
  248. for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
  249. Module *Mod = Exports[I].getPointer();
  250. if (!Exports[I].getInt()) {
  251. // Export a named module directly; no wildcards involved.
  252. Exported.push_back(Mod);
  253. continue;
  254. }
  255. // Wildcard export: export all of the imported modules that match
  256. // the given pattern.
  257. AnyWildcard = true;
  258. if (UnrestrictedWildcard)
  259. continue;
  260. if (Module *Restriction = Exports[I].getPointer())
  261. WildcardRestrictions.push_back(Restriction);
  262. else {
  263. WildcardRestrictions.clear();
  264. UnrestrictedWildcard = true;
  265. }
  266. }
  267. // If there were any wildcards, push any imported modules that were
  268. // re-exported by the wildcard restriction.
  269. if (!AnyWildcard)
  270. return;
  271. for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
  272. Module *Mod = Imports[I];
  273. bool Acceptable = UnrestrictedWildcard;
  274. if (!Acceptable) {
  275. // Check whether this module meets one of the restrictions.
  276. for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
  277. Module *Restriction = WildcardRestrictions[R];
  278. if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
  279. Acceptable = true;
  280. break;
  281. }
  282. }
  283. }
  284. if (!Acceptable)
  285. continue;
  286. Exported.push_back(Mod);
  287. }
  288. }
  289. void Module::buildVisibleModulesCache() const {
  290. assert(VisibleModulesCache.empty() && "cache does not need building");
  291. // This module is visible to itself.
  292. VisibleModulesCache.insert(this);
  293. // Every imported module is visible.
  294. SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
  295. while (!Stack.empty()) {
  296. Module *CurrModule = Stack.pop_back_val();
  297. // Every module transitively exported by an imported module is visible.
  298. if (VisibleModulesCache.insert(CurrModule).second)
  299. CurrModule->getExportedModules(Stack);
  300. }
  301. }
  302. void Module::print(raw_ostream &OS, unsigned Indent) const {
  303. OS.indent(Indent);
  304. if (IsFramework)
  305. OS << "framework ";
  306. if (IsExplicit)
  307. OS << "explicit ";
  308. OS << "module ";
  309. printModuleId(OS, &Name, &Name + 1);
  310. if (IsSystem || IsExternC) {
  311. OS.indent(Indent + 2);
  312. if (IsSystem)
  313. OS << " [system]";
  314. if (IsExternC)
  315. OS << " [extern_c]";
  316. }
  317. OS << " {\n";
  318. if (!Requirements.empty()) {
  319. OS.indent(Indent + 2);
  320. OS << "requires ";
  321. for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
  322. if (I)
  323. OS << ", ";
  324. if (!Requirements[I].second)
  325. OS << "!";
  326. OS << Requirements[I].first;
  327. }
  328. OS << "\n";
  329. }
  330. if (Header H = getUmbrellaHeader()) {
  331. OS.indent(Indent + 2);
  332. OS << "umbrella header \"";
  333. OS.write_escaped(H.NameAsWritten);
  334. OS << "\"\n";
  335. } else if (DirectoryName D = getUmbrellaDir()) {
  336. OS.indent(Indent + 2);
  337. OS << "umbrella \"";
  338. OS.write_escaped(D.NameAsWritten);
  339. OS << "\"\n";
  340. }
  341. if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
  342. OS.indent(Indent + 2);
  343. OS << "config_macros ";
  344. if (ConfigMacrosExhaustive)
  345. OS << "[exhaustive]";
  346. for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
  347. if (I)
  348. OS << ", ";
  349. OS << ConfigMacros[I];
  350. }
  351. OS << "\n";
  352. }
  353. struct {
  354. StringRef Prefix;
  355. HeaderKind Kind;
  356. } Kinds[] = {{"", HK_Normal},
  357. {"textual ", HK_Textual},
  358. {"private ", HK_Private},
  359. {"private textual ", HK_PrivateTextual},
  360. {"exclude ", HK_Excluded}};
  361. for (auto &K : Kinds) {
  362. assert(&K == &Kinds[K.Kind] && "kinds in wrong order");
  363. for (auto &H : Headers[K.Kind]) {
  364. OS.indent(Indent + 2);
  365. OS << K.Prefix << "header \"";
  366. OS.write_escaped(H.NameAsWritten);
  367. OS << "\" { size " << H.Entry->getSize()
  368. << " mtime " << H.Entry->getModificationTime() << " }\n";
  369. }
  370. }
  371. for (auto *Unresolved : {&UnresolvedHeaders, &MissingHeaders}) {
  372. for (auto &U : *Unresolved) {
  373. OS.indent(Indent + 2);
  374. OS << Kinds[U.Kind].Prefix << "header \"";
  375. OS.write_escaped(U.FileName);
  376. OS << "\"";
  377. if (U.Size || U.ModTime) {
  378. OS << " {";
  379. if (U.Size)
  380. OS << " size " << *U.Size;
  381. if (U.ModTime)
  382. OS << " mtime " << *U.ModTime;
  383. OS << " }";
  384. }
  385. OS << "\n";
  386. }
  387. }
  388. if (!ExportAsModule.empty()) {
  389. OS.indent(Indent + 2);
  390. OS << "export_as" << ExportAsModule << "\n";
  391. }
  392. for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
  393. MI != MIEnd; ++MI)
  394. // Print inferred subframework modules so that we don't need to re-infer
  395. // them (requires expensive directory iteration + stat calls) when we build
  396. // the module. Regular inferred submodules are OK, as we need to look at all
  397. // those header files anyway.
  398. if (!(*MI)->IsInferred || (*MI)->IsFramework)
  399. (*MI)->print(OS, Indent + 2);
  400. for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
  401. OS.indent(Indent + 2);
  402. OS << "export ";
  403. if (Module *Restriction = Exports[I].getPointer()) {
  404. OS << Restriction->getFullModuleName(true);
  405. if (Exports[I].getInt())
  406. OS << ".*";
  407. } else {
  408. OS << "*";
  409. }
  410. OS << "\n";
  411. }
  412. for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
  413. OS.indent(Indent + 2);
  414. OS << "export ";
  415. printModuleId(OS, UnresolvedExports[I].Id);
  416. if (UnresolvedExports[I].Wildcard)
  417. OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
  418. OS << "\n";
  419. }
  420. for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
  421. OS.indent(Indent + 2);
  422. OS << "use ";
  423. OS << DirectUses[I]->getFullModuleName(true);
  424. OS << "\n";
  425. }
  426. for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
  427. OS.indent(Indent + 2);
  428. OS << "use ";
  429. printModuleId(OS, UnresolvedDirectUses[I]);
  430. OS << "\n";
  431. }
  432. for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
  433. OS.indent(Indent + 2);
  434. OS << "link ";
  435. if (LinkLibraries[I].IsFramework)
  436. OS << "framework ";
  437. OS << "\"";
  438. OS.write_escaped(LinkLibraries[I].Library);
  439. OS << "\"";
  440. }
  441. for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
  442. OS.indent(Indent + 2);
  443. OS << "conflict ";
  444. printModuleId(OS, UnresolvedConflicts[I].Id);
  445. OS << ", \"";
  446. OS.write_escaped(UnresolvedConflicts[I].Message);
  447. OS << "\"\n";
  448. }
  449. for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
  450. OS.indent(Indent + 2);
  451. OS << "conflict ";
  452. OS << Conflicts[I].Other->getFullModuleName(true);
  453. OS << ", \"";
  454. OS.write_escaped(Conflicts[I].Message);
  455. OS << "\"\n";
  456. }
  457. if (InferSubmodules) {
  458. OS.indent(Indent + 2);
  459. if (InferExplicitSubmodules)
  460. OS << "explicit ";
  461. OS << "module * {\n";
  462. if (InferExportWildcard) {
  463. OS.indent(Indent + 4);
  464. OS << "export *\n";
  465. }
  466. OS.indent(Indent + 2);
  467. OS << "}\n";
  468. }
  469. OS.indent(Indent);
  470. OS << "}\n";
  471. }
  472. LLVM_DUMP_METHOD void Module::dump() const {
  473. print(llvm::errs());
  474. }
  475. void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
  476. VisibleCallback Vis, ConflictCallback Cb) {
  477. assert(Loc.isValid() && "setVisible expects a valid import location");
  478. if (isVisible(M))
  479. return;
  480. ++Generation;
  481. struct Visiting {
  482. Module *M;
  483. Visiting *ExportedBy;
  484. };
  485. std::function<void(Visiting)> VisitModule = [&](Visiting V) {
  486. // Modules that aren't available cannot be made visible.
  487. if (!V.M->isAvailable())
  488. return;
  489. // Nothing to do for a module that's already visible.
  490. unsigned ID = V.M->getVisibilityID();
  491. if (ImportLocs.size() <= ID)
  492. ImportLocs.resize(ID + 1);
  493. else if (ImportLocs[ID].isValid())
  494. return;
  495. ImportLocs[ID] = Loc;
  496. Vis(M);
  497. // Make any exported modules visible.
  498. SmallVector<Module *, 16> Exports;
  499. V.M->getExportedModules(Exports);
  500. for (Module *E : Exports)
  501. VisitModule({E, &V});
  502. for (auto &C : V.M->Conflicts) {
  503. if (isVisible(C.Other)) {
  504. llvm::SmallVector<Module*, 8> Path;
  505. for (Visiting *I = &V; I; I = I->ExportedBy)
  506. Path.push_back(I->M);
  507. Cb(Path, C.Other, C.Message);
  508. }
  509. }
  510. };
  511. VisitModule({M, nullptr});
  512. }