Darwin.cpp 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030
  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/AArch64.h"
  10. #include "Arch/ARM.h"
  11. #include "CommonArgs.h"
  12. #include "clang/Basic/AlignedAllocation.h"
  13. #include "clang/Basic/ObjCRuntime.h"
  14. #include "clang/Config/config.h"
  15. #include "clang/Driver/Compilation.h"
  16. #include "clang/Driver/Driver.h"
  17. #include "clang/Driver/DriverDiagnostic.h"
  18. #include "clang/Driver/Options.h"
  19. #include "clang/Driver/SanitizerArgs.h"
  20. #include "llvm/ADT/StringSwitch.h"
  21. #include "llvm/Option/ArgList.h"
  22. #include "llvm/ProfileData/InstrProf.h"
  23. #include "llvm/Support/Path.h"
  24. #include "llvm/Support/ScopedPrinter.h"
  25. #include "llvm/Support/TargetParser.h"
  26. #include "llvm/Support/Threading.h"
  27. #include "llvm/Support/VirtualFileSystem.h"
  28. #include <cstdlib> // ::getenv
  29. using namespace clang::driver;
  30. using namespace clang::driver::tools;
  31. using namespace clang::driver::toolchains;
  32. using namespace clang;
  33. using namespace llvm::opt;
  34. static VersionTuple minimumMacCatalystDeploymentTarget() {
  35. return VersionTuple(13, 1);
  36. }
  37. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  38. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  39. // archs which Darwin doesn't use.
  40. // The matching this routine does is fairly pointless, since it is neither the
  41. // complete architecture list, nor a reasonable subset. The problem is that
  42. // historically the driver driver accepts this and also ties its -march=
  43. // handling to the architecture name, so we need to be careful before removing
  44. // support for it.
  45. // This code must be kept in sync with Clang's Darwin specific argument
  46. // translation.
  47. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  48. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  49. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  50. .Case("ppc64", llvm::Triple::ppc64)
  51. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  52. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  53. llvm::Triple::x86)
  54. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  55. // This is derived from the driver driver.
  56. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  57. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  58. .Cases("armv7s", "xscale", llvm::Triple::arm)
  59. .Cases("arm64", "arm64e", llvm::Triple::aarch64)
  60. .Case("arm64_32", llvm::Triple::aarch64_32)
  61. .Case("r600", llvm::Triple::r600)
  62. .Case("amdgcn", llvm::Triple::amdgcn)
  63. .Case("nvptx", llvm::Triple::nvptx)
  64. .Case("nvptx64", llvm::Triple::nvptx64)
  65. .Case("amdil", llvm::Triple::amdil)
  66. .Case("spir", llvm::Triple::spir)
  67. .Default(llvm::Triple::UnknownArch);
  68. }
  69. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  70. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  71. llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Str);
  72. T.setArch(Arch);
  73. if (Arch != llvm::Triple::UnknownArch)
  74. T.setArchName(Str);
  75. if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
  76. ArchKind == llvm::ARM::ArchKind::ARMV7M ||
  77. ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
  78. T.setOS(llvm::Triple::UnknownOS);
  79. T.setObjectFormat(llvm::Triple::MachO);
  80. }
  81. }
  82. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  83. const InputInfo &Output,
  84. const InputInfoList &Inputs,
  85. const ArgList &Args,
  86. const char *LinkingOutput) const {
  87. const llvm::Triple &T(getToolChain().getTriple());
  88. ArgStringList CmdArgs;
  89. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  90. const InputInfo &Input = Inputs[0];
  91. // Determine the original source input.
  92. const Action *SourceAction = &JA;
  93. while (SourceAction->getKind() != Action::InputClass) {
  94. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  95. SourceAction = SourceAction->getInputs()[0];
  96. }
  97. // If -fno-integrated-as is used add -Q to the darwin assembler driver to make
  98. // sure it runs its system assembler not clang's integrated assembler.
  99. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  100. // FIXME: at run-time detect assembler capabilities or rely on version
  101. // information forwarded by -target-assembler-version.
  102. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  103. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  104. CmdArgs.push_back("-Q");
  105. }
  106. // Forward -g, assuming we are dealing with an actual assembly file.
  107. if (SourceAction->getType() == types::TY_Asm ||
  108. SourceAction->getType() == types::TY_PP_Asm) {
  109. if (Args.hasArg(options::OPT_gstabs))
  110. CmdArgs.push_back("--gstabs");
  111. else if (Args.hasArg(options::OPT_g_Group))
  112. CmdArgs.push_back("-g");
  113. }
  114. // Derived from asm spec.
  115. AddMachOArch(Args, CmdArgs);
  116. // Use -force_cpusubtype_ALL on x86 by default.
  117. if (T.isX86() || Args.hasArg(options::OPT_force__cpusubtype__ALL))
  118. CmdArgs.push_back("-force_cpusubtype_ALL");
  119. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  120. (((Args.hasArg(options::OPT_mkernel) ||
  121. Args.hasArg(options::OPT_fapple_kext)) &&
  122. getMachOToolChain().isKernelStatic()) ||
  123. Args.hasArg(options::OPT_static)))
  124. CmdArgs.push_back("-static");
  125. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  126. assert(Output.isFilename() && "Unexpected lipo output.");
  127. CmdArgs.push_back("-o");
  128. CmdArgs.push_back(Output.getFilename());
  129. assert(Input.isFilename() && "Invalid input.");
  130. CmdArgs.push_back(Input.getFilename());
  131. // asm_final spec is empty.
  132. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  133. C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
  134. Exec, CmdArgs, Inputs, Output));
  135. }
  136. void darwin::MachOTool::anchor() {}
  137. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  138. ArgStringList &CmdArgs) const {
  139. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  140. // Derived from darwin_arch spec.
  141. CmdArgs.push_back("-arch");
  142. CmdArgs.push_back(Args.MakeArgString(ArchName));
  143. // FIXME: Is this needed anymore?
  144. if (ArchName == "arm")
  145. CmdArgs.push_back("-force_cpusubtype_ALL");
  146. }
  147. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  148. // We only need to generate a temp path for LTO if we aren't compiling object
  149. // files. When compiling source files, we run 'dsymutil' after linking. We
  150. // don't run 'dsymutil' when compiling object files.
  151. for (const auto &Input : Inputs)
  152. if (Input.getType() != types::TY_Object)
  153. return true;
  154. return false;
  155. }
  156. /// Pass -no_deduplicate to ld64 under certain conditions:
  157. ///
  158. /// - Either -O0 or -O1 is explicitly specified
  159. /// - No -O option is specified *and* this is a compile+link (implicit -O0)
  160. ///
  161. /// Also do *not* add -no_deduplicate when no -O option is specified and this
  162. /// is just a link (we can't imply -O0)
  163. static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
  164. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  165. if (A->getOption().matches(options::OPT_O0))
  166. return true;
  167. if (A->getOption().matches(options::OPT_O))
  168. return llvm::StringSwitch<bool>(A->getValue())
  169. .Case("1", true)
  170. .Default(false);
  171. return false; // OPT_Ofast & OPT_O4
  172. }
  173. if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
  174. return true;
  175. return false;
  176. }
  177. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  178. ArgStringList &CmdArgs,
  179. const InputInfoList &Inputs,
  180. unsigned Version[5], bool LinkerIsLLD) const {
  181. const Driver &D = getToolChain().getDriver();
  182. const toolchains::MachO &MachOTC = getMachOToolChain();
  183. // Newer linkers support -demangle. Pass it if supported and not disabled by
  184. // the user.
  185. if ((Version[0] >= 100 || LinkerIsLLD) &&
  186. !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  187. CmdArgs.push_back("-demangle");
  188. // FIXME: Pass most of the flags below that check Version if LinkerIsLLD too.
  189. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  190. CmdArgs.push_back("-export_dynamic");
  191. // If we are using App Extension restrictions, pass a flag to the linker
  192. // telling it that the compiled code has been audited.
  193. if (Args.hasFlag(options::OPT_fapplication_extension,
  194. options::OPT_fno_application_extension, false))
  195. CmdArgs.push_back("-application_extension");
  196. if (D.isUsingLTO() && Version[0] >= 116 && NeedsTempPath(Inputs)) {
  197. std::string TmpPathName;
  198. if (D.getLTOMode() == LTOK_Full) {
  199. // If we are using full LTO, then automatically create a temporary file
  200. // path for the linker to use, so that it's lifetime will extend past a
  201. // possible dsymutil step.
  202. TmpPathName =
  203. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object));
  204. } else if (D.getLTOMode() == LTOK_Thin)
  205. // If we are using thin LTO, then create a directory instead.
  206. TmpPathName = D.GetTemporaryDirectory("thinlto");
  207. if (!TmpPathName.empty()) {
  208. auto *TmpPath = C.getArgs().MakeArgString(TmpPathName);
  209. C.addTempFile(TmpPath);
  210. CmdArgs.push_back("-object_path_lto");
  211. CmdArgs.push_back(TmpPath);
  212. }
  213. }
  214. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  215. // it in clang installed libraries. ld64 will only look at this argument
  216. // when it actually uses LTO, so libLTO.dylib only needs to exist at link
  217. // time if ld64 decides that it needs to use LTO.
  218. // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
  219. // next to it. That's ok since ld64 using a libLTO.dylib not matching the
  220. // clang version won't work anyways.
  221. // lld is built at the same revision as clang and statically links in
  222. // LLVM libraries, so it doesn't need libLTO.dylib.
  223. if (Version[0] >= 133 && !LinkerIsLLD) {
  224. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  225. StringRef P = llvm::sys::path::parent_path(D.Dir);
  226. SmallString<128> LibLTOPath(P);
  227. llvm::sys::path::append(LibLTOPath, "lib");
  228. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  229. CmdArgs.push_back("-lto_library");
  230. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  231. }
  232. // ld64 version 262 and above run the deduplicate pass by default.
  233. if (Version[0] >= 262 && shouldLinkerNotDedup(C.getJobs().empty(), Args))
  234. CmdArgs.push_back("-no_deduplicate");
  235. // Derived from the "link" spec.
  236. Args.AddAllArgs(CmdArgs, options::OPT_static);
  237. if (!Args.hasArg(options::OPT_static))
  238. CmdArgs.push_back("-dynamic");
  239. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  240. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  241. // here. How do we wish to handle such things?
  242. }
  243. if (!Args.hasArg(options::OPT_dynamiclib)) {
  244. AddMachOArch(Args, CmdArgs);
  245. // FIXME: Why do this only on this path?
  246. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  247. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  248. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  249. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  250. Arg *A;
  251. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  252. (A = Args.getLastArg(options::OPT_current__version)) ||
  253. (A = Args.getLastArg(options::OPT_install__name)))
  254. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  255. << "-dynamiclib";
  256. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  257. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  258. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  259. } else {
  260. CmdArgs.push_back("-dylib");
  261. Arg *A;
  262. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  263. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  264. (A = Args.getLastArg(options::OPT_client__name)) ||
  265. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  266. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  267. (A = Args.getLastArg(options::OPT_private__bundle)))
  268. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  269. << "-dynamiclib";
  270. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  271. "-dylib_compatibility_version");
  272. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  273. "-dylib_current_version");
  274. AddMachOArch(Args, CmdArgs);
  275. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  276. "-dylib_install_name");
  277. }
  278. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  279. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  280. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  281. if (MachOTC.isTargetIOSBased())
  282. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  283. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  284. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  285. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  286. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  287. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  288. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  289. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  290. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  291. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  292. Args.AddAllArgs(CmdArgs, options::OPT_init);
  293. // Add the deployment target.
  294. if (Version[0] >= 520 || LinkerIsLLD)
  295. MachOTC.addPlatformVersionArgs(Args, CmdArgs);
  296. else
  297. MachOTC.addMinVersionArgs(Args, CmdArgs);
  298. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  299. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  300. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  301. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  302. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  303. if (const Arg *A =
  304. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  305. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  306. if (A->getOption().matches(options::OPT_fpie) ||
  307. A->getOption().matches(options::OPT_fPIE))
  308. CmdArgs.push_back("-pie");
  309. else
  310. CmdArgs.push_back("-no_pie");
  311. }
  312. // for embed-bitcode, use -bitcode_bundle in linker command
  313. if (C.getDriver().embedBitcodeEnabled()) {
  314. // Check if the toolchain supports bitcode build flow.
  315. if (MachOTC.SupportsEmbeddedBitcode()) {
  316. CmdArgs.push_back("-bitcode_bundle");
  317. if (C.getDriver().embedBitcodeMarkerOnly() && Version[0] >= 278) {
  318. CmdArgs.push_back("-bitcode_process_mode");
  319. CmdArgs.push_back("marker");
  320. }
  321. } else
  322. D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
  323. }
  324. // If GlobalISel is enabled, pass it through to LLVM.
  325. if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
  326. options::OPT_fno_global_isel)) {
  327. if (A->getOption().matches(options::OPT_fglobal_isel)) {
  328. CmdArgs.push_back("-mllvm");
  329. CmdArgs.push_back("-global-isel");
  330. // Disable abort and fall back to SDAG silently.
  331. CmdArgs.push_back("-mllvm");
  332. CmdArgs.push_back("-global-isel-abort=0");
  333. }
  334. }
  335. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  336. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  337. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  338. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  339. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  340. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  341. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  342. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  343. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  344. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  345. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  346. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  347. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  348. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  349. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  350. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  351. // Give --sysroot= preference, over the Apple specific behavior to also use
  352. // --isysroot as the syslibroot.
  353. StringRef sysroot = C.getSysRoot();
  354. if (sysroot != "") {
  355. CmdArgs.push_back("-syslibroot");
  356. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  357. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  358. CmdArgs.push_back("-syslibroot");
  359. CmdArgs.push_back(A->getValue());
  360. }
  361. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  362. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  363. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  364. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  365. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  366. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  367. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  368. Args.AddAllArgs(CmdArgs, options::OPT_y);
  369. Args.AddLastArg(CmdArgs, options::OPT_w);
  370. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  371. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  372. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  373. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  374. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  375. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  376. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  377. Args.AddLastArg(CmdArgs, options::OPT_why_load);
  378. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  379. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  380. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  381. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  382. }
  383. /// Determine whether we are linking the ObjC runtime.
  384. static bool isObjCRuntimeLinked(const ArgList &Args) {
  385. if (isObjCAutoRefCount(Args)) {
  386. Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
  387. return true;
  388. }
  389. return Args.hasArg(options::OPT_fobjc_link_runtime);
  390. }
  391. static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
  392. const llvm::Triple &Triple) {
  393. // When enabling remarks, we need to error if:
  394. // * The remark file is specified but we're targeting multiple architectures,
  395. // which means more than one remark file is being generated.
  396. bool hasMultipleInvocations =
  397. Args.getAllArgValues(options::OPT_arch).size() > 1;
  398. bool hasExplicitOutputFile =
  399. Args.getLastArg(options::OPT_foptimization_record_file_EQ);
  400. if (hasMultipleInvocations && hasExplicitOutputFile) {
  401. D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
  402. << "-foptimization-record-file";
  403. return false;
  404. }
  405. return true;
  406. }
  407. static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
  408. const llvm::Triple &Triple,
  409. const InputInfo &Output, const JobAction &JA) {
  410. StringRef Format = "yaml";
  411. if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
  412. Format = A->getValue();
  413. CmdArgs.push_back("-mllvm");
  414. CmdArgs.push_back("-lto-pass-remarks-output");
  415. CmdArgs.push_back("-mllvm");
  416. const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
  417. if (A) {
  418. CmdArgs.push_back(A->getValue());
  419. } else {
  420. assert(Output.isFilename() && "Unexpected ld output.");
  421. SmallString<128> F;
  422. F = Output.getFilename();
  423. F += ".opt.";
  424. F += Format;
  425. CmdArgs.push_back(Args.MakeArgString(F));
  426. }
  427. if (const Arg *A =
  428. Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
  429. CmdArgs.push_back("-mllvm");
  430. std::string Passes =
  431. std::string("-lto-pass-remarks-filter=") + A->getValue();
  432. CmdArgs.push_back(Args.MakeArgString(Passes));
  433. }
  434. if (!Format.empty()) {
  435. CmdArgs.push_back("-mllvm");
  436. Twine FormatArg = Twine("-lto-pass-remarks-format=") + Format;
  437. CmdArgs.push_back(Args.MakeArgString(FormatArg));
  438. }
  439. if (getLastProfileUseArg(Args)) {
  440. CmdArgs.push_back("-mllvm");
  441. CmdArgs.push_back("-lto-pass-remarks-with-hotness");
  442. if (const Arg *A =
  443. Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
  444. CmdArgs.push_back("-mllvm");
  445. std::string Opt =
  446. std::string("-lto-pass-remarks-hotness-threshold=") + A->getValue();
  447. CmdArgs.push_back(Args.MakeArgString(Opt));
  448. }
  449. }
  450. }
  451. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  452. const InputInfo &Output,
  453. const InputInfoList &Inputs,
  454. const ArgList &Args,
  455. const char *LinkingOutput) const {
  456. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  457. // If the number of arguments surpasses the system limits, we will encode the
  458. // input files in a separate file, shortening the command line. To this end,
  459. // build a list of input file names that can be passed via a file with the
  460. // -filelist linker option.
  461. llvm::opt::ArgStringList InputFileList;
  462. // The logic here is derived from gcc's behavior; most of which
  463. // comes from specs (starting with link_command). Consult gcc for
  464. // more information.
  465. ArgStringList CmdArgs;
  466. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  467. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  468. options::OPT_ccc_arcmt_migrate)) {
  469. for (const auto &Arg : Args)
  470. Arg->claim();
  471. const char *Exec =
  472. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  473. CmdArgs.push_back(Output.getFilename());
  474. C.addCommand(std::make_unique<Command>(
  475. JA, *this, ResponseFileSupport::None(), Exec, CmdArgs, None, Output));
  476. return;
  477. }
  478. unsigned Version[5] = {0, 0, 0, 0, 0};
  479. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  480. if (!Driver::GetReleaseVersion(A->getValue(), Version))
  481. getToolChain().getDriver().Diag(diag::err_drv_invalid_version_number)
  482. << A->getAsString(Args);
  483. }
  484. bool LinkerIsLLD;
  485. const char *Exec =
  486. Args.MakeArgString(getToolChain().GetLinkerPath(&LinkerIsLLD));
  487. // I'm not sure why this particular decomposition exists in gcc, but
  488. // we follow suite for ease of comparison.
  489. AddLinkArgs(C, Args, CmdArgs, Inputs, Version, LinkerIsLLD);
  490. if (willEmitRemarks(Args) &&
  491. checkRemarksOptions(getToolChain().getDriver(), Args,
  492. getToolChain().getTriple()))
  493. renderRemarksOptions(Args, CmdArgs, getToolChain().getTriple(), Output, JA);
  494. // Propagate the -moutline flag to the linker in LTO.
  495. if (Arg *A =
  496. Args.getLastArg(options::OPT_moutline, options::OPT_mno_outline)) {
  497. if (A->getOption().matches(options::OPT_moutline)) {
  498. if (getMachOToolChain().getMachOArchName(Args) == "arm64") {
  499. CmdArgs.push_back("-mllvm");
  500. CmdArgs.push_back("-enable-machine-outliner");
  501. // Outline from linkonceodr functions by default in LTO.
  502. CmdArgs.push_back("-mllvm");
  503. CmdArgs.push_back("-enable-linkonceodr-outlining");
  504. }
  505. } else {
  506. // Disable all outlining behaviour if we have mno-outline. We need to do
  507. // this explicitly, because targets which support default outlining will
  508. // try to do work if we don't.
  509. CmdArgs.push_back("-mllvm");
  510. CmdArgs.push_back("-enable-machine-outliner=never");
  511. }
  512. }
  513. // Setup statistics file output.
  514. SmallString<128> StatsFile =
  515. getStatsFileName(Args, Output, Inputs[0], getToolChain().getDriver());
  516. if (!StatsFile.empty()) {
  517. CmdArgs.push_back("-mllvm");
  518. CmdArgs.push_back(Args.MakeArgString("-lto-stats-file=" + StatsFile.str()));
  519. }
  520. // It seems that the 'e' option is completely ignored for dynamic executables
  521. // (the default), and with static executables, the last one wins, as expected.
  522. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  523. options::OPT_Z_Flag, options::OPT_u_Group,
  524. options::OPT_e, options::OPT_r});
  525. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  526. // members of static archive libraries which implement Objective-C classes or
  527. // categories.
  528. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  529. CmdArgs.push_back("-ObjC");
  530. CmdArgs.push_back("-o");
  531. CmdArgs.push_back(Output.getFilename());
  532. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  533. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  534. Args.AddAllArgs(CmdArgs, options::OPT_L);
  535. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
  536. // Build the input file for -filelist (list of linker input files) in case we
  537. // need it later
  538. for (const auto &II : Inputs) {
  539. if (!II.isFilename()) {
  540. // This is a linker input argument.
  541. // We cannot mix input arguments and file names in a -filelist input, thus
  542. // we prematurely stop our list (remaining files shall be passed as
  543. // arguments).
  544. if (InputFileList.size() > 0)
  545. break;
  546. continue;
  547. }
  548. InputFileList.push_back(II.getFilename());
  549. }
  550. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
  551. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  552. if (isObjCRuntimeLinked(Args) &&
  553. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  554. // We use arclite library for both ARC and subscripting support.
  555. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  556. CmdArgs.push_back("-framework");
  557. CmdArgs.push_back("Foundation");
  558. // Link libobj.
  559. CmdArgs.push_back("-lobjc");
  560. }
  561. if (LinkingOutput) {
  562. CmdArgs.push_back("-arch_multiple");
  563. CmdArgs.push_back("-final_output");
  564. CmdArgs.push_back(LinkingOutput);
  565. }
  566. if (Args.hasArg(options::OPT_fnested_functions))
  567. CmdArgs.push_back("-allow_stack_execute");
  568. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  569. StringRef Parallelism = getLTOParallelism(Args, getToolChain().getDriver());
  570. if (!Parallelism.empty()) {
  571. CmdArgs.push_back("-mllvm");
  572. unsigned NumThreads =
  573. llvm::get_threadpool_strategy(Parallelism)->compute_thread_count();
  574. CmdArgs.push_back(Args.MakeArgString("-threads=" + Twine(NumThreads)));
  575. }
  576. if (getToolChain().ShouldLinkCXXStdlib(Args))
  577. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  578. bool NoStdOrDefaultLibs =
  579. Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
  580. bool ForceLinkBuiltins = Args.hasArg(options::OPT_fapple_link_rtlib);
  581. if (!NoStdOrDefaultLibs || ForceLinkBuiltins) {
  582. // link_ssp spec is empty.
  583. // If we have both -nostdlib/nodefaultlibs and -fapple-link-rtlib then
  584. // we just want to link the builtins, not the other libs like libSystem.
  585. if (NoStdOrDefaultLibs && ForceLinkBuiltins) {
  586. getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs, "builtins");
  587. } else {
  588. // Let the tool chain choose which runtime library to link.
  589. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs,
  590. ForceLinkBuiltins);
  591. // No need to do anything for pthreads. Claim argument to avoid warning.
  592. Args.ClaimAllArgs(options::OPT_pthread);
  593. Args.ClaimAllArgs(options::OPT_pthreads);
  594. }
  595. }
  596. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  597. // endfile_spec is empty.
  598. }
  599. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  600. Args.AddAllArgs(CmdArgs, options::OPT_F);
  601. // -iframework should be forwarded as -F.
  602. for (const Arg *A : Args.filtered(options::OPT_iframework))
  603. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  604. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  605. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  606. if (A->getValue() == StringRef("Accelerate")) {
  607. CmdArgs.push_back("-framework");
  608. CmdArgs.push_back("Accelerate");
  609. }
  610. }
  611. }
  612. ResponseFileSupport ResponseSupport;
  613. if (Version[0] >= 705 || LinkerIsLLD) {
  614. ResponseSupport = ResponseFileSupport::AtFileUTF8();
  615. } else {
  616. // For older versions of the linker, use the legacy filelist method instead.
  617. ResponseSupport = {ResponseFileSupport::RF_FileList, llvm::sys::WEM_UTF8,
  618. "-filelist"};
  619. }
  620. std::unique_ptr<Command> Cmd = std::make_unique<Command>(
  621. JA, *this, ResponseSupport, Exec, CmdArgs, Inputs, Output);
  622. Cmd->setInputFileList(std::move(InputFileList));
  623. C.addCommand(std::move(Cmd));
  624. }
  625. void darwin::StaticLibTool::ConstructJob(Compilation &C, const JobAction &JA,
  626. const InputInfo &Output,
  627. const InputInfoList &Inputs,
  628. const ArgList &Args,
  629. const char *LinkingOutput) const {
  630. const Driver &D = getToolChain().getDriver();
  631. // Silence warning for "clang -g foo.o -o foo"
  632. Args.ClaimAllArgs(options::OPT_g_Group);
  633. // and "clang -emit-llvm foo.o -o foo"
  634. Args.ClaimAllArgs(options::OPT_emit_llvm);
  635. // and for "clang -w foo.o -o foo". Other warning options are already
  636. // handled somewhere else.
  637. Args.ClaimAllArgs(options::OPT_w);
  638. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  639. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  640. // libtool <options> <output_file> <input_files>
  641. ArgStringList CmdArgs;
  642. // Create and insert file members with a deterministic index.
  643. CmdArgs.push_back("-static");
  644. CmdArgs.push_back("-D");
  645. CmdArgs.push_back("-no_warning_for_no_symbols");
  646. CmdArgs.push_back("-o");
  647. CmdArgs.push_back(Output.getFilename());
  648. for (const auto &II : Inputs) {
  649. if (II.isFilename()) {
  650. CmdArgs.push_back(II.getFilename());
  651. }
  652. }
  653. // Delete old output archive file if it already exists before generating a new
  654. // archive file.
  655. const auto *OutputFileName = Output.getFilename();
  656. if (Output.isFilename() && llvm::sys::fs::exists(OutputFileName)) {
  657. if (std::error_code EC = llvm::sys::fs::remove(OutputFileName)) {
  658. D.Diag(diag::err_drv_unable_to_remove_file) << EC.message();
  659. return;
  660. }
  661. }
  662. const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath());
  663. C.addCommand(std::make_unique<Command>(JA, *this,
  664. ResponseFileSupport::AtFileUTF8(),
  665. Exec, CmdArgs, Inputs, Output));
  666. }
  667. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  668. const InputInfo &Output,
  669. const InputInfoList &Inputs,
  670. const ArgList &Args,
  671. const char *LinkingOutput) const {
  672. ArgStringList CmdArgs;
  673. CmdArgs.push_back("-create");
  674. assert(Output.isFilename() && "Unexpected lipo output.");
  675. CmdArgs.push_back("-output");
  676. CmdArgs.push_back(Output.getFilename());
  677. for (const auto &II : Inputs) {
  678. assert(II.isFilename() && "Unexpected lipo input.");
  679. CmdArgs.push_back(II.getFilename());
  680. }
  681. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  682. C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
  683. Exec, CmdArgs, Inputs, Output));
  684. }
  685. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  686. const InputInfo &Output,
  687. const InputInfoList &Inputs,
  688. const ArgList &Args,
  689. const char *LinkingOutput) const {
  690. ArgStringList CmdArgs;
  691. CmdArgs.push_back("-o");
  692. CmdArgs.push_back(Output.getFilename());
  693. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  694. const InputInfo &Input = Inputs[0];
  695. assert(Input.isFilename() && "Unexpected dsymutil input.");
  696. CmdArgs.push_back(Input.getFilename());
  697. const char *Exec =
  698. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  699. C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
  700. Exec, CmdArgs, Inputs, Output));
  701. }
  702. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  703. const InputInfo &Output,
  704. const InputInfoList &Inputs,
  705. const ArgList &Args,
  706. const char *LinkingOutput) const {
  707. ArgStringList CmdArgs;
  708. CmdArgs.push_back("--verify");
  709. CmdArgs.push_back("--debug-info");
  710. CmdArgs.push_back("--eh-frame");
  711. CmdArgs.push_back("--quiet");
  712. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  713. const InputInfo &Input = Inputs[0];
  714. assert(Input.isFilename() && "Unexpected verify input");
  715. // Grabbing the output of the earlier dsymutil run.
  716. CmdArgs.push_back(Input.getFilename());
  717. const char *Exec =
  718. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  719. C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
  720. Exec, CmdArgs, Inputs, Output));
  721. }
  722. MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  723. : ToolChain(D, Triple, Args) {
  724. // We expect 'as', 'ld', etc. to be adjacent to our install dir.
  725. getProgramPaths().push_back(getDriver().getInstalledDir());
  726. if (getDriver().getInstalledDir() != getDriver().Dir)
  727. getProgramPaths().push_back(getDriver().Dir);
  728. }
  729. /// Darwin - Darwin tool chain for i386 and x86_64.
  730. Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
  731. : MachO(D, Triple, Args), TargetInitialized(false),
  732. CudaInstallation(D, Triple, Args), RocmInstallation(D, Triple, Args) {}
  733. types::ID MachO::LookupTypeForExtension(StringRef Ext) const {
  734. types::ID Ty = ToolChain::LookupTypeForExtension(Ext);
  735. // Darwin always preprocesses assembly files (unless -x is used explicitly).
  736. if (Ty == types::TY_PP_Asm)
  737. return types::TY_Asm;
  738. return Ty;
  739. }
  740. bool MachO::HasNativeLLVMSupport() const { return true; }
  741. ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
  742. // Default to use libc++ on OS X 10.9+ and iOS 7+.
  743. if ((isTargetMacOSBased() && !isMacosxVersionLT(10, 9)) ||
  744. (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
  745. isTargetWatchOSBased())
  746. return ToolChain::CST_Libcxx;
  747. return ToolChain::CST_Libstdcxx;
  748. }
  749. /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
  750. ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
  751. if (isTargetWatchOSBased())
  752. return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
  753. if (isTargetIOSBased())
  754. return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
  755. if (isNonFragile)
  756. return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
  757. return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
  758. }
  759. /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
  760. bool Darwin::hasBlocksRuntime() const {
  761. if (isTargetWatchOSBased())
  762. return true;
  763. else if (isTargetIOSBased())
  764. return !isIPhoneOSVersionLT(3, 2);
  765. else {
  766. assert(isTargetMacOSBased() && "unexpected darwin target");
  767. return !isMacosxVersionLT(10, 6);
  768. }
  769. }
  770. void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs,
  771. ArgStringList &CC1Args) const {
  772. CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
  773. }
  774. void Darwin::AddHIPIncludeArgs(const ArgList &DriverArgs,
  775. ArgStringList &CC1Args) const {
  776. RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
  777. }
  778. // This is just a MachO name translation routine and there's no
  779. // way to join this into ARMTargetParser without breaking all
  780. // other assumptions. Maybe MachO should consider standardising
  781. // their nomenclature.
  782. static const char *ArmMachOArchName(StringRef Arch) {
  783. return llvm::StringSwitch<const char *>(Arch)
  784. .Case("armv6k", "armv6")
  785. .Case("armv6m", "armv6m")
  786. .Case("armv5tej", "armv5")
  787. .Case("xscale", "xscale")
  788. .Case("armv4t", "armv4t")
  789. .Case("armv7", "armv7")
  790. .Cases("armv7a", "armv7-a", "armv7")
  791. .Cases("armv7r", "armv7-r", "armv7")
  792. .Cases("armv7em", "armv7e-m", "armv7em")
  793. .Cases("armv7k", "armv7-k", "armv7k")
  794. .Cases("armv7m", "armv7-m", "armv7m")
  795. .Cases("armv7s", "armv7-s", "armv7s")
  796. .Default(nullptr);
  797. }
  798. static const char *ArmMachOArchNameCPU(StringRef CPU) {
  799. llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
  800. if (ArchKind == llvm::ARM::ArchKind::INVALID)
  801. return nullptr;
  802. StringRef Arch = llvm::ARM::getArchName(ArchKind);
  803. // FIXME: Make sure this MachO triple mangling is really necessary.
  804. // ARMv5* normalises to ARMv5.
  805. if (Arch.startswith("armv5"))
  806. Arch = Arch.substr(0, 5);
  807. // ARMv6*, except ARMv6M, normalises to ARMv6.
  808. else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
  809. Arch = Arch.substr(0, 5);
  810. // ARMv7A normalises to ARMv7.
  811. else if (Arch.endswith("v7a"))
  812. Arch = Arch.substr(0, 5);
  813. return Arch.data();
  814. }
  815. StringRef MachO::getMachOArchName(const ArgList &Args) const {
  816. switch (getTriple().getArch()) {
  817. default:
  818. return getDefaultUniversalArchName();
  819. case llvm::Triple::aarch64_32:
  820. return "arm64_32";
  821. case llvm::Triple::aarch64: {
  822. if (getTriple().isArm64e())
  823. return "arm64e";
  824. return "arm64";
  825. }
  826. case llvm::Triple::thumb:
  827. case llvm::Triple::arm:
  828. if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ))
  829. if (const char *Arch = ArmMachOArchName(A->getValue()))
  830. return Arch;
  831. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  832. if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
  833. return Arch;
  834. return "arm";
  835. }
  836. }
  837. Darwin::~Darwin() {}
  838. MachO::~MachO() {}
  839. std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
  840. types::ID InputType) const {
  841. llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
  842. // If the target isn't initialized (e.g., an unknown Darwin platform, return
  843. // the default triple).
  844. if (!isTargetInitialized())
  845. return Triple.getTriple();
  846. SmallString<16> Str;
  847. if (isTargetWatchOSBased())
  848. Str += "watchos";
  849. else if (isTargetTvOSBased())
  850. Str += "tvos";
  851. else if (isTargetIOSBased() || isTargetMacCatalyst())
  852. Str += "ios";
  853. else
  854. Str += "macosx";
  855. Str += getTripleTargetVersion().getAsString();
  856. Triple.setOSName(Str);
  857. return Triple.getTriple();
  858. }
  859. Tool *MachO::getTool(Action::ActionClass AC) const {
  860. switch (AC) {
  861. case Action::LipoJobClass:
  862. if (!Lipo)
  863. Lipo.reset(new tools::darwin::Lipo(*this));
  864. return Lipo.get();
  865. case Action::DsymutilJobClass:
  866. if (!Dsymutil)
  867. Dsymutil.reset(new tools::darwin::Dsymutil(*this));
  868. return Dsymutil.get();
  869. case Action::VerifyDebugInfoJobClass:
  870. if (!VerifyDebug)
  871. VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
  872. return VerifyDebug.get();
  873. default:
  874. return ToolChain::getTool(AC);
  875. }
  876. }
  877. Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
  878. Tool *MachO::buildStaticLibTool() const {
  879. return new tools::darwin::StaticLibTool(*this);
  880. }
  881. Tool *MachO::buildAssembler() const {
  882. return new tools::darwin::Assembler(*this);
  883. }
  884. DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
  885. const ArgList &Args)
  886. : Darwin(D, Triple, Args) {}
  887. void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
  888. // Always error about undefined 'TARGET_OS_*' macros.
  889. CC1Args.push_back("-Wundef-prefix=TARGET_OS_");
  890. CC1Args.push_back("-Werror=undef-prefix");
  891. // For modern targets, promote certain warnings to errors.
  892. if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
  893. // Always enable -Wdeprecated-objc-isa-usage and promote it
  894. // to an error.
  895. CC1Args.push_back("-Wdeprecated-objc-isa-usage");
  896. CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
  897. // For iOS and watchOS, also error about implicit function declarations,
  898. // as that can impact calling conventions.
  899. if (!isTargetMacOS())
  900. CC1Args.push_back("-Werror=implicit-function-declaration");
  901. }
  902. }
  903. /// Take a path that speculatively points into Xcode and return the
  904. /// `XCODE/Contents/Developer` path if it is an Xcode path, or an empty path
  905. /// otherwise.
  906. static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode) {
  907. static constexpr llvm::StringLiteral XcodeAppSuffix(
  908. ".app/Contents/Developer");
  909. size_t Index = PathIntoXcode.find(XcodeAppSuffix);
  910. if (Index == StringRef::npos)
  911. return "";
  912. return PathIntoXcode.take_front(Index + XcodeAppSuffix.size());
  913. }
  914. void DarwinClang::AddLinkARCArgs(const ArgList &Args,
  915. ArgStringList &CmdArgs) const {
  916. // Avoid linking compatibility stubs on i386 mac.
  917. if (isTargetMacOSBased() && getArch() == llvm::Triple::x86)
  918. return;
  919. if (isTargetAppleSiliconMac())
  920. return;
  921. // ARC runtime is supported everywhere on arm64e.
  922. if (getTriple().isArm64e())
  923. return;
  924. ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
  925. if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
  926. runtime.hasSubscripting())
  927. return;
  928. SmallString<128> P(getDriver().ClangExecutable);
  929. llvm::sys::path::remove_filename(P); // 'clang'
  930. llvm::sys::path::remove_filename(P); // 'bin'
  931. // 'libarclite' usually lives in the same toolchain as 'clang'. However, the
  932. // Swift open source toolchains for macOS distribute Clang without libarclite.
  933. // In that case, to allow the linker to find 'libarclite', we point to the
  934. // 'libarclite' in the XcodeDefault toolchain instead.
  935. if (getXcodeDeveloperPath(P).empty()) {
  936. if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  937. // Try to infer the path to 'libarclite' in the toolchain from the
  938. // specified SDK path.
  939. StringRef XcodePathForSDK = getXcodeDeveloperPath(A->getValue());
  940. if (!XcodePathForSDK.empty()) {
  941. P = XcodePathForSDK;
  942. llvm::sys::path::append(P, "Toolchains/XcodeDefault.xctoolchain/usr");
  943. }
  944. }
  945. }
  946. CmdArgs.push_back("-force_load");
  947. llvm::sys::path::append(P, "lib", "arc", "libarclite_");
  948. // Mash in the platform.
  949. if (isTargetWatchOSSimulator())
  950. P += "watchsimulator";
  951. else if (isTargetWatchOS())
  952. P += "watchos";
  953. else if (isTargetTvOSSimulator())
  954. P += "appletvsimulator";
  955. else if (isTargetTvOS())
  956. P += "appletvos";
  957. else if (isTargetIOSSimulator())
  958. P += "iphonesimulator";
  959. else if (isTargetIPhoneOS())
  960. P += "iphoneos";
  961. else
  962. P += "macosx";
  963. P += ".a";
  964. CmdArgs.push_back(Args.MakeArgString(P));
  965. }
  966. unsigned DarwinClang::GetDefaultDwarfVersion() const {
  967. // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
  968. if ((isTargetMacOSBased() && isMacosxVersionLT(10, 11)) ||
  969. (isTargetIOSBased() && isIPhoneOSVersionLT(9)))
  970. return 2;
  971. return 4;
  972. }
  973. void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
  974. StringRef Component, RuntimeLinkOptions Opts,
  975. bool IsShared) const {
  976. SmallString<64> DarwinLibName = StringRef("libclang_rt.");
  977. // an Darwin the builtins compomnent is not in the library name
  978. if (Component != "builtins") {
  979. DarwinLibName += Component;
  980. if (!(Opts & RLO_IsEmbedded))
  981. DarwinLibName += "_";
  982. }
  983. DarwinLibName += getOSLibraryNameSuffix();
  984. DarwinLibName += IsShared ? "_dynamic.dylib" : ".a";
  985. SmallString<128> Dir(getDriver().ResourceDir);
  986. llvm::sys::path::append(
  987. Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin");
  988. SmallString<128> P(Dir);
  989. llvm::sys::path::append(P, DarwinLibName);
  990. // For now, allow missing resource libraries to support developers who may
  991. // not have compiler-rt checked out or integrated into their build (unless
  992. // we explicitly force linking with this library).
  993. if ((Opts & RLO_AlwaysLink) || getVFS().exists(P)) {
  994. const char *LibArg = Args.MakeArgString(P);
  995. CmdArgs.push_back(LibArg);
  996. }
  997. // Adding the rpaths might negatively interact when other rpaths are involved,
  998. // so we should make sure we add the rpaths last, after all user-specified
  999. // rpaths. This is currently true from this place, but we need to be
  1000. // careful if this function is ever called before user's rpaths are emitted.
  1001. if (Opts & RLO_AddRPath) {
  1002. assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
  1003. // Add @executable_path to rpath to support having the dylib copied with
  1004. // the executable.
  1005. CmdArgs.push_back("-rpath");
  1006. CmdArgs.push_back("@executable_path");
  1007. // Add the path to the resource dir to rpath to support using the dylib
  1008. // from the default location without copying.
  1009. CmdArgs.push_back("-rpath");
  1010. CmdArgs.push_back(Args.MakeArgString(Dir));
  1011. }
  1012. }
  1013. StringRef Darwin::getPlatformFamily() const {
  1014. switch (TargetPlatform) {
  1015. case DarwinPlatformKind::MacOS:
  1016. return "MacOSX";
  1017. case DarwinPlatformKind::IPhoneOS:
  1018. if (TargetEnvironment == MacCatalyst)
  1019. return "MacOSX";
  1020. return "iPhone";
  1021. case DarwinPlatformKind::TvOS:
  1022. return "AppleTV";
  1023. case DarwinPlatformKind::WatchOS:
  1024. return "Watch";
  1025. }
  1026. llvm_unreachable("Unsupported platform");
  1027. }
  1028. StringRef Darwin::getSDKName(StringRef isysroot) {
  1029. // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
  1030. auto BeginSDK = llvm::sys::path::rbegin(isysroot);
  1031. auto EndSDK = llvm::sys::path::rend(isysroot);
  1032. for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
  1033. StringRef SDK = *IT;
  1034. if (SDK.endswith(".sdk"))
  1035. return SDK.slice(0, SDK.size() - 4);
  1036. }
  1037. return "";
  1038. }
  1039. StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const {
  1040. switch (TargetPlatform) {
  1041. case DarwinPlatformKind::MacOS:
  1042. return "osx";
  1043. case DarwinPlatformKind::IPhoneOS:
  1044. if (TargetEnvironment == MacCatalyst)
  1045. return "osx";
  1046. return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios"
  1047. : "iossim";
  1048. case DarwinPlatformKind::TvOS:
  1049. return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos"
  1050. : "tvossim";
  1051. case DarwinPlatformKind::WatchOS:
  1052. return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos"
  1053. : "watchossim";
  1054. }
  1055. llvm_unreachable("Unsupported platform");
  1056. }
  1057. /// Check if the link command contains a symbol export directive.
  1058. static bool hasExportSymbolDirective(const ArgList &Args) {
  1059. for (Arg *A : Args) {
  1060. if (A->getOption().matches(options::OPT_exported__symbols__list))
  1061. return true;
  1062. if (!A->getOption().matches(options::OPT_Wl_COMMA) &&
  1063. !A->getOption().matches(options::OPT_Xlinker))
  1064. continue;
  1065. if (A->containsValue("-exported_symbols_list") ||
  1066. A->containsValue("-exported_symbol"))
  1067. return true;
  1068. }
  1069. return false;
  1070. }
  1071. /// Add an export directive for \p Symbol to the link command.
  1072. static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
  1073. CmdArgs.push_back("-exported_symbol");
  1074. CmdArgs.push_back(Symbol);
  1075. }
  1076. /// Add a sectalign directive for \p Segment and \p Section to the maximum
  1077. /// expected page size for Darwin.
  1078. ///
  1079. /// On iPhone 6+ the max supported page size is 16K. On macOS, the max is 4K.
  1080. /// Use a common alignment constant (16K) for now, and reduce the alignment on
  1081. /// macOS if it proves important.
  1082. static void addSectalignToPage(const ArgList &Args, ArgStringList &CmdArgs,
  1083. StringRef Segment, StringRef Section) {
  1084. for (const char *A : {"-sectalign", Args.MakeArgString(Segment),
  1085. Args.MakeArgString(Section), "0x4000"})
  1086. CmdArgs.push_back(A);
  1087. }
  1088. void Darwin::addProfileRTLibs(const ArgList &Args,
  1089. ArgStringList &CmdArgs) const {
  1090. if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
  1091. return;
  1092. AddLinkRuntimeLib(Args, CmdArgs, "profile",
  1093. RuntimeLinkOptions(RLO_AlwaysLink));
  1094. bool ForGCOV = needsGCovInstrumentation(Args);
  1095. // If we have a symbol export directive and we're linking in the profile
  1096. // runtime, automatically export symbols necessary to implement some of the
  1097. // runtime's functionality.
  1098. if (hasExportSymbolDirective(Args)) {
  1099. if (ForGCOV) {
  1100. addExportedSymbol(CmdArgs, "___gcov_dump");
  1101. addExportedSymbol(CmdArgs, "___gcov_reset");
  1102. addExportedSymbol(CmdArgs, "_writeout_fn_list");
  1103. addExportedSymbol(CmdArgs, "_reset_fn_list");
  1104. } else {
  1105. addExportedSymbol(CmdArgs, "___llvm_profile_filename");
  1106. addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
  1107. }
  1108. addExportedSymbol(CmdArgs, "_lprofDirMode");
  1109. }
  1110. // Align __llvm_prf_{cnts,data} sections to the maximum expected page
  1111. // alignment. This allows profile counters to be mmap()'d to disk. Note that
  1112. // it's not enough to just page-align __llvm_prf_cnts: the following section
  1113. // must also be page-aligned so that its data is not clobbered by mmap().
  1114. //
  1115. // The section alignment is only needed when continuous profile sync is
  1116. // enabled, but this is expected to be the default in Xcode. Specifying the
  1117. // extra alignment also allows the same binary to be used with/without sync
  1118. // enabled.
  1119. if (!ForGCOV) {
  1120. for (auto IPSK : {llvm::IPSK_cnts, llvm::IPSK_data}) {
  1121. addSectalignToPage(
  1122. Args, CmdArgs, "__DATA",
  1123. llvm::getInstrProfSectionName(IPSK, llvm::Triple::MachO,
  1124. /*AddSegmentInfo=*/false));
  1125. }
  1126. }
  1127. }
  1128. void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
  1129. ArgStringList &CmdArgs,
  1130. StringRef Sanitizer,
  1131. bool Shared) const {
  1132. auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
  1133. AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared);
  1134. }
  1135. ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
  1136. const ArgList &Args) const {
  1137. if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
  1138. StringRef Value = A->getValue();
  1139. if (Value != "compiler-rt")
  1140. getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
  1141. << Value << "darwin";
  1142. }
  1143. return ToolChain::RLT_CompilerRT;
  1144. }
  1145. void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
  1146. ArgStringList &CmdArgs,
  1147. bool ForceLinkBuiltinRT) const {
  1148. // Call once to ensure diagnostic is printed if wrong value was specified
  1149. GetRuntimeLibType(Args);
  1150. // Darwin doesn't support real static executables, don't link any runtime
  1151. // libraries with -static.
  1152. if (Args.hasArg(options::OPT_static) ||
  1153. Args.hasArg(options::OPT_fapple_kext) ||
  1154. Args.hasArg(options::OPT_mkernel)) {
  1155. if (ForceLinkBuiltinRT)
  1156. AddLinkRuntimeLib(Args, CmdArgs, "builtins");
  1157. return;
  1158. }
  1159. // Reject -static-libgcc for now, we can deal with this when and if someone
  1160. // cares. This is useful in situations where someone wants to statically link
  1161. // something like libstdc++, and needs its runtime support routines.
  1162. if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
  1163. getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
  1164. return;
  1165. }
  1166. const SanitizerArgs &Sanitize = getSanitizerArgs(Args);
  1167. if (Sanitize.linkRuntimes()) {
  1168. if (Sanitize.needsAsanRt())
  1169. AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
  1170. if (Sanitize.needsLsanRt())
  1171. AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
  1172. if (Sanitize.needsUbsanRt())
  1173. AddLinkSanitizerLibArgs(Args, CmdArgs,
  1174. Sanitize.requiresMinimalRuntime() ? "ubsan_minimal"
  1175. : "ubsan",
  1176. Sanitize.needsSharedRt());
  1177. if (Sanitize.needsTsanRt())
  1178. AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
  1179. if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
  1180. AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
  1181. // Libfuzzer is written in C++ and requires libcxx.
  1182. AddCXXStdlibLibArgs(Args, CmdArgs);
  1183. }
  1184. if (Sanitize.needsStatsRt()) {
  1185. AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink);
  1186. AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
  1187. }
  1188. }
  1189. const XRayArgs &XRay = getXRayArgs();
  1190. if (XRay.needsXRayRt()) {
  1191. AddLinkRuntimeLib(Args, CmdArgs, "xray");
  1192. AddLinkRuntimeLib(Args, CmdArgs, "xray-basic");
  1193. AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr");
  1194. }
  1195. // Otherwise link libSystem, then the dynamic runtime library, and finally any
  1196. // target specific static runtime library.
  1197. CmdArgs.push_back("-lSystem");
  1198. // Select the dynamic runtime library and the target specific static library.
  1199. if (isTargetIOSBased()) {
  1200. // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
  1201. // it never went into the SDK.
  1202. // Linking against libgcc_s.1 isn't needed for iOS 5.0+
  1203. if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
  1204. getTriple().getArch() != llvm::Triple::aarch64)
  1205. CmdArgs.push_back("-lgcc_s.1");
  1206. }
  1207. AddLinkRuntimeLib(Args, CmdArgs, "builtins");
  1208. }
  1209. /// Returns the most appropriate macOS target version for the current process.
  1210. ///
  1211. /// If the macOS SDK version is the same or earlier than the system version,
  1212. /// then the SDK version is returned. Otherwise the system version is returned.
  1213. static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
  1214. unsigned Major, Minor, Micro;
  1215. llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
  1216. if (!SystemTriple.isMacOSX())
  1217. return std::string(MacOSSDKVersion);
  1218. VersionTuple SystemVersion;
  1219. SystemTriple.getMacOSXVersion(SystemVersion);
  1220. bool HadExtra;
  1221. if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
  1222. HadExtra))
  1223. return std::string(MacOSSDKVersion);
  1224. VersionTuple SDKVersion(Major, Minor, Micro);
  1225. if (SDKVersion > SystemVersion)
  1226. return SystemVersion.getAsString();
  1227. return std::string(MacOSSDKVersion);
  1228. }
  1229. namespace {
  1230. /// The Darwin OS that was selected or inferred from arguments / environment.
  1231. struct DarwinPlatform {
  1232. enum SourceKind {
  1233. /// The OS was specified using the -target argument.
  1234. TargetArg,
  1235. /// The OS was specified using the -mtargetos= argument.
  1236. MTargetOSArg,
  1237. /// The OS was specified using the -m<os>-version-min argument.
  1238. OSVersionArg,
  1239. /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
  1240. DeploymentTargetEnv,
  1241. /// The OS was inferred from the SDK.
  1242. InferredFromSDK,
  1243. /// The OS was inferred from the -arch.
  1244. InferredFromArch
  1245. };
  1246. using DarwinPlatformKind = Darwin::DarwinPlatformKind;
  1247. using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
  1248. DarwinPlatformKind getPlatform() const { return Platform; }
  1249. DarwinEnvironmentKind getEnvironment() const { return Environment; }
  1250. void setEnvironment(DarwinEnvironmentKind Kind) {
  1251. Environment = Kind;
  1252. InferSimulatorFromArch = false;
  1253. }
  1254. StringRef getOSVersion() const {
  1255. if (Kind == OSVersionArg)
  1256. return Argument->getValue();
  1257. return OSVersion;
  1258. }
  1259. void setOSVersion(StringRef S) {
  1260. assert(Kind == TargetArg && "Unexpected kind!");
  1261. OSVersion = std::string(S);
  1262. }
  1263. bool hasOSVersion() const { return HasOSVersion; }
  1264. VersionTuple getNativeTargetVersion() const {
  1265. assert(Environment == DarwinEnvironmentKind::MacCatalyst &&
  1266. "native target version is specified only for Mac Catalyst");
  1267. return NativeTargetVersion;
  1268. }
  1269. /// Returns true if the target OS was explicitly specified.
  1270. bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
  1271. /// Returns true if the simulator environment can be inferred from the arch.
  1272. bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
  1273. /// Adds the -m<os>-version-min argument to the compiler invocation.
  1274. void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
  1275. if (Argument)
  1276. return;
  1277. assert(Kind != TargetArg && Kind != MTargetOSArg && Kind != OSVersionArg &&
  1278. "Invalid kind");
  1279. options::ID Opt;
  1280. switch (Platform) {
  1281. case DarwinPlatformKind::MacOS:
  1282. Opt = options::OPT_mmacosx_version_min_EQ;
  1283. break;
  1284. case DarwinPlatformKind::IPhoneOS:
  1285. Opt = options::OPT_miphoneos_version_min_EQ;
  1286. break;
  1287. case DarwinPlatformKind::TvOS:
  1288. Opt = options::OPT_mtvos_version_min_EQ;
  1289. break;
  1290. case DarwinPlatformKind::WatchOS:
  1291. Opt = options::OPT_mwatchos_version_min_EQ;
  1292. break;
  1293. }
  1294. Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion);
  1295. Args.append(Argument);
  1296. }
  1297. /// Returns the OS version with the argument / environment variable that
  1298. /// specified it.
  1299. std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
  1300. switch (Kind) {
  1301. case TargetArg:
  1302. case MTargetOSArg:
  1303. case OSVersionArg:
  1304. case InferredFromSDK:
  1305. case InferredFromArch:
  1306. assert(Argument && "OS version argument not yet inferred");
  1307. return Argument->getAsString(Args);
  1308. case DeploymentTargetEnv:
  1309. return (llvm::Twine(EnvVarName) + "=" + OSVersion).str();
  1310. }
  1311. llvm_unreachable("Unsupported Darwin Source Kind");
  1312. }
  1313. void setEnvironment(llvm::Triple::EnvironmentType EnvType,
  1314. const VersionTuple &OSVersion,
  1315. const Optional<DarwinSDKInfo> &SDKInfo) {
  1316. switch (EnvType) {
  1317. case llvm::Triple::Simulator:
  1318. Environment = DarwinEnvironmentKind::Simulator;
  1319. break;
  1320. case llvm::Triple::MacABI: {
  1321. Environment = DarwinEnvironmentKind::MacCatalyst;
  1322. // The minimum native macOS target for MacCatalyst is macOS 10.15.
  1323. NativeTargetVersion = VersionTuple(10, 15);
  1324. if (HasOSVersion && SDKInfo) {
  1325. if (const auto *MacCatalystToMacOSMapping = SDKInfo->getVersionMapping(
  1326. DarwinSDKInfo::OSEnvPair::macCatalystToMacOSPair())) {
  1327. if (auto MacOSVersion = MacCatalystToMacOSMapping->map(
  1328. OSVersion, NativeTargetVersion, None)) {
  1329. NativeTargetVersion = *MacOSVersion;
  1330. }
  1331. }
  1332. }
  1333. break;
  1334. }
  1335. default:
  1336. break;
  1337. }
  1338. }
  1339. static DarwinPlatform
  1340. createFromTarget(const llvm::Triple &TT, StringRef OSVersion, Arg *A,
  1341. const Optional<DarwinSDKInfo> &SDKInfo) {
  1342. DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
  1343. A);
  1344. VersionTuple OsVersion = TT.getOSVersion();
  1345. if (OsVersion.getMajor() == 0)
  1346. Result.HasOSVersion = false;
  1347. Result.setEnvironment(TT.getEnvironment(), OsVersion, SDKInfo);
  1348. return Result;
  1349. }
  1350. static DarwinPlatform
  1351. createFromMTargetOS(llvm::Triple::OSType OS, VersionTuple OSVersion,
  1352. llvm::Triple::EnvironmentType Environment, Arg *A,
  1353. const Optional<DarwinSDKInfo> &SDKInfo) {
  1354. DarwinPlatform Result(MTargetOSArg, getPlatformFromOS(OS),
  1355. OSVersion.getAsString(), A);
  1356. Result.InferSimulatorFromArch = false;
  1357. Result.setEnvironment(Environment, OSVersion, SDKInfo);
  1358. return Result;
  1359. }
  1360. static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform,
  1361. Arg *A) {
  1362. return DarwinPlatform(OSVersionArg, Platform, A);
  1363. }
  1364. static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
  1365. StringRef EnvVarName,
  1366. StringRef Value) {
  1367. DarwinPlatform Result(DeploymentTargetEnv, Platform, Value);
  1368. Result.EnvVarName = EnvVarName;
  1369. return Result;
  1370. }
  1371. static DarwinPlatform createFromSDK(DarwinPlatformKind Platform,
  1372. StringRef Value,
  1373. bool IsSimulator = false) {
  1374. DarwinPlatform Result(InferredFromSDK, Platform, Value);
  1375. if (IsSimulator)
  1376. Result.Environment = DarwinEnvironmentKind::Simulator;
  1377. Result.InferSimulatorFromArch = false;
  1378. return Result;
  1379. }
  1380. static DarwinPlatform createFromArch(llvm::Triple::OSType OS,
  1381. StringRef Value) {
  1382. return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value);
  1383. }
  1384. /// Constructs an inferred SDKInfo value based on the version inferred from
  1385. /// the SDK path itself. Only works for values that were created by inferring
  1386. /// the platform from the SDKPath.
  1387. DarwinSDKInfo inferSDKInfo() {
  1388. assert(Kind == InferredFromSDK && "can infer SDK info only");
  1389. llvm::VersionTuple Version;
  1390. bool IsValid = !Version.tryParse(OSVersion);
  1391. (void)IsValid;
  1392. assert(IsValid && "invalid SDK version");
  1393. return DarwinSDKInfo(
  1394. Version,
  1395. /*MaximumDeploymentTarget=*/VersionTuple(Version.getMajor(), 0, 99));
  1396. }
  1397. private:
  1398. DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
  1399. : Kind(Kind), Platform(Platform), Argument(Argument) {}
  1400. DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value,
  1401. Arg *Argument = nullptr)
  1402. : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {}
  1403. static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
  1404. switch (OS) {
  1405. case llvm::Triple::Darwin:
  1406. case llvm::Triple::MacOSX:
  1407. return DarwinPlatformKind::MacOS;
  1408. case llvm::Triple::IOS:
  1409. return DarwinPlatformKind::IPhoneOS;
  1410. case llvm::Triple::TvOS:
  1411. return DarwinPlatformKind::TvOS;
  1412. case llvm::Triple::WatchOS:
  1413. return DarwinPlatformKind::WatchOS;
  1414. default:
  1415. llvm_unreachable("Unable to infer Darwin variant");
  1416. }
  1417. }
  1418. SourceKind Kind;
  1419. DarwinPlatformKind Platform;
  1420. DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
  1421. VersionTuple NativeTargetVersion;
  1422. std::string OSVersion;
  1423. bool HasOSVersion = true, InferSimulatorFromArch = true;
  1424. Arg *Argument;
  1425. StringRef EnvVarName;
  1426. };
  1427. /// Returns the deployment target that's specified using the -m<os>-version-min
  1428. /// argument.
  1429. Optional<DarwinPlatform>
  1430. getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
  1431. const Driver &TheDriver) {
  1432. Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
  1433. Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ,
  1434. options::OPT_mios_simulator_version_min_EQ);
  1435. Arg *TvOSVersion =
  1436. Args.getLastArg(options::OPT_mtvos_version_min_EQ,
  1437. options::OPT_mtvos_simulator_version_min_EQ);
  1438. Arg *WatchOSVersion =
  1439. Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
  1440. options::OPT_mwatchos_simulator_version_min_EQ);
  1441. if (OSXVersion) {
  1442. if (iOSVersion || TvOSVersion || WatchOSVersion) {
  1443. TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
  1444. << OSXVersion->getAsString(Args)
  1445. << (iOSVersion ? iOSVersion
  1446. : TvOSVersion ? TvOSVersion : WatchOSVersion)
  1447. ->getAsString(Args);
  1448. }
  1449. return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion);
  1450. } else if (iOSVersion) {
  1451. if (TvOSVersion || WatchOSVersion) {
  1452. TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
  1453. << iOSVersion->getAsString(Args)
  1454. << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
  1455. }
  1456. return DarwinPlatform::createOSVersionArg(Darwin::IPhoneOS, iOSVersion);
  1457. } else if (TvOSVersion) {
  1458. if (WatchOSVersion) {
  1459. TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
  1460. << TvOSVersion->getAsString(Args)
  1461. << WatchOSVersion->getAsString(Args);
  1462. }
  1463. return DarwinPlatform::createOSVersionArg(Darwin::TvOS, TvOSVersion);
  1464. } else if (WatchOSVersion)
  1465. return DarwinPlatform::createOSVersionArg(Darwin::WatchOS, WatchOSVersion);
  1466. return None;
  1467. }
  1468. /// Returns the deployment target that's specified using the
  1469. /// OS_DEPLOYMENT_TARGET environment variable.
  1470. Optional<DarwinPlatform>
  1471. getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
  1472. const llvm::Triple &Triple) {
  1473. std::string Targets[Darwin::LastDarwinPlatform + 1];
  1474. const char *EnvVars[] = {
  1475. "MACOSX_DEPLOYMENT_TARGET",
  1476. "IPHONEOS_DEPLOYMENT_TARGET",
  1477. "TVOS_DEPLOYMENT_TARGET",
  1478. "WATCHOS_DEPLOYMENT_TARGET",
  1479. };
  1480. static_assert(llvm::array_lengthof(EnvVars) == Darwin::LastDarwinPlatform + 1,
  1481. "Missing platform");
  1482. for (const auto &I : llvm::enumerate(llvm::makeArrayRef(EnvVars))) {
  1483. if (char *Env = ::getenv(I.value()))
  1484. Targets[I.index()] = Env;
  1485. }
  1486. // Allow conflicts among OSX and iOS for historical reasons, but choose the
  1487. // default platform.
  1488. if (!Targets[Darwin::MacOS].empty() &&
  1489. (!Targets[Darwin::IPhoneOS].empty() ||
  1490. !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty())) {
  1491. if (Triple.getArch() == llvm::Triple::arm ||
  1492. Triple.getArch() == llvm::Triple::aarch64 ||
  1493. Triple.getArch() == llvm::Triple::thumb)
  1494. Targets[Darwin::MacOS] = "";
  1495. else
  1496. Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
  1497. Targets[Darwin::TvOS] = "";
  1498. } else {
  1499. // Don't allow conflicts in any other platform.
  1500. unsigned FirstTarget = llvm::array_lengthof(Targets);
  1501. for (unsigned I = 0; I != llvm::array_lengthof(Targets); ++I) {
  1502. if (Targets[I].empty())
  1503. continue;
  1504. if (FirstTarget == llvm::array_lengthof(Targets))
  1505. FirstTarget = I;
  1506. else
  1507. TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
  1508. << Targets[FirstTarget] << Targets[I];
  1509. }
  1510. }
  1511. for (const auto &Target : llvm::enumerate(llvm::makeArrayRef(Targets))) {
  1512. if (!Target.value().empty())
  1513. return DarwinPlatform::createDeploymentTargetEnv(
  1514. (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
  1515. Target.value());
  1516. }
  1517. return None;
  1518. }
  1519. /// Returns the SDK name without the optional prefix that ends with a '.' or an
  1520. /// empty string otherwise.
  1521. static StringRef dropSDKNamePrefix(StringRef SDKName) {
  1522. size_t PrefixPos = SDKName.find('.');
  1523. if (PrefixPos == StringRef::npos)
  1524. return "";
  1525. return SDKName.substr(PrefixPos + 1);
  1526. }
  1527. /// Tries to infer the deployment target from the SDK specified by -isysroot
  1528. /// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
  1529. /// it's available.
  1530. Optional<DarwinPlatform>
  1531. inferDeploymentTargetFromSDK(DerivedArgList &Args,
  1532. const Optional<DarwinSDKInfo> &SDKInfo) {
  1533. const Arg *A = Args.getLastArg(options::OPT_isysroot);
  1534. if (!A)
  1535. return None;
  1536. StringRef isysroot = A->getValue();
  1537. StringRef SDK = Darwin::getSDKName(isysroot);
  1538. if (!SDK.size())
  1539. return None;
  1540. std::string Version;
  1541. if (SDKInfo) {
  1542. // Get the version from the SDKSettings.json if it's available.
  1543. Version = SDKInfo->getVersion().getAsString();
  1544. } else {
  1545. // Slice the version number out.
  1546. // Version number is between the first and the last number.
  1547. size_t StartVer = SDK.find_first_of("0123456789");
  1548. size_t EndVer = SDK.find_last_of("0123456789");
  1549. if (StartVer != StringRef::npos && EndVer > StartVer)
  1550. Version = std::string(SDK.slice(StartVer, EndVer + 1));
  1551. }
  1552. if (Version.empty())
  1553. return None;
  1554. auto CreatePlatformFromSDKName =
  1555. [&](StringRef SDK) -> Optional<DarwinPlatform> {
  1556. if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
  1557. return DarwinPlatform::createFromSDK(
  1558. Darwin::IPhoneOS, Version,
  1559. /*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
  1560. else if (SDK.startswith("MacOSX"))
  1561. return DarwinPlatform::createFromSDK(Darwin::MacOS,
  1562. getSystemOrSDKMacOSVersion(Version));
  1563. else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
  1564. return DarwinPlatform::createFromSDK(
  1565. Darwin::WatchOS, Version,
  1566. /*IsSimulator=*/SDK.startswith("WatchSimulator"));
  1567. else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
  1568. return DarwinPlatform::createFromSDK(
  1569. Darwin::TvOS, Version,
  1570. /*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
  1571. return None;
  1572. };
  1573. if (auto Result = CreatePlatformFromSDKName(SDK))
  1574. return Result;
  1575. // The SDK can be an SDK variant with a name like `<prefix>.<platform>`.
  1576. return CreatePlatformFromSDKName(dropSDKNamePrefix(SDK));
  1577. }
  1578. std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple,
  1579. const Driver &TheDriver) {
  1580. VersionTuple OsVersion;
  1581. llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
  1582. switch (OS) {
  1583. case llvm::Triple::Darwin:
  1584. case llvm::Triple::MacOSX:
  1585. // If there is no version specified on triple, and both host and target are
  1586. // macos, use the host triple to infer OS version.
  1587. if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
  1588. !Triple.getOSMajorVersion())
  1589. SystemTriple.getMacOSXVersion(OsVersion);
  1590. else if (!Triple.getMacOSXVersion(OsVersion))
  1591. TheDriver.Diag(diag::err_drv_invalid_darwin_version)
  1592. << Triple.getOSName();
  1593. break;
  1594. case llvm::Triple::IOS:
  1595. if (Triple.isMacCatalystEnvironment() && !Triple.getOSMajorVersion()) {
  1596. OsVersion = VersionTuple(13, 1);
  1597. } else
  1598. OsVersion = Triple.getiOSVersion();
  1599. break;
  1600. case llvm::Triple::TvOS:
  1601. OsVersion = Triple.getOSVersion();
  1602. break;
  1603. case llvm::Triple::WatchOS:
  1604. OsVersion = Triple.getWatchOSVersion();
  1605. break;
  1606. default:
  1607. llvm_unreachable("Unexpected OS type");
  1608. break;
  1609. }
  1610. std::string OSVersion;
  1611. llvm::raw_string_ostream(OSVersion)
  1612. << OsVersion.getMajor() << '.' << OsVersion.getMinor().getValueOr(0)
  1613. << '.' << OsVersion.getSubminor().getValueOr(0);
  1614. return OSVersion;
  1615. }
  1616. /// Tries to infer the target OS from the -arch.
  1617. Optional<DarwinPlatform>
  1618. inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
  1619. const llvm::Triple &Triple,
  1620. const Driver &TheDriver) {
  1621. llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
  1622. StringRef MachOArchName = Toolchain.getMachOArchName(Args);
  1623. if (MachOArchName == "arm64" || MachOArchName == "arm64e") {
  1624. #if __arm64__
  1625. // A clang running on an Apple Silicon mac defaults
  1626. // to building for mac when building for arm64 rather than
  1627. // defaulting to iOS.
  1628. OSTy = llvm::Triple::MacOSX;
  1629. #else
  1630. OSTy = llvm::Triple::IOS;
  1631. #endif
  1632. } else if (MachOArchName == "armv7" || MachOArchName == "armv7s")
  1633. OSTy = llvm::Triple::IOS;
  1634. else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
  1635. OSTy = llvm::Triple::WatchOS;
  1636. else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
  1637. MachOArchName != "armv7em")
  1638. OSTy = llvm::Triple::MacOSX;
  1639. if (OSTy == llvm::Triple::UnknownOS)
  1640. return None;
  1641. return DarwinPlatform::createFromArch(OSTy,
  1642. getOSVersion(OSTy, Triple, TheDriver));
  1643. }
  1644. /// Returns the deployment target that's specified using the -target option.
  1645. Optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
  1646. DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver,
  1647. const Optional<DarwinSDKInfo> &SDKInfo) {
  1648. if (!Args.hasArg(options::OPT_target))
  1649. return None;
  1650. if (Triple.getOS() == llvm::Triple::Darwin ||
  1651. Triple.getOS() == llvm::Triple::UnknownOS)
  1652. return None;
  1653. std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver);
  1654. return DarwinPlatform::createFromTarget(
  1655. Triple, OSVersion, Args.getLastArg(options::OPT_target), SDKInfo);
  1656. }
  1657. /// Returns the deployment target that's specified using the -mtargetos option.
  1658. Optional<DarwinPlatform>
  1659. getDeploymentTargetFromMTargetOSArg(DerivedArgList &Args,
  1660. const Driver &TheDriver,
  1661. const Optional<DarwinSDKInfo> &SDKInfo) {
  1662. auto *A = Args.getLastArg(options::OPT_mtargetos_EQ);
  1663. if (!A)
  1664. return None;
  1665. llvm::Triple TT(llvm::Twine("unknown-apple-") + A->getValue());
  1666. switch (TT.getOS()) {
  1667. case llvm::Triple::MacOSX:
  1668. case llvm::Triple::IOS:
  1669. case llvm::Triple::TvOS:
  1670. case llvm::Triple::WatchOS:
  1671. break;
  1672. default:
  1673. TheDriver.Diag(diag::err_drv_invalid_os_in_arg)
  1674. << TT.getOSName() << A->getAsString(Args);
  1675. return None;
  1676. }
  1677. VersionTuple Version = TT.getOSVersion();
  1678. if (!Version.getMajor()) {
  1679. TheDriver.Diag(diag::err_drv_invalid_version_number)
  1680. << A->getAsString(Args);
  1681. return None;
  1682. }
  1683. return DarwinPlatform::createFromMTargetOS(TT.getOS(), Version,
  1684. TT.getEnvironment(), A, SDKInfo);
  1685. }
  1686. Optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
  1687. const ArgList &Args,
  1688. const Driver &TheDriver) {
  1689. const Arg *A = Args.getLastArg(options::OPT_isysroot);
  1690. if (!A)
  1691. return None;
  1692. StringRef isysroot = A->getValue();
  1693. auto SDKInfoOrErr = parseDarwinSDKInfo(VFS, isysroot);
  1694. if (!SDKInfoOrErr) {
  1695. llvm::consumeError(SDKInfoOrErr.takeError());
  1696. TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);
  1697. return None;
  1698. }
  1699. return *SDKInfoOrErr;
  1700. }
  1701. } // namespace
  1702. void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
  1703. const OptTable &Opts = getDriver().getOpts();
  1704. // Support allowing the SDKROOT environment variable used by xcrun and other
  1705. // Xcode tools to define the default sysroot, by making it the default for
  1706. // isysroot.
  1707. if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  1708. // Warn if the path does not exist.
  1709. if (!getVFS().exists(A->getValue()))
  1710. getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
  1711. } else {
  1712. if (char *env = ::getenv("SDKROOT")) {
  1713. // We only use this value as the default if it is an absolute path,
  1714. // exists, and it is not the root path.
  1715. if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
  1716. StringRef(env) != "/") {
  1717. Args.append(Args.MakeSeparateArg(
  1718. nullptr, Opts.getOption(options::OPT_isysroot), env));
  1719. }
  1720. }
  1721. }
  1722. // Read the SDKSettings.json file for more information, like the SDK version
  1723. // that we can pass down to the compiler.
  1724. SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
  1725. // The OS and the version can be specified using the -target argument.
  1726. Optional<DarwinPlatform> OSTarget =
  1727. getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver(), SDKInfo);
  1728. if (OSTarget) {
  1729. // Disallow mixing -target and -mtargetos=.
  1730. if (const auto *MTargetOSArg = Args.getLastArg(options::OPT_mtargetos_EQ)) {
  1731. std::string TargetArgStr = OSTarget->getAsString(Args, Opts);
  1732. std::string MTargetOSArgStr = MTargetOSArg->getAsString(Args);
  1733. getDriver().Diag(diag::err_drv_cannot_mix_options)
  1734. << TargetArgStr << MTargetOSArgStr;
  1735. }
  1736. Optional<DarwinPlatform> OSVersionArgTarget =
  1737. getDeploymentTargetFromOSVersionArg(Args, getDriver());
  1738. if (OSVersionArgTarget) {
  1739. unsigned TargetMajor, TargetMinor, TargetMicro;
  1740. bool TargetExtra;
  1741. unsigned ArgMajor, ArgMinor, ArgMicro;
  1742. bool ArgExtra;
  1743. if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() ||
  1744. (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor,
  1745. TargetMinor, TargetMicro, TargetExtra) &&
  1746. Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(),
  1747. ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
  1748. (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
  1749. VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
  1750. TargetExtra != ArgExtra))) {
  1751. // Select the OS version from the -m<os>-version-min argument when
  1752. // the -target does not include an OS version.
  1753. if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() &&
  1754. !OSTarget->hasOSVersion()) {
  1755. OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion());
  1756. } else {
  1757. // Warn about -m<os>-version-min that doesn't match the OS version
  1758. // that's specified in the target.
  1759. std::string OSVersionArg =
  1760. OSVersionArgTarget->getAsString(Args, Opts);
  1761. std::string TargetArg = OSTarget->getAsString(Args, Opts);
  1762. getDriver().Diag(clang::diag::warn_drv_overriding_flag_option)
  1763. << OSVersionArg << TargetArg;
  1764. }
  1765. }
  1766. }
  1767. } else if ((OSTarget = getDeploymentTargetFromMTargetOSArg(Args, getDriver(),
  1768. SDKInfo))) {
  1769. // The OS target can be specified using the -mtargetos= argument.
  1770. // Disallow mixing -mtargetos= and -m<os>version-min=.
  1771. Optional<DarwinPlatform> OSVersionArgTarget =
  1772. getDeploymentTargetFromOSVersionArg(Args, getDriver());
  1773. if (OSVersionArgTarget) {
  1774. std::string MTargetOSArgStr = OSTarget->getAsString(Args, Opts);
  1775. std::string OSVersionArgStr = OSVersionArgTarget->getAsString(Args, Opts);
  1776. getDriver().Diag(diag::err_drv_cannot_mix_options)
  1777. << MTargetOSArgStr << OSVersionArgStr;
  1778. }
  1779. } else {
  1780. // The OS target can be specified using the -m<os>version-min argument.
  1781. OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver());
  1782. // If no deployment target was specified on the command line, check for
  1783. // environment defines.
  1784. if (!OSTarget) {
  1785. OSTarget =
  1786. getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
  1787. if (OSTarget) {
  1788. // Don't infer simulator from the arch when the SDK is also specified.
  1789. Optional<DarwinPlatform> SDKTarget =
  1790. inferDeploymentTargetFromSDK(Args, SDKInfo);
  1791. if (SDKTarget)
  1792. OSTarget->setEnvironment(SDKTarget->getEnvironment());
  1793. }
  1794. }
  1795. // If there is no command-line argument to specify the Target version and
  1796. // no environment variable defined, see if we can set the default based
  1797. // on -isysroot using SDKSettings.json if it exists.
  1798. if (!OSTarget) {
  1799. OSTarget = inferDeploymentTargetFromSDK(Args, SDKInfo);
  1800. /// If the target was successfully constructed from the SDK path, try to
  1801. /// infer the SDK info if the SDK doesn't have it.
  1802. if (OSTarget && !SDKInfo)
  1803. SDKInfo = OSTarget->inferSDKInfo();
  1804. }
  1805. // If no OS targets have been specified, try to guess platform from -target
  1806. // or arch name and compute the version from the triple.
  1807. if (!OSTarget)
  1808. OSTarget =
  1809. inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
  1810. }
  1811. assert(OSTarget && "Unable to infer Darwin variant");
  1812. OSTarget->addOSVersionMinArgument(Args, Opts);
  1813. DarwinPlatformKind Platform = OSTarget->getPlatform();
  1814. unsigned Major, Minor, Micro;
  1815. bool HadExtra;
  1816. // Set the tool chain target information.
  1817. if (Platform == MacOS) {
  1818. if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
  1819. Micro, HadExtra) ||
  1820. HadExtra || Major < 10 || Major >= 100 || Minor >= 100 || Micro >= 100)
  1821. getDriver().Diag(diag::err_drv_invalid_version_number)
  1822. << OSTarget->getAsString(Args, Opts);
  1823. } else if (Platform == IPhoneOS) {
  1824. if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
  1825. Micro, HadExtra) ||
  1826. HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
  1827. getDriver().Diag(diag::err_drv_invalid_version_number)
  1828. << OSTarget->getAsString(Args, Opts);
  1829. ;
  1830. if (OSTarget->getEnvironment() == MacCatalyst &&
  1831. (Major < 13 || (Major == 13 && Minor < 1))) {
  1832. getDriver().Diag(diag::err_drv_invalid_version_number)
  1833. << OSTarget->getAsString(Args, Opts);
  1834. Major = 13;
  1835. Minor = 1;
  1836. Micro = 0;
  1837. }
  1838. // For 32-bit targets, the deployment target for iOS has to be earlier than
  1839. // iOS 11.
  1840. if (getTriple().isArch32Bit() && Major >= 11) {
  1841. // If the deployment target is explicitly specified, print a diagnostic.
  1842. if (OSTarget->isExplicitlySpecified()) {
  1843. if (OSTarget->getEnvironment() == MacCatalyst)
  1844. getDriver().Diag(diag::err_invalid_macos_32bit_deployment_target);
  1845. else
  1846. getDriver().Diag(diag::warn_invalid_ios_deployment_target)
  1847. << OSTarget->getAsString(Args, Opts);
  1848. // Otherwise, set it to 10.99.99.
  1849. } else {
  1850. Major = 10;
  1851. Minor = 99;
  1852. Micro = 99;
  1853. }
  1854. }
  1855. } else if (Platform == TvOS) {
  1856. if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
  1857. Micro, HadExtra) ||
  1858. HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
  1859. getDriver().Diag(diag::err_drv_invalid_version_number)
  1860. << OSTarget->getAsString(Args, Opts);
  1861. } else if (Platform == WatchOS) {
  1862. if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
  1863. Micro, HadExtra) ||
  1864. HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
  1865. getDriver().Diag(diag::err_drv_invalid_version_number)
  1866. << OSTarget->getAsString(Args, Opts);
  1867. } else
  1868. llvm_unreachable("unknown kind of Darwin platform");
  1869. DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
  1870. // Recognize iOS targets with an x86 architecture as the iOS simulator.
  1871. if (Environment == NativeEnvironment && Platform != MacOS &&
  1872. OSTarget->canInferSimulatorFromArch() && getTriple().isX86())
  1873. Environment = Simulator;
  1874. VersionTuple NativeTargetVersion;
  1875. if (Environment == MacCatalyst)
  1876. NativeTargetVersion = OSTarget->getNativeTargetVersion();
  1877. setTarget(Platform, Environment, Major, Minor, Micro, NativeTargetVersion);
  1878. if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  1879. StringRef SDK = getSDKName(A->getValue());
  1880. if (SDK.size() > 0) {
  1881. size_t StartVer = SDK.find_first_of("0123456789");
  1882. StringRef SDKName = SDK.slice(0, StartVer);
  1883. if (!SDKName.startswith(getPlatformFamily()) &&
  1884. !dropSDKNamePrefix(SDKName).startswith(getPlatformFamily()))
  1885. getDriver().Diag(diag::warn_incompatible_sysroot)
  1886. << SDKName << getPlatformFamily();
  1887. }
  1888. }
  1889. }
  1890. // Returns the effective header sysroot path to use. This comes either from
  1891. // -isysroot or --sysroot.
  1892. llvm::StringRef DarwinClang::GetHeaderSysroot(const llvm::opt::ArgList &DriverArgs) const {
  1893. if(DriverArgs.hasArg(options::OPT_isysroot))
  1894. return DriverArgs.getLastArgValue(options::OPT_isysroot);
  1895. if (!getDriver().SysRoot.empty())
  1896. return getDriver().SysRoot;
  1897. return "/";
  1898. }
  1899. void DarwinClang::AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
  1900. llvm::opt::ArgStringList &CC1Args) const {
  1901. const Driver &D = getDriver();
  1902. llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
  1903. bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
  1904. bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
  1905. bool NoBuiltinInc = DriverArgs.hasFlag(
  1906. options::OPT_nobuiltininc, options::OPT_ibuiltininc, /*Default=*/false);
  1907. bool ForceBuiltinInc = DriverArgs.hasFlag(
  1908. options::OPT_ibuiltininc, options::OPT_nobuiltininc, /*Default=*/false);
  1909. // Add <sysroot>/usr/local/include
  1910. if (!NoStdInc && !NoStdlibInc) {
  1911. SmallString<128> P(Sysroot);
  1912. llvm::sys::path::append(P, "usr", "local", "include");
  1913. addSystemInclude(DriverArgs, CC1Args, P);
  1914. }
  1915. // Add the Clang builtin headers (<resource>/include)
  1916. if (!(NoStdInc && !ForceBuiltinInc) && !NoBuiltinInc) {
  1917. SmallString<128> P(D.ResourceDir);
  1918. llvm::sys::path::append(P, "include");
  1919. addSystemInclude(DriverArgs, CC1Args, P);
  1920. }
  1921. if (NoStdInc || NoStdlibInc)
  1922. return;
  1923. // Check for configure-time C include directories.
  1924. llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
  1925. if (!CIncludeDirs.empty()) {
  1926. llvm::SmallVector<llvm::StringRef, 5> dirs;
  1927. CIncludeDirs.split(dirs, ":");
  1928. for (llvm::StringRef dir : dirs) {
  1929. llvm::StringRef Prefix =
  1930. llvm::sys::path::is_absolute(dir) ? "" : llvm::StringRef(Sysroot);
  1931. addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
  1932. }
  1933. } else {
  1934. // Otherwise, add <sysroot>/usr/include.
  1935. SmallString<128> P(Sysroot);
  1936. llvm::sys::path::append(P, "usr", "include");
  1937. addExternCSystemInclude(DriverArgs, CC1Args, P.str());
  1938. }
  1939. }
  1940. bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
  1941. llvm::opt::ArgStringList &CC1Args,
  1942. llvm::SmallString<128> Base,
  1943. llvm::StringRef Version,
  1944. llvm::StringRef ArchDir,
  1945. llvm::StringRef BitDir) const {
  1946. llvm::sys::path::append(Base, Version);
  1947. // Add the base dir
  1948. addSystemInclude(DriverArgs, CC1Args, Base);
  1949. // Add the multilib dirs
  1950. {
  1951. llvm::SmallString<128> P = Base;
  1952. if (!ArchDir.empty())
  1953. llvm::sys::path::append(P, ArchDir);
  1954. if (!BitDir.empty())
  1955. llvm::sys::path::append(P, BitDir);
  1956. addSystemInclude(DriverArgs, CC1Args, P);
  1957. }
  1958. // Add the backward dir
  1959. {
  1960. llvm::SmallString<128> P = Base;
  1961. llvm::sys::path::append(P, "backward");
  1962. addSystemInclude(DriverArgs, CC1Args, P);
  1963. }
  1964. return getVFS().exists(Base);
  1965. }
  1966. void DarwinClang::AddClangCXXStdlibIncludeArgs(
  1967. const llvm::opt::ArgList &DriverArgs,
  1968. llvm::opt::ArgStringList &CC1Args) const {
  1969. // The implementation from a base class will pass through the -stdlib to
  1970. // CC1Args.
  1971. // FIXME: this should not be necessary, remove usages in the frontend
  1972. // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
  1973. // Also check whether this is used for setting library search paths.
  1974. ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
  1975. if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
  1976. DriverArgs.hasArg(options::OPT_nostdincxx))
  1977. return;
  1978. llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
  1979. switch (GetCXXStdlibType(DriverArgs)) {
  1980. case ToolChain::CST_Libcxx: {
  1981. // On Darwin, libc++ can be installed in one of the following two places:
  1982. // 1. Alongside the compiler in <install>/include/c++/v1
  1983. // 2. In a SDK (or a custom sysroot) in <sysroot>/usr/include/c++/v1
  1984. //
  1985. // The precendence of paths is as listed above, i.e. we take the first path
  1986. // that exists. Also note that we never include libc++ twice -- we take the
  1987. // first path that exists and don't send the other paths to CC1 (otherwise
  1988. // include_next could break).
  1989. // Check for (1)
  1990. // Get from '<install>/bin' to '<install>/include/c++/v1'.
  1991. // Note that InstallBin can be relative, so we use '..' instead of
  1992. // parent_path.
  1993. llvm::SmallString<128> InstallBin =
  1994. llvm::StringRef(getDriver().getInstalledDir()); // <install>/bin
  1995. llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
  1996. if (getVFS().exists(InstallBin)) {
  1997. addSystemInclude(DriverArgs, CC1Args, InstallBin);
  1998. return;
  1999. } else if (DriverArgs.hasArg(options::OPT_v)) {
  2000. llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
  2001. << "\"\n";
  2002. }
  2003. // Otherwise, check for (2)
  2004. llvm::SmallString<128> SysrootUsr = Sysroot;
  2005. llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");
  2006. if (getVFS().exists(SysrootUsr)) {
  2007. addSystemInclude(DriverArgs, CC1Args, SysrootUsr);
  2008. return;
  2009. } else if (DriverArgs.hasArg(options::OPT_v)) {
  2010. llvm::errs() << "ignoring nonexistent directory \"" << SysrootUsr
  2011. << "\"\n";
  2012. }
  2013. // Otherwise, don't add any path.
  2014. break;
  2015. }
  2016. case ToolChain::CST_Libstdcxx:
  2017. llvm::SmallString<128> UsrIncludeCxx = Sysroot;
  2018. llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++");
  2019. llvm::Triple::ArchType arch = getTriple().getArch();
  2020. bool IsBaseFound = true;
  2021. switch (arch) {
  2022. default: break;
  2023. case llvm::Triple::ppc:
  2024. case llvm::Triple::ppc64:
  2025. IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
  2026. "4.2.1",
  2027. "powerpc-apple-darwin10",
  2028. arch == llvm::Triple::ppc64 ? "ppc64" : "");
  2029. IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
  2030. "4.0.0", "powerpc-apple-darwin10",
  2031. arch == llvm::Triple::ppc64 ? "ppc64" : "");
  2032. break;
  2033. case llvm::Triple::x86:
  2034. case llvm::Triple::x86_64:
  2035. IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
  2036. "4.2.1",
  2037. "i686-apple-darwin10",
  2038. arch == llvm::Triple::x86_64 ? "x86_64" : "");
  2039. IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
  2040. "4.0.0", "i686-apple-darwin8",
  2041. "");
  2042. break;
  2043. case llvm::Triple::arm:
  2044. case llvm::Triple::thumb:
  2045. IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
  2046. "4.2.1",
  2047. "arm-apple-darwin10",
  2048. "v7");
  2049. IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
  2050. "4.2.1",
  2051. "arm-apple-darwin10",
  2052. "v6");
  2053. break;
  2054. case llvm::Triple::aarch64:
  2055. IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
  2056. "4.2.1",
  2057. "arm64-apple-darwin10",
  2058. "");
  2059. break;
  2060. }
  2061. if (!IsBaseFound) {
  2062. getDriver().Diag(diag::warn_drv_libstdcxx_not_found);
  2063. }
  2064. break;
  2065. }
  2066. }
  2067. void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
  2068. ArgStringList &CmdArgs) const {
  2069. CXXStdlibType Type = GetCXXStdlibType(Args);
  2070. switch (Type) {
  2071. case ToolChain::CST_Libcxx:
  2072. CmdArgs.push_back("-lc++");
  2073. break;
  2074. case ToolChain::CST_Libstdcxx:
  2075. // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
  2076. // it was previously found in the gcc lib dir. However, for all the Darwin
  2077. // platforms we care about it was -lstdc++.6, so we search for that
  2078. // explicitly if we can't see an obvious -lstdc++ candidate.
  2079. // Check in the sysroot first.
  2080. if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  2081. SmallString<128> P(A->getValue());
  2082. llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
  2083. if (!getVFS().exists(P)) {
  2084. llvm::sys::path::remove_filename(P);
  2085. llvm::sys::path::append(P, "libstdc++.6.dylib");
  2086. if (getVFS().exists(P)) {
  2087. CmdArgs.push_back(Args.MakeArgString(P));
  2088. return;
  2089. }
  2090. }
  2091. }
  2092. // Otherwise, look in the root.
  2093. // FIXME: This should be removed someday when we don't have to care about
  2094. // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
  2095. if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
  2096. getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
  2097. CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
  2098. return;
  2099. }
  2100. // Otherwise, let the linker search.
  2101. CmdArgs.push_back("-lstdc++");
  2102. break;
  2103. }
  2104. }
  2105. void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
  2106. ArgStringList &CmdArgs) const {
  2107. // For Darwin platforms, use the compiler-rt-based support library
  2108. // instead of the gcc-provided one (which is also incidentally
  2109. // only present in the gcc lib dir, which makes it hard to find).
  2110. SmallString<128> P(getDriver().ResourceDir);
  2111. llvm::sys::path::append(P, "lib", "darwin");
  2112. // Use the newer cc_kext for iOS ARM after 6.0.
  2113. if (isTargetWatchOS()) {
  2114. llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
  2115. } else if (isTargetTvOS()) {
  2116. llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
  2117. } else if (isTargetIPhoneOS()) {
  2118. llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
  2119. } else {
  2120. llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
  2121. }
  2122. // For now, allow missing resource libraries to support developers who may
  2123. // not have compiler-rt checked out or integrated into their build.
  2124. if (getVFS().exists(P))
  2125. CmdArgs.push_back(Args.MakeArgString(P));
  2126. }
  2127. DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
  2128. StringRef BoundArch,
  2129. Action::OffloadKind) const {
  2130. DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
  2131. const OptTable &Opts = getDriver().getOpts();
  2132. // FIXME: We really want to get out of the tool chain level argument
  2133. // translation business, as it makes the driver functionality much
  2134. // more opaque. For now, we follow gcc closely solely for the
  2135. // purpose of easily achieving feature parity & testability. Once we
  2136. // have something that works, we should reevaluate each translation
  2137. // and try to push it down into tool specific logic.
  2138. for (Arg *A : Args) {
  2139. if (A->getOption().matches(options::OPT_Xarch__)) {
  2140. // Skip this argument unless the architecture matches either the toolchain
  2141. // triple arch, or the arch being bound.
  2142. llvm::Triple::ArchType XarchArch =
  2143. tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
  2144. if (!(XarchArch == getArch() ||
  2145. (!BoundArch.empty() &&
  2146. XarchArch ==
  2147. tools::darwin::getArchTypeForMachOArchName(BoundArch))))
  2148. continue;
  2149. Arg *OriginalArg = A;
  2150. TranslateXarchArgs(Args, A, DAL);
  2151. // Linker input arguments require custom handling. The problem is that we
  2152. // have already constructed the phase actions, so we can not treat them as
  2153. // "input arguments".
  2154. if (A->getOption().hasFlag(options::LinkerInput)) {
  2155. // Convert the argument into individual Zlinker_input_args.
  2156. for (const char *Value : A->getValues()) {
  2157. DAL->AddSeparateArg(
  2158. OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
  2159. }
  2160. continue;
  2161. }
  2162. }
  2163. // Sob. These is strictly gcc compatible for the time being. Apple
  2164. // gcc translates options twice, which means that self-expanding
  2165. // options add duplicates.
  2166. switch ((options::ID)A->getOption().getID()) {
  2167. default:
  2168. DAL->append(A);
  2169. break;
  2170. case options::OPT_mkernel:
  2171. case options::OPT_fapple_kext:
  2172. DAL->append(A);
  2173. DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
  2174. break;
  2175. case options::OPT_dependency_file:
  2176. DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
  2177. break;
  2178. case options::OPT_gfull:
  2179. DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
  2180. DAL->AddFlagArg(
  2181. A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
  2182. break;
  2183. case options::OPT_gused:
  2184. DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
  2185. DAL->AddFlagArg(
  2186. A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
  2187. break;
  2188. case options::OPT_shared:
  2189. DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
  2190. break;
  2191. case options::OPT_fconstant_cfstrings:
  2192. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
  2193. break;
  2194. case options::OPT_fno_constant_cfstrings:
  2195. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
  2196. break;
  2197. case options::OPT_Wnonportable_cfstrings:
  2198. DAL->AddFlagArg(A,
  2199. Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
  2200. break;
  2201. case options::OPT_Wno_nonportable_cfstrings:
  2202. DAL->AddFlagArg(
  2203. A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
  2204. break;
  2205. case options::OPT_fpascal_strings:
  2206. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
  2207. break;
  2208. case options::OPT_fno_pascal_strings:
  2209. DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
  2210. break;
  2211. }
  2212. }
  2213. // Add the arch options based on the particular spelling of -arch, to match
  2214. // how the driver driver works.
  2215. if (!BoundArch.empty()) {
  2216. StringRef Name = BoundArch;
  2217. const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
  2218. const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
  2219. // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
  2220. // which defines the list of which architectures we accept.
  2221. if (Name == "ppc")
  2222. ;
  2223. else if (Name == "ppc601")
  2224. DAL->AddJoinedArg(nullptr, MCpu, "601");
  2225. else if (Name == "ppc603")
  2226. DAL->AddJoinedArg(nullptr, MCpu, "603");
  2227. else if (Name == "ppc604")
  2228. DAL->AddJoinedArg(nullptr, MCpu, "604");
  2229. else if (Name == "ppc604e")
  2230. DAL->AddJoinedArg(nullptr, MCpu, "604e");
  2231. else if (Name == "ppc750")
  2232. DAL->AddJoinedArg(nullptr, MCpu, "750");
  2233. else if (Name == "ppc7400")
  2234. DAL->AddJoinedArg(nullptr, MCpu, "7400");
  2235. else if (Name == "ppc7450")
  2236. DAL->AddJoinedArg(nullptr, MCpu, "7450");
  2237. else if (Name == "ppc970")
  2238. DAL->AddJoinedArg(nullptr, MCpu, "970");
  2239. else if (Name == "ppc64" || Name == "ppc64le")
  2240. DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
  2241. else if (Name == "i386")
  2242. ;
  2243. else if (Name == "i486")
  2244. DAL->AddJoinedArg(nullptr, MArch, "i486");
  2245. else if (Name == "i586")
  2246. DAL->AddJoinedArg(nullptr, MArch, "i586");
  2247. else if (Name == "i686")
  2248. DAL->AddJoinedArg(nullptr, MArch, "i686");
  2249. else if (Name == "pentium")
  2250. DAL->AddJoinedArg(nullptr, MArch, "pentium");
  2251. else if (Name == "pentium2")
  2252. DAL->AddJoinedArg(nullptr, MArch, "pentium2");
  2253. else if (Name == "pentpro")
  2254. DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
  2255. else if (Name == "pentIIm3")
  2256. DAL->AddJoinedArg(nullptr, MArch, "pentium2");
  2257. else if (Name == "x86_64" || Name == "x86_64h")
  2258. DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
  2259. else if (Name == "arm")
  2260. DAL->AddJoinedArg(nullptr, MArch, "armv4t");
  2261. else if (Name == "armv4t")
  2262. DAL->AddJoinedArg(nullptr, MArch, "armv4t");
  2263. else if (Name == "armv5")
  2264. DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
  2265. else if (Name == "xscale")
  2266. DAL->AddJoinedArg(nullptr, MArch, "xscale");
  2267. else if (Name == "armv6")
  2268. DAL->AddJoinedArg(nullptr, MArch, "armv6k");
  2269. else if (Name == "armv6m")
  2270. DAL->AddJoinedArg(nullptr, MArch, "armv6m");
  2271. else if (Name == "armv7")
  2272. DAL->AddJoinedArg(nullptr, MArch, "armv7a");
  2273. else if (Name == "armv7em")
  2274. DAL->AddJoinedArg(nullptr, MArch, "armv7em");
  2275. else if (Name == "armv7k")
  2276. DAL->AddJoinedArg(nullptr, MArch, "armv7k");
  2277. else if (Name == "armv7m")
  2278. DAL->AddJoinedArg(nullptr, MArch, "armv7m");
  2279. else if (Name == "armv7s")
  2280. DAL->AddJoinedArg(nullptr, MArch, "armv7s");
  2281. }
  2282. return DAL;
  2283. }
  2284. void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
  2285. ArgStringList &CmdArgs,
  2286. bool ForceLinkBuiltinRT) const {
  2287. // Embedded targets are simple at the moment, not supporting sanitizers and
  2288. // with different libraries for each member of the product { static, PIC } x
  2289. // { hard-float, soft-float }
  2290. llvm::SmallString<32> CompilerRT = StringRef("");
  2291. CompilerRT +=
  2292. (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
  2293. ? "hard"
  2294. : "soft";
  2295. CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
  2296. AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
  2297. }
  2298. bool Darwin::isAlignedAllocationUnavailable() const {
  2299. llvm::Triple::OSType OS;
  2300. if (isTargetMacCatalyst())
  2301. return TargetVersion < alignedAllocMinVersion(llvm::Triple::MacOSX);
  2302. switch (TargetPlatform) {
  2303. case MacOS: // Earlier than 10.13.
  2304. OS = llvm::Triple::MacOSX;
  2305. break;
  2306. case IPhoneOS:
  2307. OS = llvm::Triple::IOS;
  2308. break;
  2309. case TvOS: // Earlier than 11.0.
  2310. OS = llvm::Triple::TvOS;
  2311. break;
  2312. case WatchOS: // Earlier than 4.0.
  2313. OS = llvm::Triple::WatchOS;
  2314. break;
  2315. }
  2316. return TargetVersion < alignedAllocMinVersion(OS);
  2317. }
  2318. void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
  2319. llvm::opt::ArgStringList &CC1Args,
  2320. Action::OffloadKind DeviceOffloadKind) const {
  2321. // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
  2322. // enabled or disabled aligned allocations.
  2323. if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
  2324. options::OPT_fno_aligned_allocation) &&
  2325. isAlignedAllocationUnavailable())
  2326. CC1Args.push_back("-faligned-alloc-unavailable");
  2327. if (SDKInfo) {
  2328. /// Pass the SDK version to the compiler when the SDK information is
  2329. /// available.
  2330. auto EmitTargetSDKVersionArg = [&](const VersionTuple &V) {
  2331. std::string Arg;
  2332. llvm::raw_string_ostream OS(Arg);
  2333. OS << "-target-sdk-version=" << V;
  2334. CC1Args.push_back(DriverArgs.MakeArgString(OS.str()));
  2335. };
  2336. if (isTargetMacCatalyst()) {
  2337. if (const auto *MacOStoMacCatalystMapping = SDKInfo->getVersionMapping(
  2338. DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
  2339. Optional<VersionTuple> SDKVersion = MacOStoMacCatalystMapping->map(
  2340. SDKInfo->getVersion(), minimumMacCatalystDeploymentTarget(), None);
  2341. EmitTargetSDKVersionArg(
  2342. SDKVersion ? *SDKVersion : minimumMacCatalystDeploymentTarget());
  2343. }
  2344. } else {
  2345. EmitTargetSDKVersionArg(SDKInfo->getVersion());
  2346. }
  2347. }
  2348. // Enable compatibility mode for NSItemProviderCompletionHandler in
  2349. // Foundation/NSItemProvider.h.
  2350. CC1Args.push_back("-fcompatibility-qualified-id-block-type-checking");
  2351. // Give static local variables in inline functions hidden visibility when
  2352. // -fvisibility-inlines-hidden is enabled.
  2353. if (!DriverArgs.getLastArgNoClaim(
  2354. options::OPT_fvisibility_inlines_hidden_static_local_var,
  2355. options::OPT_fno_visibility_inlines_hidden_static_local_var))
  2356. CC1Args.push_back("-fvisibility-inlines-hidden-static-local-var");
  2357. }
  2358. DerivedArgList *
  2359. Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
  2360. Action::OffloadKind DeviceOffloadKind) const {
  2361. // First get the generic Apple args, before moving onto Darwin-specific ones.
  2362. DerivedArgList *DAL =
  2363. MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
  2364. const OptTable &Opts = getDriver().getOpts();
  2365. // If no architecture is bound, none of the translations here are relevant.
  2366. if (BoundArch.empty())
  2367. return DAL;
  2368. // Add an explicit version min argument for the deployment target. We do this
  2369. // after argument translation because -Xarch_ arguments may add a version min
  2370. // argument.
  2371. AddDeploymentTarget(*DAL);
  2372. // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
  2373. // FIXME: It would be far better to avoid inserting those -static arguments,
  2374. // but we can't check the deployment target in the translation code until
  2375. // it is set here.
  2376. if (isTargetWatchOSBased() ||
  2377. (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
  2378. for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
  2379. Arg *A = *it;
  2380. ++it;
  2381. if (A->getOption().getID() != options::OPT_mkernel &&
  2382. A->getOption().getID() != options::OPT_fapple_kext)
  2383. continue;
  2384. assert(it != ie && "unexpected argument translation");
  2385. A = *it;
  2386. assert(A->getOption().getID() == options::OPT_static &&
  2387. "missing expected -static argument");
  2388. *it = nullptr;
  2389. ++it;
  2390. }
  2391. }
  2392. if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
  2393. GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  2394. DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
  2395. "libc++");
  2396. // Validate the C++ standard library choice.
  2397. CXXStdlibType Type = GetCXXStdlibType(*DAL);
  2398. if (Type == ToolChain::CST_Libcxx) {
  2399. // Check whether the target provides libc++.
  2400. StringRef where;
  2401. // Complain about targeting iOS < 5.0 in any way.
  2402. if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
  2403. where = "iOS 5.0";
  2404. if (where != StringRef()) {
  2405. getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
  2406. }
  2407. }
  2408. auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
  2409. if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
  2410. if (Args.hasFlag(options::OPT_fomit_frame_pointer,
  2411. options::OPT_fno_omit_frame_pointer, false))
  2412. getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
  2413. << "-fomit-frame-pointer" << BoundArch;
  2414. }
  2415. return DAL;
  2416. }
  2417. bool MachO::IsUnwindTablesDefault(const ArgList &Args) const {
  2418. // Unwind tables are not emitted if -fno-exceptions is supplied (except when
  2419. // targeting x86_64).
  2420. return getArch() == llvm::Triple::x86_64 ||
  2421. (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
  2422. Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  2423. true));
  2424. }
  2425. bool MachO::UseDwarfDebugFlags() const {
  2426. if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
  2427. return S[0] != '\0';
  2428. return false;
  2429. }
  2430. llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
  2431. // Darwin uses SjLj exceptions on ARM.
  2432. if (getTriple().getArch() != llvm::Triple::arm &&
  2433. getTriple().getArch() != llvm::Triple::thumb)
  2434. return llvm::ExceptionHandling::None;
  2435. // Only watchOS uses the new DWARF/Compact unwinding method.
  2436. llvm::Triple Triple(ComputeLLVMTriple(Args));
  2437. if (Triple.isWatchABI())
  2438. return llvm::ExceptionHandling::DwarfCFI;
  2439. return llvm::ExceptionHandling::SjLj;
  2440. }
  2441. bool Darwin::SupportsEmbeddedBitcode() const {
  2442. assert(TargetInitialized && "Target not initialized!");
  2443. if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
  2444. return false;
  2445. return true;
  2446. }
  2447. bool MachO::isPICDefault() const { return true; }
  2448. bool MachO::isPIEDefault(const llvm::opt::ArgList &Args) const { return false; }
  2449. bool MachO::isPICDefaultForced() const {
  2450. return (getArch() == llvm::Triple::x86_64 ||
  2451. getArch() == llvm::Triple::aarch64);
  2452. }
  2453. bool MachO::SupportsProfiling() const {
  2454. // Profiling instrumentation is only supported on x86.
  2455. return getTriple().isX86();
  2456. }
  2457. void Darwin::addMinVersionArgs(const ArgList &Args,
  2458. ArgStringList &CmdArgs) const {
  2459. VersionTuple TargetVersion = getTripleTargetVersion();
  2460. if (isTargetWatchOS())
  2461. CmdArgs.push_back("-watchos_version_min");
  2462. else if (isTargetWatchOSSimulator())
  2463. CmdArgs.push_back("-watchos_simulator_version_min");
  2464. else if (isTargetTvOS())
  2465. CmdArgs.push_back("-tvos_version_min");
  2466. else if (isTargetTvOSSimulator())
  2467. CmdArgs.push_back("-tvos_simulator_version_min");
  2468. else if (isTargetIOSSimulator())
  2469. CmdArgs.push_back("-ios_simulator_version_min");
  2470. else if (isTargetIOSBased())
  2471. CmdArgs.push_back("-iphoneos_version_min");
  2472. else if (isTargetMacCatalyst())
  2473. CmdArgs.push_back("-maccatalyst_version_min");
  2474. else {
  2475. assert(isTargetMacOS() && "unexpected target");
  2476. CmdArgs.push_back("-macosx_version_min");
  2477. }
  2478. VersionTuple MinTgtVers = getEffectiveTriple().getMinimumSupportedOSVersion();
  2479. if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
  2480. TargetVersion = MinTgtVers;
  2481. CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
  2482. }
  2483. static const char *getPlatformName(Darwin::DarwinPlatformKind Platform,
  2484. Darwin::DarwinEnvironmentKind Environment) {
  2485. switch (Platform) {
  2486. case Darwin::MacOS:
  2487. return "macos";
  2488. case Darwin::IPhoneOS:
  2489. if (Environment == Darwin::MacCatalyst)
  2490. return "mac catalyst";
  2491. return "ios";
  2492. case Darwin::TvOS:
  2493. return "tvos";
  2494. case Darwin::WatchOS:
  2495. return "watchos";
  2496. }
  2497. llvm_unreachable("invalid platform");
  2498. }
  2499. void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList &Args,
  2500. llvm::opt::ArgStringList &CmdArgs) const {
  2501. // -platform_version <platform> <target_version> <sdk_version>
  2502. // Both the target and SDK version support only up to 3 components.
  2503. CmdArgs.push_back("-platform_version");
  2504. std::string PlatformName = getPlatformName(TargetPlatform, TargetEnvironment);
  2505. if (TargetEnvironment == Darwin::Simulator)
  2506. PlatformName += "-simulator";
  2507. CmdArgs.push_back(Args.MakeArgString(PlatformName));
  2508. VersionTuple TargetVersion = getTripleTargetVersion().withoutBuild();
  2509. VersionTuple MinTgtVers = getEffectiveTriple().getMinimumSupportedOSVersion();
  2510. if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
  2511. TargetVersion = MinTgtVers;
  2512. CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
  2513. if (isTargetMacCatalyst()) {
  2514. // Mac Catalyst programs must use the appropriate iOS SDK version
  2515. // that corresponds to the macOS SDK version used for the compilation.
  2516. Optional<VersionTuple> iOSSDKVersion;
  2517. if (SDKInfo) {
  2518. if (const auto *MacOStoMacCatalystMapping = SDKInfo->getVersionMapping(
  2519. DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
  2520. iOSSDKVersion = MacOStoMacCatalystMapping->map(
  2521. SDKInfo->getVersion().withoutBuild(),
  2522. minimumMacCatalystDeploymentTarget(), None);
  2523. }
  2524. }
  2525. CmdArgs.push_back(Args.MakeArgString(
  2526. (iOSSDKVersion ? *iOSSDKVersion : minimumMacCatalystDeploymentTarget())
  2527. .getAsString()));
  2528. return;
  2529. }
  2530. if (SDKInfo) {
  2531. VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
  2532. CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
  2533. } else {
  2534. // Use an SDK version that's matching the deployment target if the SDK
  2535. // version is missing. This is preferred over an empty SDK version (0.0.0)
  2536. // as the system's runtime might expect the linked binary to contain a
  2537. // valid SDK version in order for the binary to work correctly. It's
  2538. // reasonable to use the deployment target version as a proxy for the
  2539. // SDK version because older SDKs don't guarantee support for deployment
  2540. // targets newer than the SDK versions, so that rules out using some
  2541. // predetermined older SDK version, which leaves the deployment target
  2542. // version as the only reasonable choice.
  2543. CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
  2544. }
  2545. }
  2546. // Add additional link args for the -dynamiclib option.
  2547. static void addDynamicLibLinkArgs(const Darwin &D, const ArgList &Args,
  2548. ArgStringList &CmdArgs) {
  2549. // Derived from darwin_dylib1 spec.
  2550. if (D.isTargetIPhoneOS()) {
  2551. if (D.isIPhoneOSVersionLT(3, 1))
  2552. CmdArgs.push_back("-ldylib1.o");
  2553. return;
  2554. }
  2555. if (!D.isTargetMacOS())
  2556. return;
  2557. if (D.isMacosxVersionLT(10, 5))
  2558. CmdArgs.push_back("-ldylib1.o");
  2559. else if (D.isMacosxVersionLT(10, 6))
  2560. CmdArgs.push_back("-ldylib1.10.5.o");
  2561. }
  2562. // Add additional link args for the -bundle option.
  2563. static void addBundleLinkArgs(const Darwin &D, const ArgList &Args,
  2564. ArgStringList &CmdArgs) {
  2565. if (Args.hasArg(options::OPT_static))
  2566. return;
  2567. // Derived from darwin_bundle1 spec.
  2568. if ((D.isTargetIPhoneOS() && D.isIPhoneOSVersionLT(3, 1)) ||
  2569. (D.isTargetMacOS() && D.isMacosxVersionLT(10, 6)))
  2570. CmdArgs.push_back("-lbundle1.o");
  2571. }
  2572. // Add additional link args for the -pg option.
  2573. static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args,
  2574. ArgStringList &CmdArgs) {
  2575. if (D.isTargetMacOS() && D.isMacosxVersionLT(10, 9)) {
  2576. if (Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_object) ||
  2577. Args.hasArg(options::OPT_preload)) {
  2578. CmdArgs.push_back("-lgcrt0.o");
  2579. } else {
  2580. CmdArgs.push_back("-lgcrt1.o");
  2581. // darwin_crt2 spec is empty.
  2582. }
  2583. // By default on OS X 10.8 and later, we don't link with a crt1.o
  2584. // file and the linker knows to use _main as the entry point. But,
  2585. // when compiling with -pg, we need to link with the gcrt1.o file,
  2586. // so pass the -no_new_main option to tell the linker to use the
  2587. // "start" symbol as the entry point.
  2588. if (!D.isMacosxVersionLT(10, 8))
  2589. CmdArgs.push_back("-no_new_main");
  2590. } else {
  2591. D.getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin)
  2592. << D.isTargetMacOSBased();
  2593. }
  2594. }
  2595. static void addDefaultCRTLinkArgs(const Darwin &D, const ArgList &Args,
  2596. ArgStringList &CmdArgs) {
  2597. // Derived from darwin_crt1 spec.
  2598. if (D.isTargetIPhoneOS()) {
  2599. if (D.getArch() == llvm::Triple::aarch64)
  2600. ; // iOS does not need any crt1 files for arm64
  2601. else if (D.isIPhoneOSVersionLT(3, 1))
  2602. CmdArgs.push_back("-lcrt1.o");
  2603. else if (D.isIPhoneOSVersionLT(6, 0))
  2604. CmdArgs.push_back("-lcrt1.3.1.o");
  2605. return;
  2606. }
  2607. if (!D.isTargetMacOS())
  2608. return;
  2609. if (D.isMacosxVersionLT(10, 5))
  2610. CmdArgs.push_back("-lcrt1.o");
  2611. else if (D.isMacosxVersionLT(10, 6))
  2612. CmdArgs.push_back("-lcrt1.10.5.o");
  2613. else if (D.isMacosxVersionLT(10, 8))
  2614. CmdArgs.push_back("-lcrt1.10.6.o");
  2615. // darwin_crt2 spec is empty.
  2616. }
  2617. void Darwin::addStartObjectFileArgs(const ArgList &Args,
  2618. ArgStringList &CmdArgs) const {
  2619. // Derived from startfile spec.
  2620. if (Args.hasArg(options::OPT_dynamiclib))
  2621. addDynamicLibLinkArgs(*this, Args, CmdArgs);
  2622. else if (Args.hasArg(options::OPT_bundle))
  2623. addBundleLinkArgs(*this, Args, CmdArgs);
  2624. else if (Args.hasArg(options::OPT_pg) && SupportsProfiling())
  2625. addPgProfilingLinkArgs(*this, Args, CmdArgs);
  2626. else if (Args.hasArg(options::OPT_static) ||
  2627. Args.hasArg(options::OPT_object) ||
  2628. Args.hasArg(options::OPT_preload))
  2629. CmdArgs.push_back("-lcrt0.o");
  2630. else
  2631. addDefaultCRTLinkArgs(*this, Args, CmdArgs);
  2632. if (isTargetMacOS() && Args.hasArg(options::OPT_shared_libgcc) &&
  2633. isMacosxVersionLT(10, 5)) {
  2634. const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
  2635. CmdArgs.push_back(Str);
  2636. }
  2637. }
  2638. void Darwin::CheckObjCARC() const {
  2639. if (isTargetIOSBased() || isTargetWatchOSBased() ||
  2640. (isTargetMacOSBased() && !isMacosxVersionLT(10, 6)))
  2641. return;
  2642. getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
  2643. }
  2644. SanitizerMask Darwin::getSupportedSanitizers() const {
  2645. const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
  2646. const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64;
  2647. SanitizerMask Res = ToolChain::getSupportedSanitizers();
  2648. Res |= SanitizerKind::Address;
  2649. Res |= SanitizerKind::PointerCompare;
  2650. Res |= SanitizerKind::PointerSubtract;
  2651. Res |= SanitizerKind::Leak;
  2652. Res |= SanitizerKind::Fuzzer;
  2653. Res |= SanitizerKind::FuzzerNoLink;
  2654. Res |= SanitizerKind::Function;
  2655. Res |= SanitizerKind::ObjCCast;
  2656. // Prior to 10.9, macOS shipped a version of the C++ standard library without
  2657. // C++11 support. The same is true of iOS prior to version 5. These OS'es are
  2658. // incompatible with -fsanitize=vptr.
  2659. if (!(isTargetMacOSBased() && isMacosxVersionLT(10, 9)) &&
  2660. !(isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0)))
  2661. Res |= SanitizerKind::Vptr;
  2662. if ((IsX86_64 || IsAArch64) && isTargetMacOSBased()) {
  2663. Res |= SanitizerKind::Thread;
  2664. } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
  2665. if (IsX86_64)
  2666. Res |= SanitizerKind::Thread;
  2667. }
  2668. return Res;
  2669. }
  2670. void Darwin::printVerboseInfo(raw_ostream &OS) const {
  2671. CudaInstallation.print(OS);
  2672. RocmInstallation.print(OS);
  2673. }