cmNinjaTargetGenerator.cxx 63 KB

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