Driver.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894
  1. //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/Driver/Driver.h"
  10. #include "clang/Driver/Action.h"
  11. #include "clang/Driver/Arg.h"
  12. #include "clang/Driver/ArgList.h"
  13. #include "clang/Driver/Compilation.h"
  14. #include "clang/Driver/DriverDiagnostic.h"
  15. #include "clang/Driver/Job.h"
  16. #include "clang/Driver/OptTable.h"
  17. #include "clang/Driver/Option.h"
  18. #include "clang/Driver/Options.h"
  19. #include "clang/Driver/Tool.h"
  20. #include "clang/Driver/ToolChain.h"
  21. #include "clang/Basic/Version.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/StringSet.h"
  24. #include "llvm/ADT/OwningPtr.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/PrettyStackTrace.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include "llvm/Support/FileSystem.h"
  29. #include "llvm/Support/Path.h"
  30. #include "llvm/Support/Program.h"
  31. #include "InputInfo.h"
  32. #include "ToolChains.h"
  33. #include <map>
  34. #include "clang/Config/config.h"
  35. using namespace clang::driver;
  36. using namespace clang;
  37. Driver::Driver(StringRef ClangExecutable,
  38. StringRef DefaultTargetTriple,
  39. StringRef DefaultImageName,
  40. bool IsProduction,
  41. DiagnosticsEngine &Diags)
  42. : Opts(createDriverOptTable()), Diags(Diags),
  43. ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
  44. UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
  45. DefaultImageName(DefaultImageName),
  46. DriverTitle("clang \"gcc-compatible\" driver"),
  47. CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
  48. CCLogDiagnosticsFilename(0), CCCIsCXX(false),
  49. CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
  50. CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
  51. CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
  52. CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true),
  53. ForcedClangUse(false), CCCUsePCH(true), SuppressMissingInputWarning(false) {
  54. if (IsProduction) {
  55. // In a "production" build, only use clang on architectures we expect to
  56. // work.
  57. //
  58. // During development its more convenient to always have the driver use
  59. // clang, but we don't want users to be confused when things don't work, or
  60. // to file bugs for things we don't support.
  61. CCCClangArchs.insert(llvm::Triple::x86);
  62. CCCClangArchs.insert(llvm::Triple::x86_64);
  63. CCCClangArchs.insert(llvm::Triple::arm);
  64. }
  65. Name = llvm::sys::path::stem(ClangExecutable);
  66. Dir = llvm::sys::path::parent_path(ClangExecutable);
  67. // Compute the path to the resource directory.
  68. StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
  69. SmallString<128> P(Dir);
  70. if (ClangResourceDir != "")
  71. llvm::sys::path::append(P, ClangResourceDir);
  72. else
  73. llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
  74. ResourceDir = P.str();
  75. }
  76. Driver::~Driver() {
  77. delete Opts;
  78. for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(),
  79. E = ToolChains.end();
  80. I != E; ++I)
  81. delete I->second;
  82. }
  83. InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) {
  84. llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
  85. unsigned MissingArgIndex, MissingArgCount;
  86. InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(),
  87. MissingArgIndex, MissingArgCount);
  88. // Check for missing argument error.
  89. if (MissingArgCount)
  90. Diag(clang::diag::err_drv_missing_argument)
  91. << Args->getArgString(MissingArgIndex) << MissingArgCount;
  92. // Check for unsupported options.
  93. for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
  94. it != ie; ++it) {
  95. Arg *A = *it;
  96. if (A->getOption().isUnsupported()) {
  97. Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
  98. continue;
  99. }
  100. // Warn about -mcpu= without an argument.
  101. if (A->getOption().matches(options::OPT_mcpu_EQ) &&
  102. A->containsValue("")) {
  103. Diag(clang::diag::warn_drv_empty_joined_argument) <<
  104. A->getAsString(*Args);
  105. }
  106. }
  107. return Args;
  108. }
  109. // Determine which compilation mode we are in. We look for options which
  110. // affect the phase, starting with the earliest phases, and record which
  111. // option we used to determine the final phase.
  112. phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg)
  113. const {
  114. Arg *PhaseArg = 0;
  115. phases::ID FinalPhase;
  116. // -{E,M,MM} only run the preprocessor.
  117. if (CCCIsCPP ||
  118. (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
  119. (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) {
  120. FinalPhase = phases::Preprocess;
  121. // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
  122. } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
  123. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
  124. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
  125. (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
  126. (PhaseArg = DAL.getLastArg(options::OPT__analyze,
  127. options::OPT__analyze_auto)) ||
  128. (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
  129. (PhaseArg = DAL.getLastArg(options::OPT_S))) {
  130. FinalPhase = phases::Compile;
  131. // -c only runs up to the assembler.
  132. } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
  133. FinalPhase = phases::Assemble;
  134. // Otherwise do everything.
  135. } else
  136. FinalPhase = phases::Link;
  137. if (FinalPhaseArg)
  138. *FinalPhaseArg = PhaseArg;
  139. return FinalPhase;
  140. }
  141. DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
  142. DerivedArgList *DAL = new DerivedArgList(Args);
  143. bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
  144. for (ArgList::const_iterator it = Args.begin(),
  145. ie = Args.end(); it != ie; ++it) {
  146. const Arg *A = *it;
  147. // Unfortunately, we have to parse some forwarding options (-Xassembler,
  148. // -Xlinker, -Xpreprocessor) because we either integrate their functionality
  149. // (assembler and preprocessor), or bypass a previous driver ('collect2').
  150. // Rewrite linker options, to replace --no-demangle with a custom internal
  151. // option.
  152. if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
  153. A->getOption().matches(options::OPT_Xlinker)) &&
  154. A->containsValue("--no-demangle")) {
  155. // Add the rewritten no-demangle argument.
  156. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
  157. // Add the remaining values as Xlinker arguments.
  158. for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
  159. if (StringRef(A->getValue(Args, i)) != "--no-demangle")
  160. DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
  161. A->getValue(Args, i));
  162. continue;
  163. }
  164. // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
  165. // some build systems. We don't try to be complete here because we don't
  166. // care to encourage this usage model.
  167. if (A->getOption().matches(options::OPT_Wp_COMMA) &&
  168. A->getNumValues() == 2 &&
  169. (A->getValue(Args, 0) == StringRef("-MD") ||
  170. A->getValue(Args, 0) == StringRef("-MMD"))) {
  171. // Rewrite to -MD/-MMD along with -MF.
  172. if (A->getValue(Args, 0) == StringRef("-MD"))
  173. DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
  174. else
  175. DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
  176. DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
  177. A->getValue(Args, 1));
  178. continue;
  179. }
  180. // Rewrite reserved library names.
  181. if (A->getOption().matches(options::OPT_l)) {
  182. StringRef Value = A->getValue(Args);
  183. // Rewrite unless -nostdlib is present.
  184. if (!HasNostdlib && Value == "stdc++") {
  185. DAL->AddFlagArg(A, Opts->getOption(
  186. options::OPT_Z_reserved_lib_stdcxx));
  187. continue;
  188. }
  189. // Rewrite unconditionally.
  190. if (Value == "cc_kext") {
  191. DAL->AddFlagArg(A, Opts->getOption(
  192. options::OPT_Z_reserved_lib_cckext));
  193. continue;
  194. }
  195. }
  196. DAL->append(*it);
  197. }
  198. // Add a default value of -mlinker-version=, if one was given and the user
  199. // didn't specify one.
  200. #if defined(HOST_LINK_VERSION)
  201. if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
  202. DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
  203. HOST_LINK_VERSION);
  204. DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
  205. }
  206. #endif
  207. return DAL;
  208. }
  209. Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
  210. llvm::PrettyStackTraceString CrashInfo("Compilation construction");
  211. // FIXME: Handle environment options which affect driver behavior, somewhere
  212. // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
  213. if (char *env = ::getenv("COMPILER_PATH")) {
  214. StringRef CompilerPath = env;
  215. while (!CompilerPath.empty()) {
  216. std::pair<StringRef, StringRef> Split = CompilerPath.split(':');
  217. PrefixDirs.push_back(Split.first);
  218. CompilerPath = Split.second;
  219. }
  220. }
  221. // FIXME: What are we going to do with -V and -b?
  222. // FIXME: This stuff needs to go into the Compilation, not the driver.
  223. bool CCCPrintOptions = false, CCCPrintActions = false;
  224. InputArgList *Args = ParseArgStrings(ArgList.slice(1));
  225. // -no-canonical-prefixes is used very early in main.
  226. Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
  227. // Ignore -pipe.
  228. Args->ClaimAllArgs(options::OPT_pipe);
  229. // Extract -ccc args.
  230. //
  231. // FIXME: We need to figure out where this behavior should live. Most of it
  232. // should be outside in the client; the parts that aren't should have proper
  233. // options, either by introducing new ones or by overloading gcc ones like -V
  234. // or -b.
  235. CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
  236. CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
  237. CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
  238. CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
  239. CCCEcho = Args->hasArg(options::OPT_ccc_echo);
  240. if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
  241. CCCGenericGCCName = A->getValue(*Args);
  242. CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
  243. options::OPT_ccc_no_clang_cxx,
  244. CCCUseClangCXX);
  245. CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
  246. options::OPT_ccc_pch_is_pth);
  247. CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
  248. CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
  249. if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
  250. StringRef Cur = A->getValue(*Args);
  251. CCCClangArchs.clear();
  252. while (!Cur.empty()) {
  253. std::pair<StringRef, StringRef> Split = Cur.split(',');
  254. if (!Split.first.empty()) {
  255. llvm::Triple::ArchType Arch =
  256. llvm::Triple(Split.first, "", "").getArch();
  257. if (Arch == llvm::Triple::UnknownArch)
  258. Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
  259. CCCClangArchs.insert(Arch);
  260. }
  261. Cur = Split.second;
  262. }
  263. }
  264. // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
  265. // and getToolChain is const.
  266. if (const Arg *A = Args->getLastArg(options::OPT_target))
  267. DefaultTargetTriple = A->getValue(*Args);
  268. if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
  269. Dir = InstalledDir = A->getValue(*Args);
  270. for (arg_iterator it = Args->filtered_begin(options::OPT_B),
  271. ie = Args->filtered_end(); it != ie; ++it) {
  272. const Arg *A = *it;
  273. A->claim();
  274. PrefixDirs.push_back(A->getValue(*Args, 0));
  275. }
  276. if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
  277. SysRoot = A->getValue(*Args);
  278. if (Args->hasArg(options::OPT_nostdlib))
  279. UseStdLib = false;
  280. // Perform the default argument translations.
  281. DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
  282. // Owned by the host.
  283. const ToolChain &TC = getToolChain(*Args);
  284. // The compilation takes ownership of Args.
  285. Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs);
  286. // FIXME: This behavior shouldn't be here.
  287. if (CCCPrintOptions) {
  288. PrintOptions(C->getInputArgs());
  289. return C;
  290. }
  291. if (!HandleImmediateArgs(*C))
  292. return C;
  293. // Construct the list of inputs.
  294. InputList Inputs;
  295. BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs);
  296. // Construct the list of abstract actions to perform for this compilation. On
  297. // Darwin target OSes this uses the driver-driver and universal actions.
  298. if (TC.getTriple().isOSDarwin())
  299. BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
  300. Inputs, C->getActions());
  301. else
  302. BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
  303. C->getActions());
  304. if (CCCPrintActions) {
  305. PrintActions(*C);
  306. return C;
  307. }
  308. BuildJobs(*C);
  309. return C;
  310. }
  311. // When clang crashes, produce diagnostic information including the fully
  312. // preprocessed source file(s). Request that the developer attach the
  313. // diagnostic information to a bug report.
  314. void Driver::generateCompilationDiagnostics(Compilation &C,
  315. const Command *FailingCommand) {
  316. if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
  317. return;
  318. // Don't try to generate diagnostics for link jobs.
  319. if (FailingCommand && FailingCommand->getCreator().isLinkJob())
  320. return;
  321. // Print the version of the compiler.
  322. PrintVersion(C, llvm::errs());
  323. Diag(clang::diag::note_drv_command_failed_diag_msg)
  324. << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
  325. "crash backtrace, preprocessed source, and associated run script.";
  326. // Suppress driver output and emit preprocessor output to temp file.
  327. CCCIsCPP = true;
  328. CCGenDiagnostics = true;
  329. C.getArgs().AddFlagArg(0, Opts->getOption(options::OPT_frewrite_includes));
  330. // Save the original job command(s).
  331. std::string Cmd;
  332. llvm::raw_string_ostream OS(Cmd);
  333. if (FailingCommand)
  334. C.PrintJob(OS, *FailingCommand, "\n", false);
  335. else
  336. // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an
  337. // associated FailingCommand, so just pass all jobs.
  338. C.PrintJob(OS, C.getJobs(), "\n", false);
  339. OS.flush();
  340. // Clear stale state and suppress tool output.
  341. C.initCompilationForDiagnostics();
  342. Diags.Reset();
  343. // Construct the list of inputs.
  344. InputList Inputs;
  345. BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
  346. for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
  347. bool IgnoreInput = false;
  348. // Ignore input from stdin or any inputs that cannot be preprocessed.
  349. if (!strcmp(it->second->getValue(C.getArgs()), "-")) {
  350. Diag(clang::diag::note_drv_command_failed_diag_msg)
  351. << "Error generating preprocessed source(s) - ignoring input from stdin"
  352. ".";
  353. IgnoreInput = true;
  354. } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
  355. IgnoreInput = true;
  356. }
  357. if (IgnoreInput) {
  358. it = Inputs.erase(it);
  359. ie = Inputs.end();
  360. } else {
  361. ++it;
  362. }
  363. }
  364. // Don't attempt to generate preprocessed files if multiple -arch options are
  365. // used, unless they're all duplicates.
  366. llvm::StringSet<> ArchNames;
  367. for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
  368. it != ie; ++it) {
  369. Arg *A = *it;
  370. if (A->getOption().matches(options::OPT_arch)) {
  371. StringRef ArchName = A->getValue(C.getArgs());
  372. ArchNames.insert(ArchName);
  373. }
  374. }
  375. if (ArchNames.size() > 1) {
  376. Diag(clang::diag::note_drv_command_failed_diag_msg)
  377. << "Error generating preprocessed source(s) - cannot generate "
  378. "preprocessed source with multiple -arch options.";
  379. return;
  380. }
  381. if (Inputs.empty()) {
  382. Diag(clang::diag::note_drv_command_failed_diag_msg)
  383. << "Error generating preprocessed source(s) - no preprocessable inputs.";
  384. return;
  385. }
  386. // Construct the list of abstract actions to perform for this compilation. On
  387. // Darwin OSes this uses the driver-driver and builds universal actions.
  388. const ToolChain &TC = C.getDefaultToolChain();
  389. if (TC.getTriple().isOSDarwin())
  390. BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
  391. else
  392. BuildActions(TC, C.getArgs(), Inputs, C.getActions());
  393. BuildJobs(C);
  394. // If there were errors building the compilation, quit now.
  395. if (Diags.hasErrorOccurred()) {
  396. Diag(clang::diag::note_drv_command_failed_diag_msg)
  397. << "Error generating preprocessed source(s).";
  398. return;
  399. }
  400. // Generate preprocessed output.
  401. FailingCommand = 0;
  402. int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
  403. // If the command succeeded, we are done.
  404. if (Res == 0) {
  405. Diag(clang::diag::note_drv_command_failed_diag_msg)
  406. << "\n********************\n\n"
  407. "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
  408. "Preprocessed source(s) and associated run script(s) are located at:";
  409. ArgStringList Files = C.getTempFiles();
  410. for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end();
  411. it != ie; ++it) {
  412. Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
  413. std::string Err;
  414. std::string Script = StringRef(*it).rsplit('.').first;
  415. Script += ".sh";
  416. llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err,
  417. llvm::raw_fd_ostream::F_Excl |
  418. llvm::raw_fd_ostream::F_Binary);
  419. if (!Err.empty()) {
  420. Diag(clang::diag::note_drv_command_failed_diag_msg)
  421. << "Error generating run script: " + Script + " " + Err;
  422. } else {
  423. // Strip away options not necessary to reproduce the crash.
  424. // FIXME: This doesn't work with quotes (e.g., -D "foo bar").
  425. SmallVector<std::string, 16> Flag;
  426. Flag.push_back("-D ");
  427. Flag.push_back("-F");
  428. Flag.push_back("-I ");
  429. Flag.push_back("-M ");
  430. Flag.push_back("-MD ");
  431. Flag.push_back("-MF ");
  432. Flag.push_back("-MG ");
  433. Flag.push_back("-MM ");
  434. Flag.push_back("-MMD ");
  435. Flag.push_back("-MP ");
  436. Flag.push_back("-MQ ");
  437. Flag.push_back("-MT ");
  438. Flag.push_back("-o ");
  439. Flag.push_back("-coverage-file ");
  440. Flag.push_back("-dependency-file ");
  441. Flag.push_back("-fdebug-compilation-dir ");
  442. Flag.push_back("-fmodule-cache-path ");
  443. Flag.push_back("-idirafter ");
  444. Flag.push_back("-include ");
  445. Flag.push_back("-include-pch ");
  446. Flag.push_back("-internal-isystem ");
  447. Flag.push_back("-internal-externc-isystem ");
  448. Flag.push_back("-iprefix ");
  449. Flag.push_back("-iwithprefix ");
  450. Flag.push_back("-iwithprefixbefore ");
  451. Flag.push_back("-isysroot ");
  452. Flag.push_back("-isystem ");
  453. Flag.push_back("-iquote ");
  454. Flag.push_back("-resource-dir ");
  455. Flag.push_back("-serialize-diagnostic-file ");
  456. for (unsigned i = 0, e = Flag.size(); i < e; ++i) {
  457. size_t I = 0, E = 0;
  458. do {
  459. I = Cmd.find(Flag[i], I);
  460. if (I == std::string::npos) break;
  461. E = Cmd.find(" ", I + Flag[i].length());
  462. if (E == std::string::npos) break;
  463. // The -D option is not removed. Instead, the argument is quoted.
  464. if (Flag[i] != "-D ") {
  465. Cmd.erase(I, E - I + 1);
  466. } else {
  467. Cmd.insert(I+3, "\"");
  468. Cmd.insert(++E, "\"");
  469. I = E;
  470. }
  471. } while(1);
  472. }
  473. // Append the new filename with correct preprocessed suffix.
  474. size_t I, E;
  475. I = Cmd.find("-main-file-name ");
  476. assert (I != std::string::npos && "Expected to find -main-file-name");
  477. I += 16;
  478. E = Cmd.find(" ", I);
  479. assert (E != std::string::npos && "-main-file-name missing argument?");
  480. StringRef OldFilename = StringRef(Cmd).slice(I, E);
  481. StringRef NewFilename = llvm::sys::path::filename(*it);
  482. I = StringRef(Cmd).rfind(OldFilename);
  483. E = I + OldFilename.size();
  484. I = Cmd.rfind(" ", I) + 1;
  485. Cmd.replace(I, E - I, NewFilename.data(), NewFilename.size());
  486. ScriptOS << Cmd;
  487. Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
  488. }
  489. }
  490. Diag(clang::diag::note_drv_command_failed_diag_msg)
  491. << "\n\n********************";
  492. } else {
  493. // Failure, remove preprocessed files.
  494. if (!C.getArgs().hasArg(options::OPT_save_temps))
  495. C.CleanupFileList(C.getTempFiles(), true);
  496. Diag(clang::diag::note_drv_command_failed_diag_msg)
  497. << "Error generating preprocessed source(s).";
  498. }
  499. }
  500. int Driver::ExecuteCompilation(const Compilation &C,
  501. const Command *&FailingCommand) const {
  502. // Just print if -### was present.
  503. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  504. C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
  505. return 0;
  506. }
  507. // If there were errors building the compilation, quit now.
  508. if (Diags.hasErrorOccurred())
  509. return 1;
  510. int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
  511. // Remove temp files.
  512. C.CleanupFileList(C.getTempFiles());
  513. // If the command succeeded, we are done.
  514. if (Res == 0)
  515. return Res;
  516. // Otherwise, remove result files as well.
  517. if (!C.getArgs().hasArg(options::OPT_save_temps)) {
  518. C.CleanupFileList(C.getResultFiles(), true);
  519. // Failure result files are valid unless we crashed.
  520. if (Res < 0)
  521. C.CleanupFileList(C.getFailureResultFiles(), true);
  522. }
  523. // Print extra information about abnormal failures, if possible.
  524. //
  525. // This is ad-hoc, but we don't want to be excessively noisy. If the result
  526. // status was 1, assume the command failed normally. In particular, if it was
  527. // the compiler then assume it gave a reasonable error code. Failures in other
  528. // tools are less common, and they generally have worse diagnostics, so always
  529. // print the diagnostic there.
  530. const Tool &FailingTool = FailingCommand->getCreator();
  531. if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
  532. // FIXME: See FIXME above regarding result code interpretation.
  533. if (Res < 0)
  534. Diag(clang::diag::err_drv_command_signalled)
  535. << FailingTool.getShortName();
  536. else
  537. Diag(clang::diag::err_drv_command_failed)
  538. << FailingTool.getShortName() << Res;
  539. }
  540. return Res;
  541. }
  542. void Driver::PrintOptions(const ArgList &Args) const {
  543. unsigned i = 0;
  544. for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
  545. it != ie; ++it, ++i) {
  546. Arg *A = *it;
  547. llvm::errs() << "Option " << i << " - "
  548. << "Name: \"" << A->getOption().getName() << "\", "
  549. << "Values: {";
  550. for (unsigned j = 0; j < A->getNumValues(); ++j) {
  551. if (j)
  552. llvm::errs() << ", ";
  553. llvm::errs() << '"' << A->getValue(Args, j) << '"';
  554. }
  555. llvm::errs() << "}\n";
  556. }
  557. }
  558. void Driver::PrintHelp(bool ShowHidden) const {
  559. getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
  560. ShowHidden);
  561. }
  562. void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
  563. // FIXME: The following handlers should use a callback mechanism, we don't
  564. // know what the client would like to do.
  565. OS << getClangFullVersion() << '\n';
  566. const ToolChain &TC = C.getDefaultToolChain();
  567. OS << "Target: " << TC.getTripleString() << '\n';
  568. // Print the threading model.
  569. //
  570. // FIXME: Implement correctly.
  571. OS << "Thread model: " << "posix" << '\n';
  572. }
  573. /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
  574. /// option.
  575. static void PrintDiagnosticCategories(raw_ostream &OS) {
  576. // Skip the empty category.
  577. for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
  578. i != max; ++i)
  579. OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
  580. }
  581. bool Driver::HandleImmediateArgs(const Compilation &C) {
  582. // The order these options are handled in gcc is all over the place, but we
  583. // don't expect inconsistencies w.r.t. that to matter in practice.
  584. if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
  585. llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
  586. return false;
  587. }
  588. if (C.getArgs().hasArg(options::OPT_dumpversion)) {
  589. // Since -dumpversion is only implemented for pedantic GCC compatibility, we
  590. // return an answer which matches our definition of __VERSION__.
  591. //
  592. // If we want to return a more correct answer some day, then we should
  593. // introduce a non-pedantically GCC compatible mode to Clang in which we
  594. // provide sensible definitions for -dumpversion, __VERSION__, etc.
  595. llvm::outs() << "4.2.1\n";
  596. return false;
  597. }
  598. if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
  599. PrintDiagnosticCategories(llvm::outs());
  600. return false;
  601. }
  602. if (C.getArgs().hasArg(options::OPT_help) ||
  603. C.getArgs().hasArg(options::OPT__help_hidden)) {
  604. PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
  605. return false;
  606. }
  607. if (C.getArgs().hasArg(options::OPT__version)) {
  608. // Follow gcc behavior and use stdout for --version and stderr for -v.
  609. PrintVersion(C, llvm::outs());
  610. return false;
  611. }
  612. if (C.getArgs().hasArg(options::OPT_v) ||
  613. C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  614. PrintVersion(C, llvm::errs());
  615. SuppressMissingInputWarning = true;
  616. }
  617. const ToolChain &TC = C.getDefaultToolChain();
  618. if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
  619. llvm::outs() << "programs: =";
  620. for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
  621. ie = TC.getProgramPaths().end(); it != ie; ++it) {
  622. if (it != TC.getProgramPaths().begin())
  623. llvm::outs() << ':';
  624. llvm::outs() << *it;
  625. }
  626. llvm::outs() << "\n";
  627. llvm::outs() << "libraries: =" << ResourceDir;
  628. StringRef sysroot = C.getSysRoot();
  629. for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
  630. ie = TC.getFilePaths().end(); it != ie; ++it) {
  631. llvm::outs() << ':';
  632. const char *path = it->c_str();
  633. if (path[0] == '=')
  634. llvm::outs() << sysroot << path + 1;
  635. else
  636. llvm::outs() << path;
  637. }
  638. llvm::outs() << "\n";
  639. return false;
  640. }
  641. // FIXME: The following handlers should use a callback mechanism, we don't
  642. // know what the client would like to do.
  643. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
  644. llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
  645. return false;
  646. }
  647. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
  648. llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
  649. return false;
  650. }
  651. if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
  652. llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
  653. return false;
  654. }
  655. if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
  656. // FIXME: We need tool chain support for this.
  657. llvm::outs() << ".;\n";
  658. switch (C.getDefaultToolChain().getTriple().getArch()) {
  659. default:
  660. break;
  661. case llvm::Triple::x86_64:
  662. llvm::outs() << "x86_64;@m64" << "\n";
  663. break;
  664. case llvm::Triple::ppc64:
  665. llvm::outs() << "ppc64;@m64" << "\n";
  666. break;
  667. }
  668. return false;
  669. }
  670. // FIXME: What is the difference between print-multi-directory and
  671. // print-multi-os-directory?
  672. if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
  673. C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
  674. switch (C.getDefaultToolChain().getTriple().getArch()) {
  675. default:
  676. case llvm::Triple::x86:
  677. case llvm::Triple::ppc:
  678. llvm::outs() << "." << "\n";
  679. break;
  680. case llvm::Triple::x86_64:
  681. llvm::outs() << "x86_64" << "\n";
  682. break;
  683. case llvm::Triple::ppc64:
  684. llvm::outs() << "ppc64" << "\n";
  685. break;
  686. }
  687. return false;
  688. }
  689. return true;
  690. }
  691. static unsigned PrintActions1(const Compilation &C, Action *A,
  692. std::map<Action*, unsigned> &Ids) {
  693. if (Ids.count(A))
  694. return Ids[A];
  695. std::string str;
  696. llvm::raw_string_ostream os(str);
  697. os << Action::getClassName(A->getKind()) << ", ";
  698. if (InputAction *IA = dyn_cast<InputAction>(A)) {
  699. os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
  700. } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
  701. os << '"' << BIA->getArchName() << '"'
  702. << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
  703. } else {
  704. os << "{";
  705. for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
  706. os << PrintActions1(C, *it, Ids);
  707. ++it;
  708. if (it != ie)
  709. os << ", ";
  710. }
  711. os << "}";
  712. }
  713. unsigned Id = Ids.size();
  714. Ids[A] = Id;
  715. llvm::errs() << Id << ": " << os.str() << ", "
  716. << types::getTypeName(A->getType()) << "\n";
  717. return Id;
  718. }
  719. void Driver::PrintActions(const Compilation &C) const {
  720. std::map<Action*, unsigned> Ids;
  721. for (ActionList::const_iterator it = C.getActions().begin(),
  722. ie = C.getActions().end(); it != ie; ++it)
  723. PrintActions1(C, *it, Ids);
  724. }
  725. /// \brief Check whether the given input tree contains any compilation or
  726. /// assembly actions.
  727. static bool ContainsCompileOrAssembleAction(const Action *A) {
  728. if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
  729. return true;
  730. for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
  731. if (ContainsCompileOrAssembleAction(*it))
  732. return true;
  733. return false;
  734. }
  735. void Driver::BuildUniversalActions(const ToolChain &TC,
  736. const DerivedArgList &Args,
  737. const InputList &BAInputs,
  738. ActionList &Actions) const {
  739. llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
  740. // Collect the list of architectures. Duplicates are allowed, but should only
  741. // be handled once (in the order seen).
  742. llvm::StringSet<> ArchNames;
  743. SmallVector<const char *, 4> Archs;
  744. for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
  745. it != ie; ++it) {
  746. Arg *A = *it;
  747. if (A->getOption().matches(options::OPT_arch)) {
  748. // Validate the option here; we don't save the type here because its
  749. // particular spelling may participate in other driver choices.
  750. llvm::Triple::ArchType Arch =
  751. llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
  752. if (Arch == llvm::Triple::UnknownArch) {
  753. Diag(clang::diag::err_drv_invalid_arch_name)
  754. << A->getAsString(Args);
  755. continue;
  756. }
  757. A->claim();
  758. if (ArchNames.insert(A->getValue(Args)))
  759. Archs.push_back(A->getValue(Args));
  760. }
  761. }
  762. // When there is no explicit arch for this platform, make sure we still bind
  763. // the architecture (to the default) so that -Xarch_ is handled correctly.
  764. if (!Archs.size())
  765. Archs.push_back(Args.MakeArgString(TC.getArchName()));
  766. // FIXME: We killed off some others but these aren't yet detected in a
  767. // functional manner. If we added information to jobs about which "auxiliary"
  768. // files they wrote then we could detect the conflict these cause downstream.
  769. if (Archs.size() > 1) {
  770. // No recovery needed, the point of this is just to prevent
  771. // overwriting the same files.
  772. if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
  773. Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
  774. << A->getAsString(Args);
  775. }
  776. ActionList SingleActions;
  777. BuildActions(TC, Args, BAInputs, SingleActions);
  778. // Add in arch bindings for every top level action, as well as lipo and
  779. // dsymutil steps if needed.
  780. for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
  781. Action *Act = SingleActions[i];
  782. // Make sure we can lipo this kind of output. If not (and it is an actual
  783. // output) then we disallow, since we can't create an output file with the
  784. // right name without overwriting it. We could remove this oddity by just
  785. // changing the output names to include the arch, which would also fix
  786. // -save-temps. Compatibility wins for now.
  787. if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
  788. Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
  789. << types::getTypeName(Act->getType());
  790. ActionList Inputs;
  791. for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
  792. Inputs.push_back(new BindArchAction(Act, Archs[i]));
  793. if (i != 0)
  794. Inputs.back()->setOwnsInputs(false);
  795. }
  796. // Lipo if necessary, we do it this way because we need to set the arch flag
  797. // so that -Xarch_ gets overwritten.
  798. if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
  799. Actions.append(Inputs.begin(), Inputs.end());
  800. else
  801. Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
  802. // Handle debug info queries.
  803. Arg *A = Args.getLastArg(options::OPT_g_Group);
  804. if (A && !A->getOption().matches(options::OPT_g0) &&
  805. !A->getOption().matches(options::OPT_gstabs) &&
  806. ContainsCompileOrAssembleAction(Actions.back())) {
  807. // Add a 'dsymutil' step if necessary, when debug info is enabled and we
  808. // have a compile input. We need to run 'dsymutil' ourselves in such cases
  809. // because the debug info will refer to a temporary object file which is
  810. // will be removed at the end of the compilation process.
  811. if (Act->getType() == types::TY_Image) {
  812. ActionList Inputs;
  813. Inputs.push_back(Actions.back());
  814. Actions.pop_back();
  815. Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
  816. }
  817. // Verify the output (debug information only) if we passed '-verify'.
  818. if (Args.hasArg(options::OPT_verify)) {
  819. ActionList VerifyInputs;
  820. VerifyInputs.push_back(Actions.back());
  821. Actions.pop_back();
  822. Actions.push_back(new VerifyJobAction(VerifyInputs,
  823. types::TY_Nothing));
  824. }
  825. }
  826. }
  827. }
  828. // Construct a the list of inputs and their types.
  829. void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args,
  830. InputList &Inputs) const {
  831. // Track the current user specified (-x) input. We also explicitly track the
  832. // argument used to set the type; we only want to claim the type when we
  833. // actually use it, so we warn about unused -x arguments.
  834. types::ID InputType = types::TY_Nothing;
  835. Arg *InputTypeArg = 0;
  836. for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
  837. it != ie; ++it) {
  838. Arg *A = *it;
  839. if (isa<InputOption>(A->getOption())) {
  840. const char *Value = A->getValue(Args);
  841. types::ID Ty = types::TY_INVALID;
  842. // Infer the input type if necessary.
  843. if (InputType == types::TY_Nothing) {
  844. // If there was an explicit arg for this, claim it.
  845. if (InputTypeArg)
  846. InputTypeArg->claim();
  847. // stdin must be handled specially.
  848. if (memcmp(Value, "-", 2) == 0) {
  849. // If running with -E, treat as a C input (this changes the builtin
  850. // macros, for example). This may be overridden by -ObjC below.
  851. //
  852. // Otherwise emit an error but still use a valid type to avoid
  853. // spurious errors (e.g., no inputs).
  854. if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
  855. Diag(clang::diag::err_drv_unknown_stdin_type);
  856. Ty = types::TY_C;
  857. } else {
  858. // Otherwise lookup by extension.
  859. // Fallback is C if invoked as C preprocessor or Object otherwise.
  860. // We use a host hook here because Darwin at least has its own
  861. // idea of what .s is.
  862. if (const char *Ext = strrchr(Value, '.'))
  863. Ty = TC.LookupTypeForExtension(Ext + 1);
  864. if (Ty == types::TY_INVALID) {
  865. if (CCCIsCPP)
  866. Ty = types::TY_C;
  867. else
  868. Ty = types::TY_Object;
  869. }
  870. // If the driver is invoked as C++ compiler (like clang++ or c++) it
  871. // should autodetect some input files as C++ for g++ compatibility.
  872. if (CCCIsCXX) {
  873. types::ID OldTy = Ty;
  874. Ty = types::lookupCXXTypeForCType(Ty);
  875. if (Ty != OldTy)
  876. Diag(clang::diag::warn_drv_treating_input_as_cxx)
  877. << getTypeName(OldTy) << getTypeName(Ty);
  878. }
  879. }
  880. // -ObjC and -ObjC++ override the default language, but only for "source
  881. // files". We just treat everything that isn't a linker input as a
  882. // source file.
  883. //
  884. // FIXME: Clean this up if we move the phase sequence into the type.
  885. if (Ty != types::TY_Object) {
  886. if (Args.hasArg(options::OPT_ObjC))
  887. Ty = types::TY_ObjC;
  888. else if (Args.hasArg(options::OPT_ObjCXX))
  889. Ty = types::TY_ObjCXX;
  890. }
  891. } else {
  892. assert(InputTypeArg && "InputType set w/o InputTypeArg");
  893. InputTypeArg->claim();
  894. Ty = InputType;
  895. }
  896. // Check that the file exists, if enabled.
  897. if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
  898. SmallString<64> Path(Value);
  899. if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
  900. SmallString<64> Directory(WorkDir->getValue(Args));
  901. if (llvm::sys::path::is_absolute(Directory.str())) {
  902. llvm::sys::path::append(Directory, Value);
  903. Path.assign(Directory);
  904. }
  905. }
  906. bool exists = false;
  907. if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists)
  908. Diag(clang::diag::err_drv_no_such_file) << Path.str();
  909. else
  910. Inputs.push_back(std::make_pair(Ty, A));
  911. } else
  912. Inputs.push_back(std::make_pair(Ty, A));
  913. } else if (A->getOption().isLinkerInput()) {
  914. // Just treat as object type, we could make a special type for this if
  915. // necessary.
  916. Inputs.push_back(std::make_pair(types::TY_Object, A));
  917. } else if (A->getOption().matches(options::OPT_x)) {
  918. InputTypeArg = A;
  919. InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
  920. A->claim();
  921. // Follow gcc behavior and treat as linker input for invalid -x
  922. // options. Its not clear why we shouldn't just revert to unknown; but
  923. // this isn't very important, we might as well be bug compatible.
  924. if (!InputType) {
  925. Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
  926. InputType = types::TY_Object;
  927. }
  928. }
  929. }
  930. if (CCCIsCPP && Inputs.empty()) {
  931. // If called as standalone preprocessor, stdin is processed
  932. // if no other input is present.
  933. unsigned Index = Args.getBaseArgs().MakeIndex("-");
  934. Arg *A = Opts->ParseOneArg(Args, Index);
  935. A->claim();
  936. Inputs.push_back(std::make_pair(types::TY_C, A));
  937. }
  938. }
  939. void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
  940. const InputList &Inputs, ActionList &Actions) const {
  941. llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
  942. if (!SuppressMissingInputWarning && Inputs.empty()) {
  943. Diag(clang::diag::err_drv_no_input_files);
  944. return;
  945. }
  946. Arg *FinalPhaseArg;
  947. phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
  948. // Reject -Z* at the top level, these options should never have been exposed
  949. // by gcc.
  950. if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
  951. Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
  952. // Construct the actions to perform.
  953. ActionList LinkerInputs;
  954. unsigned NumSteps = 0;
  955. for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
  956. types::ID InputType = Inputs[i].first;
  957. const Arg *InputArg = Inputs[i].second;
  958. NumSteps = types::getNumCompilationPhases(InputType);
  959. assert(NumSteps && "Invalid number of steps!");
  960. // If the first step comes after the final phase we are doing as part of
  961. // this compilation, warn the user about it.
  962. phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
  963. if (InitialPhase > FinalPhase) {
  964. // Claim here to avoid the more general unused warning.
  965. InputArg->claim();
  966. // Suppress all unused style warnings with -Qunused-arguments
  967. if (Args.hasArg(options::OPT_Qunused_arguments))
  968. continue;
  969. // Special case when final phase determined by binary name, rather than
  970. // by a command-line argument with a corresponding Arg.
  971. if (CCCIsCPP)
  972. Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
  973. << InputArg->getAsString(Args)
  974. << getPhaseName(InitialPhase);
  975. // Special case '-E' warning on a previously preprocessed file to make
  976. // more sense.
  977. else if (InitialPhase == phases::Compile &&
  978. FinalPhase == phases::Preprocess &&
  979. getPreprocessedType(InputType) == types::TY_INVALID)
  980. Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
  981. << InputArg->getAsString(Args)
  982. << !!FinalPhaseArg
  983. << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "";
  984. else
  985. Diag(clang::diag::warn_drv_input_file_unused)
  986. << InputArg->getAsString(Args)
  987. << getPhaseName(InitialPhase)
  988. << !!FinalPhaseArg
  989. << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "";
  990. continue;
  991. }
  992. // Build the pipeline for this file.
  993. OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
  994. for (unsigned i = 0; i != NumSteps; ++i) {
  995. phases::ID Phase = types::getCompilationPhase(InputType, i);
  996. // We are done if this step is past what the user requested.
  997. if (Phase > FinalPhase)
  998. break;
  999. // Queue linker inputs.
  1000. if (Phase == phases::Link) {
  1001. assert(i + 1 == NumSteps && "linking must be final compilation step.");
  1002. LinkerInputs.push_back(Current.take());
  1003. break;
  1004. }
  1005. // Some types skip the assembler phase (e.g., llvm-bc), but we can't
  1006. // encode this in the steps because the intermediate type depends on
  1007. // arguments. Just special case here.
  1008. if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
  1009. continue;
  1010. // Otherwise construct the appropriate action.
  1011. Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
  1012. if (Current->getType() == types::TY_Nothing)
  1013. break;
  1014. }
  1015. // If we ended with something, add to the output list.
  1016. if (Current)
  1017. Actions.push_back(Current.take());
  1018. }
  1019. // Add a link action if necessary.
  1020. if (!LinkerInputs.empty())
  1021. Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
  1022. // If we are linking, claim any options which are obviously only used for
  1023. // compilation.
  1024. if (FinalPhase == phases::Link && (NumSteps == 1))
  1025. Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
  1026. }
  1027. Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
  1028. Action *Input) const {
  1029. llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
  1030. // Build the appropriate action.
  1031. switch (Phase) {
  1032. case phases::Link: llvm_unreachable("link action invalid here.");
  1033. case phases::Preprocess: {
  1034. types::ID OutputTy;
  1035. // -{M, MM} alter the output type.
  1036. if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
  1037. OutputTy = types::TY_Dependencies;
  1038. } else {
  1039. OutputTy = Input->getType();
  1040. if (!Args.hasFlag(options::OPT_frewrite_includes,
  1041. options::OPT_fno_rewrite_includes, false))
  1042. OutputTy = types::getPreprocessedType(OutputTy);
  1043. assert(OutputTy != types::TY_INVALID &&
  1044. "Cannot preprocess this input type!");
  1045. }
  1046. return new PreprocessJobAction(Input, OutputTy);
  1047. }
  1048. case phases::Precompile: {
  1049. types::ID OutputTy = types::TY_PCH;
  1050. if (Args.hasArg(options::OPT_fsyntax_only)) {
  1051. // Syntax checks should not emit a PCH file
  1052. OutputTy = types::TY_Nothing;
  1053. }
  1054. return new PrecompileJobAction(Input, OutputTy);
  1055. }
  1056. case phases::Compile: {
  1057. if (Args.hasArg(options::OPT_fsyntax_only)) {
  1058. return new CompileJobAction(Input, types::TY_Nothing);
  1059. } else if (Args.hasArg(options::OPT_rewrite_objc)) {
  1060. return new CompileJobAction(Input, types::TY_RewrittenObjC);
  1061. } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) {
  1062. return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC);
  1063. } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
  1064. return new AnalyzeJobAction(Input, types::TY_Plist);
  1065. } else if (Args.hasArg(options::OPT__migrate)) {
  1066. return new MigrateJobAction(Input, types::TY_Remap);
  1067. } else if (Args.hasArg(options::OPT_emit_ast)) {
  1068. return new CompileJobAction(Input, types::TY_AST);
  1069. } else if (IsUsingLTO(Args)) {
  1070. types::ID Output =
  1071. Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
  1072. return new CompileJobAction(Input, Output);
  1073. } else {
  1074. return new CompileJobAction(Input, types::TY_PP_Asm);
  1075. }
  1076. }
  1077. case phases::Assemble:
  1078. return new AssembleJobAction(Input, types::TY_Object);
  1079. }
  1080. llvm_unreachable("invalid phase in ConstructPhaseAction");
  1081. }
  1082. bool Driver::IsUsingLTO(const ArgList &Args) const {
  1083. // Check for -emit-llvm or -flto.
  1084. if (Args.hasArg(options::OPT_emit_llvm) ||
  1085. Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
  1086. return true;
  1087. // Check for -O4.
  1088. if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
  1089. return A->getOption().matches(options::OPT_O4);
  1090. return false;
  1091. }
  1092. void Driver::BuildJobs(Compilation &C) const {
  1093. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  1094. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  1095. // It is an error to provide a -o option if we are making multiple output
  1096. // files.
  1097. if (FinalOutput) {
  1098. unsigned NumOutputs = 0;
  1099. for (ActionList::const_iterator it = C.getActions().begin(),
  1100. ie = C.getActions().end(); it != ie; ++it)
  1101. if ((*it)->getType() != types::TY_Nothing)
  1102. ++NumOutputs;
  1103. if (NumOutputs > 1) {
  1104. Diag(clang::diag::err_drv_output_argument_with_multiple_files);
  1105. FinalOutput = 0;
  1106. }
  1107. }
  1108. for (ActionList::const_iterator it = C.getActions().begin(),
  1109. ie = C.getActions().end(); it != ie; ++it) {
  1110. Action *A = *it;
  1111. // If we are linking an image for multiple archs then the linker wants
  1112. // -arch_multiple and -final_output <final image name>. Unfortunately, this
  1113. // doesn't fit in cleanly because we have to pass this information down.
  1114. //
  1115. // FIXME: This is a hack; find a cleaner way to integrate this into the
  1116. // process.
  1117. const char *LinkingOutput = 0;
  1118. if (isa<LipoJobAction>(A)) {
  1119. if (FinalOutput)
  1120. LinkingOutput = FinalOutput->getValue(C.getArgs());
  1121. else
  1122. LinkingOutput = DefaultImageName.c_str();
  1123. }
  1124. InputInfo II;
  1125. BuildJobsForAction(C, A, &C.getDefaultToolChain(),
  1126. /*BoundArch*/0,
  1127. /*AtTopLevel*/ true,
  1128. /*LinkingOutput*/ LinkingOutput,
  1129. II);
  1130. }
  1131. // If the user passed -Qunused-arguments or there were errors, don't warn
  1132. // about any unused arguments.
  1133. if (Diags.hasErrorOccurred() ||
  1134. C.getArgs().hasArg(options::OPT_Qunused_arguments))
  1135. return;
  1136. // Claim -### here.
  1137. (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
  1138. for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
  1139. it != ie; ++it) {
  1140. Arg *A = *it;
  1141. // FIXME: It would be nice to be able to send the argument to the
  1142. // DiagnosticsEngine, so that extra values, position, and so on could be
  1143. // printed.
  1144. if (!A->isClaimed()) {
  1145. if (A->getOption().hasNoArgumentUnused())
  1146. continue;
  1147. // Suppress the warning automatically if this is just a flag, and it is an
  1148. // instance of an argument we already claimed.
  1149. const Option &Opt = A->getOption();
  1150. if (isa<FlagOption>(Opt)) {
  1151. bool DuplicateClaimed = false;
  1152. for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
  1153. ie = C.getArgs().filtered_end(); it != ie; ++it) {
  1154. if ((*it)->isClaimed()) {
  1155. DuplicateClaimed = true;
  1156. break;
  1157. }
  1158. }
  1159. if (DuplicateClaimed)
  1160. continue;
  1161. }
  1162. Diag(clang::diag::warn_drv_unused_argument)
  1163. << A->getAsString(C.getArgs());
  1164. }
  1165. }
  1166. }
  1167. static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
  1168. const JobAction *JA,
  1169. const ActionList *&Inputs) {
  1170. const Tool *ToolForJob = 0;
  1171. // See if we should look for a compiler with an integrated assembler. We match
  1172. // bottom up, so what we are actually looking for is an assembler job with a
  1173. // compiler input.
  1174. if (C.getArgs().hasFlag(options::OPT_integrated_as,
  1175. options::OPT_no_integrated_as,
  1176. TC->IsIntegratedAssemblerDefault()) &&
  1177. !C.getArgs().hasArg(options::OPT_save_temps) &&
  1178. isa<AssembleJobAction>(JA) &&
  1179. Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
  1180. const Tool &Compiler = TC->SelectTool(
  1181. C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs());
  1182. if (Compiler.hasIntegratedAssembler()) {
  1183. Inputs = &(*Inputs)[0]->getInputs();
  1184. ToolForJob = &Compiler;
  1185. }
  1186. }
  1187. // Otherwise use the tool for the current job.
  1188. if (!ToolForJob)
  1189. ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
  1190. // See if we should use an integrated preprocessor. We do so when we have
  1191. // exactly one input, since this is the only use case we care about
  1192. // (irrelevant since we don't support combine yet).
  1193. if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
  1194. !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
  1195. !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
  1196. !C.getArgs().hasArg(options::OPT_save_temps) &&
  1197. ToolForJob->hasIntegratedCPP())
  1198. Inputs = &(*Inputs)[0]->getInputs();
  1199. return *ToolForJob;
  1200. }
  1201. void Driver::BuildJobsForAction(Compilation &C,
  1202. const Action *A,
  1203. const ToolChain *TC,
  1204. const char *BoundArch,
  1205. bool AtTopLevel,
  1206. const char *LinkingOutput,
  1207. InputInfo &Result) const {
  1208. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  1209. if (const InputAction *IA = dyn_cast<InputAction>(A)) {
  1210. // FIXME: It would be nice to not claim this here; maybe the old scheme of
  1211. // just using Args was better?
  1212. const Arg &Input = IA->getInputArg();
  1213. Input.claim();
  1214. if (Input.getOption().matches(options::OPT_INPUT)) {
  1215. const char *Name = Input.getValue(C.getArgs());
  1216. Result = InputInfo(Name, A->getType(), Name);
  1217. } else
  1218. Result = InputInfo(&Input, A->getType(), "");
  1219. return;
  1220. }
  1221. if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
  1222. const ToolChain *TC;
  1223. const char *ArchName = BAA->getArchName();
  1224. if (ArchName)
  1225. TC = &getToolChain(C.getArgs(), ArchName);
  1226. else
  1227. TC = &C.getDefaultToolChain();
  1228. BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
  1229. AtTopLevel, LinkingOutput, Result);
  1230. return;
  1231. }
  1232. const ActionList *Inputs = &A->getInputs();
  1233. const JobAction *JA = cast<JobAction>(A);
  1234. const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
  1235. // Only use pipes when there is exactly one input.
  1236. InputInfoList InputInfos;
  1237. for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
  1238. it != ie; ++it) {
  1239. // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
  1240. // temporary output names.
  1241. //
  1242. // FIXME: Clean this up.
  1243. bool SubJobAtTopLevel = false;
  1244. if (AtTopLevel && isa<DsymutilJobAction>(A))
  1245. SubJobAtTopLevel = true;
  1246. // Also treat verify sub-jobs as being at the top-level. They don't
  1247. // produce any output and so don't need temporary output names.
  1248. if (AtTopLevel && isa<VerifyJobAction>(A))
  1249. SubJobAtTopLevel = true;
  1250. InputInfo II;
  1251. BuildJobsForAction(C, *it, TC, BoundArch,
  1252. SubJobAtTopLevel, LinkingOutput, II);
  1253. InputInfos.push_back(II);
  1254. }
  1255. // Always use the first input as the base input.
  1256. const char *BaseInput = InputInfos[0].getBaseInput();
  1257. // ... except dsymutil actions, which use their actual input as the base
  1258. // input.
  1259. if (JA->getType() == types::TY_dSYM)
  1260. BaseInput = InputInfos[0].getFilename();
  1261. // Determine the place to write output to, if any.
  1262. if (JA->getType() == types::TY_Nothing) {
  1263. Result = InputInfo(A->getType(), BaseInput);
  1264. } else {
  1265. Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
  1266. A->getType(), BaseInput);
  1267. }
  1268. if (CCCPrintBindings && !CCGenDiagnostics) {
  1269. llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
  1270. << " - \"" << T.getName() << "\", inputs: [";
  1271. for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
  1272. llvm::errs() << InputInfos[i].getAsString();
  1273. if (i + 1 != e)
  1274. llvm::errs() << ", ";
  1275. }
  1276. llvm::errs() << "], output: " << Result.getAsString() << "\n";
  1277. } else {
  1278. T.ConstructJob(C, *JA, Result, InputInfos,
  1279. C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
  1280. }
  1281. }
  1282. const char *Driver::GetNamedOutputPath(Compilation &C,
  1283. const JobAction &JA,
  1284. const char *BaseInput,
  1285. bool AtTopLevel) const {
  1286. llvm::PrettyStackTraceString CrashInfo("Computing output path");
  1287. // Output to a user requested destination?
  1288. if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
  1289. !isa<VerifyJobAction>(JA)) {
  1290. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  1291. return C.addResultFile(FinalOutput->getValue(C.getArgs()));
  1292. }
  1293. // Default to writing to stdout?
  1294. if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics)
  1295. return "-";
  1296. // Output to a temporary file?
  1297. if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) ||
  1298. CCGenDiagnostics) {
  1299. StringRef Name = llvm::sys::path::filename(BaseInput);
  1300. std::pair<StringRef, StringRef> Split = Name.split('.');
  1301. std::string TmpName =
  1302. GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
  1303. return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
  1304. }
  1305. SmallString<128> BasePath(BaseInput);
  1306. StringRef BaseName;
  1307. // Dsymutil actions should use the full path.
  1308. if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
  1309. BaseName = BasePath;
  1310. else
  1311. BaseName = llvm::sys::path::filename(BasePath);
  1312. // Determine what the derived output name should be.
  1313. const char *NamedOutput;
  1314. if (JA.getType() == types::TY_Image) {
  1315. NamedOutput = DefaultImageName.c_str();
  1316. } else {
  1317. const char *Suffix = types::getTypeTempSuffix(JA.getType());
  1318. assert(Suffix && "All types used for output should have a suffix.");
  1319. std::string::size_type End = std::string::npos;
  1320. if (!types::appendSuffixForType(JA.getType()))
  1321. End = BaseName.rfind('.');
  1322. std::string Suffixed(BaseName.substr(0, End));
  1323. Suffixed += '.';
  1324. Suffixed += Suffix;
  1325. NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
  1326. }
  1327. // If we're saving temps and the temp file conflicts with the input file,
  1328. // then avoid overwriting input file.
  1329. if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
  1330. NamedOutput == BaseName) {
  1331. bool SameFile = false;
  1332. SmallString<256> Result;
  1333. llvm::sys::fs::current_path(Result);
  1334. llvm::sys::path::append(Result, BaseName);
  1335. llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
  1336. // Must share the same path to conflict.
  1337. if (SameFile) {
  1338. StringRef Name = llvm::sys::path::filename(BaseInput);
  1339. std::pair<StringRef, StringRef> Split = Name.split('.');
  1340. std::string TmpName =
  1341. GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
  1342. return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
  1343. }
  1344. }
  1345. // As an annoying special case, PCH generation doesn't strip the pathname.
  1346. if (JA.getType() == types::TY_PCH) {
  1347. llvm::sys::path::remove_filename(BasePath);
  1348. if (BasePath.empty())
  1349. BasePath = NamedOutput;
  1350. else
  1351. llvm::sys::path::append(BasePath, NamedOutput);
  1352. return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
  1353. } else {
  1354. return C.addResultFile(NamedOutput);
  1355. }
  1356. }
  1357. std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
  1358. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  1359. // attempting to use this prefix when lokup up program paths.
  1360. for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
  1361. ie = PrefixDirs.end(); it != ie; ++it) {
  1362. std::string Dir(*it);
  1363. if (Dir.empty())
  1364. continue;
  1365. if (Dir[0] == '=')
  1366. Dir = SysRoot + Dir.substr(1);
  1367. llvm::sys::Path P(Dir);
  1368. P.appendComponent(Name);
  1369. bool Exists;
  1370. if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
  1371. return P.str();
  1372. }
  1373. llvm::sys::Path P(ResourceDir);
  1374. P.appendComponent(Name);
  1375. bool Exists;
  1376. if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
  1377. return P.str();
  1378. const ToolChain::path_list &List = TC.getFilePaths();
  1379. for (ToolChain::path_list::const_iterator
  1380. it = List.begin(), ie = List.end(); it != ie; ++it) {
  1381. std::string Dir(*it);
  1382. if (Dir.empty())
  1383. continue;
  1384. if (Dir[0] == '=')
  1385. Dir = SysRoot + Dir.substr(1);
  1386. llvm::sys::Path P(Dir);
  1387. P.appendComponent(Name);
  1388. bool Exists;
  1389. if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
  1390. return P.str();
  1391. }
  1392. return Name;
  1393. }
  1394. static bool isPathExecutable(llvm::sys::Path &P, bool WantFile) {
  1395. bool Exists;
  1396. return (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
  1397. : P.canExecute());
  1398. }
  1399. std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
  1400. bool WantFile) const {
  1401. // FIXME: Needs a better variable than DefaultTargetTriple
  1402. std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name);
  1403. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  1404. // attempting to use this prefix when lokup up program paths.
  1405. for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
  1406. ie = PrefixDirs.end(); it != ie; ++it) {
  1407. llvm::sys::Path P(*it);
  1408. P.appendComponent(TargetSpecificExecutable);
  1409. if (isPathExecutable(P, WantFile)) return P.str();
  1410. P.eraseComponent();
  1411. P.appendComponent(Name);
  1412. if (isPathExecutable(P, WantFile)) return P.str();
  1413. }
  1414. const ToolChain::path_list &List = TC.getProgramPaths();
  1415. for (ToolChain::path_list::const_iterator
  1416. it = List.begin(), ie = List.end(); it != ie; ++it) {
  1417. llvm::sys::Path P(*it);
  1418. P.appendComponent(TargetSpecificExecutable);
  1419. if (isPathExecutable(P, WantFile)) return P.str();
  1420. P.eraseComponent();
  1421. P.appendComponent(Name);
  1422. if (isPathExecutable(P, WantFile)) return P.str();
  1423. }
  1424. // If all else failed, search the path.
  1425. llvm::sys::Path
  1426. P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable));
  1427. if (!P.empty())
  1428. return P.str();
  1429. P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name));
  1430. if (!P.empty())
  1431. return P.str();
  1432. return Name;
  1433. }
  1434. std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
  1435. const {
  1436. // FIXME: This is lame; sys::Path should provide this function (in particular,
  1437. // it should know how to find the temporary files dir).
  1438. std::string Error;
  1439. const char *TmpDir = ::getenv("TMPDIR");
  1440. if (!TmpDir)
  1441. TmpDir = ::getenv("TEMP");
  1442. if (!TmpDir)
  1443. TmpDir = ::getenv("TMP");
  1444. if (!TmpDir)
  1445. TmpDir = "/tmp";
  1446. llvm::sys::Path P(TmpDir);
  1447. P.appendComponent(Prefix);
  1448. if (P.makeUnique(false, &Error)) {
  1449. Diag(clang::diag::err_unable_to_make_temp) << Error;
  1450. return "";
  1451. }
  1452. // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837.
  1453. P.eraseFromDisk(false, 0);
  1454. if (Suffix)
  1455. P.appendSuffix(Suffix);
  1456. return P.str();
  1457. }
  1458. /// \brief Compute target triple from args.
  1459. ///
  1460. /// This routine provides the logic to compute a target triple from various
  1461. /// args passed to the driver and the default triple string.
  1462. static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
  1463. const ArgList &Args,
  1464. StringRef DarwinArchName) {
  1465. // FIXME: Already done in Compilation *Driver::BuildCompilation
  1466. if (const Arg *A = Args.getLastArg(options::OPT_target))
  1467. DefaultTargetTriple = A->getValue(Args);
  1468. llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
  1469. // Handle Darwin-specific options available here.
  1470. if (Target.isOSDarwin()) {
  1471. // If an explict Darwin arch name is given, that trumps all.
  1472. if (!DarwinArchName.empty()) {
  1473. Target.setArch(
  1474. llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName));
  1475. return Target;
  1476. }
  1477. // Handle the Darwin '-arch' flag.
  1478. if (Arg *A = Args.getLastArg(options::OPT_arch)) {
  1479. llvm::Triple::ArchType DarwinArch
  1480. = llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
  1481. if (DarwinArch != llvm::Triple::UnknownArch)
  1482. Target.setArch(DarwinArch);
  1483. }
  1484. }
  1485. // Skip further flag support on OSes which don't support '-m32' or '-m64'.
  1486. if (Target.getArchName() == "tce" ||
  1487. Target.getOS() == llvm::Triple::AuroraUX ||
  1488. Target.getOS() == llvm::Triple::Minix)
  1489. return Target;
  1490. // Handle pseudo-target flags '-m32' and '-m64'.
  1491. // FIXME: Should this information be in llvm::Triple?
  1492. if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) {
  1493. if (A->getOption().matches(options::OPT_m32)) {
  1494. if (Target.getArch() == llvm::Triple::x86_64)
  1495. Target.setArch(llvm::Triple::x86);
  1496. if (Target.getArch() == llvm::Triple::ppc64)
  1497. Target.setArch(llvm::Triple::ppc);
  1498. } else {
  1499. if (Target.getArch() == llvm::Triple::x86)
  1500. Target.setArch(llvm::Triple::x86_64);
  1501. if (Target.getArch() == llvm::Triple::ppc)
  1502. Target.setArch(llvm::Triple::ppc64);
  1503. }
  1504. }
  1505. return Target;
  1506. }
  1507. const ToolChain &Driver::getToolChain(const ArgList &Args,
  1508. StringRef DarwinArchName) const {
  1509. llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args,
  1510. DarwinArchName);
  1511. ToolChain *&TC = ToolChains[Target.str()];
  1512. if (!TC) {
  1513. switch (Target.getOS()) {
  1514. case llvm::Triple::AuroraUX:
  1515. TC = new toolchains::AuroraUX(*this, Target, Args);
  1516. break;
  1517. case llvm::Triple::Darwin:
  1518. case llvm::Triple::MacOSX:
  1519. case llvm::Triple::IOS:
  1520. if (Target.getArch() == llvm::Triple::x86 ||
  1521. Target.getArch() == llvm::Triple::x86_64 ||
  1522. Target.getArch() == llvm::Triple::arm ||
  1523. Target.getArch() == llvm::Triple::thumb)
  1524. TC = new toolchains::DarwinClang(*this, Target);
  1525. else
  1526. TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args);
  1527. break;
  1528. case llvm::Triple::DragonFly:
  1529. TC = new toolchains::DragonFly(*this, Target, Args);
  1530. break;
  1531. case llvm::Triple::OpenBSD:
  1532. TC = new toolchains::OpenBSD(*this, Target, Args);
  1533. break;
  1534. case llvm::Triple::Bitrig:
  1535. TC = new toolchains::Bitrig(*this, Target, Args);
  1536. break;
  1537. case llvm::Triple::NetBSD:
  1538. TC = new toolchains::NetBSD(*this, Target, Args);
  1539. break;
  1540. case llvm::Triple::FreeBSD:
  1541. TC = new toolchains::FreeBSD(*this, Target, Args);
  1542. break;
  1543. case llvm::Triple::Minix:
  1544. TC = new toolchains::Minix(*this, Target, Args);
  1545. break;
  1546. case llvm::Triple::Linux:
  1547. if (Target.getArch() == llvm::Triple::hexagon)
  1548. TC = new toolchains::Hexagon_TC(*this, Target);
  1549. else
  1550. TC = new toolchains::Linux(*this, Target, Args);
  1551. break;
  1552. case llvm::Triple::Solaris:
  1553. TC = new toolchains::Solaris(*this, Target, Args);
  1554. break;
  1555. case llvm::Triple::Win32:
  1556. TC = new toolchains::Windows(*this, Target);
  1557. break;
  1558. case llvm::Triple::MinGW32:
  1559. // FIXME: We need a MinGW toolchain. Fallthrough for now.
  1560. default:
  1561. // TCE is an OSless target
  1562. if (Target.getArchName() == "tce") {
  1563. TC = new toolchains::TCEToolChain(*this, Target);
  1564. break;
  1565. }
  1566. TC = new toolchains::Generic_GCC(*this, Target, Args);
  1567. break;
  1568. }
  1569. }
  1570. return *TC;
  1571. }
  1572. bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
  1573. const llvm::Triple &Triple) const {
  1574. // Check if user requested no clang, or clang doesn't understand this type (we
  1575. // only handle single inputs for now).
  1576. if (!CCCUseClang || JA.size() != 1 ||
  1577. !types::isAcceptedByClang((*JA.begin())->getType()))
  1578. return false;
  1579. // Otherwise make sure this is an action clang understands.
  1580. if (isa<PreprocessJobAction>(JA)) {
  1581. if (!CCCUseClangCPP) {
  1582. Diag(clang::diag::warn_drv_not_using_clang_cpp);
  1583. return false;
  1584. }
  1585. } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
  1586. return false;
  1587. // Use clang for C++?
  1588. if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
  1589. Diag(clang::diag::warn_drv_not_using_clang_cxx);
  1590. return false;
  1591. }
  1592. // Always use clang for precompiling, AST generation, and rewriting,
  1593. // regardless of archs.
  1594. if (isa<PrecompileJobAction>(JA) ||
  1595. types::isOnlyAcceptedByClang(JA.getType()))
  1596. return true;
  1597. // Finally, don't use clang if this isn't one of the user specified archs to
  1598. // build.
  1599. if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
  1600. Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
  1601. return false;
  1602. }
  1603. return true;
  1604. }
  1605. /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
  1606. /// grouped values as integers. Numbers which are not provided are set to 0.
  1607. ///
  1608. /// \return True if the entire string was parsed (9.2), or all groups were
  1609. /// parsed (10.3.5extrastuff).
  1610. bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
  1611. unsigned &Minor, unsigned &Micro,
  1612. bool &HadExtra) {
  1613. HadExtra = false;
  1614. Major = Minor = Micro = 0;
  1615. if (*Str == '\0')
  1616. return true;
  1617. char *End;
  1618. Major = (unsigned) strtol(Str, &End, 10);
  1619. if (*Str != '\0' && *End == '\0')
  1620. return true;
  1621. if (*End != '.')
  1622. return false;
  1623. Str = End+1;
  1624. Minor = (unsigned) strtol(Str, &End, 10);
  1625. if (*Str != '\0' && *End == '\0')
  1626. return true;
  1627. if (*End != '.')
  1628. return false;
  1629. Str = End+1;
  1630. Micro = (unsigned) strtol(Str, &End, 10);
  1631. if (*Str != '\0' && *End == '\0')
  1632. return true;
  1633. if (Str == End)
  1634. return false;
  1635. HadExtra = true;
  1636. return true;
  1637. }