cmMakefileTargetGenerator.cxx 89 KB

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