cmMakefileTargetGenerator.cxx 85 KB

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