cmMakefileTargetGenerator.cxx 88 KB

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