Darwin.cpp 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404
  1. //===--- Darwin.cpp - Darwin Tool and ToolChain Implementations -*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "Darwin.h"
  9. #include "Arch/ARM.h"
  10. #include "CommonArgs.h"
  11. #include "clang/Basic/AlignedAllocation.h"
  12. #include "clang/Basic/ObjCRuntime.h"
  13. #include "clang/Driver/Compilation.h"
  14. #include "clang/Driver/Driver.h"
  15. #include "clang/Driver/DriverDiagnostic.h"
  16. #include "clang/Driver/Options.h"
  17. #include "clang/Driver/SanitizerArgs.h"
  18. #include "llvm/ADT/StringSwitch.h"
  19. #include "llvm/Option/ArgList.h"
  20. #include "llvm/Support/Path.h"
  21. #include "llvm/Support/ScopedPrinter.h"
  22. #include "llvm/Support/TargetParser.h"
  23. #include "llvm/Support/VirtualFileSystem.h"
  24. #include <cstdlib> // ::getenv
  25. using namespace clang::driver;
  26. using namespace clang::driver::tools;
  27. using namespace clang::driver::toolchains;
  28. using namespace clang;
  29. using namespace llvm::opt;
  30. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  31. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  32. // archs which Darwin doesn't use.
  33. // The matching this routine does is fairly pointless, since it is neither the
  34. // complete architecture list, nor a reasonable subset. The problem is that
  35. // historically the driver driver accepts this and also ties its -march=
  36. // handling to the architecture name, so we need to be careful before removing
  37. // support for it.
  38. // This code must be kept in sync with Clang's Darwin specific argument
  39. // translation.
  40. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  41. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  42. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  43. .Case("ppc64", llvm::Triple::ppc64)
  44. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  45. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  46. llvm::Triple::x86)
  47. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  48. // This is derived from the driver driver.
  49. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  50. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  51. .Cases("armv7s", "xscale", llvm::Triple::arm)
  52. .Case("arm64", llvm::Triple::aarch64)
  53. .Case("r600", llvm::Triple::r600)
  54. .Case("amdgcn", llvm::Triple::amdgcn)
  55. .Case("nvptx", llvm::Triple::nvptx)
  56. .Case("nvptx64", llvm::Triple::nvptx64)
  57. .Case("amdil", llvm::Triple::amdil)
  58. .Case("spir", llvm::Triple::spir)
  59. .Default(llvm::Triple::UnknownArch);
  60. }
  61. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  62. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  63. llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Str);
  64. T.setArch(Arch);
  65. if (Str == "x86_64h")
  66. T.setArchName(Str);
  67. else if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
  68. ArchKind == llvm::ARM::ArchKind::ARMV7M ||
  69. ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
  70. T.setOS(llvm::Triple::UnknownOS);
  71. T.setObjectFormat(llvm::Triple::MachO);
  72. }
  73. }
  74. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  75. const InputInfo &Output,
  76. const InputInfoList &Inputs,
  77. const ArgList &Args,
  78. const char *LinkingOutput) const {
  79. ArgStringList CmdArgs;
  80. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  81. const InputInfo &Input = Inputs[0];
  82. // Determine the original source input.
  83. const Action *SourceAction = &JA;
  84. while (SourceAction->getKind() != Action::InputClass) {
  85. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  86. SourceAction = SourceAction->getInputs()[0];
  87. }
  88. // If -fno-integrated-as is used add -Q to the darwin assembler driver to make
  89. // sure it runs its system assembler not clang's integrated assembler.
  90. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  91. // FIXME: at run-time detect assembler capabilities or rely on version
  92. // information forwarded by -target-assembler-version.
  93. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  94. const llvm::Triple &T(getToolChain().getTriple());
  95. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  96. CmdArgs.push_back("-Q");
  97. }
  98. // Forward -g, assuming we are dealing with an actual assembly file.
  99. if (SourceAction->getType() == types::TY_Asm ||
  100. SourceAction->getType() == types::TY_PP_Asm) {
  101. if (Args.hasArg(options::OPT_gstabs))
  102. CmdArgs.push_back("--gstabs");
  103. else if (Args.hasArg(options::OPT_g_Group))
  104. CmdArgs.push_back("-g");
  105. }
  106. // Derived from asm spec.
  107. AddMachOArch(Args, CmdArgs);
  108. // Use -force_cpusubtype_ALL on x86 by default.
  109. if (getToolChain().getArch() == llvm::Triple::x86 ||
  110. getToolChain().getArch() == llvm::Triple::x86_64 ||
  111. Args.hasArg(options::OPT_force__cpusubtype__ALL))
  112. CmdArgs.push_back("-force_cpusubtype_ALL");
  113. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  114. (((Args.hasArg(options::OPT_mkernel) ||
  115. Args.hasArg(options::OPT_fapple_kext)) &&
  116. getMachOToolChain().isKernelStatic()) ||
  117. Args.hasArg(options::OPT_static)))
  118. CmdArgs.push_back("-static");
  119. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  120. assert(Output.isFilename() && "Unexpected lipo output.");
  121. CmdArgs.push_back("-o");
  122. CmdArgs.push_back(Output.getFilename());
  123. assert(Input.isFilename() && "Invalid input.");
  124. CmdArgs.push_back(Input.getFilename());
  125. // asm_final spec is empty.
  126. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  127. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  128. }
  129. void darwin::MachOTool::anchor() {}
  130. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  131. ArgStringList &CmdArgs) const {
  132. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  133. // Derived from darwin_arch spec.
  134. CmdArgs.push_back("-arch");
  135. CmdArgs.push_back(Args.MakeArgString(ArchName));
  136. // FIXME: Is this needed anymore?
  137. if (ArchName == "arm")
  138. CmdArgs.push_back("-force_cpusubtype_ALL");
  139. }
  140. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  141. // We only need to generate a temp path for LTO if we aren't compiling object
  142. // files. When compiling source files, we run 'dsymutil' after linking. We
  143. // don't run 'dsymutil' when compiling object files.
  144. for (const auto &Input : Inputs)
  145. if (Input.getType() != types::TY_Object)
  146. return true;
  147. return false;
  148. }
  149. /// Pass -no_deduplicate to ld64 under certain conditions:
  150. ///
  151. /// - Either -O0 or -O1 is explicitly specified
  152. /// - No -O option is specified *and* this is a compile+link (implicit -O0)
  153. ///
  154. /// Also do *not* add -no_deduplicate when no -O option is specified and this
  155. /// is just a link (we can't imply -O0)
  156. static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
  157. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  158. if (A->getOption().matches(options::OPT_O0))
  159. return true;
  160. if (A->getOption().matches(options::OPT_O))
  161. return llvm::StringSwitch<bool>(A->getValue())
  162. .Case("1", true)
  163. .Default(false);
  164. return false; // OPT_Ofast & OPT_O4
  165. }
  166. if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
  167. return true;
  168. return false;
  169. }
  170. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  171. ArgStringList &CmdArgs,
  172. const InputInfoList &Inputs) const {
  173. const Driver &D = getToolChain().getDriver();
  174. const toolchains::MachO &MachOTC = getMachOToolChain();
  175. unsigned Version[5] = {0, 0, 0, 0, 0};
  176. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  177. if (!Driver::GetReleaseVersion(A->getValue(), Version))
  178. D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
  179. }
  180. // Newer linkers support -demangle. Pass it if supported and not disabled by
  181. // the user.
  182. if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  183. CmdArgs.push_back("-demangle");
  184. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  185. CmdArgs.push_back("-export_dynamic");
  186. // If we are using App Extension restrictions, pass a flag to the linker
  187. // telling it that the compiled code has been audited.
  188. if (Args.hasFlag(options::OPT_fapplication_extension,
  189. options::OPT_fno_application_extension, false))
  190. CmdArgs.push_back("-application_extension");
  191. if (D.isUsingLTO() && Version[0] >= 116 && NeedsTempPath(Inputs)) {
  192. std::string TmpPathName;
  193. if (D.getLTOMode() == LTOK_Full) {
  194. // If we are using full LTO, then automatically create a temporary file
  195. // path for the linker to use, so that it's lifetime will extend past a
  196. // possible dsymutil step.
  197. TmpPathName =
  198. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object));
  199. } else if (D.getLTOMode() == LTOK_Thin)
  200. // If we are using thin LTO, then create a directory instead.
  201. TmpPathName = D.GetTemporaryDirectory("thinlto");
  202. if (!TmpPathName.empty()) {
  203. auto *TmpPath = C.getArgs().MakeArgString(TmpPathName);
  204. C.addTempFile(TmpPath);
  205. CmdArgs.push_back("-object_path_lto");
  206. CmdArgs.push_back(TmpPath);
  207. }
  208. }
  209. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  210. // it in clang installed libraries. ld64 will only look at this argument
  211. // when it actually uses LTO, so libLTO.dylib only needs to exist at link
  212. // time if ld64 decides that it needs to use LTO.
  213. // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
  214. // next to it. That's ok since ld64 using a libLTO.dylib not matching the
  215. // clang version won't work anyways.
  216. if (Version[0] >= 133) {
  217. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  218. StringRef P = llvm::sys::path::parent_path(D.Dir);
  219. SmallString<128> LibLTOPath(P);
  220. llvm::sys::path::append(LibLTOPath, "lib");
  221. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  222. CmdArgs.push_back("-lto_library");
  223. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  224. }
  225. // ld64 version 262 and above run the deduplicate pass by default.
  226. if (Version[0] >= 262 && shouldLinkerNotDedup(C.getJobs().empty(), Args))
  227. CmdArgs.push_back("-no_deduplicate");
  228. // Derived from the "link" spec.
  229. Args.AddAllArgs(CmdArgs, options::OPT_static);
  230. if (!Args.hasArg(options::OPT_static))
  231. CmdArgs.push_back("-dynamic");
  232. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  233. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  234. // here. How do we wish to handle such things?
  235. }
  236. if (!Args.hasArg(options::OPT_dynamiclib)) {
  237. AddMachOArch(Args, CmdArgs);
  238. // FIXME: Why do this only on this path?
  239. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  240. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  241. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  242. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  243. Arg *A;
  244. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  245. (A = Args.getLastArg(options::OPT_current__version)) ||
  246. (A = Args.getLastArg(options::OPT_install__name)))
  247. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  248. << "-dynamiclib";
  249. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  250. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  251. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  252. } else {
  253. CmdArgs.push_back("-dylib");
  254. Arg *A;
  255. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  256. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  257. (A = Args.getLastArg(options::OPT_client__name)) ||
  258. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  259. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  260. (A = Args.getLastArg(options::OPT_private__bundle)))
  261. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  262. << "-dynamiclib";
  263. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  264. "-dylib_compatibility_version");
  265. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  266. "-dylib_current_version");
  267. AddMachOArch(Args, CmdArgs);
  268. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  269. "-dylib_install_name");
  270. }
  271. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  272. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  273. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  274. if (MachOTC.isTargetIOSBased())
  275. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  276. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  277. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  278. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  279. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  280. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  281. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  282. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  283. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  284. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  285. Args.AddAllArgs(CmdArgs, options::OPT_init);
  286. // Add the deployment target.
  287. MachOTC.addMinVersionArgs(Args, CmdArgs);
  288. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  289. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  290. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  291. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  292. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  293. if (const Arg *A =
  294. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  295. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  296. if (A->getOption().matches(options::OPT_fpie) ||
  297. A->getOption().matches(options::OPT_fPIE))
  298. CmdArgs.push_back("-pie");
  299. else
  300. CmdArgs.push_back("-no_pie");
  301. }
  302. // for embed-bitcode, use -bitcode_bundle in linker command
  303. if (C.getDriver().embedBitcodeEnabled()) {
  304. // Check if the toolchain supports bitcode build flow.
  305. if (MachOTC.SupportsEmbeddedBitcode()) {
  306. CmdArgs.push_back("-bitcode_bundle");
  307. if (C.getDriver().embedBitcodeMarkerOnly() && Version[0] >= 278) {
  308. CmdArgs.push_back("-bitcode_process_mode");
  309. CmdArgs.push_back("marker");
  310. }
  311. } else
  312. D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
  313. }
  314. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  315. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  316. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  317. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  318. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  319. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  320. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  321. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  322. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  323. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  324. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  325. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  326. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  327. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  328. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  329. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  330. // Give --sysroot= preference, over the Apple specific behavior to also use
  331. // --isysroot as the syslibroot.
  332. StringRef sysroot = C.getSysRoot();
  333. if (sysroot != "") {
  334. CmdArgs.push_back("-syslibroot");
  335. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  336. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  337. CmdArgs.push_back("-syslibroot");
  338. CmdArgs.push_back(A->getValue());
  339. }
  340. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  341. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  342. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  343. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  344. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  345. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  346. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  347. Args.AddAllArgs(CmdArgs, options::OPT_y);
  348. Args.AddLastArg(CmdArgs, options::OPT_w);
  349. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  350. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  351. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  352. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  353. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  354. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  355. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  356. Args.AddLastArg(CmdArgs, options::OPT_whyload);
  357. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  358. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  359. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  360. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  361. }
  362. /// Determine whether we are linking the ObjC runtime.
  363. static bool isObjCRuntimeLinked(const ArgList &Args) {
  364. if (isObjCAutoRefCount(Args)) {
  365. Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
  366. return true;
  367. }
  368. return Args.hasArg(options::OPT_fobjc_link_runtime);
  369. }
  370. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  371. const InputInfo &Output,
  372. const InputInfoList &Inputs,
  373. const ArgList &Args,
  374. const char *LinkingOutput) const {
  375. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  376. // If the number of arguments surpasses the system limits, we will encode the
  377. // input files in a separate file, shortening the command line. To this end,
  378. // build a list of input file names that can be passed via a file with the
  379. // -filelist linker option.
  380. llvm::opt::ArgStringList InputFileList;
  381. // The logic here is derived from gcc's behavior; most of which
  382. // comes from specs (starting with link_command). Consult gcc for
  383. // more information.
  384. ArgStringList CmdArgs;
  385. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  386. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  387. options::OPT_ccc_arcmt_migrate)) {
  388. for (const auto &Arg : Args)
  389. Arg->claim();
  390. const char *Exec =
  391. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  392. CmdArgs.push_back(Output.getFilename());
  393. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
  394. return;
  395. }
  396. // I'm not sure why this particular decomposition exists in gcc, but
  397. // we follow suite for ease of comparison.
  398. AddLinkArgs(C, Args, CmdArgs, Inputs);
  399. // For LTO, pass the name of the optimization record file and other
  400. // opt-remarks flags.
  401. if (Args.hasFlag(options::OPT_fsave_optimization_record,
  402. options::OPT_fno_save_optimization_record, false)) {
  403. CmdArgs.push_back("-mllvm");
  404. CmdArgs.push_back("-lto-pass-remarks-output");
  405. CmdArgs.push_back("-mllvm");
  406. SmallString<128> F;
  407. F = Output.getFilename();
  408. F += ".opt.yaml";
  409. CmdArgs.push_back(Args.MakeArgString(F));
  410. if (getLastProfileUseArg(Args)) {
  411. CmdArgs.push_back("-mllvm");
  412. CmdArgs.push_back("-lto-pass-remarks-with-hotness");
  413. if (const Arg *A =
  414. Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
  415. CmdArgs.push_back("-mllvm");
  416. std::string Opt =
  417. std::string("-lto-pass-remarks-hotness-threshold=") + A->getValue();
  418. CmdArgs.push_back(Args.MakeArgString(Opt));
  419. }
  420. }
  421. if (const Arg *A =
  422. Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
  423. CmdArgs.push_back("-mllvm");
  424. std::string Passes =
  425. std::string("-lto-pass-remarks-filter=") + A->getValue();
  426. CmdArgs.push_back(Args.MakeArgString(Passes));
  427. }
  428. }
  429. // Propagate the -moutline flag to the linker in LTO.
  430. if (Arg *A =
  431. Args.getLastArg(options::OPT_moutline, options::OPT_mno_outline)) {
  432. if (A->getOption().matches(options::OPT_moutline)) {
  433. if (getMachOToolChain().getMachOArchName(Args) == "arm64") {
  434. CmdArgs.push_back("-mllvm");
  435. CmdArgs.push_back("-enable-machine-outliner");
  436. // Outline from linkonceodr functions by default in LTO.
  437. CmdArgs.push_back("-mllvm");
  438. CmdArgs.push_back("-enable-linkonceodr-outlining");
  439. }
  440. } else {
  441. // Disable all outlining behaviour if we have mno-outline. We need to do
  442. // this explicitly, because targets which support default outlining will
  443. // try to do work if we don't.
  444. CmdArgs.push_back("-mllvm");
  445. CmdArgs.push_back("-enable-machine-outliner=never");
  446. }
  447. }
  448. // It seems that the 'e' option is completely ignored for dynamic executables
  449. // (the default), and with static executables, the last one wins, as expected.
  450. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  451. options::OPT_Z_Flag, options::OPT_u_Group,
  452. options::OPT_e, options::OPT_r});
  453. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  454. // members of static archive libraries which implement Objective-C classes or
  455. // categories.
  456. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  457. CmdArgs.push_back("-ObjC");
  458. CmdArgs.push_back("-o");
  459. CmdArgs.push_back(Output.getFilename());
  460. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  461. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  462. Args.AddAllArgs(CmdArgs, options::OPT_L);
  463. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  464. // Build the input file for -filelist (list of linker input files) in case we
  465. // need it later
  466. for (const auto &II : Inputs) {
  467. if (!II.isFilename()) {
  468. // This is a linker input argument.
  469. // We cannot mix input arguments and file names in a -filelist input, thus
  470. // we prematurely stop our list (remaining files shall be passed as
  471. // arguments).
  472. if (InputFileList.size() > 0)
  473. break;
  474. continue;
  475. }
  476. InputFileList.push_back(II.getFilename());
  477. }
  478. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
  479. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  480. if (isObjCRuntimeLinked(Args) &&
  481. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  482. // We use arclite library for both ARC and subscripting support.
  483. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  484. CmdArgs.push_back("-framework");
  485. CmdArgs.push_back("Foundation");
  486. // Link libobj.
  487. CmdArgs.push_back("-lobjc");
  488. }
  489. if (LinkingOutput) {
  490. CmdArgs.push_back("-arch_multiple");
  491. CmdArgs.push_back("-final_output");
  492. CmdArgs.push_back(LinkingOutput);
  493. }
  494. if (Args.hasArg(options::OPT_fnested_functions))
  495. CmdArgs.push_back("-allow_stack_execute");
  496. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  497. if (unsigned Parallelism =
  498. getLTOParallelism(Args, getToolChain().getDriver())) {
  499. CmdArgs.push_back("-mllvm");
  500. CmdArgs.push_back(Args.MakeArgString("-threads=" + Twine(Parallelism)));
  501. }
  502. if (getToolChain().ShouldLinkCXXStdlib(Args))
  503. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  504. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  505. // link_ssp spec is empty.
  506. // Let the tool chain choose which runtime library to link.
  507. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
  508. // No need to do anything for pthreads. Claim argument to avoid warning.
  509. Args.ClaimAllArgs(options::OPT_pthread);
  510. Args.ClaimAllArgs(options::OPT_pthreads);
  511. }
  512. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  513. // endfile_spec is empty.
  514. }
  515. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  516. Args.AddAllArgs(CmdArgs, options::OPT_F);
  517. // -iframework should be forwarded as -F.
  518. for (const Arg *A : Args.filtered(options::OPT_iframework))
  519. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  520. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  521. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  522. if (A->getValue() == StringRef("Accelerate")) {
  523. CmdArgs.push_back("-framework");
  524. CmdArgs.push_back("Accelerate");
  525. }
  526. }
  527. }
  528. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  529. std::unique_ptr<Command> Cmd =
  530. llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
  531. Cmd->setInputFileList(std::move(InputFileList));
  532. C.addCommand(std::move(Cmd));
  533. }
  534. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  535. const InputInfo &Output,
  536. const InputInfoList &Inputs,
  537. const ArgList &Args,
  538. const char *LinkingOutput) const {
  539. ArgStringList CmdArgs;
  540. CmdArgs.push_back("-create");
  541. assert(Output.isFilename() && "Unexpected lipo output.");
  542. CmdArgs.push_back("-output");
  543. CmdArgs.push_back(Output.getFilename());
  544. for (const auto &II : Inputs) {
  545. assert(II.isFilename() && "Unexpected lipo input.");
  546. CmdArgs.push_back(II.getFilename());
  547. }
  548. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  549. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  550. }
  551. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  552. const InputInfo &Output,
  553. const InputInfoList &Inputs,
  554. const ArgList &Args,
  555. const char *LinkingOutput) const {
  556. ArgStringList CmdArgs;
  557. CmdArgs.push_back("-o");
  558. CmdArgs.push_back(Output.getFilename());
  559. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  560. const InputInfo &Input = Inputs[0];
  561. assert(Input.isFilename() && "Unexpected dsymutil input.");
  562. CmdArgs.push_back(Input.getFilename());
  563. const char *Exec =
  564. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  565. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  566. }
  567. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  568. const InputInfo &Output,
  569. const InputInfoList &Inputs,
  570. const ArgList &Args,
  571. const char *LinkingOutput) const {
  572. ArgStringList CmdArgs;
  573. CmdArgs.push_back("--verify");
  574. CmdArgs.push_back("--debug-info");
  575. CmdArgs.push_back("--eh-frame");
  576. CmdArgs.push_back("--quiet");
  577. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  578. const InputInfo &Input = Inputs[0];
  579. assert(Input.isFilename() && "Unexpected verify input");
  580. // Grabbing the output of the earlier dsymutil run.
  581. CmdArgs.push_back(Input.getFilename());
  582. const char *Exec =
  583. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  584. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  585. }
  586. MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  587. : ToolChain(D, Triple, Args) {
  588. // We expect 'as', 'ld', etc. to be adjacent to our install dir.
  589. getProgramPaths().push_back(getDriver().getInstalledDir());
  590. if (getDriver().getInstalledDir() != getDriver().Dir)
  591. getProgramPaths().push_back(getDriver().Dir);
  592. }
  593. /// Darwin - Darwin tool chain for i386 and x86_64.
  594. Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  595. : MachO(D, Triple, Args), TargetInitialized(false),
  596. CudaInstallation(D, Triple, Args) {}
  597. types::ID MachO::LookupTypeForExtension(StringRef Ext) const {
  598. types::ID Ty = types::lookupTypeForExtension(Ext);
  599. // Darwin always preprocesses assembly files (unless -x is used explicitly).
  600. if (Ty == types::TY_PP_Asm)
  601. return types::TY_Asm;
  602. return Ty;
  603. }
  604. bool MachO::HasNativeLLVMSupport() const { return true; }
  605. ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
  606. // Default to use libc++ on OS X 10.9+ and iOS 7+.
  607. if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
  608. (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
  609. isTargetWatchOSBased())
  610. return ToolChain::CST_Libcxx;
  611. return ToolChain::CST_Libstdcxx;
  612. }
  613. /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
  614. ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
  615. if (isTargetWatchOSBased())
  616. return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
  617. if (isTargetIOSBased())
  618. return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
  619. if (isNonFragile)
  620. return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
  621. return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
  622. }
  623. /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
  624. bool Darwin::hasBlocksRuntime() const {
  625. if (isTargetWatchOSBased())
  626. return true;
  627. else if (isTargetIOSBased())
  628. return !isIPhoneOSVersionLT(3, 2);
  629. else {
  630. assert(isTargetMacOS() && "unexpected darwin target");
  631. return !isMacosxVersionLT(10, 6);
  632. }
  633. }
  634. void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs,
  635. ArgStringList &CC1Args) const {
  636. CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
  637. }
  638. // This is just a MachO name translation routine and there's no
  639. // way to join this into ARMTargetParser without breaking all
  640. // other assumptions. Maybe MachO should consider standardising
  641. // their nomenclature.
  642. static const char *ArmMachOArchName(StringRef Arch) {
  643. return llvm::StringSwitch<const char *>(Arch)
  644. .Case("armv6k", "armv6")
  645. .Case("armv6m", "armv6m")
  646. .Case("armv5tej", "armv5")
  647. .Case("xscale", "xscale")
  648. .Case("armv4t", "armv4t")
  649. .Case("armv7", "armv7")
  650. .Cases("armv7a", "armv7-a", "armv7")
  651. .Cases("armv7r", "armv7-r", "armv7")
  652. .Cases("armv7em", "armv7e-m", "armv7em")
  653. .Cases("armv7k", "armv7-k", "armv7k")
  654. .Cases("armv7m", "armv7-m", "armv7m")
  655. .Cases("armv7s", "armv7-s", "armv7s")
  656. .Default(nullptr);
  657. }
  658. static const char *ArmMachOArchNameCPU(StringRef CPU) {
  659. llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
  660. if (ArchKind == llvm::ARM::ArchKind::INVALID)
  661. return nullptr;
  662. StringRef Arch = llvm::ARM::getArchName(ArchKind);
  663. // FIXME: Make sure this MachO triple mangling is really necessary.
  664. // ARMv5* normalises to ARMv5.
  665. if (Arch.startswith("armv5"))
  666. Arch = Arch.substr(0, 5);
  667. // ARMv6*, except ARMv6M, normalises to ARMv6.
  668. else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
  669. Arch = Arch.substr(0, 5);
  670. // ARMv7A normalises to ARMv7.
  671. else if (Arch.endswith("v7a"))
  672. Arch = Arch.substr(0, 5);
  673. return Arch.data();
  674. }
  675. StringRef MachO::getMachOArchName(const ArgList &Args) const {
  676. switch (getTriple().getArch()) {
  677. default:
  678. return getDefaultUniversalArchName();
  679. case llvm::Triple::aarch64:
  680. return "arm64";
  681. case llvm::Triple::thumb:
  682. case llvm::Triple::arm:
  683. if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ))
  684. if (const char *Arch = ArmMachOArchName(A->getValue()))
  685. return Arch;
  686. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  687. if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
  688. return Arch;
  689. return "arm";
  690. }
  691. }
  692. Darwin::~Darwin() {}
  693. MachO::~MachO() {}
  694. std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
  695. types::ID InputType) const {
  696. llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
  697. // If the target isn't initialized (e.g., an unknown Darwin platform, return
  698. // the default triple).
  699. if (!isTargetInitialized())
  700. return Triple.getTriple();
  701. SmallString<16> Str;
  702. if (isTargetWatchOSBased())
  703. Str += "watchos";
  704. else if (isTargetTvOSBased())
  705. Str += "tvos";
  706. else if (isTargetIOSBased())
  707. Str += "ios";
  708. else
  709. Str += "macosx";
  710. Str += getTargetVersion().getAsString();
  711. Triple.setOSName(Str);
  712. return Triple.getTriple();
  713. }
  714. Tool *MachO::getTool(Action::ActionClass AC) const {
  715. switch (AC) {
  716. case Action::LipoJobClass:
  717. if (!Lipo)
  718. Lipo.reset(new tools::darwin::Lipo(*this));
  719. return Lipo.get();
  720. case Action::DsymutilJobClass:
  721. if (!Dsymutil)
  722. Dsymutil.reset(new tools::darwin::Dsymutil(*this));
  723. return Dsymutil.get();
  724. case Action::VerifyDebugInfoJobClass:
  725. if (!VerifyDebug)
  726. VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
  727. return VerifyDebug.get();
  728. default:
  729. return ToolChain::getTool(AC);
  730. }
  731. }
  732. Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
  733. Tool *MachO::buildAssembler() const {
  734. return new tools::darwin::Assembler(*this);
  735. }
  736. DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
  737. const ArgList &Args)
  738. : Darwin(D, Triple, Args) {}
  739. void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
  740. // For modern targets, promote certain warnings to errors.
  741. if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
  742. // Always enable -Wdeprecated-objc-isa-usage and promote it
  743. // to an error.
  744. CC1Args.push_back("-Wdeprecated-objc-isa-usage");
  745. CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
  746. // For iOS and watchOS, also error about implicit function declarations,
  747. // as that can impact calling conventions.
  748. if (!isTargetMacOS())
  749. CC1Args.push_back("-Werror=implicit-function-declaration");
  750. }
  751. }
  752. void DarwinClang::AddLinkARCArgs(const ArgList &Args,
  753. ArgStringList &CmdArgs) const {
  754. // Avoid linking compatibility stubs on i386 mac.
  755. if (isTargetMacOS() && getArch() == llvm::Triple::x86)
  756. return;
  757. ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
  758. if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
  759. runtime.hasSubscripting())
  760. return;
  761. CmdArgs.push_back("-force_load");
  762. SmallString<128> P(getDriver().ClangExecutable);
  763. llvm::sys::path::remove_filename(P); // 'clang'
  764. llvm::sys::path::remove_filename(P); // 'bin'
  765. llvm::sys::path::append(P, "lib", "arc", "libarclite_");
  766. // Mash in the platform.
  767. if (isTargetWatchOSSimulator())
  768. P += "watchsimulator";
  769. else if (isTargetWatchOS())
  770. P += "watchos";
  771. else if (isTargetTvOSSimulator())
  772. P += "appletvsimulator";
  773. else if (isTargetTvOS())
  774. P += "appletvos";
  775. else if (isTargetIOSSimulator())
  776. P += "iphonesimulator";
  777. else if (isTargetIPhoneOS())
  778. P += "iphoneos";
  779. else
  780. P += "macosx";
  781. P += ".a";
  782. CmdArgs.push_back(Args.MakeArgString(P));
  783. }
  784. unsigned DarwinClang::GetDefaultDwarfVersion() const {
  785. // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
  786. if ((isTargetMacOS() && isMacosxVersionLT(10, 11)) ||
  787. (isTargetIOSBased() && isIPhoneOSVersionLT(9)))
  788. return 2;
  789. return 4;
  790. }
  791. void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
  792. StringRef Component, RuntimeLinkOptions Opts,
  793. bool IsShared) const {
  794. SmallString<64> DarwinLibName = StringRef("libclang_rt.");
  795. // an Darwin the builtins compomnent is not in the library name
  796. if (Component != "builtins") {
  797. DarwinLibName += Component;
  798. if (!(Opts & RLO_IsEmbedded))
  799. DarwinLibName += "_";
  800. DarwinLibName += getOSLibraryNameSuffix();
  801. } else
  802. DarwinLibName += getOSLibraryNameSuffix(true);
  803. DarwinLibName += IsShared ? "_dynamic.dylib" : ".a";
  804. SmallString<128> Dir(getDriver().ResourceDir);
  805. llvm::sys::path::append(
  806. Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin");
  807. SmallString<128> P(Dir);
  808. llvm::sys::path::append(P, DarwinLibName);
  809. // For now, allow missing resource libraries to support developers who may
  810. // not have compiler-rt checked out or integrated into their build (unless
  811. // we explicitly force linking with this library).
  812. if ((Opts & RLO_AlwaysLink) || getVFS().exists(P)) {
  813. const char *LibArg = Args.MakeArgString(P);
  814. if (Opts & RLO_FirstLink)
  815. CmdArgs.insert(CmdArgs.begin(), LibArg);
  816. else
  817. CmdArgs.push_back(LibArg);
  818. }
  819. // Adding the rpaths might negatively interact when other rpaths are involved,
  820. // so we should make sure we add the rpaths last, after all user-specified
  821. // rpaths. This is currently true from this place, but we need to be
  822. // careful if this function is ever called before user's rpaths are emitted.
  823. if (Opts & RLO_AddRPath) {
  824. assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
  825. // Add @executable_path to rpath to support having the dylib copied with
  826. // the executable.
  827. CmdArgs.push_back("-rpath");
  828. CmdArgs.push_back("@executable_path");
  829. // Add the path to the resource dir to rpath to support using the dylib
  830. // from the default location without copying.
  831. CmdArgs.push_back("-rpath");
  832. CmdArgs.push_back(Args.MakeArgString(Dir));
  833. }
  834. }
  835. StringRef Darwin::getPlatformFamily() const {
  836. switch (TargetPlatform) {
  837. case DarwinPlatformKind::MacOS:
  838. return "MacOSX";
  839. case DarwinPlatformKind::IPhoneOS:
  840. return "iPhone";
  841. case DarwinPlatformKind::TvOS:
  842. return "AppleTV";
  843. case DarwinPlatformKind::WatchOS:
  844. return "Watch";
  845. }
  846. llvm_unreachable("Unsupported platform");
  847. }
  848. StringRef Darwin::getSDKName(StringRef isysroot) {
  849. // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
  850. llvm::sys::path::const_iterator SDKDir;
  851. auto BeginSDK = llvm::sys::path::begin(isysroot);
  852. auto EndSDK = llvm::sys::path::end(isysroot);
  853. for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
  854. StringRef SDK = *IT;
  855. if (SDK.endswith(".sdk"))
  856. return SDK.slice(0, SDK.size() - 4);
  857. }
  858. return "";
  859. }
  860. StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const {
  861. switch (TargetPlatform) {
  862. case DarwinPlatformKind::MacOS:
  863. return "osx";
  864. case DarwinPlatformKind::IPhoneOS:
  865. return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios"
  866. : "iossim";
  867. case DarwinPlatformKind::TvOS:
  868. return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos"
  869. : "tvossim";
  870. case DarwinPlatformKind::WatchOS:
  871. return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos"
  872. : "watchossim";
  873. }
  874. llvm_unreachable("Unsupported platform");
  875. }
  876. /// Check if the link command contains a symbol export directive.
  877. static bool hasExportSymbolDirective(const ArgList &Args) {
  878. for (Arg *A : Args) {
  879. if (A->getOption().matches(options::OPT_exported__symbols__list))
  880. return true;
  881. if (!A->getOption().matches(options::OPT_Wl_COMMA) &&
  882. !A->getOption().matches(options::OPT_Xlinker))
  883. continue;
  884. if (A->containsValue("-exported_symbols_list") ||
  885. A->containsValue("-exported_symbol"))
  886. return true;
  887. }
  888. return false;
  889. }
  890. /// Add an export directive for \p Symbol to the link command.
  891. static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
  892. CmdArgs.push_back("-exported_symbol");
  893. CmdArgs.push_back(Symbol);
  894. }
  895. void Darwin::addProfileRTLibs(const ArgList &Args,
  896. ArgStringList &CmdArgs) const {
  897. if (!needsProfileRT(Args)) return;
  898. AddLinkRuntimeLib(Args, CmdArgs, "profile",
  899. RuntimeLinkOptions(RLO_AlwaysLink | RLO_FirstLink));
  900. // If we have a symbol export directive and we're linking in the profile
  901. // runtime, automatically export symbols necessary to implement some of the
  902. // runtime's functionality.
  903. if (hasExportSymbolDirective(Args)) {
  904. if (needsGCovInstrumentation(Args)) {
  905. addExportedSymbol(CmdArgs, "___gcov_flush");
  906. addExportedSymbol(CmdArgs, "_flush_fn_list");
  907. addExportedSymbol(CmdArgs, "_writeout_fn_list");
  908. } else {
  909. addExportedSymbol(CmdArgs, "___llvm_profile_filename");
  910. addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
  911. addExportedSymbol(CmdArgs, "_lprofCurFilename");
  912. }
  913. addExportedSymbol(CmdArgs, "_lprofDirMode");
  914. }
  915. }
  916. void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
  917. ArgStringList &CmdArgs,
  918. StringRef Sanitizer,
  919. bool Shared) const {
  920. auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
  921. AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared);
  922. }
  923. ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
  924. const ArgList &Args) const {
  925. if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
  926. StringRef Value = A->getValue();
  927. if (Value != "compiler-rt")
  928. getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
  929. << Value << "darwin";
  930. }
  931. return ToolChain::RLT_CompilerRT;
  932. }
  933. void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
  934. ArgStringList &CmdArgs) const {
  935. // Call once to ensure diagnostic is printed if wrong value was specified
  936. GetRuntimeLibType(Args);
  937. // Darwin doesn't support real static executables, don't link any runtime
  938. // libraries with -static.
  939. if (Args.hasArg(options::OPT_static) ||
  940. Args.hasArg(options::OPT_fapple_kext) ||
  941. Args.hasArg(options::OPT_mkernel))
  942. return;
  943. // Reject -static-libgcc for now, we can deal with this when and if someone
  944. // cares. This is useful in situations where someone wants to statically link
  945. // something like libstdc++, and needs its runtime support routines.
  946. if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
  947. getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
  948. return;
  949. }
  950. const SanitizerArgs &Sanitize = getSanitizerArgs();
  951. if (Sanitize.needsAsanRt())
  952. AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
  953. if (Sanitize.needsLsanRt())
  954. AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
  955. if (Sanitize.needsUbsanRt())
  956. AddLinkSanitizerLibArgs(Args, CmdArgs,
  957. Sanitize.requiresMinimalRuntime() ? "ubsan_minimal"
  958. : "ubsan",
  959. Sanitize.needsSharedRt());
  960. if (Sanitize.needsTsanRt())
  961. AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
  962. if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
  963. AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
  964. // Libfuzzer is written in C++ and requires libcxx.
  965. AddCXXStdlibLibArgs(Args, CmdArgs);
  966. }
  967. if (Sanitize.needsStatsRt()) {
  968. AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink);
  969. AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
  970. }
  971. const XRayArgs &XRay = getXRayArgs();
  972. if (XRay.needsXRayRt()) {
  973. AddLinkRuntimeLib(Args, CmdArgs, "xray");
  974. AddLinkRuntimeLib(Args, CmdArgs, "xray-basic");
  975. AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr");
  976. }
  977. // Otherwise link libSystem, then the dynamic runtime library, and finally any
  978. // target specific static runtime library.
  979. CmdArgs.push_back("-lSystem");
  980. // Select the dynamic runtime library and the target specific static library.
  981. if (isTargetIOSBased()) {
  982. // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
  983. // it never went into the SDK.
  984. // Linking against libgcc_s.1 isn't needed for iOS 5.0+
  985. if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
  986. getTriple().getArch() != llvm::Triple::aarch64)
  987. CmdArgs.push_back("-lgcc_s.1");
  988. }
  989. AddLinkRuntimeLib(Args, CmdArgs, "builtins");
  990. }
  991. /// Returns the most appropriate macOS target version for the current process.
  992. ///
  993. /// If the macOS SDK version is the same or earlier than the system version,
  994. /// then the SDK version is returned. Otherwise the system version is returned.
  995. static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
  996. unsigned Major, Minor, Micro;
  997. llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
  998. if (!SystemTriple.isMacOSX())
  999. return MacOSSDKVersion;
  1000. SystemTriple.getMacOSXVersion(Major, Minor, Micro);
  1001. VersionTuple SystemVersion(Major, Minor, Micro);
  1002. bool HadExtra;
  1003. if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
  1004. HadExtra))
  1005. return MacOSSDKVersion;
  1006. VersionTuple SDKVersion(Major, Minor, Micro);
  1007. if (SDKVersion > SystemVersion)
  1008. return SystemVersion.getAsString();
  1009. return MacOSSDKVersion;
  1010. }
  1011. namespace {
  1012. /// The Darwin OS that was selected or inferred from arguments / environment.
  1013. struct DarwinPlatform {
  1014. enum SourceKind {
  1015. /// The OS was specified using the -target argument.
  1016. TargetArg,
  1017. /// The OS was specified using the -m<os>-version-min argument.
  1018. OSVersionArg,
  1019. /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
  1020. DeploymentTargetEnv,
  1021. /// The OS was inferred from the SDK.
  1022. InferredFromSDK,
  1023. /// The OS was inferred from the -arch.
  1024. InferredFromArch
  1025. };
  1026. using DarwinPlatformKind = Darwin::DarwinPlatformKind;
  1027. using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
  1028. DarwinPlatformKind getPlatform() const { return Platform; }
  1029. DarwinEnvironmentKind getEnvironment() const { return Environment; }
  1030. void setEnvironment(DarwinEnvironmentKind Kind) {
  1031. Environment = Kind;
  1032. InferSimulatorFromArch = false;
  1033. }
  1034. StringRef getOSVersion() const {
  1035. if (Kind == OSVersionArg)
  1036. return Argument->getValue();
  1037. return OSVersion;
  1038. }
  1039. void setOSVersion(StringRef S) {
  1040. assert(Kind == TargetArg && "Unexpected kind!");
  1041. OSVersion = S;
  1042. }
  1043. bool hasOSVersion() const { return HasOSVersion; }
  1044. /// Returns true if the target OS was explicitly specified.
  1045. bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
  1046. /// Returns true if the simulator environment can be inferred from the arch.
  1047. bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
  1048. /// Adds the -m<os>-version-min argument to the compiler invocation.
  1049. void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
  1050. if (Argument)
  1051. return;
  1052. assert(Kind != TargetArg && Kind != OSVersionArg && "Invalid kind");
  1053. options::ID Opt;
  1054. switch (Platform) {
  1055. case DarwinPlatformKind::MacOS:
  1056. Opt = options::OPT_mmacosx_version_min_EQ;
  1057. break;
  1058. case DarwinPlatformKind::IPhoneOS:
  1059. Opt = options::OPT_miphoneos_version_min_EQ;
  1060. break;
  1061. case DarwinPlatformKind::TvOS:
  1062. Opt = options::OPT_mtvos_version_min_EQ;
  1063. break;
  1064. case DarwinPlatformKind::WatchOS:
  1065. Opt = options::OPT_mwatchos_version_min_EQ;
  1066. break;
  1067. }
  1068. Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion);
  1069. Args.append(Argument);
  1070. }
  1071. /// Returns the OS version with the argument / environment variable that
  1072. /// specified it.
  1073. std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
  1074. switch (Kind) {
  1075. case TargetArg:
  1076. case OSVersionArg:
  1077. case InferredFromSDK:
  1078. case InferredFromArch:
  1079. assert(Argument && "OS version argument not yet inferred");
  1080. return Argument->getAsString(Args);
  1081. case DeploymentTargetEnv:
  1082. return (llvm::Twine(EnvVarName) + "=" + OSVersion).str();
  1083. }
  1084. llvm_unreachable("Unsupported Darwin Source Kind");
  1085. }
  1086. static DarwinPlatform createFromTarget(const llvm::Triple &TT,
  1087. StringRef OSVersion, Arg *A) {
  1088. DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
  1089. A);
  1090. switch (TT.getEnvironment()) {
  1091. case llvm::Triple::Simulator:
  1092. Result.Environment = DarwinEnvironmentKind::Simulator;
  1093. break;
  1094. default:
  1095. break;
  1096. }
  1097. unsigned Major, Minor, Micro;
  1098. TT.getOSVersion(Major, Minor, Micro);
  1099. if (Major == 0)
  1100. Result.HasOSVersion = false;
  1101. return Result;
  1102. }
  1103. static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform,
  1104. Arg *A) {
  1105. return DarwinPlatform(OSVersionArg, Platform, A);
  1106. }
  1107. static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
  1108. StringRef EnvVarName,
  1109. StringRef Value) {
  1110. DarwinPlatform Result(DeploymentTargetEnv, Platform, Value);
  1111. Result.EnvVarName = EnvVarName;
  1112. return Result;
  1113. }
  1114. static DarwinPlatform createFromSDK(DarwinPlatformKind Platform,
  1115. StringRef Value,
  1116. bool IsSimulator = false) {
  1117. DarwinPlatform Result(InferredFromSDK, Platform, Value);
  1118. if (IsSimulator)
  1119. Result.Environment = DarwinEnvironmentKind::Simulator;
  1120. Result.InferSimulatorFromArch = false;
  1121. return Result;
  1122. }
  1123. static DarwinPlatform createFromArch(llvm::Triple::OSType OS,
  1124. StringRef Value) {
  1125. return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value);
  1126. }
  1127. /// Constructs an inferred SDKInfo value based on the version inferred from
  1128. /// the SDK path itself. Only works for values that were created by inferring
  1129. /// the platform from the SDKPath.
  1130. DarwinSDKInfo inferSDKInfo() {
  1131. assert(Kind == InferredFromSDK && "can infer SDK info only");
  1132. llvm::VersionTuple Version;
  1133. bool IsValid = !Version.tryParse(OSVersion);
  1134. (void)IsValid;
  1135. assert(IsValid && "invalid SDK version");
  1136. return DarwinSDKInfo(Version);
  1137. }
  1138. private:
  1139. DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
  1140. : Kind(Kind), Platform(Platform), Argument(Argument) {}
  1141. DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value,
  1142. Arg *Argument = nullptr)
  1143. : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {}
  1144. static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
  1145. switch (OS) {
  1146. case llvm::Triple::Darwin:
  1147. case llvm::Triple::MacOSX:
  1148. return DarwinPlatformKind::MacOS;
  1149. case llvm::Triple::IOS:
  1150. return DarwinPlatformKind::IPhoneOS;
  1151. case llvm::Triple::TvOS:
  1152. return DarwinPlatformKind::TvOS;
  1153. case llvm::Triple::WatchOS:
  1154. return DarwinPlatformKind::WatchOS;
  1155. default:
  1156. llvm_unreachable("Unable to infer Darwin variant");
  1157. }
  1158. }
  1159. SourceKind Kind;
  1160. DarwinPlatformKind Platform;
  1161. DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
  1162. std::string OSVersion;
  1163. bool HasOSVersion = true, InferSimulatorFromArch = true;
  1164. Arg *Argument;
  1165. StringRef EnvVarName;
  1166. };
  1167. /// Returns the deployment target that's specified using the -m<os>-version-min
  1168. /// argument.
  1169. Optional<DarwinPlatform>
  1170. getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
  1171. const Driver &TheDriver) {
  1172. Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
  1173. Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ,
  1174. options::OPT_mios_simulator_version_min_EQ);
  1175. Arg *TvOSVersion =
  1176. Args.getLastArg(options::OPT_mtvos_version_min_EQ,
  1177. options::OPT_mtvos_simulator_version_min_EQ);
  1178. Arg *WatchOSVersion =
  1179. Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
  1180. options::OPT_mwatchos_simulator_version_min_EQ);
  1181. if (OSXVersion) {
  1182. if (iOSVersion || TvOSVersion || WatchOSVersion) {
  1183. TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
  1184. << OSXVersion->getAsString(Args)
  1185. << (iOSVersion ? iOSVersion
  1186. : TvOSVersion ? TvOSVersion : WatchOSVersion)
  1187. ->getAsString(Args);
  1188. }
  1189. return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion);
  1190. } else if (iOSVersion) {
  1191. if (TvOSVersion || WatchOSVersion) {
  1192. TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
  1193. << iOSVersion->getAsString(Args)
  1194. << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
  1195. }
  1196. return DarwinPlatform::createOSVersionArg(Darwin::IPhoneOS, iOSVersion);
  1197. } else if (TvOSVersion) {
  1198. if (WatchOSVersion) {
  1199. TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
  1200. << TvOSVersion->getAsString(Args)
  1201. << WatchOSVersion->getAsString(Args);
  1202. }
  1203. return DarwinPlatform::createOSVersionArg(Darwin::TvOS, TvOSVersion);
  1204. } else if (WatchOSVersion)
  1205. return DarwinPlatform::createOSVersionArg(Darwin::WatchOS, WatchOSVersion);
  1206. return None;
  1207. }
  1208. /// Returns the deployment target that's specified using the
  1209. /// OS_DEPLOYMENT_TARGET environment variable.
  1210. Optional<DarwinPlatform>
  1211. getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
  1212. const llvm::Triple &Triple) {
  1213. std::string Targets[Darwin::LastDarwinPlatform + 1];
  1214. const char *EnvVars[] = {
  1215. "MACOSX_DEPLOYMENT_TARGET",
  1216. "IPHONEOS_DEPLOYMENT_TARGET",
  1217. "TVOS_DEPLOYMENT_TARGET",
  1218. "WATCHOS_DEPLOYMENT_TARGET",
  1219. };
  1220. static_assert(llvm::array_lengthof(EnvVars) == Darwin::LastDarwinPlatform + 1,
  1221. "Missing platform");
  1222. for (const auto &I : llvm::enumerate(llvm::makeArrayRef(EnvVars))) {
  1223. if (char *Env = ::getenv(I.value()))
  1224. Targets[I.index()] = Env;
  1225. }
  1226. // Do not allow conflicts with the watchOS target.
  1227. if (!Targets[Darwin::WatchOS].empty() &&
  1228. (!Targets[Darwin::IPhoneOS].empty() || !Targets[Darwin::TvOS].empty())) {
  1229. TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
  1230. << "WATCHOS_DEPLOYMENT_TARGET"
  1231. << (!Targets[Darwin::IPhoneOS].empty() ? "IPHONEOS_DEPLOYMENT_TARGET"
  1232. : "TVOS_DEPLOYMENT_TARGET");
  1233. }
  1234. // Do not allow conflicts with the tvOS target.
  1235. if (!Targets[Darwin::TvOS].empty() && !Targets[Darwin::IPhoneOS].empty()) {
  1236. TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
  1237. << "TVOS_DEPLOYMENT_TARGET"
  1238. << "IPHONEOS_DEPLOYMENT_TARGET";
  1239. }
  1240. // Allow conflicts among OSX and iOS for historical reasons, but choose the
  1241. // default platform.
  1242. if (!Targets[Darwin::MacOS].empty() &&
  1243. (!Targets[Darwin::IPhoneOS].empty() ||
  1244. !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty())) {
  1245. if (Triple.getArch() == llvm::Triple::arm ||
  1246. Triple.getArch() == llvm::Triple::aarch64 ||
  1247. Triple.getArch() == llvm::Triple::thumb)
  1248. Targets[Darwin::MacOS] = "";
  1249. else
  1250. Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
  1251. Targets[Darwin::TvOS] = "";
  1252. }
  1253. for (const auto &Target : llvm::enumerate(llvm::makeArrayRef(Targets))) {
  1254. if (!Target.value().empty())
  1255. return DarwinPlatform::createDeploymentTargetEnv(
  1256. (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
  1257. Target.value());
  1258. }
  1259. return None;
  1260. }
  1261. /// Tries to infer the deployment target from the SDK specified by -isysroot
  1262. /// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
  1263. /// it's available.
  1264. Optional<DarwinPlatform>
  1265. inferDeploymentTargetFromSDK(DerivedArgList &Args,
  1266. const Optional<DarwinSDKInfo> &SDKInfo) {
  1267. const Arg *A = Args.getLastArg(options::OPT_isysroot);
  1268. if (!A)
  1269. return None;
  1270. StringRef isysroot = A->getValue();
  1271. StringRef SDK = Darwin::getSDKName(isysroot);
  1272. if (!SDK.size())
  1273. return None;
  1274. std::string Version;
  1275. if (SDKInfo) {
  1276. // Get the version from the SDKSettings.json if it's available.
  1277. Version = SDKInfo->getVersion().getAsString();
  1278. } else {
  1279. // Slice the version number out.
  1280. // Version number is between the first and the last number.
  1281. size_t StartVer = SDK.find_first_of("0123456789");
  1282. size_t EndVer = SDK.find_last_of("0123456789");
  1283. if (StartVer != StringRef::npos && EndVer > StartVer)
  1284. Version = SDK.slice(StartVer, EndVer + 1);
  1285. }
  1286. if (Version.empty())
  1287. return None;
  1288. if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
  1289. return DarwinPlatform::createFromSDK(
  1290. Darwin::IPhoneOS, Version,
  1291. /*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
  1292. else if (SDK.startswith("MacOSX"))
  1293. return DarwinPlatform::createFromSDK(Darwin::MacOS,
  1294. getSystemOrSDKMacOSVersion(Version));
  1295. else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
  1296. return DarwinPlatform::createFromSDK(
  1297. Darwin::WatchOS, Version,
  1298. /*IsSimulator=*/SDK.startswith("WatchSimulator"));
  1299. else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
  1300. return DarwinPlatform::createFromSDK(
  1301. Darwin::TvOS, Version,
  1302. /*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
  1303. return None;
  1304. }
  1305. std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple,
  1306. const Driver &TheDriver) {
  1307. unsigned Major, Minor, Micro;
  1308. llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
  1309. switch (OS) {
  1310. case llvm::Triple::Darwin:
  1311. case llvm::Triple::MacOSX:
  1312. // If there is no version specified on triple, and both host and target are
  1313. // macos, use the host triple to infer OS version.
  1314. if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
  1315. !Triple.getOSMajorVersion())
  1316. SystemTriple.getMacOSXVersion(Major, Minor, Micro);
  1317. else if (!Triple.getMacOSXVersion(Major, Minor, Micro))
  1318. TheDriver.Diag(diag::err_drv_invalid_darwin_version)
  1319. << Triple.getOSName();
  1320. break;
  1321. case llvm::Triple::IOS:
  1322. Triple.getiOSVersion(Major, Minor, Micro);
  1323. break;
  1324. case llvm::Triple::TvOS:
  1325. Triple.getOSVersion(Major, Minor, Micro);
  1326. break;
  1327. case llvm::Triple::WatchOS:
  1328. Triple.getWatchOSVersion(Major, Minor, Micro);
  1329. break;
  1330. default:
  1331. llvm_unreachable("Unexpected OS type");
  1332. break;
  1333. }
  1334. std::string OSVersion;
  1335. llvm::raw_string_ostream(OSVersion) << Major << '.' << Minor << '.' << Micro;
  1336. return OSVersion;
  1337. }
  1338. /// Tries to infer the target OS from the -arch.
  1339. Optional<DarwinPlatform>
  1340. inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
  1341. const llvm::Triple &Triple,
  1342. const Driver &TheDriver) {
  1343. llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
  1344. StringRef MachOArchName = Toolchain.getMachOArchName(Args);
  1345. if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
  1346. MachOArchName == "arm64")
  1347. OSTy = llvm::Triple::IOS;
  1348. else if (MachOArchName == "armv7k")
  1349. OSTy = llvm::Triple::WatchOS;
  1350. else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
  1351. MachOArchName != "armv7em")
  1352. OSTy = llvm::Triple::MacOSX;
  1353. if (OSTy == llvm::Triple::UnknownOS)
  1354. return None;
  1355. return DarwinPlatform::createFromArch(OSTy,
  1356. getOSVersion(OSTy, Triple, TheDriver));
  1357. }
  1358. /// Returns the deployment target that's specified using the -target option.
  1359. Optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
  1360. DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver) {
  1361. if (!Args.hasArg(options::OPT_target))
  1362. return None;
  1363. if (Triple.getOS() == llvm::Triple::Darwin ||
  1364. Triple.getOS() == llvm::Triple::UnknownOS)
  1365. return None;
  1366. std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver);
  1367. return DarwinPlatform::createFromTarget(Triple, OSVersion,
  1368. Args.getLastArg(options::OPT_target));
  1369. }
  1370. Optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
  1371. const ArgList &Args,
  1372. const Driver &TheDriver) {
  1373. const Arg *A = Args.getLastArg(options::OPT_isysroot);
  1374. if (!A)
  1375. return None;
  1376. StringRef isysroot = A->getValue();
  1377. auto SDKInfoOrErr = driver::parseDarwinSDKInfo(VFS, isysroot);
  1378. if (!SDKInfoOrErr) {
  1379. llvm::consumeError(SDKInfoOrErr.takeError());
  1380. TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);
  1381. return None;
  1382. }
  1383. return *SDKInfoOrErr;
  1384. }
  1385. } // namespace
  1386. void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
  1387. const OptTable &Opts = getDriver().getOpts();
  1388. // Support allowing the SDKROOT environment variable used by xcrun and other
  1389. // Xcode tools to define the default sysroot, by making it the default for
  1390. // isysroot.
  1391. if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  1392. // Warn if the path does not exist.
  1393. if (!getVFS().exists(A->getValue()))
  1394. getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
  1395. } else {
  1396. if (char *env = ::getenv("SDKROOT")) {
  1397. // We only use this value as the default if it is an absolute path,
  1398. // exists, and it is not the root path.
  1399. if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
  1400. StringRef(env) != "/") {
  1401. Args.append(Args.MakeSeparateArg(
  1402. nullptr, Opts.getOption(options::OPT_isysroot), env));
  1403. }
  1404. }
  1405. }
  1406. // Read the SDKSettings.json file for more information, like the SDK version
  1407. // that we can pass down to the compiler.
  1408. SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
  1409. // The OS and the version can be specified using the -target argument.
  1410. Optional<DarwinPlatform> OSTarget =
  1411. getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver());
  1412. if (OSTarget) {
  1413. Optional<DarwinPlatform> OSVersionArgTarget =
  1414. getDeploymentTargetFromOSVersionArg(Args, getDriver());
  1415. if (OSVersionArgTarget) {
  1416. unsigned TargetMajor, TargetMinor, TargetMicro;
  1417. bool TargetExtra;
  1418. unsigned ArgMajor, ArgMinor, ArgMicro;
  1419. bool ArgExtra;
  1420. if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() ||
  1421. (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor,
  1422. TargetMinor, TargetMicro, TargetExtra) &&
  1423. Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(),
  1424. ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
  1425. (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
  1426. VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
  1427. TargetExtra != ArgExtra))) {
  1428. // Select the OS version from the -m<os>-version-min argument when
  1429. // the -target does not include an OS version.
  1430. if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() &&
  1431. !OSTarget->hasOSVersion()) {
  1432. OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion());
  1433. } else {
  1434. // Warn about -m<os>-version-min that doesn't match the OS version
  1435. // that's specified in the target.
  1436. std::string OSVersionArg =
  1437. OSVersionArgTarget->getAsString(Args, Opts);
  1438. std::string TargetArg = OSTarget->getAsString(Args, Opts);
  1439. getDriver().Diag(clang::diag::warn_drv_overriding_flag_option)
  1440. << OSVersionArg << TargetArg;
  1441. }
  1442. }
  1443. }
  1444. } else {
  1445. // The OS target can be specified using the -m<os>version-min argument.
  1446. OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver());
  1447. // If no deployment target was specified on the command line, check for
  1448. // environment defines.
  1449. if (!OSTarget) {
  1450. OSTarget =
  1451. getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
  1452. if (OSTarget) {
  1453. // Don't infer simulator from the arch when the SDK is also specified.
  1454. Optional<DarwinPlatform> SDKTarget =
  1455. inferDeploymentTargetFromSDK(Args, SDKInfo);
  1456. if (SDKTarget)
  1457. OSTarget->setEnvironment(SDKTarget->getEnvironment());
  1458. }
  1459. }
  1460. // If there is no command-line argument to specify the Target version and
  1461. // no environment variable defined, see if we can set the default based
  1462. // on -isysroot using SDKSettings.json if it exists.
  1463. if (!OSTarget) {
  1464. OSTarget = inferDeploymentTargetFromSDK(Args, SDKInfo);
  1465. /// If the target was successfully constructed from the SDK path, try to
  1466. /// infer the SDK info if the SDK doesn't have it.
  1467. if (OSTarget && !SDKInfo)
  1468. SDKInfo = OSTarget->inferSDKInfo();
  1469. }
  1470. // If no OS targets have been specified, try to guess platform from -target
  1471. // or arch name and compute the version from the triple.
  1472. if (!OSTarget)
  1473. OSTarget =
  1474. inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
  1475. }
  1476. assert(OSTarget && "Unable to infer Darwin variant");
  1477. OSTarget->addOSVersionMinArgument(Args, Opts);
  1478. DarwinPlatformKind Platform = OSTarget->getPlatform();
  1479. unsigned Major, Minor, Micro;
  1480. bool HadExtra;
  1481. // Set the tool chain target information.
  1482. if (Platform == MacOS) {
  1483. if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
  1484. Micro, HadExtra) ||
  1485. HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
  1486. getDriver().Diag(diag::err_drv_invalid_version_number)
  1487. << OSTarget->getAsString(Args, Opts);
  1488. } else if (Platform == IPhoneOS) {
  1489. if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
  1490. Micro, HadExtra) ||
  1491. HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
  1492. getDriver().Diag(diag::err_drv_invalid_version_number)
  1493. << OSTarget->getAsString(Args, Opts);
  1494. ;
  1495. // For 32-bit targets, the deployment target for iOS has to be earlier than
  1496. // iOS 11.
  1497. if (getTriple().isArch32Bit() && Major >= 11) {
  1498. // If the deployment target is explicitly specified, print a diagnostic.
  1499. if (OSTarget->isExplicitlySpecified()) {
  1500. getDriver().Diag(diag::warn_invalid_ios_deployment_target)
  1501. << OSTarget->getAsString(Args, Opts);
  1502. // Otherwise, set it to 10.99.99.
  1503. } else {
  1504. Major = 10;
  1505. Minor = 99;
  1506. Micro = 99;
  1507. }
  1508. }
  1509. } else if (Platform == TvOS) {
  1510. if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
  1511. Micro, HadExtra) ||
  1512. HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
  1513. getDriver().Diag(diag::err_drv_invalid_version_number)
  1514. << OSTarget->getAsString(Args, Opts);
  1515. } else if (Platform == WatchOS) {
  1516. if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
  1517. Micro, HadExtra) ||
  1518. HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
  1519. getDriver().Diag(diag::err_drv_invalid_version_number)
  1520. << OSTarget->getAsString(Args, Opts);
  1521. } else
  1522. llvm_unreachable("unknown kind of Darwin platform");
  1523. DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
  1524. // Recognize iOS targets with an x86 architecture as the iOS simulator.
  1525. if (Environment == NativeEnvironment && Platform != MacOS &&
  1526. OSTarget->canInferSimulatorFromArch() &&
  1527. (getTriple().getArch() == llvm::Triple::x86 ||
  1528. getTriple().getArch() == llvm::Triple::x86_64))
  1529. Environment = Simulator;
  1530. setTarget(Platform, Environment, Major, Minor, Micro);
  1531. if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  1532. StringRef SDK = getSDKName(A->getValue());
  1533. if (SDK.size() > 0) {
  1534. size_t StartVer = SDK.find_first_of("0123456789");
  1535. StringRef SDKName = SDK.slice(0, StartVer);
  1536. if (!SDKName.startswith(getPlatformFamily()))
  1537. getDriver().Diag(diag::warn_incompatible_sysroot)
  1538. << SDKName << getPlatformFamily();
  1539. }
  1540. }
  1541. }
  1542. void DarwinClang::AddClangCXXStdlibIncludeArgs(
  1543. const llvm::opt::ArgList &DriverArgs,
  1544. llvm::opt::ArgStringList &CC1Args) const {
  1545. // The implementation from a base class will pass through the -stdlib to
  1546. // CC1Args.
  1547. // FIXME: this should not be necessary, remove usages in the frontend
  1548. // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
  1549. ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
  1550. if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
  1551. DriverArgs.hasArg(options::OPT_nostdincxx))
  1552. return;
  1553. switch (GetCXXStdlibType(DriverArgs)) {
  1554. case ToolChain::CST_Libcxx: {
  1555. llvm::StringRef InstallDir = getDriver().getInstalledDir();
  1556. if (InstallDir.empty())
  1557. break;
  1558. // On Darwin, libc++ may be installed alongside the compiler in
  1559. // include/c++/v1.
  1560. // Get from 'foo/bin' to 'foo/include/c++/v1'.
  1561. SmallString<128> P = InstallDir;
  1562. // Note that InstallDir can be relative, so we have to '..' and not
  1563. // parent_path.
  1564. llvm::sys::path::append(P, "..", "include", "c++", "v1");
  1565. addSystemInclude(DriverArgs, CC1Args, P);
  1566. break;
  1567. }
  1568. case ToolChain::CST_Libstdcxx:
  1569. // FIXME: should we do something about it?
  1570. break;
  1571. }
  1572. }
  1573. void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
  1574. ArgStringList &CmdArgs) const {
  1575. CXXStdlibType Type = GetCXXStdlibType(Args);
  1576. switch (Type) {
  1577. case ToolChain::CST_Libcxx:
  1578. CmdArgs.push_back("-lc++");
  1579. break;
  1580. case ToolChain::CST_Libstdcxx:
  1581. // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
  1582. // it was previously found in the gcc lib dir. However, for all the Darwin
  1583. // platforms we care about it was -lstdc++.6, so we search for that
  1584. // explicitly if we can't see an obvious -lstdc++ candidate.
  1585. // Check in the sysroot first.
  1586. if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  1587. SmallString<128> P(A->getValue());
  1588. llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
  1589. if (!getVFS().exists(P)) {
  1590. llvm::sys::path::remove_filename(P);
  1591. llvm::sys::path::append(P, "libstdc++.6.dylib");
  1592. if (getVFS().exists(P)) {
  1593. CmdArgs.push_back(Args.MakeArgString(P));
  1594. return;
  1595. }
  1596. }
  1597. }
  1598. // Otherwise, look in the root.
  1599. // FIXME: This should be removed someday when we don't have to care about
  1600. // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
  1601. if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
  1602. getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
  1603. CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
  1604. return;
  1605. }
  1606. // Otherwise, let the linker search.
  1607. CmdArgs.push_back("-lstdc++");
  1608. break;
  1609. }
  1610. }
  1611. void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
  1612. ArgStringList &CmdArgs) const {
  1613. // For Darwin platforms, use the compiler-rt-based support library
  1614. // instead of the gcc-provided one (which is also incidentally
  1615. // only present in the gcc lib dir, which makes it hard to find).
  1616. SmallString<128> P(getDriver().ResourceDir);
  1617. llvm::sys::path::append(P, "lib", "darwin");
  1618. // Use the newer cc_kext for iOS ARM after 6.0.
  1619. if (isTargetWatchOS()) {
  1620. llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
  1621. } else if (isTargetTvOS()) {
  1622. llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
  1623. } else if (isTargetIPhoneOS()) {
  1624. llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
  1625. } else {
  1626. llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
  1627. }
  1628. // For now, allow missing resource libraries to support developers who may
  1629. // not have compiler-rt checked out or integrated into their build.
  1630. if (getVFS().exists(P))
  1631. CmdArgs.push_back(Args.MakeArgString(P));
  1632. }
  1633. DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
  1634. StringRef BoundArch,
  1635. Action::OffloadKind) const {
  1636. DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
  1637. const OptTable &Opts = getDriver().getOpts();
  1638. // FIXME: We really want to get out of the tool chain level argument
  1639. // translation business, as it makes the driver functionality much
  1640. // more opaque. For now, we follow gcc closely solely for the
  1641. // purpose of easily achieving feature parity & testability. Once we
  1642. // have something that works, we should reevaluate each translation
  1643. // and try to push it down into tool specific logic.
  1644. for (Arg *A : Args) {
  1645. if (A->getOption().matches(options::OPT_Xarch__)) {
  1646. // Skip this argument unless the architecture matches either the toolchain
  1647. // triple arch, or the arch being bound.
  1648. llvm::Triple::ArchType XarchArch =
  1649. tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
  1650. if (!(XarchArch == getArch() ||
  1651. (!BoundArch.empty() &&
  1652. XarchArch ==
  1653. tools::darwin::getArchTypeForMachOArchName(BoundArch))))
  1654. continue;
  1655. Arg *OriginalArg = A;
  1656. unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
  1657. unsigned Prev = Index;
  1658. std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
  1659. // If the argument parsing failed or more than one argument was
  1660. // consumed, the -Xarch_ argument's parameter tried to consume
  1661. // extra arguments. Emit an error and ignore.
  1662. //
  1663. // We also want to disallow any options which would alter the
  1664. // driver behavior; that isn't going to work in our model. We
  1665. // use isDriverOption() as an approximation, although things
  1666. // like -O4 are going to slip through.
  1667. if (!XarchArg || Index > Prev + 1) {
  1668. getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
  1669. << A->getAsString(Args);
  1670. continue;
  1671. } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
  1672. getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
  1673. << A->getAsString(Args);
  1674. continue;
  1675. }
  1676. XarchArg->setBaseArg(A);
  1677. A = XarchArg.release();
  1678. DAL->AddSynthesizedArg(A);
  1679. // Linker input arguments require custom handling. The problem is that we
  1680. // have already constructed the phase actions, so we can not treat them as
  1681. // "input arguments".
  1682. if (A->getOption().hasFlag(options::LinkerInput)) {
  1683. // Convert the argument into individual Zlinker_input_args.
  1684. for (const char *Value : A->getValues()) {
  1685. DAL->AddSeparateArg(
  1686. OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
  1687. }
  1688. continue;
  1689. }
  1690. }
  1691. // Sob. These is strictly gcc compatible for the time being. Apple
  1692. // gcc translates options twice, which means that self-expanding
  1693. // options add duplicates.
  1694. switch ((options::ID)A->getOption().getID()) {
  1695. default:
  1696. DAL->append(A);
  1697. break;
  1698. case options::OPT_mkernel:
  1699. case options::OPT_fapple_kext:
  1700. DAL->append(A);
  1701. DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
  1702. break;
  1703. case options::OPT_dependency_file:
  1704. DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
  1705. break;
  1706. case options::OPT_gfull:
  1707. DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
  1708. DAL->AddFlagArg(
  1709. A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
  1710. break;
  1711. case options::OPT_gused:
  1712. DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
  1713. DAL->AddFlagArg(
  1714. A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
  1715. break;
  1716. case options::OPT_shared:
  1717. DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
  1718. break;
  1719. case options::OPT_fconstant_cfstrings:
  1720. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
  1721. break;
  1722. case options::OPT_fno_constant_cfstrings:
  1723. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
  1724. break;
  1725. case options::OPT_Wnonportable_cfstrings:
  1726. DAL->AddFlagArg(A,
  1727. Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
  1728. break;
  1729. case options::OPT_Wno_nonportable_cfstrings:
  1730. DAL->AddFlagArg(
  1731. A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
  1732. break;
  1733. case options::OPT_fpascal_strings:
  1734. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
  1735. break;
  1736. case options::OPT_fno_pascal_strings:
  1737. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
  1738. break;
  1739. }
  1740. }
  1741. if (getTriple().getArch() == llvm::Triple::x86 ||
  1742. getTriple().getArch() == llvm::Triple::x86_64)
  1743. if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
  1744. DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
  1745. "core2");
  1746. // Add the arch options based on the particular spelling of -arch, to match
  1747. // how the driver driver works.
  1748. if (!BoundArch.empty()) {
  1749. StringRef Name = BoundArch;
  1750. const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
  1751. const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
  1752. // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
  1753. // which defines the list of which architectures we accept.
  1754. if (Name == "ppc")
  1755. ;
  1756. else if (Name == "ppc601")
  1757. DAL->AddJoinedArg(nullptr, MCpu, "601");
  1758. else if (Name == "ppc603")
  1759. DAL->AddJoinedArg(nullptr, MCpu, "603");
  1760. else if (Name == "ppc604")
  1761. DAL->AddJoinedArg(nullptr, MCpu, "604");
  1762. else if (Name == "ppc604e")
  1763. DAL->AddJoinedArg(nullptr, MCpu, "604e");
  1764. else if (Name == "ppc750")
  1765. DAL->AddJoinedArg(nullptr, MCpu, "750");
  1766. else if (Name == "ppc7400")
  1767. DAL->AddJoinedArg(nullptr, MCpu, "7400");
  1768. else if (Name == "ppc7450")
  1769. DAL->AddJoinedArg(nullptr, MCpu, "7450");
  1770. else if (Name == "ppc970")
  1771. DAL->AddJoinedArg(nullptr, MCpu, "970");
  1772. else if (Name == "ppc64" || Name == "ppc64le")
  1773. DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
  1774. else if (Name == "i386")
  1775. ;
  1776. else if (Name == "i486")
  1777. DAL->AddJoinedArg(nullptr, MArch, "i486");
  1778. else if (Name == "i586")
  1779. DAL->AddJoinedArg(nullptr, MArch, "i586");
  1780. else if (Name == "i686")
  1781. DAL->AddJoinedArg(nullptr, MArch, "i686");
  1782. else if (Name == "pentium")
  1783. DAL->AddJoinedArg(nullptr, MArch, "pentium");
  1784. else if (Name == "pentium2")
  1785. DAL->AddJoinedArg(nullptr, MArch, "pentium2");
  1786. else if (Name == "pentpro")
  1787. DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
  1788. else if (Name == "pentIIm3")
  1789. DAL->AddJoinedArg(nullptr, MArch, "pentium2");
  1790. else if (Name == "x86_64" || Name == "x86_64h")
  1791. DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
  1792. else if (Name == "arm")
  1793. DAL->AddJoinedArg(nullptr, MArch, "armv4t");
  1794. else if (Name == "armv4t")
  1795. DAL->AddJoinedArg(nullptr, MArch, "armv4t");
  1796. else if (Name == "armv5")
  1797. DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
  1798. else if (Name == "xscale")
  1799. DAL->AddJoinedArg(nullptr, MArch, "xscale");
  1800. else if (Name == "armv6")
  1801. DAL->AddJoinedArg(nullptr, MArch, "armv6k");
  1802. else if (Name == "armv6m")
  1803. DAL->AddJoinedArg(nullptr, MArch, "armv6m");
  1804. else if (Name == "armv7")
  1805. DAL->AddJoinedArg(nullptr, MArch, "armv7a");
  1806. else if (Name == "armv7em")
  1807. DAL->AddJoinedArg(nullptr, MArch, "armv7em");
  1808. else if (Name == "armv7k")
  1809. DAL->AddJoinedArg(nullptr, MArch, "armv7k");
  1810. else if (Name == "armv7m")
  1811. DAL->AddJoinedArg(nullptr, MArch, "armv7m");
  1812. else if (Name == "armv7s")
  1813. DAL->AddJoinedArg(nullptr, MArch, "armv7s");
  1814. }
  1815. return DAL;
  1816. }
  1817. void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
  1818. ArgStringList &CmdArgs) const {
  1819. // Embedded targets are simple at the moment, not supporting sanitizers and
  1820. // with different libraries for each member of the product { static, PIC } x
  1821. // { hard-float, soft-float }
  1822. llvm::SmallString<32> CompilerRT = StringRef("");
  1823. CompilerRT +=
  1824. (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
  1825. ? "hard"
  1826. : "soft";
  1827. CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
  1828. AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
  1829. }
  1830. bool Darwin::isAlignedAllocationUnavailable() const {
  1831. llvm::Triple::OSType OS;
  1832. switch (TargetPlatform) {
  1833. case MacOS: // Earlier than 10.13.
  1834. OS = llvm::Triple::MacOSX;
  1835. break;
  1836. case IPhoneOS:
  1837. OS = llvm::Triple::IOS;
  1838. break;
  1839. case TvOS: // Earlier than 11.0.
  1840. OS = llvm::Triple::TvOS;
  1841. break;
  1842. case WatchOS: // Earlier than 4.0.
  1843. OS = llvm::Triple::WatchOS;
  1844. break;
  1845. }
  1846. return TargetVersion < alignedAllocMinVersion(OS);
  1847. }
  1848. void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
  1849. llvm::opt::ArgStringList &CC1Args,
  1850. Action::OffloadKind DeviceOffloadKind) const {
  1851. // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
  1852. // enabled or disabled aligned allocations.
  1853. if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
  1854. options::OPT_fno_aligned_allocation) &&
  1855. isAlignedAllocationUnavailable())
  1856. CC1Args.push_back("-faligned-alloc-unavailable");
  1857. if (SDKInfo) {
  1858. /// Pass the SDK version to the compiler when the SDK information is
  1859. /// available.
  1860. std::string Arg;
  1861. llvm::raw_string_ostream OS(Arg);
  1862. OS << "-target-sdk-version=" << SDKInfo->getVersion();
  1863. CC1Args.push_back(DriverArgs.MakeArgString(OS.str()));
  1864. }
  1865. }
  1866. DerivedArgList *
  1867. Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
  1868. Action::OffloadKind DeviceOffloadKind) const {
  1869. // First get the generic Apple args, before moving onto Darwin-specific ones.
  1870. DerivedArgList *DAL =
  1871. MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
  1872. const OptTable &Opts = getDriver().getOpts();
  1873. // If no architecture is bound, none of the translations here are relevant.
  1874. if (BoundArch.empty())
  1875. return DAL;
  1876. // Add an explicit version min argument for the deployment target. We do this
  1877. // after argument translation because -Xarch_ arguments may add a version min
  1878. // argument.
  1879. AddDeploymentTarget(*DAL);
  1880. // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
  1881. // FIXME: It would be far better to avoid inserting those -static arguments,
  1882. // but we can't check the deployment target in the translation code until
  1883. // it is set here.
  1884. if (isTargetWatchOSBased() ||
  1885. (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
  1886. for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
  1887. Arg *A = *it;
  1888. ++it;
  1889. if (A->getOption().getID() != options::OPT_mkernel &&
  1890. A->getOption().getID() != options::OPT_fapple_kext)
  1891. continue;
  1892. assert(it != ie && "unexpected argument translation");
  1893. A = *it;
  1894. assert(A->getOption().getID() == options::OPT_static &&
  1895. "missing expected -static argument");
  1896. *it = nullptr;
  1897. ++it;
  1898. }
  1899. }
  1900. if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
  1901. GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  1902. DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
  1903. "libc++");
  1904. // Validate the C++ standard library choice.
  1905. CXXStdlibType Type = GetCXXStdlibType(*DAL);
  1906. if (Type == ToolChain::CST_Libcxx) {
  1907. // Check whether the target provides libc++.
  1908. StringRef where;
  1909. // Complain about targeting iOS < 5.0 in any way.
  1910. if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
  1911. where = "iOS 5.0";
  1912. if (where != StringRef()) {
  1913. getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
  1914. }
  1915. }
  1916. auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
  1917. if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
  1918. if (Args.hasFlag(options::OPT_fomit_frame_pointer,
  1919. options::OPT_fno_omit_frame_pointer, false))
  1920. getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
  1921. << "-fomit-frame-pointer" << BoundArch;
  1922. }
  1923. return DAL;
  1924. }
  1925. bool MachO::IsUnwindTablesDefault(const ArgList &Args) const {
  1926. // Unwind tables are not emitted if -fno-exceptions is supplied (except when
  1927. // targeting x86_64).
  1928. return getArch() == llvm::Triple::x86_64 ||
  1929. (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
  1930. Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  1931. true));
  1932. }
  1933. bool MachO::UseDwarfDebugFlags() const {
  1934. if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
  1935. return S[0] != '\0';
  1936. return false;
  1937. }
  1938. llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
  1939. // Darwin uses SjLj exceptions on ARM.
  1940. if (getTriple().getArch() != llvm::Triple::arm &&
  1941. getTriple().getArch() != llvm::Triple::thumb)
  1942. return llvm::ExceptionHandling::None;
  1943. // Only watchOS uses the new DWARF/Compact unwinding method.
  1944. llvm::Triple Triple(ComputeLLVMTriple(Args));
  1945. if (Triple.isWatchABI())
  1946. return llvm::ExceptionHandling::DwarfCFI;
  1947. return llvm::ExceptionHandling::SjLj;
  1948. }
  1949. bool Darwin::SupportsEmbeddedBitcode() const {
  1950. assert(TargetInitialized && "Target not initialized!");
  1951. if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
  1952. return false;
  1953. return true;
  1954. }
  1955. bool MachO::isPICDefault() const { return true; }
  1956. bool MachO::isPIEDefault() const { return false; }
  1957. bool MachO::isPICDefaultForced() const {
  1958. return (getArch() == llvm::Triple::x86_64 ||
  1959. getArch() == llvm::Triple::aarch64);
  1960. }
  1961. bool MachO::SupportsProfiling() const {
  1962. // Profiling instrumentation is only supported on x86.
  1963. return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
  1964. }
  1965. void Darwin::addMinVersionArgs(const ArgList &Args,
  1966. ArgStringList &CmdArgs) const {
  1967. VersionTuple TargetVersion = getTargetVersion();
  1968. if (isTargetWatchOS())
  1969. CmdArgs.push_back("-watchos_version_min");
  1970. else if (isTargetWatchOSSimulator())
  1971. CmdArgs.push_back("-watchos_simulator_version_min");
  1972. else if (isTargetTvOS())
  1973. CmdArgs.push_back("-tvos_version_min");
  1974. else if (isTargetTvOSSimulator())
  1975. CmdArgs.push_back("-tvos_simulator_version_min");
  1976. else if (isTargetIOSSimulator())
  1977. CmdArgs.push_back("-ios_simulator_version_min");
  1978. else if (isTargetIOSBased())
  1979. CmdArgs.push_back("-iphoneos_version_min");
  1980. else {
  1981. assert(isTargetMacOS() && "unexpected target");
  1982. CmdArgs.push_back("-macosx_version_min");
  1983. }
  1984. CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
  1985. }
  1986. void Darwin::addStartObjectFileArgs(const ArgList &Args,
  1987. ArgStringList &CmdArgs) const {
  1988. // Derived from startfile spec.
  1989. if (Args.hasArg(options::OPT_dynamiclib)) {
  1990. // Derived from darwin_dylib1 spec.
  1991. if (isTargetWatchOSBased()) {
  1992. ; // watchOS does not need dylib1.o.
  1993. } else if (isTargetIOSSimulator()) {
  1994. ; // iOS simulator does not need dylib1.o.
  1995. } else if (isTargetIPhoneOS()) {
  1996. if (isIPhoneOSVersionLT(3, 1))
  1997. CmdArgs.push_back("-ldylib1.o");
  1998. } else {
  1999. if (isMacosxVersionLT(10, 5))
  2000. CmdArgs.push_back("-ldylib1.o");
  2001. else if (isMacosxVersionLT(10, 6))
  2002. CmdArgs.push_back("-ldylib1.10.5.o");
  2003. }
  2004. } else {
  2005. if (Args.hasArg(options::OPT_bundle)) {
  2006. if (!Args.hasArg(options::OPT_static)) {
  2007. // Derived from darwin_bundle1 spec.
  2008. if (isTargetWatchOSBased()) {
  2009. ; // watchOS does not need bundle1.o.
  2010. } else if (isTargetIOSSimulator()) {
  2011. ; // iOS simulator does not need bundle1.o.
  2012. } else if (isTargetIPhoneOS()) {
  2013. if (isIPhoneOSVersionLT(3, 1))
  2014. CmdArgs.push_back("-lbundle1.o");
  2015. } else {
  2016. if (isMacosxVersionLT(10, 6))
  2017. CmdArgs.push_back("-lbundle1.o");
  2018. }
  2019. }
  2020. } else {
  2021. if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
  2022. if (isTargetMacOS() && isMacosxVersionLT(10, 9)) {
  2023. if (Args.hasArg(options::OPT_static) ||
  2024. Args.hasArg(options::OPT_object) ||
  2025. Args.hasArg(options::OPT_preload)) {
  2026. CmdArgs.push_back("-lgcrt0.o");
  2027. } else {
  2028. CmdArgs.push_back("-lgcrt1.o");
  2029. // darwin_crt2 spec is empty.
  2030. }
  2031. // By default on OS X 10.8 and later, we don't link with a crt1.o
  2032. // file and the linker knows to use _main as the entry point. But,
  2033. // when compiling with -pg, we need to link with the gcrt1.o file,
  2034. // so pass the -no_new_main option to tell the linker to use the
  2035. // "start" symbol as the entry point.
  2036. if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
  2037. CmdArgs.push_back("-no_new_main");
  2038. } else {
  2039. getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin)
  2040. << isTargetMacOS();
  2041. }
  2042. } else {
  2043. if (Args.hasArg(options::OPT_static) ||
  2044. Args.hasArg(options::OPT_object) ||
  2045. Args.hasArg(options::OPT_preload)) {
  2046. CmdArgs.push_back("-lcrt0.o");
  2047. } else {
  2048. // Derived from darwin_crt1 spec.
  2049. if (isTargetWatchOSBased()) {
  2050. ; // watchOS does not need crt1.o.
  2051. } else if (isTargetIOSSimulator()) {
  2052. ; // iOS simulator does not need crt1.o.
  2053. } else if (isTargetIPhoneOS()) {
  2054. if (getArch() == llvm::Triple::aarch64)
  2055. ; // iOS does not need any crt1 files for arm64
  2056. else if (isIPhoneOSVersionLT(3, 1))
  2057. CmdArgs.push_back("-lcrt1.o");
  2058. else if (isIPhoneOSVersionLT(6, 0))
  2059. CmdArgs.push_back("-lcrt1.3.1.o");
  2060. } else {
  2061. if (isMacosxVersionLT(10, 5))
  2062. CmdArgs.push_back("-lcrt1.o");
  2063. else if (isMacosxVersionLT(10, 6))
  2064. CmdArgs.push_back("-lcrt1.10.5.o");
  2065. else if (isMacosxVersionLT(10, 8))
  2066. CmdArgs.push_back("-lcrt1.10.6.o");
  2067. // darwin_crt2 spec is empty.
  2068. }
  2069. }
  2070. }
  2071. }
  2072. }
  2073. if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
  2074. !isTargetWatchOS() && isMacosxVersionLT(10, 5)) {
  2075. const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
  2076. CmdArgs.push_back(Str);
  2077. }
  2078. }
  2079. void Darwin::CheckObjCARC() const {
  2080. if (isTargetIOSBased() || isTargetWatchOSBased() ||
  2081. (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
  2082. return;
  2083. getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
  2084. }
  2085. SanitizerMask Darwin::getSupportedSanitizers() const {
  2086. const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
  2087. SanitizerMask Res = ToolChain::getSupportedSanitizers();
  2088. Res |= SanitizerKind::Address;
  2089. Res |= SanitizerKind::PointerCompare;
  2090. Res |= SanitizerKind::PointerSubtract;
  2091. Res |= SanitizerKind::Leak;
  2092. Res |= SanitizerKind::Fuzzer;
  2093. Res |= SanitizerKind::FuzzerNoLink;
  2094. Res |= SanitizerKind::Function;
  2095. // Prior to 10.9, macOS shipped a version of the C++ standard library without
  2096. // C++11 support. The same is true of iOS prior to version 5. These OS'es are
  2097. // incompatible with -fsanitize=vptr.
  2098. if (!(isTargetMacOS() && isMacosxVersionLT(10, 9))
  2099. && !(isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0)))
  2100. Res |= SanitizerKind::Vptr;
  2101. if (isTargetMacOS()) {
  2102. if (IsX86_64)
  2103. Res |= SanitizerKind::Thread;
  2104. } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
  2105. if (IsX86_64)
  2106. Res |= SanitizerKind::Thread;
  2107. }
  2108. return Res;
  2109. }
  2110. void Darwin::printVerboseInfo(raw_ostream &OS) const {
  2111. CudaInstallation.print(OS);
  2112. }