Module.cpp 15 KB

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