cmMakefileTargetGenerator.cxx 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269
  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 "cmMakefileTargetGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <iterator>
  8. #include <sstream>
  9. #include <unordered_map>
  10. #include <unordered_set>
  11. #include <utility>
  12. #include <cm/memory>
  13. #include <cm/string_view>
  14. #include <cmext/algorithm>
  15. #include <cmext/string_view>
  16. #include "cmComputeLinkInformation.h"
  17. #include "cmCustomCommand.h"
  18. #include "cmCustomCommandGenerator.h"
  19. #include "cmGeneratedFileStream.h"
  20. #include "cmGeneratorExpression.h"
  21. #include "cmGeneratorTarget.h"
  22. #include "cmGlobalUnixMakefileGenerator3.h"
  23. #include "cmLinkLineComputer.h" // IWYU pragma: keep
  24. #include "cmLocalCommonGenerator.h"
  25. #include "cmLocalGenerator.h"
  26. #include "cmLocalUnixMakefileGenerator3.h"
  27. #include "cmMakefile.h"
  28. #include "cmMakefileExecutableTargetGenerator.h"
  29. #include "cmMakefileLibraryTargetGenerator.h"
  30. #include "cmMakefileUtilityTargetGenerator.h"
  31. #include "cmMessageType.h"
  32. #include "cmOutputConverter.h"
  33. #include "cmPolicies.h"
  34. #include "cmProperty.h"
  35. #include "cmRange.h"
  36. #include "cmRulePlaceholderExpander.h"
  37. #include "cmSourceFile.h"
  38. #include "cmSourceFileLocationKind.h"
  39. #include "cmState.h"
  40. #include "cmStateDirectory.h"
  41. #include "cmStateSnapshot.h"
  42. #include "cmStateTypes.h"
  43. #include "cmStringAlgorithms.h"
  44. #include "cmSystemTools.h"
  45. #include "cmake.h"
  46. cmMakefileTargetGenerator::cmMakefileTargetGenerator(cmGeneratorTarget* target)
  47. : cmCommonTargetGenerator(target)
  48. {
  49. this->CustomCommandDriver = OnBuild;
  50. this->LocalGenerator =
  51. static_cast<cmLocalUnixMakefileGenerator3*>(target->GetLocalGenerator());
  52. this->GlobalGenerator = static_cast<cmGlobalUnixMakefileGenerator3*>(
  53. this->LocalGenerator->GetGlobalGenerator());
  54. cmake* cm = this->GlobalGenerator->GetCMakeInstance();
  55. this->NoRuleMessages = false;
  56. if (cmProp ruleStatus = cm->GetState()->GetGlobalProperty("RULE_MESSAGES")) {
  57. this->NoRuleMessages = cmIsOff(*ruleStatus);
  58. }
  59. switch (this->GeneratorTarget->GetPolicyStatusCMP0113()) {
  60. case cmPolicies::WARN:
  61. case cmPolicies::OLD:
  62. this->CMP0113New = false;
  63. break;
  64. case cmPolicies::NEW:
  65. case cmPolicies::REQUIRED_IF_USED:
  66. case cmPolicies::REQUIRED_ALWAYS:
  67. this->CMP0113New = true;
  68. break;
  69. }
  70. this->MacOSXContentGenerator =
  71. cm::make_unique<MacOSXContentGeneratorType>(this);
  72. }
  73. cmMakefileTargetGenerator::~cmMakefileTargetGenerator() = default;
  74. std::unique_ptr<cmMakefileTargetGenerator> cmMakefileTargetGenerator::New(
  75. cmGeneratorTarget* tgt)
  76. {
  77. std::unique_ptr<cmMakefileTargetGenerator> result;
  78. switch (tgt->GetType()) {
  79. case cmStateEnums::EXECUTABLE:
  80. result = cm::make_unique<cmMakefileExecutableTargetGenerator>(tgt);
  81. break;
  82. case cmStateEnums::STATIC_LIBRARY:
  83. case cmStateEnums::SHARED_LIBRARY:
  84. case cmStateEnums::MODULE_LIBRARY:
  85. case cmStateEnums::OBJECT_LIBRARY:
  86. result = cm::make_unique<cmMakefileLibraryTargetGenerator>(tgt);
  87. break;
  88. case cmStateEnums::INTERFACE_LIBRARY:
  89. case cmStateEnums::UTILITY:
  90. result = cm::make_unique<cmMakefileUtilityTargetGenerator>(tgt);
  91. break;
  92. default:
  93. return result;
  94. // break; /* unreachable */
  95. }
  96. return result;
  97. }
  98. std::string cmMakefileTargetGenerator::GetConfigName()
  99. {
  100. auto const& configNames = this->LocalGenerator->GetConfigNames();
  101. assert(configNames.size() == 1);
  102. return configNames.front();
  103. }
  104. void cmMakefileTargetGenerator::GetDeviceLinkFlags(
  105. std::string& linkFlags, const std::string& linkLanguage)
  106. {
  107. cmGeneratorTarget::DeviceLinkSetter setter(*this->GetGeneratorTarget());
  108. std::vector<std::string> linkOpts;
  109. this->GeneratorTarget->GetLinkOptions(linkOpts, this->GetConfigName(),
  110. linkLanguage);
  111. // LINK_OPTIONS are escaped.
  112. this->LocalGenerator->AppendCompileOptions(linkFlags, linkOpts);
  113. }
  114. void cmMakefileTargetGenerator::GetTargetLinkFlags(
  115. std::string& flags, const std::string& linkLanguage)
  116. {
  117. this->LocalGenerator->AppendFlags(
  118. flags, this->GeneratorTarget->GetSafeProperty("LINK_FLAGS"));
  119. std::string linkFlagsConfig =
  120. cmStrCat("LINK_FLAGS_", cmSystemTools::UpperCase(this->GetConfigName()));
  121. this->LocalGenerator->AppendFlags(
  122. flags, this->GeneratorTarget->GetSafeProperty(linkFlagsConfig));
  123. std::vector<std::string> opts;
  124. this->GeneratorTarget->GetLinkOptions(opts, this->GetConfigName(),
  125. linkLanguage);
  126. // LINK_OPTIONS are escaped.
  127. this->LocalGenerator->AppendCompileOptions(flags, opts);
  128. this->LocalGenerator->AppendPositionIndependentLinkerFlags(
  129. flags, this->GeneratorTarget, this->GetConfigName(), linkLanguage);
  130. }
  131. void cmMakefileTargetGenerator::CreateRuleFile()
  132. {
  133. // Create a directory for this target.
  134. this->TargetBuildDirectory =
  135. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  136. this->TargetBuildDirectoryFull =
  137. this->LocalGenerator->ConvertToFullPath(this->TargetBuildDirectory);
  138. cmSystemTools::MakeDirectory(this->TargetBuildDirectoryFull);
  139. // Construct the rule file name.
  140. this->BuildFileName = cmStrCat(this->TargetBuildDirectory, "/build.make");
  141. this->BuildFileNameFull =
  142. cmStrCat(this->TargetBuildDirectoryFull, "/build.make");
  143. // Construct the rule file name.
  144. this->ProgressFileNameFull =
  145. cmStrCat(this->TargetBuildDirectoryFull, "/progress.make");
  146. // reset the progress count
  147. this->NumberOfProgressActions = 0;
  148. // Open the rule file. This should be copy-if-different because the
  149. // rules may depend on this file itself.
  150. this->BuildFileStream = cm::make_unique<cmGeneratedFileStream>(
  151. this->BuildFileNameFull, false,
  152. this->GlobalGenerator->GetMakefileEncoding());
  153. if (!this->BuildFileStream) {
  154. return;
  155. }
  156. this->BuildFileStream->SetCopyIfDifferent(true);
  157. this->LocalGenerator->WriteDisclaimer(*this->BuildFileStream);
  158. if (this->GlobalGenerator->AllowDeleteOnError()) {
  159. std::vector<std::string> no_depends;
  160. std::vector<std::string> no_commands;
  161. this->LocalGenerator->WriteMakeRule(
  162. *this->BuildFileStream, "Delete rule output on recipe failure.",
  163. ".DELETE_ON_ERROR", no_depends, no_commands, false);
  164. }
  165. this->LocalGenerator->WriteSpecialTargetsTop(*this->BuildFileStream);
  166. }
  167. void cmMakefileTargetGenerator::WriteTargetBuildRules()
  168. {
  169. // -- Write the custom commands for this target
  170. // Evaluates generator expressions and expands prop_value
  171. auto evaluatedFiles =
  172. [this](const std::string& prop_value) -> std::vector<std::string> {
  173. std::vector<std::string> files;
  174. cmExpandList(cmGeneratorExpression::Evaluate(
  175. prop_value, this->LocalGenerator, this->GetConfigName(),
  176. this->GeneratorTarget),
  177. files);
  178. return files;
  179. };
  180. // Look for additional files registered for cleaning in this directory.
  181. if (cmProp prop_value =
  182. this->Makefile->GetProperty("ADDITIONAL_MAKE_CLEAN_FILES")) {
  183. std::vector<std::string> const files = evaluatedFiles(*prop_value);
  184. this->CleanFiles.insert(files.begin(), files.end());
  185. }
  186. // Look for additional files registered for cleaning in this target.
  187. if (cmProp prop_value =
  188. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  189. std::vector<std::string> const files = evaluatedFiles(*prop_value);
  190. // For relative path support
  191. std::string const& binaryDir =
  192. this->LocalGenerator->GetCurrentBinaryDirectory();
  193. for (std::string const& cfl : files) {
  194. this->CleanFiles.insert(cmSystemTools::CollapseFullPath(cfl, binaryDir));
  195. }
  196. }
  197. std::string currentBinDir =
  198. this->LocalGenerator->GetCurrentBinaryDirectory();
  199. // Look for ISPC extra object files generated by this target
  200. auto ispcAdditionalObjs =
  201. this->GeneratorTarget->GetGeneratedISPCObjects(this->GetConfigName());
  202. for (std::string const& ispcObj : ispcAdditionalObjs) {
  203. this->CleanFiles.insert(this->LocalGenerator->MaybeConvertToRelativePath(
  204. currentBinDir, ispcObj));
  205. }
  206. // add custom commands to the clean rules?
  207. bool clean = cmIsOff(this->Makefile->GetProperty("CLEAN_NO_CUSTOM"));
  208. // First generate the object rule files. Save a list of all object
  209. // files for this target.
  210. std::vector<cmSourceFile const*> customCommands;
  211. this->GeneratorTarget->GetCustomCommands(customCommands,
  212. this->GetConfigName());
  213. for (cmSourceFile const* sf : customCommands) {
  214. if (this->CMP0113New &&
  215. !this->LocalGenerator->GetCommandsVisited(this->GeneratorTarget)
  216. .insert(sf)
  217. .second) {
  218. continue;
  219. }
  220. cmCustomCommandGenerator ccg(*sf->GetCustomCommand(),
  221. this->GetConfigName(), this->LocalGenerator);
  222. this->GenerateCustomRuleFile(ccg);
  223. if (clean) {
  224. const std::vector<std::string>& outputs = ccg.GetOutputs();
  225. for (std::string const& output : outputs) {
  226. this->CleanFiles.insert(
  227. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir,
  228. output));
  229. }
  230. const std::vector<std::string>& byproducts = ccg.GetByproducts();
  231. for (std::string const& byproduct : byproducts) {
  232. this->CleanFiles.insert(
  233. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir,
  234. byproduct));
  235. }
  236. }
  237. }
  238. // Add byproducts from build events to the clean rules
  239. if (clean) {
  240. std::vector<cmCustomCommand> buildEventCommands =
  241. this->GeneratorTarget->GetPreBuildCommands();
  242. cm::append(buildEventCommands,
  243. this->GeneratorTarget->GetPreLinkCommands());
  244. cm::append(buildEventCommands,
  245. this->GeneratorTarget->GetPostBuildCommands());
  246. for (const auto& be : buildEventCommands) {
  247. cmCustomCommandGenerator beg(be, this->GetConfigName(),
  248. this->LocalGenerator);
  249. const std::vector<std::string>& byproducts = beg.GetByproducts();
  250. for (std::string const& byproduct : byproducts) {
  251. this->CleanFiles.insert(
  252. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir,
  253. byproduct));
  254. }
  255. }
  256. }
  257. std::vector<cmSourceFile const*> headerSources;
  258. this->GeneratorTarget->GetHeaderSources(headerSources,
  259. this->GetConfigName());
  260. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  261. headerSources, this->MacOSXContentGenerator.get(), this->GetConfigName());
  262. std::vector<cmSourceFile const*> extraSources;
  263. this->GeneratorTarget->GetExtraSources(extraSources, this->GetConfigName());
  264. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  265. extraSources, this->MacOSXContentGenerator.get(), this->GetConfigName());
  266. cmProp pchExtension = this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  267. std::vector<cmSourceFile const*> externalObjects;
  268. this->GeneratorTarget->GetExternalObjects(externalObjects,
  269. this->GetConfigName());
  270. for (cmSourceFile const* sf : externalObjects) {
  271. auto const& objectFileName = sf->GetFullPath();
  272. if (!cmSystemTools::StringEndsWith(objectFileName,
  273. cmToCStr(pchExtension))) {
  274. this->ExternalObjects.push_back(objectFileName);
  275. }
  276. }
  277. std::vector<cmSourceFile const*> objectSources;
  278. this->GeneratorTarget->GetObjectSources(objectSources,
  279. this->GetConfigName());
  280. for (cmSourceFile const* sf : objectSources) {
  281. // Generate this object file's rule file.
  282. this->WriteObjectRuleFiles(*sf);
  283. }
  284. }
  285. void cmMakefileTargetGenerator::WriteCommonCodeRules()
  286. {
  287. const char* root = (this->Makefile->IsOn("CMAKE_MAKE_INCLUDE_FROM_ROOT")
  288. ? "$(CMAKE_BINARY_DIR)/"
  289. : "");
  290. // Include the dependencies for the target.
  291. std::string dependFileNameFull =
  292. cmStrCat(this->TargetBuildDirectoryFull, "/depend.make");
  293. *this->BuildFileStream
  294. << "# Include any dependencies generated for this target.\n"
  295. << this->GlobalGenerator->IncludeDirective << " " << root
  296. << cmSystemTools::ConvertToOutputPath(
  297. this->LocalGenerator->MaybeConvertToRelativePath(
  298. this->LocalGenerator->GetBinaryDirectory(), dependFileNameFull))
  299. << "\n";
  300. std::string depsUseCompiler = "CMAKE_DEPENDS_USE_COMPILER";
  301. if (!this->Makefile->IsDefinitionSet(depsUseCompiler) ||
  302. this->Makefile->IsOn(depsUseCompiler)) {
  303. std::string compilerDependFile =
  304. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.make");
  305. *this->BuildFileStream
  306. << "# Include any dependencies generated by the "
  307. "compiler for this target.\n"
  308. << this->GlobalGenerator->IncludeDirective << " " << root
  309. << cmSystemTools::ConvertToOutputPath(
  310. this->LocalGenerator->MaybeConvertToRelativePath(
  311. this->LocalGenerator->GetBinaryDirectory(), compilerDependFile))
  312. << "\n\n";
  313. // Write an empty dependency file.
  314. cmGeneratedFileStream depFileStream(
  315. compilerDependFile, false, this->GlobalGenerator->GetMakefileEncoding());
  316. depFileStream << "# Empty compiler generated dependencies file for "
  317. << this->GeneratorTarget->GetName() << ".\n"
  318. << "# This may be replaced when dependencies are built.\n";
  319. // remove internal dependency file
  320. cmSystemTools::RemoveFile(
  321. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.internal"));
  322. std::string compilerDependTimestamp =
  323. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.ts");
  324. if (!cmSystemTools::FileExists(compilerDependTimestamp)) {
  325. // Write a dependency timestamp file.
  326. cmGeneratedFileStream timestampFileStream(
  327. compilerDependTimestamp, false,
  328. this->GlobalGenerator->GetMakefileEncoding());
  329. timestampFileStream
  330. << "# CMAKE generated file: DO NOT EDIT!\n"
  331. << "# Timestamp file for compiler generated dependencies "
  332. "management for "
  333. << this->GeneratorTarget->GetName() << ".\n";
  334. }
  335. // deactivate no longer needed legacy dependency files
  336. // Write an empty dependency file.
  337. cmGeneratedFileStream legacyDepFileStream(
  338. dependFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  339. legacyDepFileStream
  340. << "# Empty dependencies file for " << this->GeneratorTarget->GetName()
  341. << ".\n"
  342. << "# This may be replaced when dependencies are built.\n";
  343. // remove internal dependency file
  344. cmSystemTools::RemoveFile(
  345. cmStrCat(this->TargetBuildDirectoryFull, "/depend.internal"));
  346. } else {
  347. // make sure the depend file exists
  348. if (!cmSystemTools::FileExists(dependFileNameFull)) {
  349. // Write an empty dependency file.
  350. cmGeneratedFileStream depFileStream(
  351. dependFileNameFull, false,
  352. this->GlobalGenerator->GetMakefileEncoding());
  353. depFileStream << "# Empty dependencies file for "
  354. << this->GeneratorTarget->GetName() << ".\n"
  355. << "# This may be replaced when dependencies are built.\n";
  356. }
  357. }
  358. if (!this->NoRuleMessages) {
  359. // Include the progress variables for the target.
  360. *this->BuildFileStream
  361. << "# Include the progress variables for this target.\n"
  362. << this->GlobalGenerator->IncludeDirective << " " << root
  363. << cmSystemTools::ConvertToOutputPath(
  364. this->LocalGenerator->MaybeConvertToRelativePath(
  365. this->LocalGenerator->GetBinaryDirectory(),
  366. this->ProgressFileNameFull))
  367. << "\n\n";
  368. }
  369. // Open the flags file. This should be copy-if-different because the
  370. // rules may depend on this file itself.
  371. this->FlagFileNameFull =
  372. cmStrCat(this->TargetBuildDirectoryFull, "/flags.make");
  373. this->FlagFileStream = cm::make_unique<cmGeneratedFileStream>(
  374. this->FlagFileNameFull, false,
  375. this->GlobalGenerator->GetMakefileEncoding());
  376. if (!this->FlagFileStream) {
  377. return;
  378. }
  379. this->FlagFileStream->SetCopyIfDifferent(true);
  380. this->LocalGenerator->WriteDisclaimer(*this->FlagFileStream);
  381. // Include the flags for the target.
  382. *this->BuildFileStream
  383. << "# Include the compile flags for this target's objects.\n"
  384. << this->GlobalGenerator->IncludeDirective << " " << root
  385. << cmSystemTools::ConvertToOutputPath(
  386. this->LocalGenerator->MaybeConvertToRelativePath(
  387. this->LocalGenerator->GetBinaryDirectory(), this->FlagFileNameFull))
  388. << "\n\n";
  389. }
  390. void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  391. {
  392. // write language flags for target
  393. std::set<std::string> languages;
  394. this->GeneratorTarget->GetLanguages(
  395. languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  396. // put the compiler in the rules.make file so that if it changes
  397. // things rebuild
  398. for (std::string const& language : languages) {
  399. std::string compiler = cmStrCat("CMAKE_", language, "_COMPILER");
  400. *this->FlagFileStream << "# compile " << language << " with "
  401. << this->Makefile->GetSafeDefinition(compiler)
  402. << "\n";
  403. }
  404. bool const escapeOctothorpe = this->GlobalGenerator->CanEscapeOctothorpe();
  405. for (std::string const& language : languages) {
  406. std::string defines = this->GetDefines(language, this->GetConfigName());
  407. std::string includes = this->GetIncludes(language, this->GetConfigName());
  408. if (escapeOctothorpe) {
  409. // Escape comment characters so they do not terminate assignment.
  410. cmSystemTools::ReplaceString(defines, "#", "\\#");
  411. cmSystemTools::ReplaceString(includes, "#", "\\#");
  412. }
  413. *this->FlagFileStream << language << "_DEFINES = " << defines << "\n\n";
  414. *this->FlagFileStream << language << "_INCLUDES = " << includes << "\n\n";
  415. std::vector<std::string> architectures;
  416. this->GeneratorTarget->GetAppleArchs(this->GetConfigName(), architectures);
  417. architectures.emplace_back();
  418. for (const std::string& arch : architectures) {
  419. std::string flags =
  420. this->GetFlags(language, this->GetConfigName(), arch);
  421. if (escapeOctothorpe) {
  422. cmSystemTools::ReplaceString(flags, "#", "\\#");
  423. }
  424. *this->FlagFileStream << language << "_FLAGS" << arch << " = " << flags
  425. << "\n\n";
  426. }
  427. }
  428. }
  429. void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()(
  430. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  431. {
  432. // Skip OS X content when not building a Framework or Bundle.
  433. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  434. return;
  435. }
  436. std::string macdir =
  437. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  438. config);
  439. // Get the input file location.
  440. std::string const& input = source.GetFullPath();
  441. // Get the output file location.
  442. std::string output =
  443. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  444. this->Generator->CleanFiles.insert(
  445. this->Generator->LocalGenerator->MaybeConvertToRelativePath(
  446. this->Generator->LocalGenerator->GetCurrentBinaryDirectory(), output));
  447. output = this->Generator->LocalGenerator->MaybeConvertToRelativePath(
  448. this->Generator->LocalGenerator->GetBinaryDirectory(), output);
  449. // Create a rule to copy the content into the bundle.
  450. std::vector<std::string> depends;
  451. std::vector<std::string> commands;
  452. depends.push_back(input);
  453. std::string copyEcho = cmStrCat("Copying OS X content ", output);
  454. this->Generator->LocalGenerator->AppendEcho(
  455. commands, copyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  456. std::string copyCommand =
  457. cmStrCat("$(CMAKE_COMMAND) -E copy ",
  458. this->Generator->LocalGenerator->ConvertToOutputFormat(
  459. input, cmOutputConverter::SHELL),
  460. ' ',
  461. this->Generator->LocalGenerator->ConvertToOutputFormat(
  462. output, cmOutputConverter::SHELL));
  463. commands.push_back(std::move(copyCommand));
  464. this->Generator->LocalGenerator->WriteMakeRule(
  465. *this->Generator->BuildFileStream, nullptr, output, depends, commands,
  466. false);
  467. this->Generator->ExtraFiles.insert(output);
  468. }
  469. void cmMakefileTargetGenerator::WriteObjectRuleFiles(
  470. cmSourceFile const& source)
  471. {
  472. // Identify the language of the source file.
  473. const std::string& lang =
  474. this->LocalGenerator->GetSourceFileLanguage(source);
  475. if (lang.empty()) {
  476. // don't know anything about this file so skip it
  477. return;
  478. }
  479. // Use compiler to generate dependencies, if supported.
  480. bool compilerGenerateDeps =
  481. this->GlobalGenerator->SupportsCompilerDependencies() &&
  482. cmIsOn(this->Makefile->GetDefinition(
  483. cmStrCat("CMAKE_", lang, "_DEPENDS_USE_COMPILER")));
  484. auto scanner = compilerGenerateDeps ? cmDependencyScannerKind::Compiler
  485. : cmDependencyScannerKind::CMake;
  486. // Get the full path name of the object file.
  487. std::string const& objectName =
  488. this->GeneratorTarget->GetObjectName(&source);
  489. std::string obj =
  490. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  491. '/', objectName);
  492. // Avoid generating duplicate rules.
  493. if (this->ObjectFiles.find(obj) == this->ObjectFiles.end()) {
  494. this->ObjectFiles.insert(obj);
  495. } else {
  496. std::ostringstream err;
  497. err << "Warning: Source file \"" << source.GetFullPath()
  498. << "\" is listed multiple times for target \""
  499. << this->GeneratorTarget->GetName() << "\".";
  500. cmSystemTools::Message(err.str(), "Warning");
  501. return;
  502. }
  503. // Create the directory containing the object file. This may be a
  504. // subdirectory under the target's directory.
  505. {
  506. std::string dir = cmSystemTools::GetFilenamePath(obj);
  507. cmSystemTools::MakeDirectory(this->LocalGenerator->ConvertToFullPath(dir));
  508. }
  509. // Save this in the target's list of object files.
  510. this->Objects.push_back(obj);
  511. this->CleanFiles.insert(obj);
  512. std::vector<std::string> depends;
  513. // The object file should be checked for dependency integrity.
  514. std::string objFullPath =
  515. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', obj);
  516. objFullPath = cmSystemTools::CollapseFullPath(objFullPath);
  517. std::string srcFullPath =
  518. cmSystemTools::CollapseFullPath(source.GetFullPath());
  519. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, lang,
  520. objFullPath, srcFullPath, scanner);
  521. this->LocalGenerator->AppendRuleDepend(depends,
  522. this->FlagFileNameFull.c_str());
  523. this->LocalGenerator->AppendRuleDepends(depends,
  524. this->FlagFileDepends[lang]);
  525. // generate the depend scanning rule
  526. this->WriteObjectDependRules(source, depends);
  527. std::string config = this->GetConfigName();
  528. std::string configUpper = cmSystemTools::UpperCase(config);
  529. // Add precompile headers dependencies
  530. std::vector<std::string> architectures;
  531. this->GeneratorTarget->GetAppleArchs(config, architectures);
  532. if (architectures.empty()) {
  533. architectures.emplace_back();
  534. }
  535. std::string filterArch;
  536. std::unordered_map<std::string, std::string> pchSources;
  537. for (const std::string& arch : architectures) {
  538. const std::string pchSource =
  539. this->GeneratorTarget->GetPchSource(config, lang, arch);
  540. if (pchSource == source.GetFullPath()) {
  541. filterArch = arch;
  542. }
  543. if (!pchSource.empty()) {
  544. pchSources.insert(std::make_pair(pchSource, arch));
  545. }
  546. }
  547. if (!pchSources.empty() && !source.GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  548. for (const std::string& arch : architectures) {
  549. std::string const& pchHeader =
  550. this->GeneratorTarget->GetPchHeader(config, lang, arch);
  551. depends.push_back(pchHeader);
  552. if (pchSources.find(source.GetFullPath()) == pchSources.end()) {
  553. depends.push_back(
  554. this->GeneratorTarget->GetPchFile(config, lang, arch));
  555. }
  556. this->LocalGenerator->AddImplicitDepends(
  557. this->GeneratorTarget, lang, objFullPath, pchHeader, scanner);
  558. }
  559. }
  560. if (lang != "ISPC") {
  561. auto const& headers =
  562. this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  563. if (!headers.empty()) {
  564. depends.insert(depends.end(), headers.begin(), headers.end());
  565. }
  566. }
  567. std::string relativeObj =
  568. cmStrCat(this->LocalGenerator->GetHomeRelativeOutputPath(), obj);
  569. // Write the build rule.
  570. // Build the set of compiler flags.
  571. std::string flags;
  572. // Explicitly add the explicit language flag before any other flag
  573. // so user flags can override it.
  574. this->GeneratorTarget->AddExplicitLanguageFlags(flags, source);
  575. // Add language-specific flags.
  576. std::string langFlags = cmStrCat("$(", lang, "_FLAGS", filterArch, ")");
  577. this->LocalGenerator->AppendFlags(flags, langFlags);
  578. cmGeneratorExpressionInterpreter genexInterpreter(
  579. this->LocalGenerator, config, this->GeneratorTarget, lang);
  580. // Add Fortran format flags.
  581. if (lang == "Fortran") {
  582. this->AppendFortranFormatFlags(flags, source);
  583. this->AppendFortranPreprocessFlags(flags, source);
  584. }
  585. std::string ispcHeaderRelative;
  586. std::string ispcHeaderForShell;
  587. if (lang == "ISPC") {
  588. std::string ispcSource =
  589. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  590. ispcSource = cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  591. cmProp ispcSuffixProp =
  592. this->GeneratorTarget->GetProperty("ISPC_HEADER_SUFFIX");
  593. assert(ispcSuffixProp);
  594. std::string directory = this->GeneratorTarget->GetObjectDirectory(config);
  595. if (cmProp prop =
  596. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  597. directory =
  598. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', *prop);
  599. }
  600. ispcHeaderRelative = cmStrCat(directory, '/', ispcSource, *ispcSuffixProp);
  601. ispcHeaderForShell = this->LocalGenerator->ConvertToOutputFormat(
  602. ispcHeaderRelative, cmOutputConverter::SHELL);
  603. }
  604. // Add flags from source file properties.
  605. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  606. if (cmProp cflags = source.GetProperty(COMPILE_FLAGS)) {
  607. const std::string& evaluatedFlags =
  608. genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS);
  609. this->LocalGenerator->AppendFlags(flags, evaluatedFlags);
  610. *this->FlagFileStream << "# Custom flags: " << relativeObj
  611. << "_FLAGS = " << evaluatedFlags << "\n"
  612. << "\n";
  613. }
  614. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  615. if (cmProp coptions = source.GetProperty(COMPILE_OPTIONS)) {
  616. const std::string& evaluatedOptions =
  617. genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS);
  618. this->LocalGenerator->AppendCompileOptions(flags, evaluatedOptions);
  619. *this->FlagFileStream << "# Custom options: " << relativeObj
  620. << "_OPTIONS = " << evaluatedOptions << "\n"
  621. << "\n";
  622. }
  623. // Add precompile headers compile options.
  624. if (!pchSources.empty() && !source.GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  625. std::string pchOptions;
  626. auto pchIt = pchSources.find(source.GetFullPath());
  627. if (pchIt != pchSources.end()) {
  628. pchOptions = this->GeneratorTarget->GetPchCreateCompileOptions(
  629. config, lang, pchIt->second);
  630. } else {
  631. pchOptions =
  632. this->GeneratorTarget->GetPchUseCompileOptions(config, lang);
  633. }
  634. const std::string& evaluatedFlags =
  635. genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS);
  636. this->LocalGenerator->AppendCompileOptions(flags, evaluatedFlags);
  637. *this->FlagFileStream << "# PCH options: " << relativeObj
  638. << "_OPTIONS = " << evaluatedFlags << "\n"
  639. << "\n";
  640. }
  641. // Add include directories from source file properties.
  642. std::vector<std::string> includes;
  643. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  644. if (cmProp cincludes = source.GetProperty(INCLUDE_DIRECTORIES)) {
  645. const std::string& evaluatedIncludes =
  646. genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES);
  647. this->LocalGenerator->AppendIncludeDirectories(includes, evaluatedIncludes,
  648. source);
  649. *this->FlagFileStream << "# Custom include directories: " << relativeObj
  650. << "_INCLUDE_DIRECTORIES = " << evaluatedIncludes
  651. << "\n"
  652. << "\n";
  653. }
  654. // Add language-specific defines.
  655. std::set<std::string> defines;
  656. // Add source-specific preprocessor definitions.
  657. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  658. if (cmProp compile_defs = source.GetProperty(COMPILE_DEFINITIONS)) {
  659. const std::string& evaluatedDefs =
  660. genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS);
  661. this->LocalGenerator->AppendDefines(defines, evaluatedDefs);
  662. *this->FlagFileStream << "# Custom defines: " << relativeObj
  663. << "_DEFINES = " << evaluatedDefs << "\n"
  664. << "\n";
  665. }
  666. std::string defPropName = cmStrCat("COMPILE_DEFINITIONS_", configUpper);
  667. if (cmProp config_compile_defs = source.GetProperty(defPropName)) {
  668. const std::string& evaluatedDefs =
  669. genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS);
  670. this->LocalGenerator->AppendDefines(defines, evaluatedDefs);
  671. *this->FlagFileStream << "# Custom defines: " << relativeObj << "_DEFINES_"
  672. << configUpper << " = " << evaluatedDefs << "\n"
  673. << "\n";
  674. }
  675. // Get the output paths for source and object files.
  676. std::string sourceFile = this->LocalGenerator->ConvertToOutputFormat(
  677. source.GetFullPath(), cmOutputConverter::SHELL);
  678. // Construct the build message.
  679. std::vector<std::string> no_depends;
  680. std::vector<std::string> commands;
  681. // add in a progress call if needed
  682. this->NumberOfProgressActions++;
  683. if (!this->NoRuleMessages) {
  684. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  685. this->MakeEchoProgress(progress);
  686. std::string buildEcho =
  687. cmStrCat("Building ", lang, " object ", relativeObj);
  688. this->LocalGenerator->AppendEcho(commands, buildEcho,
  689. cmLocalUnixMakefileGenerator3::EchoBuild,
  690. &progress);
  691. }
  692. std::string targetOutPathReal;
  693. std::string targetOutPathPDB;
  694. std::string targetOutPathCompilePDB;
  695. {
  696. std::string targetFullPathReal;
  697. std::string targetFullPathPDB;
  698. std::string targetFullPathCompilePDB =
  699. this->ComputeTargetCompilePDB(this->GetConfigName());
  700. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  701. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  702. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  703. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  704. targetFullPathReal = this->GeneratorTarget->GetFullPath(
  705. this->GetConfigName(), cmStateEnums::RuntimeBinaryArtifact, true);
  706. targetFullPathPDB = cmStrCat(
  707. this->GeneratorTarget->GetPDBDirectory(this->GetConfigName()), '/',
  708. this->GeneratorTarget->GetPDBName(this->GetConfigName()));
  709. }
  710. targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
  711. this->LocalGenerator->MaybeConvertToRelativePath(
  712. this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
  713. cmOutputConverter::SHELL);
  714. targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
  715. targetFullPathPDB, cmOutputConverter::SHELL);
  716. targetOutPathCompilePDB = this->LocalGenerator->ConvertToOutputFormat(
  717. this->LocalGenerator->MaybeConvertToRelativePath(
  718. this->LocalGenerator->GetCurrentBinaryDirectory(),
  719. targetFullPathCompilePDB),
  720. cmOutputConverter::SHELL);
  721. if (this->LocalGenerator->IsMinGWMake() &&
  722. cmHasLiteralSuffix(targetOutPathCompilePDB, "\\")) {
  723. // mingw32-make incorrectly interprets 'a\ b c' as 'a b' and 'c'
  724. // (but 'a\ b "c"' as 'a\', 'b', and 'c'!). Workaround this by
  725. // avoiding a trailing backslash in the argument.
  726. targetOutPathCompilePDB.back() = '/';
  727. }
  728. std::string compilePdbOutputPath =
  729. this->GeneratorTarget->GetCompilePDBDirectory(this->GetConfigName());
  730. cmSystemTools::MakeDirectory(compilePdbOutputPath);
  731. }
  732. cmRulePlaceholderExpander::RuleVariables vars;
  733. vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
  734. vars.CMTargetType =
  735. cmState::GetTargetTypeName(this->GeneratorTarget->GetType()).c_str();
  736. vars.Language = lang.c_str();
  737. vars.Target = targetOutPathReal.c_str();
  738. vars.TargetPDB = targetOutPathPDB.c_str();
  739. vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
  740. vars.Source = sourceFile.c_str();
  741. std::string shellObj =
  742. this->LocalGenerator->ConvertToOutputFormat(obj, cmOutputConverter::SHELL);
  743. vars.Object = shellObj.c_str();
  744. std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
  745. objectDir = this->LocalGenerator->ConvertToOutputFormat(
  746. this->LocalGenerator->MaybeConvertToRelativePath(
  747. this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
  748. cmOutputConverter::SHELL);
  749. vars.ObjectDir = objectDir.c_str();
  750. std::string objectFileDir = cmSystemTools::GetFilenamePath(obj);
  751. objectFileDir = this->LocalGenerator->ConvertToOutputFormat(
  752. this->LocalGenerator->MaybeConvertToRelativePath(
  753. this->LocalGenerator->GetCurrentBinaryDirectory(), objectFileDir),
  754. cmOutputConverter::SHELL);
  755. vars.ObjectFileDir = objectFileDir.c_str();
  756. vars.Flags = flags.c_str();
  757. vars.ISPCHeader = ispcHeaderForShell.c_str();
  758. std::string definesString = cmStrCat("$(", lang, "_DEFINES)");
  759. this->LocalGenerator->JoinDefines(defines, definesString, lang);
  760. vars.Defines = definesString.c_str();
  761. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  762. includes, this->GeneratorTarget, lang, config);
  763. this->LocalGenerator->AppendFlags(includesString,
  764. "$(" + lang + "_INCLUDES)");
  765. vars.Includes = includesString.c_str();
  766. std::string dependencyTarget;
  767. std::string shellDependencyFile;
  768. std::string dependencyTimestamp;
  769. if (compilerGenerateDeps) {
  770. dependencyTarget = this->LocalGenerator->EscapeForShell(
  771. this->LocalGenerator->ConvertToMakefilePath(
  772. this->LocalGenerator->MaybeConvertToRelativePath(
  773. this->LocalGenerator->GetBinaryDirectory(), relativeObj)));
  774. vars.DependencyTarget = dependencyTarget.c_str();
  775. auto depFile = cmStrCat(obj, ".d");
  776. shellDependencyFile = this->LocalGenerator->ConvertToOutputFormat(
  777. depFile, cmOutputConverter::SHELL);
  778. vars.DependencyFile = shellDependencyFile.c_str();
  779. this->CleanFiles.insert(depFile);
  780. dependencyTimestamp = this->LocalGenerator->MaybeConvertToRelativePath(
  781. this->LocalGenerator->GetBinaryDirectory(),
  782. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.ts"));
  783. }
  784. // At the moment, it is assumed that C, C++, Fortran, and CUDA have both
  785. // assembly and preprocessor capabilities. The same is true for the
  786. // ability to export compile commands
  787. bool lang_has_preprocessor =
  788. ((lang == "C") || (lang == "CXX") || (lang == "OBJC") ||
  789. (lang == "OBJCXX") || (lang == "Fortran") || (lang == "CUDA") ||
  790. lang == "ISPC" || lang == "ASM");
  791. bool const lang_has_assembly = lang_has_preprocessor;
  792. bool const lang_can_export_cmds = lang_has_preprocessor;
  793. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  794. this->LocalGenerator->CreateRulePlaceholderExpander());
  795. // Construct the compile rules.
  796. {
  797. std::vector<std::string> compileCommands;
  798. if (lang == "CUDA") {
  799. std::string cmdVar;
  800. if (this->GeneratorTarget->GetPropertyAsBool(
  801. "CUDA_SEPARABLE_COMPILATION")) {
  802. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  803. } else if (this->GeneratorTarget->GetPropertyAsBool(
  804. "CUDA_PTX_COMPILATION")) {
  805. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  806. } else {
  807. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  808. }
  809. const std::string& compileRule =
  810. this->Makefile->GetRequiredDefinition(cmdVar);
  811. cmExpandList(compileRule, compileCommands);
  812. } else {
  813. const std::string cmdVar = "CMAKE_" + lang + "_COMPILE_OBJECT";
  814. const std::string& compileRule =
  815. this->Makefile->GetRequiredDefinition(cmdVar);
  816. cmExpandList(compileRule, compileCommands);
  817. }
  818. if (this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS") &&
  819. lang_can_export_cmds && compileCommands.size() == 1) {
  820. std::string compileCommand = compileCommands[0];
  821. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  822. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  823. compileCommand, vars);
  824. std::string workingDirectory =
  825. this->LocalGenerator->GetCurrentBinaryDirectory();
  826. compileCommand.replace(compileCommand.find(langFlags), langFlags.size(),
  827. this->GetFlags(lang, this->GetConfigName()));
  828. std::string langDefines = std::string("$(") + lang + "_DEFINES)";
  829. std::string::size_type ldPos = compileCommand.find(langDefines);
  830. if (ldPos != std::string::npos) {
  831. compileCommand.replace(ldPos, langDefines.size(),
  832. this->GetDefines(lang, this->GetConfigName()));
  833. }
  834. std::string langIncludes = std::string("$(") + lang + "_INCLUDES)";
  835. std::string::size_type liPos = compileCommand.find(langIncludes);
  836. if (liPos != std::string::npos) {
  837. compileCommand.replace(liPos, langIncludes.size(),
  838. this->GetIncludes(lang, this->GetConfigName()));
  839. }
  840. cmProp eliminate[] = {
  841. this->Makefile->GetDefinition("CMAKE_START_TEMP_FILE"),
  842. this->Makefile->GetDefinition("CMAKE_END_TEMP_FILE")
  843. };
  844. for (cmProp el : eliminate) {
  845. if (el) {
  846. cmSystemTools::ReplaceString(compileCommand, *el, "");
  847. }
  848. }
  849. this->GlobalGenerator->AddCXXCompileCommand(
  850. source.GetFullPath(), workingDirectory, compileCommand);
  851. }
  852. // See if we need to use a compiler launcher like ccache or distcc
  853. std::string compilerLauncher;
  854. if (!compileCommands.empty() &&
  855. (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA" ||
  856. lang == "ISPC" || lang == "OBJC" || lang == "OBJCXX")) {
  857. std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
  858. cmProp clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
  859. if (cmNonempty(clauncher)) {
  860. compilerLauncher = *clauncher;
  861. }
  862. }
  863. // Maybe insert an include-what-you-use runner.
  864. if (!compileCommands.empty() &&
  865. (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX")) {
  866. std::string const tidy_prop = lang + "_CLANG_TIDY";
  867. cmProp tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  868. cmProp iwyu = nullptr;
  869. cmProp cpplint = nullptr;
  870. cmProp cppcheck = nullptr;
  871. if (lang == "C" || lang == "CXX") {
  872. std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE";
  873. iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  874. std::string const cpplint_prop = lang + "_CPPLINT";
  875. cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  876. std::string const cppcheck_prop = lang + "_CPPCHECK";
  877. cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  878. }
  879. if (cmNonempty(iwyu) || cmNonempty(tidy) || cmNonempty(cpplint) ||
  880. cmNonempty(cppcheck)) {
  881. std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_co_compile";
  882. if (!compilerLauncher.empty()) {
  883. // In __run_co_compile case the launcher command is supplied
  884. // via --launcher=<maybe-list> and consumed
  885. run_iwyu += " --launcher=";
  886. run_iwyu += this->LocalGenerator->EscapeForShell(compilerLauncher);
  887. compilerLauncher.clear();
  888. }
  889. if (cmNonempty(iwyu)) {
  890. run_iwyu += " --iwyu=";
  891. run_iwyu += this->LocalGenerator->EscapeForShell(*iwyu);
  892. }
  893. if (cmNonempty(tidy)) {
  894. run_iwyu += " --tidy=";
  895. cmProp p = this->Makefile->GetDefinition("CMAKE_" + lang +
  896. "_CLANG_TIDY_DRIVER_MODE");
  897. std::string driverMode;
  898. if (cmNonempty(p)) {
  899. driverMode = *p;
  900. } else {
  901. driverMode = lang == "C" ? "gcc" : "g++";
  902. }
  903. run_iwyu += this->LocalGenerator->EscapeForShell(
  904. cmStrCat(*tidy, ";--extra-arg-before=--driver-mode=", driverMode));
  905. }
  906. if (cmNonempty(cpplint)) {
  907. run_iwyu += " --cpplint=";
  908. run_iwyu += this->LocalGenerator->EscapeForShell(*cpplint);
  909. }
  910. if (cmNonempty(cppcheck)) {
  911. run_iwyu += " --cppcheck=";
  912. run_iwyu += this->LocalGenerator->EscapeForShell(*cppcheck);
  913. }
  914. if (cmNonempty(tidy) || (cmNonempty(cpplint)) ||
  915. (cmNonempty(cppcheck))) {
  916. run_iwyu += " --source=";
  917. run_iwyu += sourceFile;
  918. }
  919. run_iwyu += " -- ";
  920. compileCommands.front().insert(0, run_iwyu);
  921. }
  922. }
  923. // If compiler launcher was specified and not consumed above, it
  924. // goes to the beginning of the command line.
  925. if (!compileCommands.empty() && !compilerLauncher.empty()) {
  926. std::vector<std::string> args = cmExpandedList(compilerLauncher, true);
  927. if (!args.empty()) {
  928. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  929. args[0], cmOutputConverter::SHELL);
  930. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  931. i = this->LocalGenerator->EscapeForShell(i);
  932. }
  933. }
  934. compileCommands.front().insert(0, cmJoin(args, " ") + " ");
  935. }
  936. std::string launcher;
  937. {
  938. cmProp val = this->LocalGenerator->GetRuleLauncher(
  939. this->GeneratorTarget, "RULE_LAUNCH_COMPILE");
  940. if (cmNonempty(val)) {
  941. launcher = cmStrCat(*val, ' ');
  942. }
  943. }
  944. std::string flagsWithDeps(flags);
  945. if (compilerGenerateDeps) {
  946. // Injects dependency computation
  947. auto depFlags = this->Makefile->GetSafeDefinition(
  948. cmStrCat("CMAKE_DEPFILE_FLAGS_", lang));
  949. if (!depFlags.empty()) {
  950. // Add dependency flags
  951. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  952. depFlags, vars);
  953. flagsWithDeps.append(1, ' ');
  954. flagsWithDeps.append(depFlags);
  955. }
  956. vars.Flags = flagsWithDeps.c_str();
  957. const auto& extraCommands = this->Makefile->GetSafeDefinition(
  958. cmStrCat("CMAKE_", lang, "_DEPENDS_EXTRA_COMMANDS"));
  959. if (!extraCommands.empty()) {
  960. auto commandList = cmExpandedList(extraCommands);
  961. compileCommands.insert(compileCommands.end(), commandList.cbegin(),
  962. commandList.cend());
  963. }
  964. const auto& depFormat = this->Makefile->GetRequiredDefinition(
  965. cmStrCat("CMAKE_", lang, "_DEPFILE_FORMAT"));
  966. if (depFormat == "msvc"_s) {
  967. // compiler must be launched through a wrapper to pick-up dependencies
  968. std::string depFilter =
  969. "$(CMAKE_COMMAND) -E cmake_cl_compile_depends ";
  970. depFilter += cmStrCat("--dep-file=", shellDependencyFile);
  971. depFilter +=
  972. cmStrCat(" --working-dir=",
  973. this->LocalGenerator->ConvertToOutputFormat(
  974. this->LocalGenerator->GetCurrentBinaryDirectory(),
  975. cmOutputConverter::SHELL));
  976. const auto& prefix = this->Makefile->GetSafeDefinition(
  977. cmStrCat("CMAKE_", lang, "_CL_SHOWINCLUDES_PREFIX"));
  978. depFilter += cmStrCat(" --filter-prefix=",
  979. this->LocalGenerator->ConvertToOutputFormat(
  980. prefix, cmOutputConverter::SHELL));
  981. depFilter += " -- ";
  982. compileCommands.front().insert(0, depFilter);
  983. }
  984. }
  985. // Expand placeholders in the commands.
  986. for (std::string& compileCommand : compileCommands) {
  987. compileCommand = cmStrCat(launcher, compileCommand);
  988. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  989. compileCommand, vars);
  990. }
  991. // Change the command working directory to the local build tree.
  992. this->LocalGenerator->CreateCDCommand(
  993. compileCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  994. this->LocalGenerator->GetBinaryDirectory());
  995. cm::append(commands, compileCommands);
  996. }
  997. // Check for extra outputs created by the compilation.
  998. std::vector<std::string> outputs(1, relativeObj);
  999. if (cmProp extra_outputs_str = source.GetProperty("OBJECT_OUTPUTS")) {
  1000. std::string evaluated_outputs = cmGeneratorExpression::Evaluate(
  1001. *extra_outputs_str, this->LocalGenerator, config);
  1002. if (!evaluated_outputs.empty()) {
  1003. // Register these as extra files to clean.
  1004. cmExpandList(evaluated_outputs, outputs);
  1005. }
  1006. }
  1007. if (!ispcHeaderRelative.empty()) {
  1008. // can't move ispcHeader as vars is using it
  1009. outputs.emplace_back(ispcHeaderRelative);
  1010. }
  1011. if (outputs.size() > 1) {
  1012. this->CleanFiles.insert(outputs.begin() + 1, outputs.end());
  1013. }
  1014. if (compilerGenerateDeps) {
  1015. depends.push_back(dependencyTimestamp);
  1016. }
  1017. // Write the rule.
  1018. this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
  1019. commands);
  1020. if (compilerGenerateDeps) {
  1021. // set back flags without dependency generation
  1022. vars.Flags = flags.c_str();
  1023. }
  1024. bool do_preprocess_rules = lang_has_preprocessor &&
  1025. this->LocalGenerator->GetCreatePreprocessedSourceRules();
  1026. bool do_assembly_rules =
  1027. lang_has_assembly && this->LocalGenerator->GetCreateAssemblySourceRules();
  1028. if (do_preprocess_rules || do_assembly_rules) {
  1029. std::vector<std::string> force_depends;
  1030. force_depends.emplace_back("cmake_force");
  1031. std::string::size_type dot_pos = relativeObj.rfind('.');
  1032. std::string relativeObjBase = relativeObj.substr(0, dot_pos);
  1033. dot_pos = obj.rfind('.');
  1034. std::string objBase = obj.substr(0, dot_pos);
  1035. if (do_preprocess_rules) {
  1036. commands.clear();
  1037. std::string relativeObjI = relativeObjBase + ".i";
  1038. std::string objI = objBase + ".i";
  1039. std::string preprocessEcho =
  1040. cmStrCat("Preprocessing ", lang, " source to ", objI);
  1041. this->LocalGenerator->AppendEcho(
  1042. commands, preprocessEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  1043. std::string preprocessRuleVar =
  1044. cmStrCat("CMAKE_", lang, "_CREATE_PREPROCESSED_SOURCE");
  1045. if (cmProp preprocessRule =
  1046. this->Makefile->GetDefinition(preprocessRuleVar)) {
  1047. std::vector<std::string> preprocessCommands =
  1048. cmExpandedList(*preprocessRule);
  1049. std::string shellObjI = this->LocalGenerator->ConvertToOutputFormat(
  1050. objI, cmOutputConverter::SHELL);
  1051. vars.PreprocessedSource = shellObjI.c_str();
  1052. // Expand placeholders in the commands.
  1053. for (std::string& preprocessCommand : preprocessCommands) {
  1054. // no launcher for preprocessor commands
  1055. rulePlaceholderExpander->ExpandRuleVariables(
  1056. this->LocalGenerator, preprocessCommand, vars);
  1057. }
  1058. this->LocalGenerator->CreateCDCommand(
  1059. preprocessCommands,
  1060. this->LocalGenerator->GetCurrentBinaryDirectory(),
  1061. this->LocalGenerator->GetBinaryDirectory());
  1062. cm::append(commands, preprocessCommands);
  1063. } else {
  1064. std::string cmd =
  1065. cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ",
  1066. preprocessRuleVar);
  1067. commands.push_back(std::move(cmd));
  1068. }
  1069. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1070. relativeObjI, force_depends,
  1071. commands, false);
  1072. }
  1073. if (do_assembly_rules) {
  1074. commands.clear();
  1075. std::string relativeObjS = relativeObjBase + ".s";
  1076. std::string objS = objBase + ".s";
  1077. std::string assemblyEcho =
  1078. cmStrCat("Compiling ", lang, " source to assembly ", objS);
  1079. this->LocalGenerator->AppendEcho(
  1080. commands, assemblyEcho, cmLocalUnixMakefileGenerator3::EchoBuild);
  1081. std::string assemblyRuleVar =
  1082. cmStrCat("CMAKE_", lang, "_CREATE_ASSEMBLY_SOURCE");
  1083. if (cmProp assemblyRule =
  1084. this->Makefile->GetDefinition(assemblyRuleVar)) {
  1085. std::vector<std::string> assemblyCommands =
  1086. cmExpandedList(*assemblyRule);
  1087. std::string shellObjS = this->LocalGenerator->ConvertToOutputFormat(
  1088. objS, cmOutputConverter::SHELL);
  1089. vars.AssemblySource = shellObjS.c_str();
  1090. // Expand placeholders in the commands.
  1091. for (std::string& assemblyCommand : assemblyCommands) {
  1092. // no launcher for assembly commands
  1093. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  1094. assemblyCommand, vars);
  1095. }
  1096. this->LocalGenerator->CreateCDCommand(
  1097. assemblyCommands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  1098. this->LocalGenerator->GetBinaryDirectory());
  1099. cm::append(commands, assemblyCommands);
  1100. } else {
  1101. std::string cmd =
  1102. cmStrCat("$(CMAKE_COMMAND) -E cmake_unimplemented_variable ",
  1103. assemblyRuleVar);
  1104. commands.push_back(std::move(cmd));
  1105. }
  1106. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1107. relativeObjS, force_depends,
  1108. commands, false);
  1109. }
  1110. }
  1111. }
  1112. void cmMakefileTargetGenerator::WriteTargetCleanRules()
  1113. {
  1114. std::vector<std::string> depends;
  1115. std::vector<std::string> commands;
  1116. // Construct the clean target name.
  1117. std::string cleanTarget = cmStrCat(
  1118. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  1119. "/clean");
  1120. // Construct the clean command.
  1121. this->LocalGenerator->AppendCleanCommand(commands, this->CleanFiles,
  1122. this->GeneratorTarget);
  1123. this->LocalGenerator->CreateCDCommand(
  1124. commands, this->LocalGenerator->GetCurrentBinaryDirectory(),
  1125. this->LocalGenerator->GetBinaryDirectory());
  1126. // Write the rule.
  1127. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1128. cleanTarget, depends, commands, true);
  1129. }
  1130. bool cmMakefileTargetGenerator::WriteMakeRule(
  1131. std::ostream& os, const char* comment,
  1132. const std::vector<std::string>& outputs,
  1133. const std::vector<std::string>& depends,
  1134. const std::vector<std::string>& commands, bool in_help)
  1135. {
  1136. bool symbolic = false;
  1137. if (outputs.empty()) {
  1138. return symbolic;
  1139. }
  1140. // Check whether we need to bother checking for a symbolic output.
  1141. bool need_symbolic = this->GlobalGenerator->GetNeedSymbolicMark();
  1142. // Check whether the first output is marked as symbolic.
  1143. if (need_symbolic) {
  1144. if (cmSourceFile* sf = this->Makefile->GetSource(outputs[0])) {
  1145. symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  1146. }
  1147. }
  1148. // We always attach the actual commands to the first output.
  1149. this->LocalGenerator->WriteMakeRule(os, comment, outputs[0], depends,
  1150. commands, symbolic, in_help);
  1151. // For single outputs, we are done.
  1152. if (outputs.size() == 1) {
  1153. return symbolic;
  1154. }
  1155. // For multiple outputs, make the extra ones depend on the first one.
  1156. std::vector<std::string> const output_depends(1, outputs[0]);
  1157. std::string binDir = this->LocalGenerator->GetBinaryDirectory();
  1158. for (std::string const& output : cmMakeRange(outputs).advance(1)) {
  1159. // Touch the extra output so "make" knows that it was updated,
  1160. // but only if the output was actually created.
  1161. std::string const out = this->LocalGenerator->ConvertToOutputFormat(
  1162. this->LocalGenerator->MaybeConvertToRelativePath(binDir, output),
  1163. cmOutputConverter::SHELL);
  1164. std::vector<std::string> output_commands;
  1165. bool o_symbolic = false;
  1166. if (need_symbolic) {
  1167. if (cmSourceFile* sf = this->Makefile->GetSource(output)) {
  1168. o_symbolic = sf->GetPropertyAsBool("SYMBOLIC");
  1169. }
  1170. }
  1171. symbolic = symbolic && o_symbolic;
  1172. if (!o_symbolic) {
  1173. output_commands.push_back("@$(CMAKE_COMMAND) -E touch_nocreate " + out);
  1174. }
  1175. this->LocalGenerator->WriteMakeRule(os, nullptr, output, output_depends,
  1176. output_commands, o_symbolic, in_help);
  1177. if (!o_symbolic) {
  1178. // At build time, remove the first output if this one does not exist
  1179. // so that "make" will rerun the real commands that create this one.
  1180. MultipleOutputPairsType::value_type p(output, outputs[0]);
  1181. this->MultipleOutputPairs.insert(p);
  1182. }
  1183. }
  1184. return symbolic;
  1185. }
  1186. void cmMakefileTargetGenerator::WriteTargetDependRules()
  1187. {
  1188. // must write the targets depend info file
  1189. std::string dir =
  1190. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  1191. this->InfoFileNameFull = cmStrCat(dir, "/DependInfo.cmake");
  1192. this->InfoFileNameFull =
  1193. this->LocalGenerator->ConvertToFullPath(this->InfoFileNameFull);
  1194. this->InfoFileStream =
  1195. cm::make_unique<cmGeneratedFileStream>(this->InfoFileNameFull);
  1196. if (!this->InfoFileStream) {
  1197. return;
  1198. }
  1199. this->InfoFileStream->SetCopyIfDifferent(true);
  1200. this->LocalGenerator->WriteDependLanguageInfo(*this->InfoFileStream,
  1201. this->GeneratorTarget);
  1202. // Store multiple output pairs in the depend info file.
  1203. if (!this->MultipleOutputPairs.empty()) {
  1204. /* clang-format off */
  1205. *this->InfoFileStream
  1206. << "\n"
  1207. << "# Pairs of files generated by the same build rule.\n"
  1208. << "set(CMAKE_MULTIPLE_OUTPUT_PAIRS\n";
  1209. /* clang-format on */
  1210. for (auto const& pi : this->MultipleOutputPairs) {
  1211. *this->InfoFileStream
  1212. << " " << cmOutputConverter::EscapeForCMake(pi.first) << " "
  1213. << cmOutputConverter::EscapeForCMake(pi.second) << "\n";
  1214. }
  1215. *this->InfoFileStream << " )\n\n";
  1216. }
  1217. // Store list of targets linked directly or transitively.
  1218. {
  1219. /* clang-format off */
  1220. *this->InfoFileStream
  1221. << "\n"
  1222. << "# Targets to which this target links.\n"
  1223. << "set(CMAKE_TARGET_LINKED_INFO_FILES\n";
  1224. /* clang-format on */
  1225. std::vector<std::string> dirs =
  1226. this->GetLinkedTargetDirectories(this->GetConfigName());
  1227. for (std::string const& d : dirs) {
  1228. *this->InfoFileStream << " \"" << d << "/DependInfo.cmake\"\n";
  1229. }
  1230. *this->InfoFileStream << " )\n";
  1231. }
  1232. std::string const& working_dir =
  1233. this->LocalGenerator->GetCurrentBinaryDirectory();
  1234. /* clang-format off */
  1235. *this->InfoFileStream
  1236. << "\n"
  1237. << "# Fortran module output directory.\n"
  1238. << "set(CMAKE_Fortran_TARGET_MODULE_DIR \""
  1239. << this->GeneratorTarget->GetFortranModuleDirectory(working_dir)
  1240. << "\")\n";
  1241. /* clang-format on */
  1242. // and now write the rule to use it
  1243. std::vector<std::string> depends;
  1244. std::vector<std::string> commands;
  1245. // Construct the name of the dependency generation target.
  1246. std::string depTarget = cmStrCat(
  1247. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget),
  1248. "/depend");
  1249. // Add a command to call CMake to scan dependencies. CMake will
  1250. // touch the corresponding depends file after scanning dependencies.
  1251. std::ostringstream depCmd;
  1252. // TODO: Account for source file properties and directory-level
  1253. // definitions when scanning for dependencies.
  1254. #if !defined(_WIN32) || defined(__CYGWIN__)
  1255. // This platform supports symlinks, so cmSystemTools will translate
  1256. // paths. Make sure PWD is set to the original name of the home
  1257. // output directory to help cmSystemTools to create the same
  1258. // translation table for the dependency scanning process.
  1259. depCmd << "cd "
  1260. << (this->LocalGenerator->ConvertToOutputFormat(
  1261. this->LocalGenerator->GetBinaryDirectory(),
  1262. cmOutputConverter::SHELL))
  1263. << " && ";
  1264. #endif
  1265. // Generate a call this signature:
  1266. //
  1267. // cmake -E cmake_depends <generator>
  1268. // <home-src-dir> <start-src-dir>
  1269. // <home-out-dir> <start-out-dir>
  1270. // <dep-info> --color=$(COLOR)
  1271. //
  1272. // This gives the dependency scanner enough information to recreate
  1273. // the state of our local generator sufficiently for its needs.
  1274. depCmd << "$(CMAKE_COMMAND) -E cmake_depends \""
  1275. << this->GlobalGenerator->GetName() << "\" "
  1276. << this->LocalGenerator->ConvertToOutputFormat(
  1277. this->LocalGenerator->GetSourceDirectory(),
  1278. cmOutputConverter::SHELL)
  1279. << " "
  1280. << this->LocalGenerator->ConvertToOutputFormat(
  1281. this->LocalGenerator->GetCurrentSourceDirectory(),
  1282. cmOutputConverter::SHELL)
  1283. << " "
  1284. << this->LocalGenerator->ConvertToOutputFormat(
  1285. this->LocalGenerator->GetBinaryDirectory(),
  1286. cmOutputConverter::SHELL)
  1287. << " "
  1288. << this->LocalGenerator->ConvertToOutputFormat(
  1289. this->LocalGenerator->GetCurrentBinaryDirectory(),
  1290. cmOutputConverter::SHELL)
  1291. << " "
  1292. << this->LocalGenerator->ConvertToOutputFormat(
  1293. cmSystemTools::CollapseFullPath(this->InfoFileNameFull),
  1294. cmOutputConverter::SHELL);
  1295. if (this->LocalGenerator->GetColorMakefile()) {
  1296. depCmd << " --color=$(COLOR)";
  1297. }
  1298. commands.push_back(depCmd.str());
  1299. // Make sure all custom command outputs in this target are built.
  1300. if (this->CustomCommandDriver == OnDepends) {
  1301. this->DriveCustomCommands(depends);
  1302. }
  1303. // Write the rule.
  1304. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1305. depTarget, depends, commands, true);
  1306. }
  1307. void cmMakefileTargetGenerator::DriveCustomCommands(
  1308. std::vector<std::string>& depends)
  1309. {
  1310. // Depend on all custom command outputs.
  1311. cm::append(depends, this->CustomCommandOutputs);
  1312. }
  1313. void cmMakefileTargetGenerator::WriteObjectDependRules(
  1314. cmSourceFile const& source, std::vector<std::string>& depends)
  1315. {
  1316. // Create the list of dependencies known at cmake time. These are
  1317. // shared between the object file and dependency scanning rule.
  1318. depends.push_back(source.GetFullPath());
  1319. if (cmProp objectDeps = source.GetProperty("OBJECT_DEPENDS")) {
  1320. cmExpandList(*objectDeps, depends);
  1321. }
  1322. }
  1323. void cmMakefileTargetGenerator::WriteDeviceLinkRule(
  1324. std::vector<std::string>& commands, const std::string& output)
  1325. {
  1326. std::string architecturesStr =
  1327. this->GeneratorTarget->GetSafeProperty("CUDA_ARCHITECTURES");
  1328. if (cmIsOff(architecturesStr)) {
  1329. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  1330. "CUDA_SEPARABLE_COMPILATION on Clang "
  1331. "requires CUDA_ARCHITECTURES to be set.");
  1332. return;
  1333. }
  1334. std::vector<std::string> architectures = cmExpandedList(architecturesStr);
  1335. // Ensure there are no duplicates.
  1336. const std::vector<std::string> linkDeps = [&]() -> std::vector<std::string> {
  1337. std::vector<std::string> deps;
  1338. this->AppendTargetDepends(deps, true);
  1339. this->GeneratorTarget->GetLinkDepends(deps, this->GetConfigName(), "CUDA");
  1340. std::copy(this->Objects.begin(), this->Objects.end(),
  1341. std::back_inserter(deps));
  1342. std::unordered_set<std::string> depsSet(deps.begin(), deps.end());
  1343. deps.clear();
  1344. std::copy(depsSet.begin(), depsSet.end(), std::back_inserter(deps));
  1345. return deps;
  1346. }();
  1347. const std::string objectDir = this->GeneratorTarget->ObjectDirectory;
  1348. const std::string relObjectDir =
  1349. this->LocalGenerator->MaybeConvertToRelativePath(
  1350. this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir);
  1351. // Construct a list of files associated with this executable that
  1352. // may need to be cleaned.
  1353. std::vector<std::string> cleanFiles;
  1354. cleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
  1355. this->LocalGenerator->GetCurrentBinaryDirectory(), output));
  1356. std::string profiles;
  1357. std::vector<std::string> fatbinaryDepends;
  1358. std::string registerFile = cmStrCat(objectDir, "cmake_cuda_register.h");
  1359. // Link device code for each architecture.
  1360. for (const std::string& architectureKind : architectures) {
  1361. // Clang always generates real code, so strip the specifier.
  1362. const std::string architecture =
  1363. architectureKind.substr(0, architectureKind.find('-'));
  1364. const std::string cubin =
  1365. cmStrCat(relObjectDir, "sm_", architecture, ".cubin");
  1366. profiles += cmStrCat(" -im=profile=sm_", architecture, ",file=", cubin);
  1367. fatbinaryDepends.emplace_back(cubin);
  1368. std::string registerFileCmd;
  1369. // The generated register file contains macros that when expanded
  1370. // register the device routines. Because the routines are the same for
  1371. // all architectures the register file will be the same too. Thus
  1372. // generate it only on the first invocation to reduce overhead.
  1373. if (fatbinaryDepends.size() == 1) {
  1374. std::string registerFileRel =
  1375. this->LocalGenerator->MaybeConvertToRelativePath(
  1376. this->LocalGenerator->GetCurrentBinaryDirectory(), registerFile);
  1377. registerFileCmd =
  1378. cmStrCat(" --register-link-binaries=", registerFileRel);
  1379. cleanFiles.push_back(registerFileRel);
  1380. }
  1381. std::string command = cmStrCat(
  1382. this->Makefile->GetRequiredDefinition("CMAKE_CUDA_DEVICE_LINKER"),
  1383. " -arch=sm_", architecture, registerFileCmd, " -o=$@ ",
  1384. cmJoin(linkDeps, " "));
  1385. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr, cubin,
  1386. linkDeps, { command }, false);
  1387. }
  1388. // Combine all architectures into a single fatbinary.
  1389. const std::string fatbinaryCommand =
  1390. cmStrCat(this->Makefile->GetRequiredDefinition("CMAKE_CUDA_FATBINARY"),
  1391. " -64 -cmdline=--compile-only -compress-all -link "
  1392. "--embedded-fatbin=$@",
  1393. profiles);
  1394. const std::string fatbinaryOutput =
  1395. cmStrCat(objectDir, "cmake_cuda_fatbin.h");
  1396. const std::string fatbinaryOutputRel =
  1397. this->LocalGenerator->MaybeConvertToRelativePath(
  1398. this->LocalGenerator->GetCurrentBinaryDirectory(), fatbinaryOutput);
  1399. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1400. fatbinaryOutputRel, fatbinaryDepends,
  1401. { fatbinaryCommand }, false);
  1402. // Compile the stub that registers the kernels and contains the
  1403. // fatbinaries.
  1404. cmRulePlaceholderExpander::RuleVariables vars;
  1405. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  1406. vars.CMTargetType =
  1407. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  1408. vars.Language = "CUDA";
  1409. vars.Object = output.c_str();
  1410. vars.Fatbinary = fatbinaryOutput.c_str();
  1411. vars.RegisterFile = registerFile.c_str();
  1412. std::string flags = this->GetFlags("CUDA", this->GetConfigName());
  1413. vars.Flags = flags.c_str();
  1414. std::string compileCmd = this->GetLinkRule("CMAKE_CUDA_DEVICE_LINK_COMPILE");
  1415. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  1416. this->LocalGenerator->CreateRulePlaceholderExpander());
  1417. rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
  1418. compileCmd, vars);
  1419. commands.emplace_back(compileCmd);
  1420. this->LocalGenerator->WriteMakeRule(
  1421. *this->BuildFileStream, nullptr, output,
  1422. { cmStrCat(relObjectDir, "cmake_cuda_fatbin.h") }, commands, false);
  1423. // Clean all the possible executable names and symlinks.
  1424. this->CleanFiles.insert(cleanFiles.begin(), cleanFiles.end());
  1425. }
  1426. void cmMakefileTargetGenerator::GenerateCustomRuleFile(
  1427. cmCustomCommandGenerator const& ccg)
  1428. {
  1429. // Collect the commands.
  1430. std::vector<std::string> commands;
  1431. std::string comment = this->LocalGenerator->ConstructComment(ccg);
  1432. if (!comment.empty()) {
  1433. // add in a progress call if needed
  1434. this->NumberOfProgressActions++;
  1435. if (!this->NoRuleMessages) {
  1436. cmLocalUnixMakefileGenerator3::EchoProgress progress;
  1437. this->MakeEchoProgress(progress);
  1438. this->LocalGenerator->AppendEcho(
  1439. commands, comment, cmLocalUnixMakefileGenerator3::EchoGenerate,
  1440. &progress);
  1441. }
  1442. }
  1443. // Now append the actual user-specified commands.
  1444. std::ostringstream content;
  1445. this->LocalGenerator->AppendCustomCommand(
  1446. commands, ccg, this->GeneratorTarget,
  1447. this->LocalGenerator->GetBinaryDirectory(), false, &content);
  1448. // Collect the dependencies.
  1449. std::vector<std::string> depends;
  1450. this->LocalGenerator->AppendCustomDepend(depends, ccg);
  1451. if (!ccg.GetCC().GetDepfile().empty()) {
  1452. // Add dependency over timestamp file for dependencies management
  1453. auto dependTimestamp = cmSystemTools::ConvertToOutputPath(
  1454. this->LocalGenerator->MaybeConvertToRelativePath(
  1455. this->LocalGenerator->GetBinaryDirectory(),
  1456. cmStrCat(this->TargetBuildDirectoryFull, "/compiler_depend.ts")));
  1457. depends.push_back(dependTimestamp);
  1458. }
  1459. // Write the rule.
  1460. const std::vector<std::string>& outputs = ccg.GetOutputs();
  1461. bool symbolic = this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs,
  1462. depends, commands);
  1463. // Symbolic inputs are not expected to exist, so add dummy rules.
  1464. if (this->CMP0113New && !depends.empty()) {
  1465. std::vector<std::string> no_depends;
  1466. std::vector<std::string> no_commands;
  1467. for (std::string const& dep : depends) {
  1468. if (cmSourceFile* dsf =
  1469. this->Makefile->GetSource(dep, cmSourceFileLocationKind::Known)) {
  1470. if (dsf->GetPropertyAsBool("SYMBOLIC")) {
  1471. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
  1472. dep, no_depends, no_commands,
  1473. true);
  1474. }
  1475. }
  1476. }
  1477. }
  1478. // If the rule has changed make sure the output is rebuilt.
  1479. if (!symbolic) {
  1480. this->GlobalGenerator->AddRuleHash(ccg.GetOutputs(), content.str());
  1481. }
  1482. // Setup implicit dependency scanning.
  1483. for (auto const& idi : ccg.GetCC().GetImplicitDepends()) {
  1484. std::string objFullPath = cmSystemTools::CollapseFullPath(
  1485. outputs[0], this->LocalGenerator->GetCurrentBinaryDirectory());
  1486. std::string srcFullPath = cmSystemTools::CollapseFullPath(
  1487. idi.second, this->LocalGenerator->GetCurrentBinaryDirectory());
  1488. this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi.first,
  1489. objFullPath, srcFullPath);
  1490. }
  1491. // Setup implicit depend for depfile if any
  1492. if (!ccg.GetCC().GetDepfile().empty()) {
  1493. std::string objFullPath = cmSystemTools::CollapseFullPath(
  1494. outputs[0], this->LocalGenerator->GetCurrentBinaryDirectory());
  1495. this->LocalGenerator->AddImplicitDepends(
  1496. this->GeneratorTarget, "CUSTOM", objFullPath, ccg.GetFullDepfile(),
  1497. cmDependencyScannerKind::Compiler);
  1498. }
  1499. this->CustomCommandOutputs.insert(outputs.begin(), outputs.end());
  1500. }
  1501. void cmMakefileTargetGenerator::MakeEchoProgress(
  1502. cmLocalUnixMakefileGenerator3::EchoProgress& progress) const
  1503. {
  1504. progress.Dir =
  1505. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), "/CMakeFiles");
  1506. std::ostringstream progressArg;
  1507. progressArg << "$(CMAKE_PROGRESS_" << this->NumberOfProgressActions << ")";
  1508. progress.Arg = progressArg.str();
  1509. }
  1510. void cmMakefileTargetGenerator::WriteObjectsVariable(
  1511. std::string& variableName, std::string& variableNameExternal,
  1512. bool useWatcomQuote)
  1513. {
  1514. // Write a make variable assignment that lists all objects for the
  1515. // target.
  1516. variableName = this->LocalGenerator->CreateMakeVariable(
  1517. this->GeneratorTarget->GetName(), "_OBJECTS");
  1518. *this->BuildFileStream << "# Object files for target "
  1519. << this->GeneratorTarget->GetName() << "\n"
  1520. << variableName << " =";
  1521. std::string object;
  1522. const auto& lineContinue = this->GlobalGenerator->LineContinueDirective;
  1523. cmProp pchExtension = this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  1524. for (std::string const& obj : this->Objects) {
  1525. if (cmSystemTools::StringEndsWith(obj, cmToCStr(pchExtension))) {
  1526. continue;
  1527. }
  1528. *this->BuildFileStream << " " << lineContinue;
  1529. *this->BuildFileStream
  1530. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1531. obj, useWatcomQuote);
  1532. }
  1533. *this->BuildFileStream << "\n";
  1534. // Write a make variable assignment that lists all external objects
  1535. // for the target.
  1536. variableNameExternal = this->LocalGenerator->CreateMakeVariable(
  1537. this->GeneratorTarget->GetName(), "_EXTERNAL_OBJECTS");
  1538. /* clang-format off */
  1539. *this->BuildFileStream
  1540. << "\n"
  1541. << "# External object files for target "
  1542. << this->GeneratorTarget->GetName() << "\n"
  1543. << variableNameExternal << " =";
  1544. /* clang-format on */
  1545. std::string currentBinDir =
  1546. this->LocalGenerator->GetCurrentBinaryDirectory();
  1547. for (std::string const& obj : this->ExternalObjects) {
  1548. object =
  1549. this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, obj);
  1550. *this->BuildFileStream << " " << lineContinue;
  1551. *this->BuildFileStream
  1552. << cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
  1553. obj, useWatcomQuote);
  1554. }
  1555. *this->BuildFileStream << "\n"
  1556. << "\n";
  1557. }
  1558. class cmMakefileTargetGeneratorObjectStrings
  1559. {
  1560. public:
  1561. cmMakefileTargetGeneratorObjectStrings(std::vector<std::string>& strings,
  1562. cmOutputConverter* outputConverter,
  1563. cmStateDirectory const& stateDir,
  1564. std::string::size_type limit)
  1565. : Strings(strings)
  1566. , OutputConverter(outputConverter)
  1567. , StateDir(stateDir)
  1568. , LengthLimit(limit)
  1569. {
  1570. this->Space = "";
  1571. }
  1572. void Feed(std::string const& obj)
  1573. {
  1574. // Construct the name of the next object.
  1575. this->NextObject = this->OutputConverter->ConvertToOutputFormat(
  1576. this->MaybeConvertToRelativePath(obj), cmOutputConverter::RESPONSE);
  1577. // Roll over to next string if the limit will be exceeded.
  1578. if (this->LengthLimit != std::string::npos &&
  1579. (this->CurrentString.length() + 1 + this->NextObject.length() >
  1580. this->LengthLimit)) {
  1581. this->Strings.push_back(this->CurrentString);
  1582. this->CurrentString.clear();
  1583. this->Space = "";
  1584. }
  1585. // Separate from previous object.
  1586. this->CurrentString += this->Space;
  1587. this->Space = " ";
  1588. // Append this object.
  1589. this->CurrentString += this->NextObject;
  1590. }
  1591. void Done() { this->Strings.push_back(this->CurrentString); }
  1592. private:
  1593. std::string MaybeConvertToRelativePath(std::string const& obj)
  1594. {
  1595. if (!this->StateDir.ContainsBoth(this->StateDir.GetCurrentBinary(), obj)) {
  1596. return obj;
  1597. }
  1598. return cmSystemTools::ForceToRelativePath(
  1599. this->StateDir.GetCurrentBinary(), obj);
  1600. }
  1601. std::vector<std::string>& Strings;
  1602. cmOutputConverter* OutputConverter;
  1603. cmStateDirectory StateDir;
  1604. std::string::size_type LengthLimit;
  1605. std::string CurrentString;
  1606. std::string NextObject;
  1607. const char* Space;
  1608. };
  1609. void cmMakefileTargetGenerator::WriteObjectsStrings(
  1610. std::vector<std::string>& objStrings, std::string::size_type limit)
  1611. {
  1612. cmProp pchExtension = this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  1613. cmMakefileTargetGeneratorObjectStrings helper(
  1614. objStrings, this->LocalGenerator,
  1615. this->LocalGenerator->GetStateSnapshot().GetDirectory(), limit);
  1616. for (std::string const& obj : this->Objects) {
  1617. if (cmSystemTools::StringEndsWith(obj, cmToCStr(pchExtension))) {
  1618. continue;
  1619. }
  1620. helper.Feed(obj);
  1621. }
  1622. for (std::string const& obj : this->ExternalObjects) {
  1623. helper.Feed(obj);
  1624. }
  1625. auto ispcAdditionalObjs =
  1626. this->GeneratorTarget->GetGeneratedISPCObjects(this->GetConfigName());
  1627. for (std::string const& obj : ispcAdditionalObjs) {
  1628. helper.Feed(obj);
  1629. }
  1630. helper.Done();
  1631. }
  1632. void cmMakefileTargetGenerator::WriteTargetDriverRule(
  1633. const std::string& main_output, bool relink)
  1634. {
  1635. // Compute the name of the driver target.
  1636. std::string dir =
  1637. this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget);
  1638. std::string buildTargetRuleName =
  1639. cmStrCat(dir, relink ? "/preinstall" : "/build");
  1640. buildTargetRuleName = this->LocalGenerator->MaybeConvertToRelativePath(
  1641. this->LocalGenerator->GetBinaryDirectory(), buildTargetRuleName);
  1642. // Build the list of target outputs to drive.
  1643. std::vector<std::string> depends;
  1644. depends.push_back(main_output);
  1645. const char* comment = nullptr;
  1646. if (relink) {
  1647. // Setup the comment for the preinstall driver.
  1648. comment = "Rule to relink during preinstall.";
  1649. } else {
  1650. // Setup the comment for the main build driver.
  1651. comment = "Rule to build all files generated by this target.";
  1652. // Make sure all custom command outputs in this target are built.
  1653. if (this->CustomCommandDriver == OnBuild) {
  1654. this->DriveCustomCommands(depends);
  1655. }
  1656. // Make sure the extra files are built.
  1657. cm::append(depends, this->ExtraFiles);
  1658. }
  1659. // Write the driver rule.
  1660. std::vector<std::string> no_commands;
  1661. this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, comment,
  1662. buildTargetRuleName, depends,
  1663. no_commands, true);
  1664. }
  1665. void cmMakefileTargetGenerator::AppendTargetDepends(
  1666. std::vector<std::string>& depends, bool ignoreType)
  1667. {
  1668. // Static libraries never depend on anything for linking.
  1669. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY &&
  1670. !ignoreType) {
  1671. return;
  1672. }
  1673. // Loop over all library dependencies.
  1674. const std::string& cfg = this->GetConfigName();
  1675. if (cmComputeLinkInformation* cli =
  1676. this->GeneratorTarget->GetLinkInformation(cfg)) {
  1677. cm::append(depends, cli->GetDepends());
  1678. }
  1679. }
  1680. void cmMakefileTargetGenerator::AppendObjectDepends(
  1681. std::vector<std::string>& depends)
  1682. {
  1683. // Add dependencies on the compiled object files.
  1684. std::string const& relPath =
  1685. this->LocalGenerator->GetHomeRelativeOutputPath();
  1686. for (std::string const& obj : this->Objects) {
  1687. std::string objTarget = cmStrCat(relPath, obj);
  1688. depends.push_back(std::move(objTarget));
  1689. }
  1690. // Add dependencies on the external object files.
  1691. cm::append(depends, this->ExternalObjects);
  1692. // Add a dependency on the rule file itself.
  1693. this->LocalGenerator->AppendRuleDepend(depends,
  1694. this->BuildFileNameFull.c_str());
  1695. }
  1696. void cmMakefileTargetGenerator::AppendLinkDepends(
  1697. std::vector<std::string>& depends, const std::string& linkLanguage)
  1698. {
  1699. this->AppendObjectDepends(depends);
  1700. // Add dependencies on targets that must be built first.
  1701. this->AppendTargetDepends(depends);
  1702. // Add a dependency on the link definitions file, if any.
  1703. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1704. this->GeneratorTarget->GetModuleDefinitionInfo(
  1705. this->GetConfigName())) {
  1706. for (cmSourceFile const* src : mdi->Sources) {
  1707. depends.push_back(src->GetFullPath());
  1708. }
  1709. }
  1710. // Add a dependency on user-specified manifest files, if any.
  1711. std::vector<cmSourceFile const*> manifest_srcs;
  1712. this->GeneratorTarget->GetManifests(manifest_srcs, this->GetConfigName());
  1713. for (cmSourceFile const* manifest_src : manifest_srcs) {
  1714. depends.push_back(manifest_src->GetFullPath());
  1715. }
  1716. // Add user-specified dependencies.
  1717. this->GeneratorTarget->GetLinkDepends(depends, this->GetConfigName(),
  1718. linkLanguage);
  1719. }
  1720. std::string cmMakefileTargetGenerator::GetLinkRule(
  1721. const std::string& linkRuleVar)
  1722. {
  1723. std::string linkRule = this->Makefile->GetRequiredDefinition(linkRuleVar);
  1724. if (this->GeneratorTarget->HasImplibGNUtoMS(this->GetConfigName())) {
  1725. std::string ruleVar =
  1726. cmStrCat("CMAKE_",
  1727. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName()),
  1728. "_GNUtoMS_RULE");
  1729. if (cmProp rule = this->Makefile->GetDefinition(ruleVar)) {
  1730. linkRule += *rule;
  1731. }
  1732. }
  1733. return linkRule;
  1734. }
  1735. void cmMakefileTargetGenerator::CloseFileStreams()
  1736. {
  1737. this->BuildFileStream.reset();
  1738. this->InfoFileStream.reset();
  1739. this->FlagFileStream.reset();
  1740. }
  1741. void cmMakefileTargetGenerator::CreateLinkScript(
  1742. const char* name, std::vector<std::string> const& link_commands,
  1743. std::vector<std::string>& makefile_commands,
  1744. std::vector<std::string>& makefile_depends)
  1745. {
  1746. // Create the link script file.
  1747. std::string linkScriptName =
  1748. cmStrCat(this->TargetBuildDirectoryFull, '/', name);
  1749. cmGeneratedFileStream linkScriptStream(linkScriptName);
  1750. linkScriptStream.SetCopyIfDifferent(true);
  1751. for (std::string const& link_command : link_commands) {
  1752. // Do not write out empty commands or commands beginning in the
  1753. // shell no-op ":".
  1754. if (!link_command.empty() && link_command[0] != ':') {
  1755. linkScriptStream << link_command << "\n";
  1756. }
  1757. }
  1758. // Create the makefile command to invoke the link script.
  1759. std::string link_command = cmStrCat(
  1760. "$(CMAKE_COMMAND) -E cmake_link_script ",
  1761. this->LocalGenerator->ConvertToOutputFormat(
  1762. this->LocalGenerator->MaybeConvertToRelativePath(
  1763. this->LocalGenerator->GetCurrentBinaryDirectory(), linkScriptName),
  1764. cmOutputConverter::SHELL),
  1765. " --verbose=$(VERBOSE)");
  1766. makefile_commands.push_back(std::move(link_command));
  1767. makefile_depends.push_back(std::move(linkScriptName));
  1768. }
  1769. bool cmMakefileTargetGenerator::CheckUseResponseFileForObjects(
  1770. std::string const& l) const
  1771. {
  1772. // Check for an explicit setting one way or the other.
  1773. std::string const responseVar =
  1774. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_OBJECTS";
  1775. if (cmProp val = this->Makefile->GetDefinition(responseVar)) {
  1776. if (!val->empty()) {
  1777. return cmIsOn(val);
  1778. }
  1779. }
  1780. // Check for a system limit.
  1781. if (size_t const limit = cmSystemTools::CalculateCommandLineLengthLimit()) {
  1782. // Compute the total length of our list of object files with room
  1783. // for argument separation and quoting. This does not convert paths
  1784. // relative to CMAKE_CURRENT_BINARY_DIR like the final list will be, so
  1785. // the actual list will likely be much shorter than this. However, in
  1786. // the worst case all objects will remain as absolute paths.
  1787. size_t length = 0;
  1788. for (std::string const& obj : this->Objects) {
  1789. length += obj.size() + 3;
  1790. }
  1791. for (std::string const& ext_obj : this->ExternalObjects) {
  1792. length += ext_obj.size() + 3;
  1793. }
  1794. // We need to guarantee room for both objects and libraries, so
  1795. // if the objects take up more than half then use a response file
  1796. // for them.
  1797. if (length > (limit / 2)) {
  1798. return true;
  1799. }
  1800. }
  1801. // We do not need a response file for objects.
  1802. return false;
  1803. }
  1804. bool cmMakefileTargetGenerator::CheckUseResponseFileForLibraries(
  1805. std::string const& l) const
  1806. {
  1807. // Check for an explicit setting one way or the other.
  1808. std::string const responseVar =
  1809. "CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_LIBRARIES";
  1810. if (cmProp val = this->Makefile->GetDefinition(responseVar)) {
  1811. if (!val->empty()) {
  1812. return cmIsOn(val);
  1813. }
  1814. }
  1815. // We do not need a response file for libraries.
  1816. return false;
  1817. }
  1818. std::string cmMakefileTargetGenerator::CreateResponseFile(
  1819. const char* name, std::string const& options,
  1820. std::vector<std::string>& makefile_depends)
  1821. {
  1822. // Create the response file.
  1823. std::string responseFileNameFull =
  1824. cmStrCat(this->TargetBuildDirectoryFull, '/', name);
  1825. cmGeneratedFileStream responseStream(
  1826. responseFileNameFull, false, this->GlobalGenerator->GetMakefileEncoding());
  1827. responseStream.SetCopyIfDifferent(true);
  1828. responseStream << options << "\n";
  1829. // Add a dependency so the target will rebuild when the set of
  1830. // objects changes.
  1831. makefile_depends.push_back(std::move(responseFileNameFull));
  1832. // Construct the name to be used on the command line.
  1833. std::string responseFileName =
  1834. cmStrCat(this->TargetBuildDirectory, '/', name);
  1835. return responseFileName;
  1836. }
  1837. std::unique_ptr<cmLinkLineComputer>
  1838. cmMakefileTargetGenerator::CreateLinkLineComputer(
  1839. cmOutputConverter* outputConverter, cmStateDirectory const& stateDir)
  1840. {
  1841. if (this->Makefile->IsOn("MSVC60")) {
  1842. return this->GlobalGenerator->CreateMSVC60LinkLineComputer(outputConverter,
  1843. stateDir);
  1844. }
  1845. return this->GlobalGenerator->CreateLinkLineComputer(outputConverter,
  1846. stateDir);
  1847. }
  1848. void cmMakefileTargetGenerator::CreateLinkLibs(
  1849. cmLinkLineComputer* linkLineComputer, std::string& linkLibs,
  1850. bool useResponseFile, std::vector<std::string>& makefile_depends)
  1851. {
  1852. std::string frameworkPath;
  1853. std::string linkPath;
  1854. cmComputeLinkInformation* pcli =
  1855. this->GeneratorTarget->GetLinkInformation(this->GetConfigName());
  1856. this->LocalGenerator->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1857. frameworkPath, linkPath);
  1858. linkLibs = frameworkPath + linkPath + linkLibs;
  1859. if (useResponseFile &&
  1860. linkLibs.find_first_not_of(' ') != std::string::npos) {
  1861. // Lookup the response file reference flag.
  1862. std::string responseFlagVar =
  1863. cmStrCat("CMAKE_",
  1864. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName()),
  1865. "_RESPONSE_FILE_LINK_FLAG");
  1866. std::string responseFlag;
  1867. if (cmProp p = this->Makefile->GetDefinition(responseFlagVar)) {
  1868. responseFlag = *p;
  1869. } else {
  1870. responseFlag = "@";
  1871. }
  1872. // Create this response file.
  1873. std::string link_rsp =
  1874. this->CreateResponseFile("linklibs.rsp", linkLibs, makefile_depends);
  1875. // Reference the response file.
  1876. linkLibs = cmStrCat(responseFlag,
  1877. this->LocalGenerator->ConvertToOutputFormat(
  1878. link_rsp, cmOutputConverter::SHELL));
  1879. }
  1880. }
  1881. void cmMakefileTargetGenerator::CreateObjectLists(
  1882. bool useLinkScript, bool useArchiveRules, bool useResponseFile,
  1883. std::string& buildObjs, std::vector<std::string>& makefile_depends,
  1884. bool useWatcomQuote)
  1885. {
  1886. std::string variableName;
  1887. std::string variableNameExternal;
  1888. this->WriteObjectsVariable(variableName, variableNameExternal,
  1889. useWatcomQuote);
  1890. if (useResponseFile) {
  1891. // MSVC response files cannot exceed 128K.
  1892. std::string::size_type const responseFileLimit = 131000;
  1893. // Construct the individual object list strings.
  1894. std::vector<std::string> object_strings;
  1895. this->WriteObjectsStrings(object_strings, responseFileLimit);
  1896. // Lookup the response file reference flag.
  1897. std::string responseFlagVar =
  1898. cmStrCat("CMAKE_",
  1899. this->GeneratorTarget->GetLinkerLanguage(this->GetConfigName()),
  1900. "_RESPONSE_FILE_LINK_FLAG");
  1901. std::string responseFlag;
  1902. if (cmProp p = this->Makefile->GetDefinition(responseFlagVar)) {
  1903. responseFlag = *p;
  1904. } else {
  1905. responseFlag = "@";
  1906. }
  1907. // Write a response file for each string.
  1908. const char* sep = "";
  1909. for (unsigned int i = 0; i < object_strings.size(); ++i) {
  1910. // Number the response files.
  1911. char rsp[32];
  1912. sprintf(rsp, "objects%u.rsp", i + 1);
  1913. // Create this response file.
  1914. std::string objects_rsp =
  1915. this->CreateResponseFile(rsp, object_strings[i], makefile_depends);
  1916. // Separate from previous response file references.
  1917. buildObjs += sep;
  1918. sep = " ";
  1919. // Reference the response file.
  1920. buildObjs += responseFlag;
  1921. buildObjs += this->LocalGenerator->ConvertToOutputFormat(
  1922. objects_rsp, cmOutputConverter::SHELL);
  1923. }
  1924. } else if (useLinkScript) {
  1925. if (!useArchiveRules) {
  1926. std::vector<std::string> objStrings;
  1927. this->WriteObjectsStrings(objStrings);
  1928. buildObjs = objStrings[0];
  1929. }
  1930. } else {
  1931. buildObjs =
  1932. cmStrCat("$(", variableName, ") $(", variableNameExternal, ')');
  1933. }
  1934. }
  1935. void cmMakefileTargetGenerator::AddIncludeFlags(std::string& flags,
  1936. const std::string& lang,
  1937. const std::string& /*config*/)
  1938. {
  1939. std::string responseVar =
  1940. cmStrCat("CMAKE_", lang, "_USE_RESPONSE_FILE_FOR_INCLUDES");
  1941. bool useResponseFile = this->Makefile->IsOn(responseVar);
  1942. std::vector<std::string> includes;
  1943. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1944. lang, this->GetConfigName());
  1945. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  1946. includes, this->GeneratorTarget, lang, this->GetConfigName(),
  1947. useResponseFile);
  1948. if (includeFlags.empty()) {
  1949. return;
  1950. }
  1951. if (useResponseFile) {
  1952. std::string const responseFlagVar =
  1953. "CMAKE_" + lang + "_RESPONSE_FILE_FLAG";
  1954. std::string responseFlag =
  1955. this->Makefile->GetSafeDefinition(responseFlagVar);
  1956. if (responseFlag.empty()) {
  1957. responseFlag = "@";
  1958. }
  1959. std::string name = cmStrCat("includes_", lang, ".rsp");
  1960. std::string arg = std::move(responseFlag) +
  1961. this->CreateResponseFile(name.c_str(), includeFlags,
  1962. this->FlagFileDepends[lang]);
  1963. this->LocalGenerator->AppendFlags(flags, arg);
  1964. } else {
  1965. this->LocalGenerator->AppendFlags(flags, includeFlags);
  1966. }
  1967. }
  1968. void cmMakefileTargetGenerator::GenDefFile(
  1969. std::vector<std::string>& real_link_commands)
  1970. {
  1971. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1972. this->GeneratorTarget->GetModuleDefinitionInfo(this->GetConfigName());
  1973. if (!mdi || !mdi->DefFileGenerated) {
  1974. return;
  1975. }
  1976. std::string cmd = cmSystemTools::GetCMakeCommand();
  1977. cmd = cmStrCat(
  1978. this->LocalGenerator->ConvertToOutputFormat(cmd, cmOutputConverter::SHELL),
  1979. " -E __create_def ",
  1980. this->LocalGenerator->ConvertToOutputFormat(
  1981. this->LocalGenerator->MaybeConvertToRelativePath(
  1982. this->LocalGenerator->GetCurrentBinaryDirectory(), mdi->DefFile),
  1983. cmOutputConverter::SHELL),
  1984. ' ');
  1985. std::string objlist_file = mdi->DefFile + ".objs";
  1986. cmd += this->LocalGenerator->ConvertToOutputFormat(
  1987. this->LocalGenerator->MaybeConvertToRelativePath(
  1988. this->LocalGenerator->GetCurrentBinaryDirectory(), objlist_file),
  1989. cmOutputConverter::SHELL);
  1990. cmProp nm_executable = this->Makefile->GetDefinition("CMAKE_NM");
  1991. if (cmNonempty(nm_executable)) {
  1992. cmd += " --nm=";
  1993. cmd += this->LocalCommonGenerator->ConvertToOutputFormat(
  1994. *nm_executable, cmOutputConverter::SHELL);
  1995. }
  1996. real_link_commands.insert(real_link_commands.begin(), cmd);
  1997. // create a list of obj files for the -E __create_def to read
  1998. cmGeneratedFileStream fout(objlist_file);
  1999. if (mdi->WindowsExportAllSymbols) {
  2000. for (std::string const& obj : this->Objects) {
  2001. if (cmHasLiteralSuffix(obj, ".obj")) {
  2002. fout << obj << "\n";
  2003. }
  2004. }
  2005. for (std::string const& obj : this->ExternalObjects) {
  2006. fout << obj << "\n";
  2007. }
  2008. }
  2009. for (cmSourceFile const* src : mdi->Sources) {
  2010. fout << src->GetFullPath() << "\n";
  2011. }
  2012. }