cmMakefileTargetGenerator.cxx 90 KB

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