cmNinjaTargetGenerator.cxx 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmNinjaTargetGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <iterator>
  7. #include <map>
  8. #include <ostream>
  9. #include <unordered_map>
  10. #include <unordered_set>
  11. #include <utility>
  12. #include <cm/memory>
  13. #include <cmext/algorithm>
  14. #include "cm_jsoncpp_value.h"
  15. #include "cm_jsoncpp_writer.h"
  16. #include "cmComputeLinkInformation.h"
  17. #include "cmCustomCommandGenerator.h"
  18. #include "cmGeneratedFileStream.h"
  19. #include "cmGeneratorExpression.h"
  20. #include "cmGeneratorTarget.h"
  21. #include "cmGlobalNinjaGenerator.h"
  22. #include "cmLocalGenerator.h"
  23. #include "cmLocalNinjaGenerator.h"
  24. #include "cmMakefile.h"
  25. #include "cmNinjaNormalTargetGenerator.h"
  26. #include "cmNinjaUtilityTargetGenerator.h"
  27. #include "cmOutputConverter.h"
  28. #include "cmRange.h"
  29. #include "cmRulePlaceholderExpander.h"
  30. #include "cmSourceFile.h"
  31. #include "cmState.h"
  32. #include "cmStateTypes.h"
  33. #include "cmStringAlgorithms.h"
  34. #include "cmSystemTools.h"
  35. #include "cmake.h"
  36. std::unique_ptr<cmNinjaTargetGenerator> cmNinjaTargetGenerator::New(
  37. cmGeneratorTarget* target)
  38. {
  39. switch (target->GetType()) {
  40. case cmStateEnums::EXECUTABLE:
  41. case cmStateEnums::SHARED_LIBRARY:
  42. case cmStateEnums::STATIC_LIBRARY:
  43. case cmStateEnums::MODULE_LIBRARY:
  44. case cmStateEnums::OBJECT_LIBRARY:
  45. return cm::make_unique<cmNinjaNormalTargetGenerator>(target);
  46. case cmStateEnums::UTILITY:
  47. case cmStateEnums::GLOBAL_TARGET:
  48. return cm::make_unique<cmNinjaUtilityTargetGenerator>(target);
  49. default:
  50. return std::unique_ptr<cmNinjaTargetGenerator>();
  51. }
  52. }
  53. cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
  54. : cmCommonTargetGenerator(target)
  55. , OSXBundleGenerator(nullptr)
  56. , LocalGenerator(
  57. static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
  58. {
  59. for (auto const& fileConfig : target->Makefile->GetGeneratorConfigs()) {
  60. this->Configs[fileConfig].MacOSXContentGenerator =
  61. cm::make_unique<MacOSXContentGeneratorType>(this, fileConfig);
  62. }
  63. }
  64. cmNinjaTargetGenerator::~cmNinjaTargetGenerator() = default;
  65. cmGeneratedFileStream& cmNinjaTargetGenerator::GetImplFileStream(
  66. const std::string& config) const
  67. {
  68. return *this->GetGlobalGenerator()->GetImplFileStream(config);
  69. }
  70. cmGeneratedFileStream& cmNinjaTargetGenerator::GetCommonFileStream() const
  71. {
  72. return *this->GetGlobalGenerator()->GetCommonFileStream();
  73. }
  74. cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
  75. {
  76. return *this->GetGlobalGenerator()->GetRulesFileStream();
  77. }
  78. cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
  79. {
  80. return this->LocalGenerator->GetGlobalNinjaGenerator();
  81. }
  82. std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  83. const std::string& lang, const std::string& config) const
  84. {
  85. return cmStrCat(
  86. lang, "_COMPILER__",
  87. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  88. '_', config);
  89. }
  90. std::string cmNinjaTargetGenerator::LanguagePreprocessRule(
  91. std::string const& lang, const std::string& config) const
  92. {
  93. return cmStrCat(
  94. lang, "_PREPROCESS__",
  95. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  96. '_', config);
  97. }
  98. bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
  99. std::string const& lang) const
  100. {
  101. return lang == "Fortran";
  102. }
  103. bool cmNinjaTargetGenerator::UsePreprocessedSource(
  104. std::string const& lang) const
  105. {
  106. return lang == "Fortran";
  107. }
  108. bool cmNinjaTargetGenerator::CompilePreprocessedSourceWithDefines(
  109. std::string const& lang) const
  110. {
  111. return this->Makefile->IsOn(
  112. cmStrCat("CMAKE_", lang, "_COMPILE_WITH_DEFINES"));
  113. }
  114. std::string cmNinjaTargetGenerator::LanguageDyndepRule(
  115. const std::string& lang, const std::string& config) const
  116. {
  117. return cmStrCat(
  118. lang, "_DYNDEP__",
  119. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  120. '_', config);
  121. }
  122. bool cmNinjaTargetGenerator::NeedDyndep(std::string const& lang) const
  123. {
  124. return lang == "Fortran";
  125. }
  126. std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget(
  127. const std::string& config)
  128. {
  129. return this->GetGlobalGenerator()->OrderDependsTargetForTarget(
  130. this->GeneratorTarget, config);
  131. }
  132. // TODO: Most of the code is picked up from
  133. // void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink),
  134. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  135. // Refactor it.
  136. std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
  137. cmSourceFile const* source, const std::string& language,
  138. const std::string& config)
  139. {
  140. std::vector<std::string> architectures;
  141. std::unordered_map<std::string, std::string> pchSources;
  142. this->GeneratorTarget->GetAppleArchs(config, architectures);
  143. if (architectures.empty()) {
  144. architectures.emplace_back();
  145. }
  146. std::string filterArch;
  147. for (const std::string& arch : architectures) {
  148. const std::string pchSource =
  149. this->GeneratorTarget->GetPchSource(config, language, arch);
  150. if (pchSource == source->GetFullPath()) {
  151. filterArch = arch;
  152. }
  153. if (!pchSource.empty()) {
  154. pchSources.insert(std::make_pair(pchSource, arch));
  155. }
  156. }
  157. std::string flags = this->GetFlags(language, config, filterArch);
  158. // Add Fortran format flags.
  159. if (language == "Fortran") {
  160. this->AppendFortranFormatFlags(flags, *source);
  161. this->AppendFortranPreprocessFlags(flags, *source);
  162. }
  163. // Add source file specific flags.
  164. cmGeneratorExpressionInterpreter genexInterpreter(
  165. this->LocalGenerator, config, this->GeneratorTarget, language);
  166. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  167. if (cmProp cflags = source->GetProperty(COMPILE_FLAGS)) {
  168. this->LocalGenerator->AppendFlags(
  169. flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  170. }
  171. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  172. if (cmProp coptions = source->GetProperty(COMPILE_OPTIONS)) {
  173. this->LocalGenerator->AppendCompileOptions(
  174. flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  175. }
  176. // Add precompile headers compile options.
  177. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  178. std::string pchOptions;
  179. auto pchIt = pchSources.find(source->GetFullPath());
  180. if (pchIt != pchSources.end()) {
  181. pchOptions = this->GeneratorTarget->GetPchCreateCompileOptions(
  182. config, language, pchIt->second);
  183. } else {
  184. pchOptions =
  185. this->GeneratorTarget->GetPchUseCompileOptions(config, language);
  186. }
  187. this->LocalGenerator->AppendCompileOptions(
  188. flags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  189. }
  190. return flags;
  191. }
  192. void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
  193. std::string const& language,
  194. const std::string& config)
  195. {
  196. std::vector<std::string> includes;
  197. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  198. language, config);
  199. // Add include directory flags.
  200. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  201. includes, this->GeneratorTarget, language,
  202. language == "RC", // full include paths for RC needed by cmcldeps
  203. false, config);
  204. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  205. std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
  206. }
  207. this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
  208. }
  209. bool cmNinjaTargetGenerator::NeedDepTypeMSVC(const std::string& lang) const
  210. {
  211. std::string const& deptype = this->GetMakefile()->GetSafeDefinition(
  212. cmStrCat("CMAKE_NINJA_DEPTYPE_", lang));
  213. if (deptype == "msvc") {
  214. return true;
  215. }
  216. if (deptype == "intel") {
  217. // Ninja does not really define "intel", but we use it to switch based
  218. // on whether this environment supports "gcc" or "msvc" deptype.
  219. if (!this->GetGlobalGenerator()->SupportsMultilineDepfile()) {
  220. // This ninja version is too old to support the Intel depfile format.
  221. // Fall back to msvc deptype.
  222. return true;
  223. }
  224. if ((this->Makefile->GetHomeDirectory().find(' ') != std::string::npos) ||
  225. (this->Makefile->GetHomeOutputDirectory().find(' ') !=
  226. std::string::npos)) {
  227. // The Intel compiler does not properly escape spaces in a depfile.
  228. // Fall back to msvc deptype.
  229. return true;
  230. }
  231. }
  232. return false;
  233. }
  234. // TODO: Refactor with
  235. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  236. std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
  237. const std::string& language,
  238. const std::string& config)
  239. {
  240. std::set<std::string> defines;
  241. cmGeneratorExpressionInterpreter genexInterpreter(
  242. this->LocalGenerator, config, this->GeneratorTarget, language);
  243. // Seriously??
  244. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  245. defines.insert(cmStrCat("CMAKE_INTDIR=\"", config, '"'));
  246. }
  247. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  248. if (cmProp compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  249. this->LocalGenerator->AppendDefines(
  250. defines, genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS));
  251. }
  252. std::string defPropName =
  253. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
  254. if (cmProp config_compile_defs = source->GetProperty(defPropName)) {
  255. this->LocalGenerator->AppendDefines(
  256. defines,
  257. genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS));
  258. }
  259. std::string definesString = this->GetDefines(language, config);
  260. this->LocalGenerator->JoinDefines(defines, definesString, language);
  261. return definesString;
  262. }
  263. std::string cmNinjaTargetGenerator::ComputeIncludes(
  264. cmSourceFile const* source, const std::string& language,
  265. const std::string& config)
  266. {
  267. std::vector<std::string> includes;
  268. cmGeneratorExpressionInterpreter genexInterpreter(
  269. this->LocalGenerator, config, this->GeneratorTarget, language);
  270. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  271. if (cmProp cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  272. this->LocalGenerator->AppendIncludeDirectories(
  273. includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
  274. *source);
  275. }
  276. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  277. includes, this->GeneratorTarget, language, true, false, config);
  278. this->LocalGenerator->AppendFlags(includesString,
  279. this->GetIncludes(language, config));
  280. return includesString;
  281. }
  282. cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps(
  283. const std::string& linkLanguage, const std::string& config) const
  284. {
  285. // Static libraries never depend on other targets for linking.
  286. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  287. this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  288. return cmNinjaDeps();
  289. }
  290. cmComputeLinkInformation* cli =
  291. this->GeneratorTarget->GetLinkInformation(config);
  292. if (!cli) {
  293. return cmNinjaDeps();
  294. }
  295. const std::vector<std::string>& deps = cli->GetDepends();
  296. cmNinjaDeps result(deps.size());
  297. std::transform(deps.begin(), deps.end(), result.begin(), MapToNinjaPath());
  298. // Add a dependency on the link definitions file, if any.
  299. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  300. this->GeneratorTarget->GetModuleDefinitionInfo(config)) {
  301. for (cmSourceFile const* src : mdi->Sources) {
  302. result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
  303. }
  304. }
  305. // Add a dependency on user-specified manifest files, if any.
  306. std::vector<cmSourceFile const*> manifest_srcs;
  307. this->GeneratorTarget->GetManifests(manifest_srcs, config);
  308. for (cmSourceFile const* manifest_src : manifest_srcs) {
  309. result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
  310. }
  311. // Add user-specified dependencies.
  312. std::vector<std::string> linkDeps;
  313. this->GeneratorTarget->GetLinkDepends(linkDeps, config, linkLanguage);
  314. std::transform(linkDeps.begin(), linkDeps.end(), std::back_inserter(result),
  315. MapToNinjaPath());
  316. return result;
  317. }
  318. std::string cmNinjaTargetGenerator::GetSourceFilePath(
  319. cmSourceFile const* source) const
  320. {
  321. return ConvertToNinjaPath(source->GetFullPath());
  322. }
  323. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  324. cmSourceFile const* source, const std::string& config) const
  325. {
  326. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  327. if (!path.empty()) {
  328. path += '/';
  329. }
  330. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  331. path += cmStrCat(
  332. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  333. this->GetGlobalGenerator()->ConfigDirectory(config), '/', objectName);
  334. return path;
  335. }
  336. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  337. cmSourceFile const* source, const std::string& config) const
  338. {
  339. // Choose an extension to compile already-preprocessed source.
  340. std::string ppExt = source->GetExtension();
  341. if (cmHasLiteralPrefix(ppExt, "F")) {
  342. // Some Fortran compilers automatically enable preprocessing for
  343. // upper-case extensions. Since the source is already preprocessed,
  344. // use a lower-case extension.
  345. ppExt = cmSystemTools::LowerCase(ppExt);
  346. }
  347. if (ppExt == "fpp") {
  348. // Some Fortran compilers automatically enable preprocessing for
  349. // the ".fpp" extension. Since the source is already preprocessed,
  350. // use the ".f" extension.
  351. ppExt = "f";
  352. }
  353. // Take the object file name and replace the extension.
  354. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  355. std::string const& objExt =
  356. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  357. assert(objName.size() >= objExt.size());
  358. std::string const ppName =
  359. cmStrCat(objName.substr(0, objName.size() - objExt.size()), "-pp.", ppExt);
  360. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  361. if (!path.empty()) {
  362. path += '/';
  363. }
  364. path +=
  365. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  366. this->GetGlobalGenerator()->ConfigDirectory(config), '/', ppName);
  367. return path;
  368. }
  369. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  370. std::string const& lang, const std::string& config) const
  371. {
  372. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  373. if (!path.empty()) {
  374. path += '/';
  375. }
  376. path += cmStrCat(
  377. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  378. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang, ".dd");
  379. return path;
  380. }
  381. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  382. std::string const& lang, const std::string& config) const
  383. {
  384. std::string path =
  385. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  386. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  387. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang,
  388. "DependInfo.json");
  389. return path;
  390. }
  391. std::string cmNinjaTargetGenerator::GetTargetOutputDir(
  392. const std::string& config) const
  393. {
  394. std::string dir = this->GeneratorTarget->GetDirectory(config);
  395. return ConvertToNinjaPath(dir);
  396. }
  397. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  398. const std::string& name, const std::string& config) const
  399. {
  400. std::string path = this->GetTargetOutputDir(config);
  401. if (path.empty() || path == ".") {
  402. return name;
  403. }
  404. path += cmStrCat('/', name);
  405. return path;
  406. }
  407. std::string cmNinjaTargetGenerator::GetTargetName() const
  408. {
  409. return this->GeneratorTarget->GetName();
  410. }
  411. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(
  412. cmNinjaVars& vars, const std::string& config) const
  413. {
  414. cmMakefile* mf = this->GetMakefile();
  415. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  416. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  417. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  418. std::string pdbPath;
  419. std::string compilePdbPath = this->ComputeTargetCompilePDB(config);
  420. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  421. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  422. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  423. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  424. pdbPath = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config), '/',
  425. this->GeneratorTarget->GetPDBName(config));
  426. }
  427. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  428. ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  429. vars["TARGET_COMPILE_PDB"] =
  430. this->GetLocalGenerator()->ConvertToOutputFormat(
  431. ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  432. EnsureParentDirectoryExists(pdbPath);
  433. EnsureParentDirectoryExists(compilePdbPath);
  434. return true;
  435. }
  436. return false;
  437. }
  438. void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language,
  439. const std::string& config)
  440. {
  441. #ifdef NINJA_GEN_VERBOSE_FILES
  442. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  443. #endif
  444. this->WriteCompileRule(language, config);
  445. }
  446. namespace {
  447. // Create the command to run the dependency scanner
  448. std::string GetScanCommand(const std::string& cmakeCmd, const std::string& tdi,
  449. const std::string& lang, const std::string& ppFile,
  450. bool needDyndep, const std::string& ddiFile)
  451. {
  452. std::string ccmd =
  453. cmStrCat(cmakeCmd, " -E cmake_ninja_depends --tdi=", tdi, " --lang=", lang,
  454. " --pp=", ppFile, " --dep=$DEP_FILE");
  455. if (needDyndep) {
  456. ccmd = cmStrCat(ccmd, " --obj=$OBJ_FILE --ddi=", ddiFile);
  457. }
  458. return ccmd;
  459. }
  460. // Helper function to create dependency scanning rule, with optional
  461. // explicit preprocessing step if preprocessCommand is non-empty
  462. cmNinjaRule GetPreprocessScanRule(
  463. const std::string& ruleName, cmRulePlaceholderExpander::RuleVariables& vars,
  464. const std::string& responseFlag, const std::string& flags,
  465. const std::string& launcher,
  466. cmRulePlaceholderExpander* const rulePlaceholderExpander,
  467. std::string scanCommand, cmLocalNinjaGenerator* generator,
  468. const std::string& preprocessCommand = "")
  469. {
  470. cmNinjaRule rule(ruleName);
  471. // Explicit preprocessing always uses a depfile.
  472. rule.DepType = ""; // no deps= for multiple outputs
  473. rule.DepFile = "$DEP_FILE";
  474. cmRulePlaceholderExpander::RuleVariables ppVars;
  475. ppVars.CMTargetName = vars.CMTargetName;
  476. ppVars.CMTargetType = vars.CMTargetType;
  477. ppVars.Language = vars.Language;
  478. ppVars.Object = "$out"; // for RULE_LAUNCH_COMPILE
  479. ppVars.PreprocessedSource = "$out";
  480. ppVars.DependencyFile = rule.DepFile.c_str();
  481. // Preprocessing uses the original source, compilation uses
  482. // preprocessed output or original source
  483. ppVars.Source = vars.Source;
  484. vars.Source = "$in";
  485. // Copy preprocessor definitions to the preprocessor rule.
  486. ppVars.Defines = vars.Defines;
  487. // Copy include directories to the preprocessor rule. The Fortran
  488. // compilation rule still needs them for the INCLUDE directive.
  489. ppVars.Includes = vars.Includes;
  490. // Preprocessing and compilation use the same flags.
  491. std::string ppFlags = flags;
  492. // If using a response file, move defines, includes, and flags into it.
  493. if (!responseFlag.empty()) {
  494. rule.RspFile = "$RSP_FILE";
  495. rule.RspContent =
  496. cmStrCat(' ', ppVars.Defines, ' ', ppVars.Includes, ' ', ppFlags);
  497. ppFlags = cmStrCat(responseFlag, rule.RspFile);
  498. ppVars.Defines = "";
  499. ppVars.Includes = "";
  500. }
  501. ppVars.Flags = ppFlags.c_str();
  502. // Rule for preprocessing source file.
  503. std::vector<std::string> ppCmds;
  504. if (!preprocessCommand.empty()) {
  505. // Lookup the explicit preprocessing rule.
  506. cmExpandList(preprocessCommand, ppCmds);
  507. for (std::string& i : ppCmds) {
  508. i = cmStrCat(launcher, i);
  509. rulePlaceholderExpander->ExpandRuleVariables(generator, i, ppVars);
  510. }
  511. }
  512. // Run CMake dependency scanner on either preprocessed output or source file
  513. ppCmds.emplace_back(std::move(scanCommand));
  514. rule.Command = generator->BuildCommandLine(ppCmds);
  515. return rule;
  516. }
  517. }
  518. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  519. const std::string& config)
  520. {
  521. cmRulePlaceholderExpander::RuleVariables vars;
  522. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  523. vars.CMTargetType =
  524. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  525. vars.Language = lang.c_str();
  526. vars.Source = "$in";
  527. vars.Object = "$out";
  528. vars.Defines = "$DEFINES";
  529. vars.Includes = "$INCLUDES";
  530. vars.TargetPDB = "$TARGET_PDB";
  531. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  532. vars.ObjectDir = "$OBJECT_DIR";
  533. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  534. cmMakefile* mf = this->GetMakefile();
  535. // For some cases we do an explicit preprocessor invocation.
  536. bool const explicitPP = this->NeedExplicitPreprocessing(lang);
  537. bool const compilePPWithDefines = this->UsePreprocessedSource(lang) &&
  538. this->CompilePreprocessedSourceWithDefines(lang);
  539. bool const needDyndep = this->NeedDyndep(lang);
  540. std::string flags = "$FLAGS";
  541. std::string responseFlag;
  542. bool const lang_supports_response = lang != "RC";
  543. if (lang_supports_response && this->ForceResponseFile()) {
  544. std::string const responseFlagVar =
  545. cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_FLAG");
  546. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  547. if (responseFlag.empty() && lang != "CUDA") {
  548. responseFlag = "@";
  549. }
  550. }
  551. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  552. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  553. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  554. ConvertToNinjaPath(this->GetTargetDependInfoPath(lang, config)),
  555. cmLocalGenerator::SHELL);
  556. std::string launcher;
  557. const char* val = this->GetLocalGenerator()->GetRuleLauncher(
  558. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE");
  559. if (val && *val) {
  560. launcher = cmStrCat(val, ' ');
  561. }
  562. std::string const cmakeCmd =
  563. this->GetLocalGenerator()->ConvertToOutputFormat(
  564. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  565. if (explicitPP) {
  566. // Combined preprocessing and dependency scanning
  567. const auto ppScanCommand = GetScanCommand(
  568. cmakeCmd, tdi, lang, "$out", needDyndep, "$DYNDEP_INTERMEDIATE_FILE");
  569. const auto ppVar = cmStrCat("CMAKE_", lang, "_PREPROCESS_SOURCE");
  570. auto ppRule = GetPreprocessScanRule(
  571. this->LanguagePreprocessRule(lang, config), vars, responseFlag, flags,
  572. launcher, rulePlaceholderExpander.get(), ppScanCommand,
  573. this->GetLocalGenerator(), mf->GetRequiredDefinition(ppVar));
  574. // Write the rule for preprocessing file of the given language.
  575. ppRule.Comment = cmStrCat("Rule for preprocessing ", lang, " files.");
  576. ppRule.Description = cmStrCat("Building ", lang, " preprocessed $out");
  577. this->GetGlobalGenerator()->AddRule(ppRule);
  578. if (!compilePPWithDefines) {
  579. // Remove preprocessor definitions from compilation step
  580. vars.Defines = "";
  581. }
  582. }
  583. if (needDyndep) {
  584. // Write the rule for ninja dyndep file generation.
  585. cmNinjaRule rule(this->LanguageDyndepRule(lang, config));
  586. // Command line length is almost always limited -> use response file for
  587. // dyndep rules
  588. rule.RspFile = "$out.rsp";
  589. rule.RspContent = "$in";
  590. // Run CMake dependency scanner on the source file (using the preprocessed
  591. // source if that was performed).
  592. {
  593. std::vector<std::string> ddCmds;
  594. {
  595. std::string ccmd =
  596. cmStrCat(cmakeCmd, " -E cmake_ninja_dyndep --tdi=", tdi,
  597. " --lang=", lang, " --dd=$out @", rule.RspFile);
  598. ddCmds.emplace_back(std::move(ccmd));
  599. }
  600. rule.Command = this->GetLocalGenerator()->BuildCommandLine(ddCmds);
  601. }
  602. rule.Comment =
  603. cmStrCat("Rule to generate ninja dyndep files for ", lang, '.');
  604. rule.Description = cmStrCat("Generating ", lang, " dyndep file $out");
  605. this->GetGlobalGenerator()->AddRule(rule);
  606. }
  607. cmNinjaRule rule(this->LanguageCompilerRule(lang, config));
  608. // If using a response file, move defines, includes, and flags into it.
  609. if (!responseFlag.empty()) {
  610. rule.RspFile = "$RSP_FILE";
  611. rule.RspContent =
  612. cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags);
  613. flags = cmStrCat(responseFlag, rule.RspFile);
  614. vars.Defines = "";
  615. vars.Includes = "";
  616. }
  617. // Tell ninja dependency format so all deps can be loaded into a database
  618. std::string cldeps;
  619. if (explicitPP) {
  620. // The explicit preprocessing step will handle dependency scanning.
  621. } else if (this->NeedDepTypeMSVC(lang)) {
  622. rule.DepType = "msvc";
  623. rule.DepFile.clear();
  624. flags += " /showIncludes";
  625. } else if (mf->IsOn(cmStrCat("CMAKE_NINJA_CMCLDEPS_", lang))) {
  626. // For the MS resource compiler we need cmcldeps, but skip dependencies
  627. // for source-file try_compile cases because they are always fresh.
  628. if (!mf->GetIsSourceFileTryCompile()) {
  629. rule.DepType = "gcc";
  630. rule.DepFile = "$DEP_FILE";
  631. const std::string cl = mf->GetDefinition("CMAKE_C_COMPILER")
  632. ? mf->GetSafeDefinition("CMAKE_C_COMPILER")
  633. : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  634. cldeps = cmStrCat('"', cmSystemTools::GetCMClDepsCommand(), "\" ", lang,
  635. ' ', vars.Source, " $DEP_FILE $out \"",
  636. mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"),
  637. "\" \"", cl, "\" ");
  638. }
  639. } else {
  640. rule.DepType = "gcc";
  641. rule.DepFile = "$DEP_FILE";
  642. const std::string flagsName = cmStrCat("CMAKE_DEPFILE_FLAGS_", lang);
  643. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  644. if (!depfileFlags.empty()) {
  645. cmSystemTools::ReplaceString(depfileFlags, "<DEPFILE>", "$DEP_FILE");
  646. cmSystemTools::ReplaceString(depfileFlags, "<OBJECT>", "$out");
  647. cmSystemTools::ReplaceString(depfileFlags, "<CMAKE_C_COMPILER>",
  648. mf->GetDefinition("CMAKE_C_COMPILER"));
  649. flags += cmStrCat(' ', depfileFlags);
  650. }
  651. }
  652. vars.Flags = flags.c_str();
  653. vars.DependencyFile = rule.DepFile.c_str();
  654. // Rule for compiling object file.
  655. std::vector<std::string> compileCmds;
  656. if (lang == "CUDA") {
  657. std::string cmdVar;
  658. if (this->GeneratorTarget->GetPropertyAsBool(
  659. "CUDA_SEPARABLE_COMPILATION")) {
  660. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  661. } else if (this->GeneratorTarget->GetPropertyAsBool(
  662. "CUDA_PTX_COMPILATION")) {
  663. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  664. } else {
  665. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  666. }
  667. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  668. cmExpandList(compileCmd, compileCmds);
  669. } else {
  670. const std::string cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  671. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  672. cmExpandList(compileCmd, compileCmds);
  673. }
  674. // See if we need to use a compiler launcher like ccache or distcc
  675. std::string compilerLauncher;
  676. if (!compileCmds.empty() &&
  677. (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA" ||
  678. lang == "OBJC" || lang == "OBJCXX")) {
  679. std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
  680. cmProp clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
  681. if (clauncher && !clauncher->empty()) {
  682. compilerLauncher = *clauncher;
  683. }
  684. }
  685. // Maybe insert an include-what-you-use runner.
  686. if (!compileCmds.empty() && (lang == "C" || lang == "CXX")) {
  687. std::string const iwyu_prop = cmStrCat(lang, "_INCLUDE_WHAT_YOU_USE");
  688. cmProp iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  689. std::string const tidy_prop = cmStrCat(lang, "_CLANG_TIDY");
  690. cmProp tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  691. std::string const cpplint_prop = cmStrCat(lang, "_CPPLINT");
  692. cmProp cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  693. std::string const cppcheck_prop = cmStrCat(lang, "_CPPCHECK");
  694. cmProp cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  695. if ((iwyu && !iwyu->empty()) || (tidy && !tidy->empty()) ||
  696. (cpplint && !cpplint->empty()) || (cppcheck && !cppcheck->empty())) {
  697. std::string run_iwyu = cmStrCat(cmakeCmd, " -E __run_co_compile");
  698. if (!compilerLauncher.empty()) {
  699. // In __run_co_compile case the launcher command is supplied
  700. // via --launcher=<maybe-list> and consumed
  701. run_iwyu +=
  702. cmStrCat(" --launcher=",
  703. this->LocalGenerator->EscapeForShell(compilerLauncher));
  704. compilerLauncher.clear();
  705. }
  706. if (iwyu && !iwyu->empty()) {
  707. run_iwyu += cmStrCat(" --iwyu=",
  708. this->GetLocalGenerator()->EscapeForShell(*iwyu));
  709. }
  710. if (tidy && !tidy->empty()) {
  711. run_iwyu += " --tidy=";
  712. const char* driverMode = this->Makefile->GetDefinition(
  713. cmStrCat("CMAKE_", lang, "_CLANG_TIDY_DRIVER_MODE"));
  714. if (!(driverMode && *driverMode)) {
  715. driverMode = lang == "C" ? "gcc" : "g++";
  716. }
  717. run_iwyu += this->GetLocalGenerator()->EscapeForShell(
  718. cmStrCat(*tidy, ";--extra-arg-before=--driver-mode=", driverMode));
  719. }
  720. if (cpplint && !cpplint->empty()) {
  721. run_iwyu += cmStrCat(
  722. " --cpplint=", this->GetLocalGenerator()->EscapeForShell(*cpplint));
  723. }
  724. if (cppcheck && !cppcheck->empty()) {
  725. run_iwyu +=
  726. cmStrCat(" --cppcheck=",
  727. this->GetLocalGenerator()->EscapeForShell(*cppcheck));
  728. }
  729. if ((tidy && !tidy->empty()) || (cpplint && !cpplint->empty()) ||
  730. (cppcheck && !cppcheck->empty())) {
  731. run_iwyu += " --source=$in";
  732. }
  733. run_iwyu += " -- ";
  734. compileCmds.front().insert(0, run_iwyu);
  735. }
  736. }
  737. // If compiler launcher was specified and not consumed above, it
  738. // goes to the beginning of the command line.
  739. if (!compileCmds.empty() && !compilerLauncher.empty()) {
  740. std::vector<std::string> args = cmExpandedList(compilerLauncher, true);
  741. if (!args.empty()) {
  742. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  743. args[0], cmOutputConverter::SHELL);
  744. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  745. i = this->LocalGenerator->EscapeForShell(i);
  746. }
  747. }
  748. compileCmds.front().insert(0, cmStrCat(cmJoin(args, " "), ' '));
  749. }
  750. if (!compileCmds.empty()) {
  751. compileCmds.front().insert(0, cldeps);
  752. }
  753. for (std::string& i : compileCmds) {
  754. i = cmStrCat(launcher, i);
  755. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  756. vars);
  757. }
  758. rule.Command = this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  759. // Write the rule for compiling file of the given language.
  760. rule.Comment = cmStrCat("Rule for compiling ", lang, " files.");
  761. rule.Description = cmStrCat("Building ", lang, " object $out");
  762. this->GetGlobalGenerator()->AddRule(rule);
  763. }
  764. void cmNinjaTargetGenerator::WriteObjectBuildStatements(
  765. const std::string& config, const std::string& fileConfig,
  766. bool firstForConfig)
  767. {
  768. // Write comments.
  769. cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
  770. this->GetImplFileStream(fileConfig)
  771. << "# Object build statements for "
  772. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  773. << " target " << this->GetTargetName() << "\n\n";
  774. {
  775. std::vector<cmSourceFile const*> customCommands;
  776. this->GeneratorTarget->GetCustomCommands(customCommands, config);
  777. for (cmSourceFile const* sf : customCommands) {
  778. cmCustomCommand const* cc = sf->GetCustomCommand();
  779. this->GetLocalGenerator()->AddCustomCommandTarget(
  780. cc, this->GetGeneratorTarget());
  781. // Record the custom commands for this target. The container is used
  782. // in WriteObjectBuildStatement when called in a loop below.
  783. this->Configs[config].CustomCommands.push_back(cc);
  784. }
  785. }
  786. {
  787. std::vector<cmSourceFile const*> headerSources;
  788. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  789. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  790. headerSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  791. config);
  792. }
  793. {
  794. std::vector<cmSourceFile const*> extraSources;
  795. this->GeneratorTarget->GetExtraSources(extraSources, config);
  796. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  797. extraSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  798. config);
  799. }
  800. if (firstForConfig) {
  801. const char* pchExtension =
  802. GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  803. std::vector<cmSourceFile const*> externalObjects;
  804. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  805. for (cmSourceFile const* sf : externalObjects) {
  806. auto objectFileName = this->GetGlobalGenerator()->ExpandCFGIntDir(
  807. this->GetSourceFilePath(sf), config);
  808. if (!cmSystemTools::StringEndsWith(objectFileName, pchExtension)) {
  809. this->Configs[config].Objects.push_back(objectFileName);
  810. }
  811. }
  812. }
  813. {
  814. cmNinjaBuild build("phony");
  815. build.Comment =
  816. cmStrCat("Order-only phony target for ", this->GetTargetName());
  817. build.Outputs.push_back(this->OrderDependsTargetForTarget(config));
  818. cmNinjaDeps& orderOnlyDeps = build.OrderOnlyDeps;
  819. this->GetLocalGenerator()->AppendTargetDepends(
  820. this->GeneratorTarget, orderOnlyDeps, config, fileConfig,
  821. DependOnTargetOrdering);
  822. // Add order-only dependencies on other files associated with the target.
  823. cm::append(orderOnlyDeps, this->Configs[config].ExtraFiles);
  824. // Add order-only dependencies on custom command outputs.
  825. for (cmCustomCommand const* cc : this->Configs[config].CustomCommands) {
  826. cmCustomCommandGenerator ccg(*cc, config, this->GetLocalGenerator());
  827. const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
  828. const std::vector<std::string>& ccbyproducts = ccg.GetByproducts();
  829. std::transform(ccoutputs.begin(), ccoutputs.end(),
  830. std::back_inserter(orderOnlyDeps), MapToNinjaPath());
  831. std::transform(ccbyproducts.begin(), ccbyproducts.end(),
  832. std::back_inserter(orderOnlyDeps), MapToNinjaPath());
  833. }
  834. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  835. orderOnlyDeps.erase(
  836. std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  837. orderOnlyDeps.end());
  838. // The phony target must depend on at least one input or ninja will explain
  839. // that "output ... of phony edge with no inputs doesn't exist" and
  840. // consider the phony output "dirty".
  841. if (orderOnlyDeps.empty()) {
  842. // Any path that always exists will work here. It would be nice to
  843. // use just "." but that is not supported by Ninja < 1.7.
  844. std::string tgtDir = cmStrCat(
  845. this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
  846. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget));
  847. orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir));
  848. }
  849. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  850. build);
  851. }
  852. {
  853. std::vector<cmSourceFile const*> objectSources;
  854. this->GeneratorTarget->GetObjectSources(objectSources, config);
  855. for (cmSourceFile const* sf : objectSources) {
  856. this->WriteObjectBuildStatement(sf, config, fileConfig, firstForConfig);
  857. }
  858. }
  859. for (auto const& langDDIFiles : this->Configs[config].DDIFiles) {
  860. std::string const& language = langDDIFiles.first;
  861. cmNinjaDeps const& ddiFiles = langDDIFiles.second;
  862. cmNinjaBuild build(this->LanguageDyndepRule(language, config));
  863. build.Outputs.push_back(this->GetDyndepFilePath(language, config));
  864. build.ExplicitDeps = ddiFiles;
  865. this->WriteTargetDependInfo(language, config);
  866. // Make sure dyndep files for all our dependencies have already
  867. // been generated so that the '<LANG>Modules.json' files they
  868. // produced as side-effects are available for us to read.
  869. // Ideally we should depend on the '<LANG>Modules.json' files
  870. // from our dependencies directly, but we don't know which of
  871. // our dependencies produces them. Fixing this will require
  872. // refactoring the Ninja generator to generate targets in
  873. // dependency order so that we can collect the needed information.
  874. this->GetLocalGenerator()->AppendTargetDepends(
  875. this->GeneratorTarget, build.OrderOnlyDeps, config, fileConfig,
  876. DependOnTargetArtifact);
  877. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  878. build);
  879. }
  880. this->GetImplFileStream(fileConfig) << "\n";
  881. if (!this->Configs[config].SwiftOutputMap.empty()) {
  882. std::string const mapFilePath =
  883. cmStrCat(this->GeneratorTarget->GetSupportDirectory(), '/', config, '/',
  884. "output-file-map.json");
  885. std::string const targetSwiftDepsPath = [this, config]() -> std::string {
  886. cmGeneratorTarget const* target = this->GeneratorTarget;
  887. if (cmProp name = target->GetProperty("Swift_DEPENDENCIES_FILE")) {
  888. return *name;
  889. }
  890. return this->ConvertToNinjaPath(
  891. cmStrCat(target->GetSupportDirectory(), '/', config, '/',
  892. target->GetName(), ".swiftdeps"));
  893. }();
  894. // build the global target dependencies
  895. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  896. Json::Value deps(Json::objectValue);
  897. deps["swift-dependencies"] = targetSwiftDepsPath;
  898. this->Configs[config].SwiftOutputMap[""] = deps;
  899. cmGeneratedFileStream output(mapFilePath);
  900. output << this->Configs[config].SwiftOutputMap;
  901. }
  902. }
  903. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  904. cmSourceFile const* source, const std::string& config,
  905. const std::string& fileConfig, bool firstForConfig)
  906. {
  907. std::string const language = source->GetLanguage();
  908. std::string const sourceFileName =
  909. language == "RC" ? source->GetFullPath() : this->GetSourceFilePath(source);
  910. std::string const objectDir = this->ConvertToNinjaPath(
  911. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  912. this->GetGlobalGenerator()->ConfigDirectory(config)));
  913. std::string const objectFileName =
  914. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  915. std::string const objectFileDir =
  916. cmSystemTools::GetFilenamePath(objectFileName);
  917. std::string cmakeVarLang = cmStrCat("CMAKE_", language);
  918. // build response file name
  919. std::string cmakeLinkVar = cmStrCat(cmakeVarLang, "_RESPONSE_FILE_FLAG");
  920. const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar);
  921. bool const lang_supports_response =
  922. !(language == "RC" || (language == "CUDA" && !flag));
  923. int const commandLineLengthLimit =
  924. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  925. cmNinjaBuild objBuild(this->LanguageCompilerRule(language, config));
  926. cmNinjaVars& vars = objBuild.Variables;
  927. vars["FLAGS"] = this->ComputeFlagsForObject(source, language, config);
  928. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  929. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  930. if (!this->NeedDepTypeMSVC(language)) {
  931. bool replaceExt(false);
  932. if (!language.empty()) {
  933. std::string repVar =
  934. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  935. replaceExt = this->Makefile->IsOn(repVar);
  936. }
  937. if (!replaceExt) {
  938. // use original code
  939. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  940. cmStrCat(objectFileName, ".d"), cmOutputConverter::SHELL);
  941. } else {
  942. // Replace the original source file extension with the
  943. // depend file extension.
  944. std::string dependFileName = cmStrCat(
  945. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  946. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  947. cmStrCat(objectFileDir, '/', dependFileName),
  948. cmOutputConverter::SHELL);
  949. }
  950. }
  951. this->ExportObjectCompileCommand(
  952. language, sourceFileName, objectDir, objectFileName, objectFileDir,
  953. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"]);
  954. objBuild.Outputs.push_back(objectFileName);
  955. if (firstForConfig) {
  956. const char* pchExtension =
  957. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  958. if (!cmSystemTools::StringEndsWith(objectFileName, pchExtension)) {
  959. // Add this object to the list of object files.
  960. this->Configs[config].Objects.push_back(objectFileName);
  961. }
  962. }
  963. objBuild.ExplicitDeps.push_back(sourceFileName);
  964. // Add precompile headers dependencies
  965. std::vector<std::string> depList;
  966. std::vector<std::string> architectures;
  967. this->GeneratorTarget->GetAppleArchs(config, architectures);
  968. if (architectures.empty()) {
  969. architectures.emplace_back();
  970. }
  971. std::unordered_set<std::string> pchSources;
  972. for (const std::string& arch : architectures) {
  973. const std::string pchSource =
  974. this->GeneratorTarget->GetPchSource(config, language, arch);
  975. if (!pchSource.empty()) {
  976. pchSources.insert(pchSource);
  977. }
  978. }
  979. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  980. for (const std::string& arch : architectures) {
  981. depList.push_back(
  982. this->GeneratorTarget->GetPchHeader(config, language, arch));
  983. if (pchSources.find(source->GetFullPath()) == pchSources.end()) {
  984. depList.push_back(
  985. this->GeneratorTarget->GetPchFile(config, language, arch));
  986. }
  987. }
  988. }
  989. if (cmProp objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  990. std::vector<std::string> objDepList = cmExpandedList(*objectDeps);
  991. std::copy(objDepList.begin(), objDepList.end(),
  992. std::back_inserter(depList));
  993. }
  994. if (!depList.empty()) {
  995. for (std::string& odi : depList) {
  996. if (cmSystemTools::FileIsFullPath(odi)) {
  997. odi = cmSystemTools::CollapseFullPath(odi);
  998. }
  999. }
  1000. std::transform(depList.begin(), depList.end(),
  1001. std::back_inserter(objBuild.ImplicitDeps),
  1002. MapToNinjaPath());
  1003. }
  1004. objBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1005. // If the source file is GENERATED and does not have a custom command
  1006. // (either attached to this source file or another one), assume that one of
  1007. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  1008. // will rebuild the file.
  1009. if (source->GetIsGenerated() &&
  1010. !source->GetPropertyAsBool("__CMAKE_GENERATED_BY_CMAKE") &&
  1011. !source->GetCustomCommand() &&
  1012. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFileName)) {
  1013. this->GetGlobalGenerator()->AddAssumedSourceDependencies(
  1014. sourceFileName, objBuild.OrderOnlyDeps);
  1015. }
  1016. // For some cases we need to generate a ninja dyndep file.
  1017. bool const needDyndep = this->NeedDyndep(language);
  1018. // For some cases we do an explicit preprocessor invocation.
  1019. bool const explicitPP = this->NeedExplicitPreprocessing(language);
  1020. if (explicitPP) {
  1021. cmNinjaBuild ppBuild(this->LanguagePreprocessRule(language, config));
  1022. std::string const ppFileName =
  1023. this->ConvertToNinjaPath(this->GetPreprocessedFilePath(source, config));
  1024. ppBuild.Outputs.push_back(ppFileName);
  1025. ppBuild.RspFile = cmStrCat(ppFileName, ".rsp");
  1026. bool const compilePP = this->UsePreprocessedSource(language);
  1027. bool const compilePPWithDefines =
  1028. compilePP && this->CompilePreprocessedSourceWithDefines(language);
  1029. if (compilePP) {
  1030. // Move compilation dependencies to the preprocessing build statement.
  1031. std::swap(ppBuild.ExplicitDeps, objBuild.ExplicitDeps);
  1032. std::swap(ppBuild.ImplicitDeps, objBuild.ImplicitDeps);
  1033. std::swap(ppBuild.OrderOnlyDeps, objBuild.OrderOnlyDeps);
  1034. std::swap(ppBuild.Variables["IN_ABS"], vars["IN_ABS"]);
  1035. // The actual compilation will now use the preprocessed source.
  1036. objBuild.ExplicitDeps.push_back(ppFileName);
  1037. } else {
  1038. // Copy compilation dependencies to the preprocessing build statement.
  1039. ppBuild.ExplicitDeps = objBuild.ExplicitDeps;
  1040. ppBuild.ImplicitDeps = objBuild.ImplicitDeps;
  1041. ppBuild.OrderOnlyDeps = objBuild.OrderOnlyDeps;
  1042. ppBuild.Variables["IN_ABS"] = vars["IN_ABS"];
  1043. }
  1044. // Preprocessing and compilation generally use the same flags.
  1045. ppBuild.Variables["FLAGS"] = vars["FLAGS"];
  1046. if (compilePP) {
  1047. // In case compilation requires flags that are incompatible with
  1048. // preprocessing, include them here.
  1049. std::string const& postFlag = this->Makefile->GetSafeDefinition(
  1050. cmStrCat("CMAKE_", language, "_POSTPROCESS_FLAG"));
  1051. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  1052. }
  1053. if (compilePP && !compilePPWithDefines) {
  1054. // Move preprocessor definitions to the preprocessor build statement.
  1055. std::swap(ppBuild.Variables["DEFINES"], vars["DEFINES"]);
  1056. } else {
  1057. // Copy preprocessor definitions to the preprocessor build statement.
  1058. ppBuild.Variables["DEFINES"] = vars["DEFINES"];
  1059. }
  1060. // Copy include directories to the preprocessor build statement. The
  1061. // Fortran compilation build statement still needs them for the INCLUDE
  1062. // directive.
  1063. ppBuild.Variables["INCLUDES"] = vars["INCLUDES"];
  1064. if (compilePP) {
  1065. // Prepend source file's original directory as an include directory
  1066. // so e.g. Fortran INCLUDE statements can look for files in it.
  1067. std::vector<std::string> sourceDirectory;
  1068. sourceDirectory.push_back(
  1069. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  1070. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  1071. sourceDirectory, this->GeneratorTarget, language, false, false,
  1072. config);
  1073. vars["INCLUDES"] = cmStrCat(sourceDirectoryFlag, ' ', vars["INCLUDES"]);
  1074. }
  1075. // Explicit preprocessing always uses a depfile.
  1076. ppBuild.Variables["DEP_FILE"] =
  1077. this->GetLocalGenerator()->ConvertToOutputFormat(
  1078. cmStrCat(objectFileName, ".pp.d"), cmOutputConverter::SHELL);
  1079. if (compilePP) {
  1080. // The actual compilation does not need a depfile because it
  1081. // depends on the already-preprocessed source.
  1082. vars.erase("DEP_FILE");
  1083. }
  1084. if (needDyndep) {
  1085. // Tell dependency scanner the object file that will result from
  1086. // compiling the source.
  1087. ppBuild.Variables["OBJ_FILE"] = objectFileName;
  1088. // Tell dependency scanner where to store dyndep intermediate results.
  1089. std::string const ddiFile = cmStrCat(objectFileName, ".ddi");
  1090. ppBuild.Variables["DYNDEP_INTERMEDIATE_FILE"] = ddiFile;
  1091. ppBuild.ImplicitOuts.push_back(ddiFile);
  1092. if (firstForConfig) {
  1093. this->Configs[config].DDIFiles[language].push_back(ddiFile);
  1094. }
  1095. }
  1096. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1097. ppBuild.Variables);
  1098. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1099. ppBuild, commandLineLengthLimit);
  1100. }
  1101. if (needDyndep) {
  1102. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1103. objBuild.OrderOnlyDeps.push_back(dyndep);
  1104. vars["dyndep"] = dyndep;
  1105. }
  1106. EnsureParentDirectoryExists(objectFileName);
  1107. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1108. objectDir, cmOutputConverter::SHELL);
  1109. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1110. objectFileDir, cmOutputConverter::SHELL);
  1111. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1112. vars);
  1113. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1114. auto pchIt = pchSources.find(source->GetFullPath());
  1115. if (pchIt != pchSources.end()) {
  1116. this->addPoolNinjaVariable("JOB_POOL_PRECOMPILE_HEADER",
  1117. this->GetGeneratorTarget(), vars);
  1118. }
  1119. }
  1120. this->SetMsvcTargetPdbVariable(vars, config);
  1121. objBuild.RspFile = cmStrCat(objectFileName, ".rsp");
  1122. if (language == "Swift") {
  1123. this->EmitSwiftDependencyInfo(source, config);
  1124. } else {
  1125. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1126. objBuild, commandLineLengthLimit);
  1127. }
  1128. if (cmProp objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  1129. cmNinjaBuild build("phony");
  1130. build.Comment = "Additional output files.";
  1131. build.Outputs = cmExpandedList(*objectOutputs);
  1132. std::transform(build.Outputs.begin(), build.Outputs.end(),
  1133. build.Outputs.begin(), MapToNinjaPath());
  1134. build.ExplicitDeps = objBuild.Outputs;
  1135. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1136. build);
  1137. }
  1138. }
  1139. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang,
  1140. const std::string& config)
  1141. {
  1142. Json::Value tdi(Json::objectValue);
  1143. tdi["language"] = lang;
  1144. tdi["compiler-id"] = this->Makefile->GetSafeDefinition(
  1145. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1146. if (lang == "Fortran") {
  1147. std::string mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  1148. this->Makefile->GetHomeOutputDirectory());
  1149. if (mod_dir.empty()) {
  1150. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  1151. }
  1152. tdi["module-dir"] = mod_dir;
  1153. tdi["submodule-sep"] =
  1154. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1155. tdi["submodule-ext"] =
  1156. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1157. }
  1158. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  1159. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  1160. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  1161. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  1162. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  1163. std::vector<std::string> includes;
  1164. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1165. lang, config);
  1166. for (std::string const& i : includes) {
  1167. // Convert the include directories the same way we do for -I flags.
  1168. // See upstream ninja issue 1251.
  1169. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  1170. }
  1171. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1172. Json::arrayValue;
  1173. for (std::string const& l : this->GetLinkedTargetDirectories(config)) {
  1174. tdi_linked_target_dirs.append(l);
  1175. }
  1176. std::string const tdin = this->GetTargetDependInfoPath(lang, config);
  1177. cmGeneratedFileStream tdif(tdin);
  1178. tdif << tdi;
  1179. }
  1180. void cmNinjaTargetGenerator::EmitSwiftDependencyInfo(
  1181. cmSourceFile const* source, const std::string& config)
  1182. {
  1183. std::string const sourceFilePath =
  1184. this->ConvertToNinjaPath(this->GetSourceFilePath(source));
  1185. std::string const objectFilePath =
  1186. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1187. std::string const swiftDepsPath = [source, objectFilePath]() -> std::string {
  1188. if (cmProp name = source->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1189. return *name;
  1190. }
  1191. return cmStrCat(objectFilePath, ".swiftdeps");
  1192. }();
  1193. std::string const swiftDiaPath = [source, objectFilePath]() -> std::string {
  1194. if (cmProp name = source->GetProperty("Swift_DIAGNOSTICS_FILE")) {
  1195. return *name;
  1196. }
  1197. return cmStrCat(objectFilePath, ".dia");
  1198. }();
  1199. std::string const makeDepsPath = [this, source, config]() -> std::string {
  1200. cmLocalNinjaGenerator const* local = this->GetLocalGenerator();
  1201. std::string const objectFileName =
  1202. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1203. std::string const objectFileDir =
  1204. cmSystemTools::GetFilenamePath(objectFileName);
  1205. if (this->Makefile->IsOn("CMAKE_Swift_DEPFLE_EXTNSION_REPLACE")) {
  1206. std::string dependFileName = cmStrCat(
  1207. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1208. return local->ConvertToOutputFormat(
  1209. cmStrCat(objectFileDir, '/', dependFileName),
  1210. cmOutputConverter::SHELL);
  1211. }
  1212. return local->ConvertToOutputFormat(cmStrCat(objectFileName, ".d"),
  1213. cmOutputConverter::SHELL);
  1214. }();
  1215. // build the source file mapping
  1216. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1217. Json::Value entry = Json::Value(Json::objectValue);
  1218. entry["object"] = objectFilePath;
  1219. entry["dependencies"] = makeDepsPath;
  1220. entry["swift-dependencies"] = swiftDepsPath;
  1221. entry["diagnostics"] = swiftDiaPath;
  1222. this->Configs[config].SwiftOutputMap[sourceFilePath] = entry;
  1223. }
  1224. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  1225. std::string const& language, std::string const& sourceFileName,
  1226. std::string const& objectDir, std::string const& objectFileName,
  1227. std::string const& objectFileDir, std::string const& flags,
  1228. std::string const& defines, std::string const& includes)
  1229. {
  1230. if (!this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS")) {
  1231. return;
  1232. }
  1233. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1234. compileObjectVars.Language = language.c_str();
  1235. std::string escapedSourceFileName = sourceFileName;
  1236. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1237. escapedSourceFileName =
  1238. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1239. this->GetGlobalGenerator()
  1240. ->GetCMakeInstance()
  1241. ->GetHomeOutputDirectory());
  1242. }
  1243. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1244. escapedSourceFileName, cmOutputConverter::SHELL);
  1245. compileObjectVars.Source = escapedSourceFileName.c_str();
  1246. compileObjectVars.Object = objectFileName.c_str();
  1247. compileObjectVars.ObjectDir = objectDir.c_str();
  1248. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1249. compileObjectVars.Flags = flags.c_str();
  1250. compileObjectVars.Defines = defines.c_str();
  1251. compileObjectVars.Includes = includes.c_str();
  1252. // Rule for compiling object file.
  1253. std::vector<std::string> compileCmds;
  1254. if (language == "CUDA") {
  1255. std::string cmdVar;
  1256. if (this->GeneratorTarget->GetPropertyAsBool(
  1257. "CUDA_SEPARABLE_COMPILATION")) {
  1258. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  1259. } else if (this->GeneratorTarget->GetPropertyAsBool(
  1260. "CUDA_PTX_COMPILATION")) {
  1261. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  1262. } else {
  1263. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  1264. }
  1265. const std::string& compileCmd =
  1266. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1267. cmExpandList(compileCmd, compileCmds);
  1268. } else {
  1269. const std::string cmdVar = cmStrCat("CMAKE_", language, "_COMPILE_OBJECT");
  1270. const std::string& compileCmd =
  1271. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1272. cmExpandList(compileCmd, compileCmds);
  1273. }
  1274. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  1275. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  1276. for (std::string& i : compileCmds) {
  1277. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  1278. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  1279. compileObjectVars);
  1280. }
  1281. std::string cmdLine =
  1282. this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  1283. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName);
  1284. }
  1285. void cmNinjaTargetGenerator::AdditionalCleanFiles(const std::string& config)
  1286. {
  1287. if (cmProp prop_value =
  1288. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  1289. cmLocalNinjaGenerator* lg = this->LocalGenerator;
  1290. std::vector<std::string> cleanFiles;
  1291. cmExpandList(cmGeneratorExpression::Evaluate(*prop_value, lg, config,
  1292. this->GeneratorTarget),
  1293. cleanFiles);
  1294. std::string const& binaryDir = lg->GetCurrentBinaryDirectory();
  1295. cmGlobalNinjaGenerator* gg = lg->GetGlobalNinjaGenerator();
  1296. for (std::string const& cleanFile : cleanFiles) {
  1297. // Support relative paths
  1298. gg->AddAdditionalCleanFile(
  1299. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  1300. }
  1301. }
  1302. }
  1303. cmNinjaDeps cmNinjaTargetGenerator::GetObjects(const std::string& config) const
  1304. {
  1305. auto const it = this->Configs.find(config);
  1306. if (it != this->Configs.end()) {
  1307. return it->second.Objects;
  1308. }
  1309. return {};
  1310. }
  1311. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  1312. const std::string& path) const
  1313. {
  1314. if (cmSystemTools::FileIsFullPath(path)) {
  1315. cmSystemTools::MakeDirectory(path);
  1316. } else {
  1317. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  1318. std::string fullPath = gg->GetCMakeInstance()->GetHomeOutputDirectory();
  1319. // Also ensures their is a trailing slash.
  1320. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  1321. fullPath += path;
  1322. cmSystemTools::MakeDirectory(fullPath);
  1323. }
  1324. }
  1325. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  1326. const std::string& path) const
  1327. {
  1328. EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  1329. }
  1330. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  1331. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  1332. {
  1333. // Skip OS X content when not building a Framework or Bundle.
  1334. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  1335. return;
  1336. }
  1337. std::string macdir =
  1338. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  1339. config);
  1340. // Reject files that collide with files from the Ninja file's native config.
  1341. if (config != this->FileConfig) {
  1342. std::string nativeMacdir =
  1343. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(
  1344. pkgloc, this->FileConfig);
  1345. if (macdir == nativeMacdir) {
  1346. return;
  1347. }
  1348. }
  1349. // Get the input file location.
  1350. std::string input = source.GetFullPath();
  1351. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  1352. // Get the output file location.
  1353. std::string output =
  1354. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  1355. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  1356. // Write a build statement to copy the content into the bundle.
  1357. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(
  1358. input, output, this->FileConfig);
  1359. // Add as a dependency to the target so that it gets called.
  1360. this->Generator->Configs[config].ExtraFiles.push_back(std::move(output));
  1361. }
  1362. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  1363. const std::string& pool_property, cmGeneratorTarget* target,
  1364. cmNinjaVars& vars)
  1365. {
  1366. cmProp pool = target->GetProperty(pool_property);
  1367. if (pool) {
  1368. vars["pool"] = *pool;
  1369. }
  1370. }
  1371. bool cmNinjaTargetGenerator::ForceResponseFile()
  1372. {
  1373. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  1374. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  1375. cmSystemTools::HasEnv(forceRspFile));
  1376. }