cmMakefileTargetGenerator.cxx 89 KB

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