cmNinjaTargetGenerator.cxx 51 KB

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