cmNinjaTargetGenerator.cxx 63 KB

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