cmNinjaTargetGenerator.cxx 53 KB

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