cmMakefileTargetGenerator.cxx 88 KB

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