cmNinjaTargetGenerator.cxx 55 KB

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