cmNinjaTargetGenerator.cxx 48 KB

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