cmMakefileTargetGenerator.cxx 91 KB

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