cmMakefileTargetGenerator.cxx 91 KB

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