cmMakefileTargetGenerator.cxx 84 KB

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